answer
stringlengths 17
10.2M
|
|---|
package com.gildorym.basicchar;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
public class AddExpCommand implements CommandExecutor {
private BasicChar plugin;
public AddExpCommand(BasicChar plugin) {
this.plugin = plugin;
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (sender.hasPermission("basicchar.command.addexp")) {
if (plugin.getServer().getPlayer(args[0]) != null) {
if (plugin.levels.get(plugin.getServer().getPlayer(args[0]).getName()) == null) {
plugin.levels.put(plugin.getServer().getPlayer(args[0]).getName(), 1);
}
if (plugin.experience.get(plugin.getServer().getPlayer(args[0]).getName()) == null) {
plugin.experience.put(plugin.getServer().getPlayer(args[0]).getName(), 0);
}
plugin.experience.put(plugin.getServer().getPlayer(args[0]).getName(), plugin.experience.get(plugin.getServer().getPlayer(args[0]).getName()) + Integer.parseInt(args[1]));
int expToNextLevel = (int) Math.round((1000 * plugin.levels.get(plugin.getServer().getPlayer(args[0]).getName())) * (0.5 * (plugin.levels.get(plugin.getServer().getPlayer(args[0]).getName()) + 1)));
if (plugin.experience.get(plugin.getServer().getPlayer(args[0]).getName()) >= expToNextLevel) {
plugin.experience.put(plugin.getServer().getPlayer(args[0]).getName(), expToNextLevel);
plugin.levels.put(plugin.getServer().getPlayer(args[0]).getName(), plugin.levels.get(plugin.getServer().getPlayer(args[0]).getName()) + 1);
}
plugin.getServer().getPlayer(args[0]).setExp(plugin.experience.get(plugin.getServer().getPlayer(args[0]).getName()) / expToNextLevel);
plugin.getServer().getPlayer(args[0]).setLevel(plugin.levels.get(plugin.getServer().getPlayer(args[0]).getName()));
}
}
return true;
}
}
|
package com.github.kmkt.util;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.Arrays;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* MJPEG over HTTP callback
*/
public class MjpegHTTPReader {
private static final Logger logger = LoggerFactory.getLogger(MjpegHTTPReader.class);
/**
* callback interface
*/
public interface RecvFrameCallback {
/**
* callback
* @param frame_data 1
*/
void onRecvFrame(byte[] frame_data);
}
/**
* callback interface
*/
public interface StateChangeCallback {
/**
* callback
*/
void onStreamClosed();
/**
* callback
*/
void onFinished();
}
private URI target = null;
private StreamReaderThread streamReadLoop = null;
private RecvFrameCallback recv_callback = null;
private StateChangeCallback state_callback = null;
/**
*
* @param target MJPEG URL
* @param recv_callback callback
* @param state_callback callback
*/
public MjpegHTTPReader(URI target, RecvFrameCallback recv_callback, StateChangeCallback state_callback) {
if (target == null)
throw new IllegalArgumentException("target should not be null");
this.target = target;
this.recv_callback = recv_callback;
this.state_callback = state_callback;
}
public synchronized boolean isActive() {
if (this.streamReadLoop == null)
return false;
return this.streamReadLoop.isAlive();
}
/**
* MJPEG
*
* @param connecte_timeout
* @throws ClientProtocolException
* @throws IOException
*/
public synchronized void start(int connecte_timeout) throws ClientProtocolException, IOException {
if (connecte_timeout < 0)
throw new IllegalArgumentException("connecte_timeout should be positive");
if (isActive())
throw new IllegalStateException("Already started");
HttpClient httpclient = new DefaultHttpClient();
HttpParams params = httpclient.getParams();
HttpConnectionParams.setConnectionTimeout(params, connecte_timeout);
HttpGet httpget = new HttpGet(target);
try {
// GET
HttpResponse response = httpclient.execute(httpget);
int status = response.getStatusLine().getStatusCode();
if (status != 200) {
httpget.abort();
throw new IOException("HTTP Response is not 200 but " + status);
}
HttpEntity entity = response.getEntity();
String[] content_type = entity.getContentType().getValue().split("\\s*;\\s*");
if (!"multipart/x-mixed-replace".equals(content_type[0])) {
httpget.abort();
throw new IOException("Content-type is not multipart/x-mixed-replace but " + content_type[0]);
}
if (!content_type[1].startsWith("boundary=")) {
httpget.abort();
throw new IOException("Content-type should have boundary option");
}
// boundary
String boundary_str = "--"+content_type[1].replaceFirst("boundary=", "");
ByteArrayOutputStream b = new ByteArrayOutputStream();
b.write((byte) 0x0d);
b.write((byte) 0x0a);
b.write(boundary_str.getBytes());
b.write((byte) 0x0d);
b.write((byte) 0x0a);
byte[] boundary = b.toByteArray();
streamReadLoop = new StreamReaderThread(entity.getContent(), boundary, recv_callback, state_callback);
streamReadLoop.start();
} catch(ClientProtocolException e) {
httpget.abort();
throw e;
} catch(IOException e) {
httpget.abort();
throw e;
}
}
public synchronized void stop() throws InterruptedException {
if (!isActive())
return;
streamReadLoop.requestStop();
streamReadLoop.join();
streamReadLoop = null;
}
/**
* HTTP body MJPEGJPEG Thread
*/
private class StreamReaderThread extends Thread {
private StreamSplitter splitter = null;
private InputStream inputStream = null;
private RecvFrameCallback recv_callback = null;
private StateChangeCallback state_callback = null;
private volatile boolean threadLoop = true;
/**
*
* @param is InputStream
* @param boundary
* @param recv_callback callback null
* @param state_callback callback
*/
public StreamReaderThread(InputStream is, byte[] boundary, RecvFrameCallback recv_callback, StateChangeCallback state_callback) {
if (is == null)
throw new IllegalArgumentException("is should not be null");
if (boundary == null)
throw new IllegalArgumentException("boundary should not be null");
this.inputStream = is;
this.splitter = new StreamSplitter(is, boundary);
this.recv_callback = recv_callback;
this.state_callback = state_callback;
}
public void requestStop() {
threadLoop = true;
if (this.getState() == Thread.State.BLOCKED ||
this.getState() == Thread.State.WAITING ||
this.getState() == Thread.State.TIMED_WAITING) {
streamReadLoop.interrupt();
}
}
@Override
public void run() {
logger.info("Start recv thread");
try {
byte[] deleimter_of_header = new byte[]{(byte) 0x0d, (byte) 0x0a, (byte) 0x0d, (byte) 0x0a};
byte[] readbuf = new byte[4*1024];
while (threadLoop) {
int len = 0;
logger.trace("Wait next stream");
InputStream is = splitter.nextStream();
if (is == null) {
logger.info("Stream ended");
if (state_callback != null) {
state_callback.onStreamClosed();
}
break;
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
logger.trace("Wait recving");
while (true) {
len = is.read(readbuf);
if (len == -1)
break;
bos.write(readbuf, 0, len);
}
byte[] recv_block = bos.toByteArray();
logger.debug("Recv {} byte", recv_block.length);
// TODO multipart
// body JPEG
byte[] jpeg_frame = new byte[]{};
for (int i = 0; i < recv_block.length; i++) {
for (int j = 0; j < deleimter_of_header.length && i + j < recv_block.length; j++) {
if (recv_block[i + j] != deleimter_of_header[j])
break;
if (j == deleimter_of_header.length - 1) { // found delimiter
int limit = recv_block.length;
jpeg_frame = Arrays.copyOfRange(recv_block, i + deleimter_of_header.length, limit);
}
}
}
// XXX JPEG
logger.debug("Frame size {} byte", jpeg_frame.length);
if (recv_callback != null)
recv_callback.onRecvFrame(jpeg_frame);
}
} catch (IOException e) {
logger.error("IOException when stream reading", e);
} finally {
try {
inputStream.close();
} catch (IOException e) {
logger.error("IOException when stream closing", e);
}
}
logger.info("Stop recv thread");
if (state_callback != null) {
state_callback.onFinished();
}
}
}
}
|
package com.haskforce.parsing;
import com.haskforce.parsing.jsonParser.JsonParser;
import com.haskforce.parsing.srcExtsDatatypes.*;
import com.intellij.lang.ASTNode;
import com.intellij.lang.PsiBuilder;
import com.intellij.lang.PsiParser;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.psi.tree.IElementType;
import org.jetbrains.annotations.NotNull;
import static com.haskforce.parsing.HaskellTypes2.*;
// These can be imported as * when the old parser is removed.
import static com.haskforce.psi.HaskellTypes.OPENPRAGMA;
import static com.haskforce.psi.HaskellTypes.CLOSEPRAGMA;
import static com.haskforce.psi.HaskellTypes.OPENCOM;
import static com.haskforce.psi.HaskellTypes.CLOSECOM;
import static com.haskforce.psi.HaskellTypes.CPPIF;
import static com.haskforce.psi.HaskellTypes.CPPELSE;
import static com.haskforce.psi.HaskellTypes.CPPENDIF;
import static com.haskforce.psi.HaskellTypes.COMMENT;
import static com.haskforce.psi.HaskellTypes.COMMENTTEXT;
import static com.haskforce.psi.HaskellTypes.DOUBLEQUOTE;
import static com.haskforce.psi.HaskellTypes.STRINGTOKEN;
import static com.haskforce.psi.HaskellTypes.BADSTRINGTOKEN;
import static com.haskforce.psi.HaskellTypes.MODULE;
import static com.haskforce.psi.HaskellTypes.WHERE;
import static com.haskforce.psi.HaskellTypes.PRAGMA;
import static com.haskforce.psi.HaskellTypes.EQUALS;
import static com.haskforce.psi.HaskellTypes.IMPORT;
import static com.haskforce.psi.HaskellTypes.QUALIFIED;
import static com.haskforce.psi.HaskellTypes.HIDING;
import static com.haskforce.psi.HaskellTypes.PERIOD;
import static com.haskforce.psi.HaskellTypes.DOUBLEPERIOD;
import static com.haskforce.psi.HaskellTypes.RPAREN;
import static com.haskforce.psi.HaskellTypes.LPAREN;
import static com.haskforce.psi.HaskellTypes.RBRACKET;
import static com.haskforce.psi.HaskellTypes.LBRACKET;
import static com.haskforce.psi.HaskellTypes.AS;
import static com.haskforce.psi.HaskellTypes.TYPE;
import static com.haskforce.psi.HaskellTypes.DATA;
import static com.haskforce.psi.HaskellTypes.IN;
import static com.haskforce.psi.HaskellTypes.DOUBLECOLON;
import static com.haskforce.psi.HaskellTypes.COLON;
import static com.haskforce.psi.HaskellTypes.COMMA;
import static com.haskforce.psi.HaskellTypes.RIGHTARROW;
import static com.haskforce.psi.HaskellTypes.LEFTARROW;
import static com.haskforce.psi.HaskellTypes.MINUS;
import static com.haskforce.psi.HaskellTypes.DO;
import static com.haskforce.psi.HaskellTypes.BACKSLASH;
import static com.haskforce.psi.HaskellTypes.HASH;
import static com.haskforce.psi.HaskellTypes.FOREIGN;
import static com.haskforce.psi.HaskellTypes.EXPORTTOKEN;
import static com.haskforce.psi.HaskellTypes.DOUBLEARROW;
import static com.haskforce.psi.HaskellTypes.BACKTICK;
import static com.haskforce.psi.HaskellTypes.INSTANCE;
import static com.haskforce.psi.HaskellTypes.LBRACE;
import static com.haskforce.psi.HaskellTypes.RBRACE;
import static com.haskforce.psi.HaskellTypes.EXLAMATION; // FIXME: Rename.
import static com.haskforce.psi.HaskellTypes.PIPE;
import static com.haskforce.psi.HaskellTypes.CHARTOKEN;
import static com.haskforce.psi.HaskellTypes.LET;
import static com.haskforce.psi.HaskellTypes.INTEGERTOKEN;
import static com.haskforce.psi.HaskellTypes.VARIDREGEXP;
import static com.haskforce.psi.HaskellTypes.ASTERISK;
import static com.haskforce.psi.HaskellTypes.SINGLEQUOTE;
import static com.haskforce.psi.HaskellTypes.DEFAULT;
import static com.haskforce.psi.HaskellTypes.AMPERSAT;
import static com.haskforce.psi.HaskellTypes.PLUS;
import static com.haskforce.psi.HaskellTypes.TILDE;
import static com.haskforce.psi.HaskellTypes.THEN;
import static com.haskforce.psi.HaskellTypes.CASE;
import static com.haskforce.psi.HaskellTypes.OF;
import static com.haskforce.psi.HaskellTypes.SEMICOLON;
import static com.haskforce.psi.HaskellTypes.DERIVING;
import static com.haskforce.psi.HaskellTypes.FLOATTOKEN;
import static com.haskforce.psi.HaskellTypes.IF;
import static com.haskforce.psi.HaskellTypes.ELSE;
import static com.haskforce.psi.HaskellTypes.QUESTION;
import static com.haskforce.psi.HaskellTypes.PERCENT;
import static com.haskforce.psi.HaskellTypes.CLASSTOKEN;
/**
* New Parser using parser-helper.
*/
public class HaskellParser2 implements PsiParser {
private static final Logger LOG = Logger.getInstance(HaskellParser2.class);
private final Project myProject;
private final JsonParser myJsonParser;
public HaskellParser2(@NotNull Project project) {
myProject = project;
myJsonParser = new JsonParser(project);
}
@NotNull
@Override
public ASTNode parse(IElementType root, PsiBuilder builder) {
PsiBuilder.Marker rootMarker = builder.mark();
TopPair tp = myJsonParser.parse(builder.getOriginalText());
if (tp.error != null && !tp.error.isEmpty()) {
// TODO: Parse failed. Possibly warn. Could be annoying.
}
IElementType e = builder.getTokenType();
while (!builder.eof() && (isInterruption(e) && e != OPENPRAGMA)) {
if (e == COMMENT || e == OPENCOM) {
parseComment(e, builder, tp.comments);
e = builder.getTokenType();
} else if (e == CPPIF || e == CPPELSE || e == CPPENDIF) {
// Ignore CPP-tokens, they are not fed to parser-helper anyways.
builder.advanceLexer();
e = builder.getTokenType();
} else {
throw new RuntimeException("Unexpected failure on:" + e.toString());
}
}
parseModule(builder, (Module) tp.moduleType, tp.comments);
return chewEverything(rootMarker, root, builder);
}
private static ASTNode chewEverything(PsiBuilder.Marker marker, IElementType e, PsiBuilder builder) {
while (!builder.eof()) {
builder.advanceLexer();
}
marker.done(e);
ASTNode result = builder.getTreeBuilt();
// System.out.println("Psifile:" + builder.getTreeBuilt().getPsi().getContainingFile().getName());
return result;
}
/**
* Parses a complete module.
*/
private static void parseModule(PsiBuilder builder, Module module, Comment[] comments) {
parseModulePragmas(builder, module == null ? null : module.modulePragmas, comments);
parseModuleHead(builder, module == null ? null : module.moduleHeadMaybe, comments);
parseImportDecls(builder, module == null ? null : module.importDecls, comments);
parseBody(builder, module == null ? null : module.decls, comments);
}
/**
* Parses "module NAME [modulepragmas] [exportSpecList] where".
*/
private static void parseModuleHead(PsiBuilder builder, ModuleHead head, Comment[] comments) {
IElementType e = builder.getTokenType();
if (e != MODULE) return;
PsiBuilder.Marker moduleMark = builder.mark();
consumeToken(builder, MODULE);
parseModuleName(builder, head == null ? null : head.moduleName, comments);
// TODO: parseExportSpecList(builder, head.exportSpecList, comments);
IElementType e2 = builder.getTokenType();
while (e2 != WHERE) {
if (e2 == OPENPRAGMA) {
parseGenericPragma(builder, null, comments);
} else {
builder.advanceLexer();
}
e2 = builder.getTokenType();
}
consumeToken(builder, WHERE);
moduleMark.done(e);
}
private static void parseModuleName(PsiBuilder builder, ModuleName name, Comment[] comments) {
builder.getTokenType(); // Need to getTokenType to advance lexer over whitespace.
int startPos = builder.getCurrentOffset();
IElementType e = builder.getTokenType();
while ((name != null &&
(builder.getCurrentOffset() - startPos) < name.name.length()) ||
name == null && e != WHERE) {
builder.remapCurrentToken(NAME);
consumeToken(builder, NAME);
e = builder.getTokenType();
if (e == PERIOD) builder.advanceLexer();
}
}
/**
* Parses a list of import statements.
*/
private static void parseImportDecls(PsiBuilder builder, ImportDecl[] importDecls, Comment[] comments) {
IElementType e = builder.getTokenType();
int i = 0;
while (isInterruption(e) ||
importDecls != null && i < importDecls.length) {
if (e == CPPIF || e == CPPELSE || e == CPPENDIF) {
builder.advanceLexer();
e = builder.getTokenType();
continue;
} else if (e == OPENCOM) {
parseComment(e, builder, comments);
e = builder.getTokenType();
continue;
} else if (e == OPENPRAGMA) {
parseGenericPragma(builder, null, comments);
e = builder.getTokenType();
continue;
}
if (e != IMPORT) return;
parseImportDecl(builder, importDecls[i], comments);
i++;
e = builder.getTokenType();
}
}
/**
* Returns true for elements that can occur anywhere in the tree,
* for example comments or pragmas.
*/
private static boolean isInterruption(IElementType e) {
return (e == CPPIF || e == CPPELSE || e == CPPENDIF || e == OPENCOM ||
e == OPENPRAGMA);
}
/**
* Parses an import statement.
*/
private static void parseImportDecl(PsiBuilder builder, ImportDecl importDecl, Comment[] comments) {
IElementType e = builder.getTokenType();
PsiBuilder.Marker importMark = builder.mark();
consumeToken(builder, IMPORT);
IElementType e2 = builder.getTokenType();
if (e2 == QUALIFIED || (importDecl != null && importDecl.importQualified)) {
consumeToken(builder, QUALIFIED);
}
parseModuleName(builder, importDecl == null ? null : importDecl.importModule, comments);
e2 = builder.getTokenType();
if (e2 == AS || false) { // TODO: Update.
consumeToken(builder, AS);
e2 = builder.getTokenType();
parseModuleName(builder, importDecl == null ? null : importDecl.importAs, comments);
e2 = builder.getTokenType();
}
if (e2 == HIDING || false) { // (importDecl != null && importDecl.importSpecs)) { TODO: FIXME
consumeToken(builder, HIDING);
e2 = builder.getTokenType();
}
int nest = e2 == LPAREN ? 1 : 0;
while (nest > 0) {
builder.advanceLexer();
e2 = builder.getTokenType();
if (e2 == LPAREN) {
nest++;
} else if (e2 == RPAREN) {
nest
}
}
if (e2 == RPAREN) consumeToken(builder, RPAREN);
importMark.done(e);
}
/**
* Parses a foreign import statement.
*/
private static void parseForeignImportDecl(PsiBuilder builder, ForImp importDecl, Comment[] comments) {
IElementType e = builder.getTokenType();
consumeToken(builder, FOREIGN);
consumeToken(builder, IMPORT);
IElementType e2 = builder.getTokenType();
builder.advanceLexer(); // TODO: Parse 'ccall' etc.
e2 = builder.getTokenType();
if (e2 != DOUBLEQUOTE) { // TODO: Parse safety.
builder.advanceLexer();
e2 = builder.getTokenType();
}
if (e2 == DOUBLEQUOTE || false) {
parseStringLiteral(builder);
}
e2 = builder.getTokenType();
parseName(builder, importDecl.name, comments);
e2 = builder.getTokenType();
consumeToken(builder, DOUBLECOLON);
parseTypeTopType(builder, importDecl.type, comments);
}
/**
* Parses a foreign export statement.
*/
private static void parseForeignExportDecl(PsiBuilder builder, ForExp forExp, Comment[] comments) {
IElementType e = builder.getTokenType();
consumeToken(builder, FOREIGN);
e = builder.getTokenType();
consumeToken(builder, EXPORTTOKEN);
IElementType e2 = builder.getTokenType();
builder.advanceLexer(); // TODO: Parse 'ccall' etc.
e2 = builder.getTokenType();
if (e2 == DOUBLEQUOTE || false) {
parseStringLiteral(builder);
}
e2 = builder.getTokenType();
parseName(builder, forExp.name, comments);
e2 = builder.getTokenType();
consumeToken(builder, DOUBLECOLON);
parseTypeTopType(builder, forExp.type, comments);
}
private static void parseBody(PsiBuilder builder, DeclTopType[] decls, Comment[] comments) {
IElementType e = builder.getTokenType();
int i = 0;
while (isInterruption(e) ||
decls != null && i < decls.length) {
if (e == CPPIF || e == CPPELSE || e == CPPENDIF) {
builder.advanceLexer();
e = builder.getTokenType();
continue;
} else if (e == OPENCOM) {
parseComment(e, builder, comments);
e = builder.getTokenType();
continue;
} else if (e == OPENPRAGMA) {
parseGenericPragma(builder, null, comments);
e = builder.getTokenType();
continue;
}
parseDecl(builder, decls[i], comments);
e = builder.getTokenType();
i++;
}
}
/**
* Parse a list of declarations.
*/
private static void parseDecls(PsiBuilder builder, DeclTopType[] decl, Comment[] comments) {
IElementType e = builder.getTokenType();
int i = 0;
while (decl != null && i < decl.length) {
parseDecl(builder, decl[i], comments);
i++;
e = builder.getTokenType();
}
}
/**
* Parse a single declaration.
*/
private static void parseDecl(PsiBuilder builder, DeclTopType decl, Comment[] comments) {
IElementType e = builder.getTokenType();
// Pragmas are handled by the outer loop in parseBody, so they are no-ops.
if (decl instanceof PatBind) {
PsiBuilder.Marker declMark = builder.mark();
parsePatBind(builder, (PatBind) decl, comments);
declMark.done(e);
} else if (decl instanceof FunBind) {
PsiBuilder.Marker declMark = builder.mark();
parseFunBind(builder, (FunBind) decl, comments);
declMark.done(e);
} else if (decl instanceof DataDecl) {
PsiBuilder.Marker declMark = builder.mark();
parseDataDecl(builder, (DataDecl) decl, comments);
declMark.done(e);
} else if (decl instanceof GDataDecl) {
PsiBuilder.Marker declMark = builder.mark();
parseGDataDecl(builder, (GDataDecl) decl, comments);
declMark.done(e);
} else if (decl instanceof TypeDecl) {
PsiBuilder.Marker declMark = builder.mark();
parseTypeDecl(builder, (TypeDecl) decl, comments);
declMark.done(e);
} else if (decl instanceof DataInsDecl) {
PsiBuilder.Marker declMark = builder.mark();
parseDataInstanceDecl(builder, (DataInsDecl) decl, comments);
declMark.done(e);
} else if (decl instanceof GDataInsDecl) {
PsiBuilder.Marker declMark = builder.mark();
parseGDataInstanceDecl(builder, (GDataInsDecl) decl, comments);
declMark.done(e);
} else if (decl instanceof ClassDecl) {
PsiBuilder.Marker declMark = builder.mark();
parseClassDecl(builder, (ClassDecl) decl, comments);
declMark.done(e);
} else if (decl instanceof InstDecl) {
PsiBuilder.Marker declMark = builder.mark();
parseInstDecl(builder, (InstDecl) decl, comments);
declMark.done(e);
} else if (decl instanceof DerivDecl) {
PsiBuilder.Marker declMark = builder.mark();
parseDerivDecl(builder, (DerivDecl) decl, comments);
declMark.done(e);
} else if (decl instanceof InfixDecl) {
PsiBuilder.Marker declMark = builder.mark();
parseInfixDecl(builder, (InfixDecl) decl, comments);
declMark.done(e);
} else if (decl instanceof DefaultDecl) {
PsiBuilder.Marker declMark = builder.mark();
parseDefaultDecl(builder, (DefaultDecl) decl, comments);
declMark.done(e);
} else if (decl instanceof SpliceDecl) {
PsiBuilder.Marker declMark = builder.mark();
parseExpTopType(builder, ((SpliceDecl) decl).exp, comments);
declMark.done(e);
} else if (decl instanceof TypeSig) {
PsiBuilder.Marker declMark = builder.mark();
parseTypeSig(builder, (TypeSig) decl, comments);
declMark.done(e);
} else if (decl instanceof ForImp) {
PsiBuilder.Marker declMark = builder.mark();
parseForeignImportDecl(builder, (ForImp) decl, comments);
declMark.done(e);
} else if (decl instanceof ForExp) {
PsiBuilder.Marker declMark = builder.mark();
parseForeignExportDecl(builder, (ForExp) decl, comments);
declMark.done(e);
} else if (decl instanceof InlineSig) {
// parseGenericPragma(builder, (InlineSig) decl, comments);
} else if (decl instanceof InlineConlikeSig) {
// parseGenericPragma(builder, (InlineConlikeSig) decl, comments);
} else if (decl instanceof SpecSig) {
// parseGenericPragma(builder, (SpecSig) decl, comments);
} else if (decl instanceof SpecInlineSig) {
// parseGenericPragma(builder, (SpecSig) decl, comments);
} else if (decl instanceof RulePragmaDecl) {
// parseGenericPragma(builder, (SpecSig) decl, comments);
} else if (decl instanceof DeprPragmaDecl) {
// parseGenericPragma(builder, (DeprPragmaDecl) decl, comments);
} else if (decl instanceof WarnPragmaDecl) {
// parseGenericPragma(builder, (WarnPragmaDecl) decl, comments);
} else if (decl instanceof InstSig) {
PsiBuilder.Marker declMark = builder.mark();
parseInstSig(builder, (InstSig) decl, comments);
declMark.done(e);
} else if (decl instanceof AnnPragma) {
// parseGenericPragma(builder, (AnnPragma) decl, comments);
} else {
throw new RuntimeException("Unexpected decl type: " + decl.toString());
}
}
/**
* Parse a pattern binding.
*/
private static void parsePatBind(PsiBuilder builder, PatBind patBind, Comment[] comments) {
IElementType e = builder.getTokenType();
parsePatTopType(builder, patBind.pat, comments);
if (patBind.type != null) throw new RuntimeException("Unexpected type in patbind");
// TODO: parseType(builder, patBind.type, comments);
parseRhsTopType(builder, patBind.rhs, comments);
if (patBind.binds != null) throw new RuntimeException("Unexpected binds in patbind");
}
/**
* Parse a function binding.
*/
private static void parseFunBind(PsiBuilder builder, FunBind funBind, Comment[] comments) {
IElementType e = builder.getTokenType();
int i = 0;
while (funBind.match != null && i < funBind.match.length) {
parseMatchTop(builder, funBind.match[i], comments);
i++;
}
}
/**
* Parse a derive declaration.
*/
private static void parseDerivDecl(PsiBuilder builder, DerivDecl derivDecl, Comment[] comments) {
IElementType e = builder.getTokenType();
consumeToken(builder, DERIVING);
e = builder.getTokenType();
consumeToken(builder, INSTANCE);
parseContextTopType(builder, derivDecl.contextMaybe, comments);
e = builder.getTokenType();
parseInstHead(builder, derivDecl.instHead, comments);
e = builder.getTokenType();
}
/**
* Parses an instance specialization.
*/
private static void parseInstSig(PsiBuilder builder, InstSig instSig, Comment[] comments) {
IElementType e = builder.getTokenType();
parseGenericPragma(builder, null, null);
e = builder.getTokenType();
// TODO: Improve precision of specialize instance pragma parsing.
// parseContextTopType(builder, instSig.contextMaybe, comments);
// e = builder.getTokenType();
// parseInstHead(builder, instSig.instHead, comments);
// e = builder.getTokenType();
}
/**
* Parse a list of class declarations.
*/
private static void parseClassDeclTopTypes(PsiBuilder builder, ClassDeclTopType[] classDecls, Comment[] comments) {
IElementType e = builder.getTokenType();
int i = 0;
while (classDecls != null && i < classDecls.length) {
parseClassDeclTopType(builder, classDecls[i], comments);
i++;
}
}
/**
* Parse a class declaration.
*/
private static void parseClassDeclTopType(PsiBuilder builder, ClassDeclTopType classDecl, Comment[] comments) {
IElementType e = builder.getTokenType();
if (classDecl instanceof ClsDecl) {
parseDecl(builder, ((ClsDecl) classDecl).decl, comments);
e = builder.getTokenType();
} else if (classDecl instanceof ClsDataFam) {
throw new RuntimeException("TODO: ClsDataFam");
} else if (classDecl instanceof ClsTyFam) {
throw new RuntimeException("TODO: ClsTyFam");
} else if (classDecl instanceof ClsTyDef) {
throw new RuntimeException("TODO: ClsTyDef");
}
}
/**
* Parse a class declaration.
*/
private static void parseClassDecl(PsiBuilder builder, ClassDecl classDecl, Comment[] comments) {
IElementType e = builder.getTokenType();
consumeToken(builder, CLASSTOKEN);
e = builder.getTokenType();
parseContextTopType(builder, classDecl.contextMaybe, comments);
e = builder.getTokenType();
if (classDecl.contextMaybe != null) consumeToken(builder, DOUBLEARROW);
parseDeclHead(builder, classDecl.declHead, comments);
e = builder.getTokenType();
if (classDecl.funDeps != null && classDecl.funDeps.length > 0) throw new RuntimeException("Fundeps unimplemented:" + classDecl.funDeps);
if (e == WHERE) {
consumeToken(builder, WHERE);
e = builder.getTokenType();
}
parseClassDeclTopTypes(builder, classDecl.classDecls, comments);
e = builder.getTokenType();
}
/**
* Parse a instance declaration.
*/
private static void parseInstDecl(PsiBuilder builder, InstDecl instDecl, Comment[] comments) {
IElementType e = builder.getTokenType();
consumeToken(builder, INSTANCE);
e = builder.getTokenType();
parseContextTopType(builder, instDecl.contextMaybe, comments);
e = builder.getTokenType();
if (instDecl.contextMaybe != null) consumeToken(builder, DOUBLEARROW);
parseInstHead(builder, instDecl.instHead, comments);
e = builder.getTokenType();
consumeToken(builder, WHERE);
parseInstDeclTopTypes(builder, instDecl.instDecls, comments);
e = builder.getTokenType();
}
/**
* Parse a list of instance declarations.
*/
private static void parseInstDeclTopTypes(PsiBuilder builder, InstDeclTopType[] instDecls, Comment[] comments) {
IElementType e = builder.getTokenType();
int i = 0;
while (instDecls != null && i < instDecls.length) {
parseInstDeclTopType(builder, instDecls[i], comments);
i++;
}
}
/**
* Parses a single instance declaration.
*/
private static void parseInstDeclTopType(PsiBuilder builder, InstDeclTopType decl, Comment[] comments) {
IElementType e = builder.getTokenType();
if (decl instanceof InsDecl) {
parseDecl(builder, ((InsDecl) decl).decl, comments);
e = builder.getTokenType();
} else if (decl instanceof InsType) {
throw new RuntimeException("InsType not implemented: " + decl.toString());
/* Preliminary implementation:
parseTypeTopType(builder, ((InsType) decl).t1, comments);
e = builder.getTokenType();
parseTypeTopType(builder, ((InsType) decl).t2, comments);
e = builder.getTokenType();
*/
} else if (decl instanceof InsData) {
throw new RuntimeException("InsData not implemented:" + decl.toString());
} else if (decl instanceof InsGData) {
throw new RuntimeException("InsGData not implemented:" + decl.toString());
}
}
/**
* Parses a data declaration.
*/
private static void parseDataDecl(PsiBuilder builder, DataDecl dataDecl, Comment[] comments) {
IElementType e = builder.getTokenType();
consumeToken(builder, DATA);
parseDeclHead(builder, dataDecl.declHead, comments);
e = builder.getTokenType();
if (e == EQUALS) consumeToken(builder, EQUALS);
int i = 0;
e = builder.getTokenType();
while (dataDecl.qualConDecls != null && i < dataDecl.qualConDecls.length) {
parseQualConDecl(builder, dataDecl.qualConDecls[i], comments);
i++;
if (i < dataDecl.qualConDecls.length) {
builder.advanceLexer();
e = builder.getTokenType();
}
}
}
/**
* Parses a gadt-style data declaration.
*/
private static void parseGDataDecl(PsiBuilder builder, GDataDecl gDataDecl, Comment[] comments) {
IElementType e = builder.getTokenType();
consumeToken(builder, DATA);
parseDeclHead(builder, gDataDecl.declHead, comments);
e = builder.getTokenType();
if (e == DOUBLECOLON) {
consumeToken(builder, DOUBLECOLON);
e = builder.getTokenType();
parseKindTopType(builder, gDataDecl.kindMaybe, comments);
e = builder.getTokenType();
}
if (e == WHERE) consumeToken(builder, WHERE);
int i = 0;
e = builder.getTokenType();
while (gDataDecl.gadtDecls != null && i < gDataDecl.gadtDecls.length) {
parseGadtDecl(builder, gDataDecl.gadtDecls[i], comments);
i++;
if (i < gDataDecl.gadtDecls.length) {
builder.advanceLexer();
e = builder.getTokenType();
}
}
}
/**
* Parses a data instance declaration.
*/
private static void parseDataInstanceDecl(PsiBuilder builder, DataInsDecl dataDecl, Comment[] comments) {
IElementType e = builder.getTokenType();
consumeToken(builder, DATA);
e = builder.getTokenType();
consumeToken(builder, INSTANCE);
e = builder.getTokenType();
parseTypeTopType(builder, dataDecl.type, comments);
e = builder.getTokenType();
if (e == EQUALS) consumeToken(builder, EQUALS);
int i = 0;
e = builder.getTokenType();
while (dataDecl.qualConDecls != null && i < dataDecl.qualConDecls.length) {
parseQualConDecl(builder, dataDecl.qualConDecls[i], comments);
i++;
if (i < dataDecl.qualConDecls.length) {
builder.advanceLexer();
e = builder.getTokenType();
}
}
e = builder.getTokenType();
if (dataDecl.derivingMaybe != null) throw new RuntimeException("TODO: deriving unimplemeted");
}
/**
* Parses a gadt-style data instance declaration.
*/
private static void parseGDataInstanceDecl(PsiBuilder builder, GDataInsDecl gDataInsDecl, Comment[] comments) {
IElementType e = builder.getTokenType();
consumeToken(builder, DATA);
e = builder.getTokenType();
consumeToken(builder, INSTANCE);
e = builder.getTokenType();
parseTypeTopType(builder, gDataInsDecl.type, comments);
e = builder.getTokenType();
parseKindTopType(builder, gDataInsDecl.kindMaybe, comments);
e = builder.getTokenType();
if (e == WHERE) consumeToken(builder, WHERE);
int i = 0;
e = builder.getTokenType();
while (gDataInsDecl.gadtDecls != null && i < gDataInsDecl.gadtDecls.length) {
parseGadtDecl(builder, gDataInsDecl.gadtDecls[i], comments);
i++;
if (i < gDataInsDecl.gadtDecls.length) {
builder.advanceLexer();
e = builder.getTokenType();
}
}
e = builder.getTokenType();
if (gDataInsDecl.derivingMaybe != null) throw new RuntimeException("TODO: deriving unimplemeted");
}
/**
* Parse a single gadt-style declaration.
*/
private static void parseGadtDecl(PsiBuilder builder, GadtDecl gadtDecl, Comment[] comments) {
IElementType e = builder.getTokenType();
parseName(builder, gadtDecl.name, comments);
e = builder.getTokenType();
consumeToken(builder, DOUBLECOLON);
e = builder.getTokenType();
parseTypeTopType(builder, gadtDecl.type, comments);
e = builder.getTokenType();
}
/**
* Parses the left side of '=' in a data/type declaration.
*/
private static void parseDeclHead(PsiBuilder builder, DeclHeadTopType declHead, Comment[] comments) {
IElementType e = builder.getTokenType();
if (declHead instanceof DHead) {
parseName(builder, ((DHead) declHead).name, comments);
e = builder.getTokenType();
parseTyVarBinds(builder, ((DHead) declHead).tyVars, comments);
} else if (declHead instanceof DHInfix) {
parseTyVarBind(builder, ((DHInfix) declHead).tb1, comments);
e = builder.getTokenType();
parseName(builder, ((DHInfix) declHead).name, comments);
e = builder.getTokenType();
parseTyVarBind(builder, ((DHInfix) declHead).tb2, comments);
e = builder.getTokenType();
} else if (declHead instanceof DHParen) {
consumeToken(builder, LPAREN);
e = builder.getTokenType();
parseDeclHead(builder, ((DHParen) declHead).declHead, comments);
e = builder.getTokenType();
consumeToken(builder, RPAREN);
e = builder.getTokenType();
}
}
/**
* Parses the left side of '=>' in an instance declaration.
*/
private static void parseInstHead(PsiBuilder builder, InstHeadTopType instHead, Comment[] comments) {
IElementType e = builder.getTokenType();
if (instHead instanceof IHead) {
parseQName(builder, ((IHead) instHead).qName, comments);
e = builder.getTokenType();
parseTypeTopTypes(builder, ((IHead) instHead).types, comments);
e = builder.getTokenType();
} else if (instHead instanceof IHInfix) {
parseTypeTopType(builder, ((IHInfix) instHead).t1, comments);
e = builder.getTokenType();
parseQName(builder, ((IHInfix) instHead).qName, comments);
e = builder.getTokenType();
parseTypeTopType(builder, ((IHInfix) instHead).t2, comments);
e = builder.getTokenType();
} else if (instHead instanceof IHParen) {
consumeToken(builder, LPAREN);
e = builder.getTokenType();
parseInstHead(builder, ((IHParen) instHead).instHead, comments);
consumeToken(builder, RPAREN);
e = builder.getTokenType();
}
}
/**
* Parses the type variables in a data declaration.
*/
private static void parseTyVarBinds(PsiBuilder builder, TyVarBindTopType[] tyVarBindTopType, Comment[] comments) {
IElementType e = builder.getTokenType();
int i = 0;
while (tyVarBindTopType != null && i < tyVarBindTopType.length) {
parseTyVarBind(builder, tyVarBindTopType[i], comments);
i++;
}
e = builder.getTokenType();
}
/**
* Parses the type variables in a data declaration.
*/
private static void parseTyVarBind(PsiBuilder builder, TyVarBindTopType tyVarBindTopType, Comment[] comments) {
IElementType e = builder.getTokenType();
if (tyVarBindTopType instanceof KindedVar) {
consumeToken(builder, LPAREN);
e = builder.getTokenType();
parseName(builder, ((KindedVar) tyVarBindTopType).name, comments);
e = builder.getTokenType();
consumeToken(builder, DOUBLECOLON);
e = builder.getTokenType();
parseKindTopType(builder, ((KindedVar) tyVarBindTopType).kind, comments);
consumeToken(builder, RPAREN);
} else if (tyVarBindTopType instanceof UnkindedVar) {
parseName(builder, ((UnkindedVar) tyVarBindTopType).name, comments);
}
e = builder.getTokenType();
}
/**
* Parses a type declaration.
*/
private static void parseTypeDecl(PsiBuilder builder, TypeDecl typeDecl, Comment[] comments) {
IElementType e = builder.getTokenType();
consumeToken(builder, TYPE);
parseDeclHead(builder, typeDecl.declHead, comments);
e = builder.getTokenType();
if (e == EQUALS) consumeToken(builder, EQUALS);
parseTypeTopType(builder, typeDecl.type, comments);
e = builder.getTokenType();
}
/**
* Parses a type signature.
*/
private static void parseTypeSig(PsiBuilder builder, TypeSig dataDecl, Comment[] comments) {
IElementType e = builder.getTokenType();
parseNames(builder, dataDecl.names, comments);
e = builder.getTokenType();
consumeToken(builder, DOUBLECOLON);
e = builder.getTokenType();
parseTypeTopType(builder, dataDecl.type, comments);
}
/**
* Parses a qualified constructor declaration.
*/
private static void parseQualConDecl(PsiBuilder builder, QualConDecl qualConDecl, Comment[] comments) {
IElementType e = builder.getTokenType();
parseConDecl(builder, qualConDecl == null ? null : qualConDecl.conDecl, comments);
}
/**
* Parses a constructor declaration.
*/
private static void parseConDecl(PsiBuilder builder, ConDeclTopType conDecl, Comment[] comments) {
if (conDecl instanceof ConDecl) {
parseName(builder, ((ConDecl) conDecl).name, comments);
IElementType e = builder.getTokenType();
parseBangTypes(builder, conDecl == null ? null : ((ConDecl) conDecl).bangTypes, comments);
} else if (conDecl instanceof InfixConDecl) {
IElementType e = builder.getTokenType();
parseBangType(builder, ((InfixConDecl) conDecl).b1, comments);
e = builder.getTokenType();
parseName(builder, ((InfixConDecl) conDecl).name, comments);
parseBangType(builder, ((InfixConDecl) conDecl).b2, comments);
} else if (conDecl instanceof RecDecl) {
parseName(builder, ((RecDecl) conDecl).name, comments);
boolean layouted = false;
IElementType e = builder.getTokenType();
if (e == LBRACE) {
consumeToken(builder, LBRACE);
e = builder.getTokenType();
layouted = true;
}
parseFieldDecls(builder, ((RecDecl) conDecl).fields, comments);
e = builder.getTokenType();
if (layouted) {
consumeToken(builder, RBRACE);
e = builder.getTokenType();
}
}
}
/**
* Parses the field declarations in a GADT-style declaration.
*/
private static void parseFieldDecls(PsiBuilder builder, FieldDecl[] fieldDecls, Comment[] comments) {
IElementType e = builder.getTokenType();
int i = 0;
while (fieldDecls != null && i < fieldDecls.length) {
parseFieldDecl(builder, fieldDecls[i], comments);
i++;
}
e = builder.getTokenType();
}
/**
* Parses a field declaration.
*/
private static void parseFieldDecl(PsiBuilder builder, FieldDecl fieldDecl, Comment[] comments) {
IElementType e = builder.getTokenType();
parseNames(builder, fieldDecl.names, comments);
e = builder.getTokenType();
consumeToken(builder, DOUBLECOLON);
e = builder.getTokenType();
parseBangType(builder, fieldDecl.bang, comments);
e = builder.getTokenType();
}
/**
* Parses a list of bang types.
*/
private static void parseBangTypes(PsiBuilder builder, BangTypeTopType[] bangTypes, Comment[] comments) {
int i = 0;
while (bangTypes != null && i < bangTypes.length) {
parseBangType(builder, bangTypes[i], comments);
i++;
}
}
/**
* Parses one bang type.
*/
private static void parseBangType(PsiBuilder builder, BangTypeTopType bangType, Comment[] comments) {
IElementType e = builder.getTokenType();
// TODO: Refine bangType.
if (bangType instanceof UnBangedTy) {
parseTypeTopType(builder, ((UnBangedTy) bangType).type, comments);
} else if (bangType instanceof BangedTy) {
consumeToken(builder, EXLAMATION);
parseTypeTopType(builder, ((BangedTy) bangType).type, comments);
e = builder.getTokenType();
} else if (bangType instanceof UnpackedTy) {
parseGenericPragma(builder, null, comments);
consumeToken(builder, EXLAMATION);
e = builder.getTokenType();
parseTypeTopType(builder, ((UnpackedTy) bangType).type, comments);
e = builder.getTokenType();
}
}
private static void parseMatchTop(PsiBuilder builder, MatchTopType matchTopType, Comment[] comments) {
IElementType e = builder.getTokenType();
if (matchTopType instanceof Match) {
parseMatch(builder, (Match) matchTopType, comments);
} else if (matchTopType instanceof InfixMatch) {
parseInfixMatch(builder, (InfixMatch) matchTopType, comments);
}
}
/**
* Parses a single match.
*/
private static void parseMatch(PsiBuilder builder, Match match, Comment[] comments) {
IElementType e = builder.getTokenType();
parseName(builder, match.name, comments);
int i = 0;
while (match.pats != null && i < match.pats.length) {
parsePatTopType(builder, match.pats[i], comments);
i++;
}
parseRhsTopType(builder, match.rhs, comments);
e = builder.getTokenType();
if (e == WHERE) {
consumeToken(builder, WHERE);
parseBindsTopType(builder, match.bindsMaybe, comments);
e = builder.getTokenType();
}
}
/**
* Parses a single infix declaration.
*/
private static void parseInfixDecl(PsiBuilder builder, InfixDecl decl, Comment[] comments) {
IElementType e = builder.getTokenType();
builder.advanceLexer(); // TOOD: Parse infix/infixl/infixr
e = builder.getTokenType();
if (e == INTEGERTOKEN) consumeToken(builder, INTEGERTOKEN);
e = builder.getTokenType();
int i = 0;
while (decl.ops != null && i < decl.ops.length) {
parseOp(builder, decl.ops[i], comments);
i++;
e = builder.getTokenType();
if (e == COMMA) {
consumeToken(builder, COMMA);
e = builder.getTokenType();
}
}
}
/**
* Parses a single default declaration.
*/
private static void parseDefaultDecl(PsiBuilder builder, DefaultDecl decl, Comment[] comments) {
IElementType e = builder.getTokenType();
consumeToken(builder, DEFAULT);
e = builder.getTokenType();
consumeToken(builder, LPAREN);
e = builder.getTokenType();
parseTypeTopTypes(builder, decl.types, comments);
e = builder.getTokenType();
consumeToken(builder, RPAREN);
}
/**
* Parses a single infix match.
*/
private static void parseInfixMatch(PsiBuilder builder, InfixMatch match, Comment[] comments) {
IElementType e = builder.getTokenType();
boolean startParen = e == LPAREN && !(match.pat instanceof PParen);
if (startParen) consumeToken(builder, LPAREN);
e = builder.getTokenType();
parsePatTopType(builder, match.pat, comments);
e = builder.getTokenType();
parseName(builder, match.name, comments);
int i = 0;
while (match.pats != null && i < match.pats.length) {
parsePatTopType(builder, match.pats[i], comments);
if (startParen && i == 0) {
consumeToken(builder, RPAREN);
e = builder.getTokenType();
}
i++;
}
parseRhsTopType(builder, match.rhs, comments);
e = builder.getTokenType();
if (e == WHERE) {
consumeToken(builder, WHERE);
parseBindsTopType(builder, match.bindsMaybe, comments);
e = builder.getTokenType();
}
}
/**
* Parses one binding.
*/
private static void parseBindsTopType(PsiBuilder builder, BindsTopType bindsTopType, Comment[] comments) {
IElementType e = builder.getTokenType();
if (bindsTopType instanceof BDecls) {
parseDecls(builder, ((BDecls) bindsTopType).decls, comments);
} else if (bindsTopType instanceof IPBinds) {
throw new RuntimeException("TODO: Implement IPBinds:" + bindsTopType.toString());
}
}
/**
* Parses several patterns.
*/
private static void parsePatTopTypes(PsiBuilder builder, PatTopType[] pats, Comment[] comments) {
IElementType e = builder.getTokenType();
int i = 0;
while(pats != null && i < pats.length) {
parsePatTopType(builder, pats[i], comments);
i++;
e = builder.getTokenType();
if (e == COMMA) {
consumeToken(builder, COMMA);
e = builder.getTokenType();
}
}
}
/**
* Parses one pattern.
*/
private static void parsePatTopType(PsiBuilder builder, PatTopType patTopType, Comment[] comments) {
IElementType e = builder.getTokenType();
if (patTopType instanceof PVar) {
parsePVar(builder, (PVar) patTopType, comments);
} else if (patTopType instanceof PLit) {
parseLiteralTop(builder, ((PLit) patTopType).lit, comments);
e = builder.getTokenType();
} else if (patTopType instanceof PNeg) {
e = builder.getTokenType();
consumeToken(builder, MINUS);
e = builder.getTokenType();
parsePatTopType(builder, ((PNeg) patTopType).pat, comments);
e = builder.getTokenType();
} else if (patTopType instanceof PNPlusK) {
e = builder.getTokenType();
parseName(builder, ((PNPlusK) patTopType).name, comments);
e = builder.getTokenType();
consumeToken(builder, PLUS);
e = builder.getTokenType();
consumeToken(builder, INTEGERTOKEN);
e = builder.getTokenType();
} else if (patTopType instanceof PApp) {
e = builder.getTokenType();
parseQName(builder, ((PApp) patTopType).qName, comments);
e = builder.getTokenType();
parsePatTopTypes(builder, ((PApp) patTopType).pats, comments);
e = builder.getTokenType();
} else if (patTopType instanceof PInfixApp) {
e = builder.getTokenType();
parsePatTopType(builder, ((PInfixApp) patTopType).p1, comments);
e = builder.getTokenType();
parseQName(builder, ((PInfixApp) patTopType).qName, comments);
e = builder.getTokenType();
parsePatTopType(builder, ((PInfixApp) patTopType).p1, comments);
e = builder.getTokenType();
} else if (patTopType instanceof PTuple) {
consumeToken(builder, LPAREN);
e = builder.getTokenType();
boolean unboxed = parseBoxed(builder, ((PTuple) patTopType).boxed, comments);
parsePatTopTypes(builder, ((PTuple) patTopType).pats, comments);
e = builder.getTokenType();
if (unboxed) {
consumeToken(builder, HASH);
e = builder.getTokenType();
}
consumeToken(builder, RPAREN);
e = builder.getTokenType();
} else if (patTopType instanceof PList) {
consumeToken(builder, LBRACKET);
parsePatTopTypes(builder, ((PList) patTopType).pats, comments);
e = builder.getTokenType();
consumeToken(builder, RBRACKET);
e = builder.getTokenType();
} else if (patTopType instanceof PParen) {
consumeToken(builder, LPAREN);
e = builder.getTokenType();
parsePatTopType(builder, ((PParen) patTopType).pat, comments);
consumeToken(builder, RPAREN);
e = builder.getTokenType();
} else if (patTopType instanceof PRec) {
parseQName(builder, ((PRec) patTopType).qName, comments);
e = builder.getTokenType();
consumeToken(builder, LBRACE);
parsePatFieldTopTypes(builder, ((PRec) patTopType).patFields, comments);
e = builder.getTokenType();
consumeToken(builder, RBRACE);
e = builder.getTokenType();
} else if (patTopType instanceof PAsPat) {
parseName(builder, ((PAsPat) patTopType).name, comments);
e = builder.getTokenType();
consumeToken(builder, AMPERSAT);
parsePatTopType(builder, ((PAsPat) patTopType).pat, comments);
e = builder.getTokenType();
} else if (patTopType instanceof PWildCard) {
builder.advanceLexer(); // TODO: Token.UNDERSCORE?
e = builder.getTokenType();
} else if (patTopType instanceof PIrrPat) {
consumeToken(builder, TILDE);
e = builder.getTokenType();
parsePatTopType(builder, ((PIrrPat) patTopType).pat, comments);
e = builder.getTokenType();
} else if (patTopType instanceof PatTypeSig) {
parsePatTopType(builder, ((PatTypeSig) patTopType).pat, comments);
e = builder.getTokenType();
consumeToken(builder, DOUBLECOLON);
parseTypeTopType(builder, ((PatTypeSig) patTopType).type, comments);
e = builder.getTokenType();
} else if (patTopType instanceof PViewPat) {
parseExpTopType(builder, ((PViewPat) patTopType).exp, comments);
e = builder.getTokenType();
consumeToken(builder, RIGHTARROW);
parsePatTopType(builder, ((PViewPat) patTopType).pat, comments);
e = builder.getTokenType();
} else if (patTopType instanceof PBangPat) {
consumeToken(builder, EXLAMATION);
e = builder.getTokenType();
parsePatTopType(builder, ((PBangPat) patTopType).pat, comments);
e = builder.getTokenType();
} else {
throw new RuntimeException("parsePatTopType" + patTopType.toString());
}
}
private static void parseComment(IElementType start, PsiBuilder builder, Comment[] comments) {
PsiBuilder.Marker startCom = builder.mark();
IElementType e = builder.getTokenType();
while (e == COMMENT || e == COMMENTTEXT ||
e == OPENCOM || e == CLOSECOM) {
builder.advanceLexer();
e = builder.getTokenType();
}
startCom.done(start);
}
/**
* Parses a group of module pragmas.
*/
private static void parseModulePragmas(PsiBuilder builder, ModulePragmaTopType[] modulePragmas, Comment[] comments) {
int i = 0;
while(modulePragmas != null && i < modulePragmas.length) {
parseModulePragma(builder, modulePragmas[i], comments);
i++;
}
}
/**
* Parses a module pragma.
*/
private static void parseModulePragma(PsiBuilder builder, ModulePragmaTopType modulePragmaTopType, Comment[] comments) {
int i = 0;
if (modulePragmaTopType instanceof LanguagePragma) {
LanguagePragma langPragma = (LanguagePragma) modulePragmaTopType;
IElementType e = builder.getTokenType();
PsiBuilder.Marker pragmaMark = builder.mark();
consumeToken(builder, OPENPRAGMA);
consumeToken(builder, PRAGMA);
while (langPragma.names != null && i < langPragma.names.length) {
// TODO: Improve precision of pragma lexing.
// parseName(builder, langPragma.names[i], comments);
i++;
}
consumeToken(builder, CLOSEPRAGMA);
pragmaMark.done(e);
} else if (modulePragmaTopType instanceof OptionsPragma) {
// FIXME: Use optionsPragma information.
OptionsPragma optionsPragma = (OptionsPragma) modulePragmaTopType;
IElementType e = builder.getTokenType();
PsiBuilder.Marker pragmaMark = builder.mark();
chewPragma(builder);
consumeToken(builder, CLOSEPRAGMA);
pragmaMark.done(e);
} else if (modulePragmaTopType instanceof AnnModulePragma) {
// FIXME: Use annModulePragma information.
AnnModulePragma annModulePragma = (AnnModulePragma) modulePragmaTopType;
IElementType e = builder.getTokenType();
PsiBuilder.Marker pragmaMark = builder.mark();
chewPragma(builder);
consumeToken(builder, CLOSEPRAGMA);
pragmaMark.done(e);
}
}
/**
* Parses a pattern variable.
*/
private static void parsePVar(PsiBuilder builder, PVar pVar, Comment[] comments) {
parseName(builder, pVar.name, comments);
}
/**
* Parses a group of GuardedRhss.
*/
private static void parseGuardedRhss(PsiBuilder builder, GuardedRhs[] rhss, Comment[] comments) {
IElementType e = builder.getTokenType();
int i = 0;
while(rhss != null && i < rhss.length) {
parseGuardedRhs(builder, rhss[i], comments);
i++;
e = builder.getTokenType();
}
}
/**
* Parses one GuardedRhs.
*/
private static void parseGuardedRhs(PsiBuilder builder, GuardedRhs rhs, Comment[] comments) {
IElementType e = builder.getTokenType();
consumeToken(builder, PIPE);
e = builder.getTokenType();
parseStmtTopTypes(builder, rhs.stmts, comments);
e = builder.getTokenType();
consumeToken(builder, EQUALS);
parseExpTopType(builder, rhs.exp, comments);
e = builder.getTokenType();
}
/**
* Parses one Rhs.
*/
private static void parseRhsTopType(PsiBuilder builder, RhsTopType rhsTopType, Comment[] comments) {
IElementType e = builder.getTokenType();
if (rhsTopType instanceof UnGuardedRhs) {
consumeToken(builder, EQUALS);
parseExpTopType(builder, ((UnGuardedRhs) rhsTopType).exp, comments);
} else if (rhsTopType instanceof GuardedRhss) {
e = builder.getTokenType();
parseGuardedRhss(builder, ((GuardedRhss) rhsTopType).rhsses, comments);
}
}
/**
* Parses an unqualified op.
*/
private static void parseOp(PsiBuilder builder, OpTopType opTopType, Comment[] comments) {
IElementType e = builder.getTokenType();
boolean backticked = e == BACKTICK;
if (backticked) {
consumeToken(builder, BACKTICK);
e = builder.getTokenType();
}
if (opTopType instanceof VarOp) {
parseName(builder, ((VarOp) opTopType).name, comments);
} else if (opTopType instanceof ConOp) {
parseName(builder, ((ConOp) opTopType).name, comments);
}
if (backticked) consumeToken(builder, BACKTICK);
e = builder.getTokenType();
}
/**
* Parses a qualified op.
*/
private static void parseQOp(PsiBuilder builder, QOpTopType qOpTopType, Comment[] comments) {
IElementType e = builder.getTokenType();
boolean backticked = e == BACKTICK;
if (backticked) {
consumeToken(builder, BACKTICK);
e = builder.getTokenType();
}
if (qOpTopType instanceof QVarOp) {
parseQName(builder, ((QVarOp) qOpTopType).qName, comments);
} else if (qOpTopType instanceof QConOp) {
parseQName(builder, ((QConOp) qOpTopType).qName, comments);
}
if (backticked) consumeToken(builder, BACKTICK);
e = builder.getTokenType();
}
/**
* Parses a qualified name.
*/
private static void parseQName(PsiBuilder builder, QNameTopType qNameTopType, Comment[] comments) {
if (qNameTopType instanceof Qual) {
Qual name = (Qual) qNameTopType;
parseModuleName(builder, name.moduleName, comments);
parseName(builder, name.name, comments);
} else if (qNameTopType instanceof UnQual) {
parseName(builder, ((UnQual) qNameTopType).name, comments);
} else if (qNameTopType instanceof Special) {
parseSpecialConTopType(builder, ((Special) qNameTopType).specialCon, comments);
}
}
/**
* Parses a special constructor.
*/
private static void parseSpecialConTopType(PsiBuilder builder, SpecialConTopType specialConTopType, Comment[] comments) {
IElementType e = builder.getTokenType();
if (specialConTopType instanceof UnitCon) {
consumeToken(builder, LPAREN);
e = builder.getTokenType();
consumeToken(builder, RPAREN);
e = builder.getTokenType();
} else if (specialConTopType instanceof ListCon) {
consumeToken(builder, LBRACKET);
e = builder.getTokenType();
consumeToken(builder, RBRACKET);
e = builder.getTokenType();
} else if (specialConTopType instanceof FunCon) {
consumeToken(builder, LPAREN);
e = builder.getTokenType();
consumeToken(builder, RIGHTARROW);
e = builder.getTokenType();
consumeToken(builder, RPAREN);
e = builder.getTokenType();
} else if (specialConTopType instanceof TupleCon) {
consumeToken(builder, LPAREN);
e = builder.getTokenType();
boolean unboxed = parseBoxed(builder, ((TupleCon) specialConTopType).boxed, comments);
e = builder.getTokenType();
int i = 1;
while (i < ((TupleCon) specialConTopType).i) {
consumeToken(builder, COMMA);
e = builder.getTokenType();
i++;
}
e = builder.getTokenType();
if (unboxed) {
consumeToken(builder, HASH);
e = builder.getTokenType();
}
consumeToken(builder, RPAREN);
e = builder.getTokenType();
} else if (specialConTopType instanceof Cons) {
consumeToken(builder, COLON);
e = builder.getTokenType();
} else if (specialConTopType instanceof UnboxedSingleCon) {
consumeToken(builder, LPAREN);
e = builder.getTokenType();
consumeToken(builder, HASH);
e = builder.getTokenType();
consumeToken(builder, HASH);
e = builder.getTokenType();
consumeToken(builder, RPAREN);
}
}
/**
* Parses a list of names.
*/
private static void parseNames(PsiBuilder builder, NameTopType[] names, Comment[] comments) {
IElementType e = builder.getTokenType();
int i = 0;
while (names != null && i < names.length) {
parseName(builder, names[i], comments);
i++;
e = builder.getTokenType();
if (e == COMMA) consumeToken(builder, COMMA);
}
}
/**
* Parses a name.
*/
private static void parseName(PsiBuilder builder, NameTopType nameTopType, Comment[] comments) {
IElementType e = builder.getTokenType();
if (nameTopType instanceof Ident) {
int startPos = builder.getCurrentOffset();
while ((builder.getCurrentOffset() - startPos) <
((Ident) nameTopType).name.length()) {
builder.remapCurrentToken(NAME);
consumeToken(builder, NAME);
e = builder.getTokenType();
}
} else if (nameTopType instanceof Symbol) {
boolean startParen = e == LPAREN;
if (startParen) consumeToken(builder, LPAREN);
e = builder.getTokenType();
int startPos = builder.getCurrentOffset();
while ((builder.getCurrentOffset() - startPos) <
((Symbol) nameTopType).symbol.length()) {
builder.remapCurrentToken(SYMBOL);
consumeToken(builder, SYMBOL);
e = builder.getTokenType();
}
e = builder.getTokenType();
if (startParen) {
consumeToken(builder, RPAREN);
e = builder.getTokenType();
}
}
}
/**
* Parses a literal
*/
private static void parseLiteralTop(PsiBuilder builder, LiteralTopType literalTopType, Comment[] comments) {
IElementType e = builder.getTokenType();
if (literalTopType instanceof CharLit) {
consumeToken(builder, CHARTOKEN);
e = builder.getTokenType();
} else if (literalTopType instanceof StringLit) {
parseStringLiteral(builder);
} else if (literalTopType instanceof IntLit) {
consumeToken(builder, INTEGERTOKEN);
e = builder.getTokenType();
} else if (literalTopType instanceof FracLit) {
consumeToken(builder, FLOATTOKEN);
e = builder.getTokenType();
} else if (literalTopType instanceof PrimInt) {
consumeToken(builder, INTEGERTOKEN);
e = builder.getTokenType();
consumeToken(builder, HASH);
e = builder.getTokenType();
} else if (literalTopType instanceof PrimWord) {
consumeToken(builder, INTEGERTOKEN);
e = builder.getTokenType();
consumeToken(builder, HASH);
e = builder.getTokenType();
consumeToken(builder, HASH);
e = builder.getTokenType();
} else if (literalTopType instanceof PrimFloat) {
consumeToken(builder, FLOATTOKEN);
e = builder.getTokenType();
consumeToken(builder, HASH);
e = builder.getTokenType();
} else if (literalTopType instanceof PrimDouble) {
consumeToken(builder, FLOATTOKEN);
e = builder.getTokenType();
consumeToken(builder, HASH);
e = builder.getTokenType();
consumeToken(builder, HASH);
e = builder.getTokenType();
} else if (literalTopType instanceof PrimChar) {
consumeToken(builder, CHARTOKEN);
e = builder.getTokenType();
consumeToken(builder, HASH);
e = builder.getTokenType();
} else if (literalTopType instanceof PrimString) {
parseStringLiteral(builder);
e = builder.getTokenType();
consumeToken(builder, HASH);
e = builder.getTokenType();
} else {
throw new RuntimeException("LiteralTop: " + literalTopType.toString());
}
}
/**
* Parse a string literal.
*/
private static void parseStringLiteral(PsiBuilder builder) {
IElementType e = builder.getTokenType();
PsiBuilder.Marker marker = builder.mark();
consumeToken(builder, DOUBLEQUOTE);
IElementType e2 = builder.getTokenType();
while (e2 != DOUBLEQUOTE) {
if (e2 == BADSTRINGTOKEN) {
builder.error("Bad stringtoken");
builder.advanceLexer();
} else {
consumeToken(builder, STRINGTOKEN);
}
e2 = builder.getTokenType();
}
consumeToken(builder, DOUBLEQUOTE);
marker.done(e);
}
/**
* Parses a list of statements.
*/
private static void parseStmtTopTypes(PsiBuilder builder, StmtTopType[] stmtTopTypes, Comment[] comments) {
IElementType e = builder.getTokenType();
int i = 0;
while (stmtTopTypes != null && i < stmtTopTypes.length) {
parseStmtTopType(builder, stmtTopTypes[i], comments);
i++;
}
}
/**
* Parses a statement.
*/
private static void parseStmtTopType(PsiBuilder builder, StmtTopType stmtTopType, Comment[] comments) {
IElementType e = builder.getTokenType();
PsiBuilder.Marker stmtMark = builder.mark();
if (stmtTopType instanceof Generator) {
parsePatTopType(builder, ((Generator) stmtTopType).pat, comments);
consumeToken(builder, LEFTARROW);
parseExpTopType(builder, ((Generator) stmtTopType).exp, comments);
} else if (stmtTopType instanceof Qualifier) {
parseExpTopType(builder, ((Qualifier) stmtTopType).exp, comments);
} else if (stmtTopType instanceof LetStmt) {
consumeToken(builder, LET);
parseBindsTopType(builder, ((LetStmt) stmtTopType).binds, comments);
} else if (stmtTopType instanceof RecStmt) {
builder.advanceLexer();
IElementType e1 = builder.getTokenType();
parseStmtTopTypes(builder, ((RecStmt) stmtTopType).stmts, comments);
e1 = builder.getTokenType();
}
stmtMark.done(e);
}
/**
* Parses a list of expressions.
*/
private static void parseExpTopTypes(PsiBuilder builder, ExpTopType[] expTopType, Comment[] comments) {
IElementType e = builder.getTokenType();
int i = 0;
while (expTopType != null && i < expTopType.length) {
parseExpTopType(builder, expTopType[i], comments);
i++;
e = builder.getTokenType();
if (e == COMMA) consumeToken(builder, COMMA);
}
}
/**
* Parses an expression.
*/
private static void parseExpTopType(PsiBuilder builder, ExpTopType expTopType, Comment[] comments) {
IElementType e1 = builder.getTokenType();
if (expTopType instanceof App) {
parseExpTopType(builder, ((App) expTopType).e1, comments);
parseExpTopType(builder, ((App) expTopType).e2, comments);
} else if (expTopType instanceof Var) {
parseQName(builder, ((Var) expTopType).qName, comments);
} else if (expTopType instanceof IPVar) {
parseIPNameTopType(builder, ((IPVar) expTopType).ipName, comments);
} else if (expTopType instanceof Con) {
parseQName(builder, ((Con) expTopType).qName, comments);
} else if (expTopType instanceof Lit) {
parseLiteralTop(builder, ((Lit) expTopType).literal, comments);
} else if (expTopType instanceof InfixApp) {
parseExpTopType(builder, ((InfixApp) expTopType).e1, comments);
IElementType e = builder.getTokenType();
parseQOp(builder, ((InfixApp) expTopType).qop, comments);
e = builder.getTokenType();
parseExpTopType(builder, ((InfixApp) expTopType).e2, comments);
e = builder.getTokenType();
} else if (expTopType instanceof List) {
builder.advanceLexer();
parseExpTopTypes(builder, ((List) expTopType).exps, comments);
IElementType e = builder.getTokenType();
builder.advanceLexer();
} else if (expTopType instanceof NegApp) {
consumeToken(builder, MINUS);
parseExpTopType(builder, ((NegApp) expTopType).e1, comments);
} else if (expTopType instanceof Case) {
IElementType e = builder.getTokenType();
consumeToken(builder, CASE);
e = builder.getTokenType();
parseExpTopType(builder, ((Case) expTopType).scrutinee, comments);
e = builder.getTokenType();
consumeToken(builder, OF);
e = builder.getTokenType();
parseAlts(builder, ((Case) expTopType).alts, comments);
e = builder.getTokenType();
} else if (expTopType instanceof Do) {
IElementType e = builder.getTokenType();
PsiBuilder.Marker doMark = builder.mark();
consumeToken(builder, DO);
parseStmtTopTypes(builder, ((Do) expTopType).stmts, comments);
doMark.done(e);
} else if (expTopType instanceof MDo) {
IElementType e = builder.getTokenType();
PsiBuilder.Marker doMark = builder.mark();
builder.advanceLexer(); // TODO: Token.MDO
parseStmtTopTypes(builder, ((MDo) expTopType).stmts, comments);
doMark.done(e);
} else if (expTopType instanceof Lambda) {
consumeToken(builder, BACKSLASH);
IElementType e = builder.getTokenType();
parsePatTopTypes(builder, ((Lambda) expTopType).pats, comments);
e = builder.getTokenType();
consumeToken(builder, RIGHTARROW);
parseExpTopType(builder, ((Lambda) expTopType).exp, comments);
e = builder.getTokenType();
} else if (expTopType instanceof Tuple) {
consumeToken(builder, LPAREN);
IElementType e = builder.getTokenType();
boolean unboxed = parseBoxed(builder, ((Tuple) expTopType).boxed, comments);
e = builder.getTokenType();
parseExpTopTypes(builder, ((Tuple) expTopType).exps, comments);
e = builder.getTokenType();
if (unboxed) {
consumeToken(builder, HASH);
e = builder.getTokenType();
}
consumeToken(builder, RPAREN);
e1 = builder.getTokenType();
} else if (expTopType instanceof TupleSection) {
TupleSection ts = (TupleSection) expTopType;
consumeToken(builder, LPAREN);
IElementType e = builder.getTokenType();
boolean unboxed = parseBoxed(builder, ((TupleSection) expTopType).boxed, comments);
e = builder.getTokenType();
int i = 0;
while (ts.expMaybes != null && i < ts.expMaybes.length) {
if (ts.expMaybes[i] != null) parseExpTopType(builder, ts.expMaybes[i], comments);
i++;
e = builder.getTokenType();
if (e == COMMA) consumeToken(builder, COMMA);
}
e = builder.getTokenType();
if (unboxed) {
consumeToken(builder, HASH);
e = builder.getTokenType();
}
consumeToken(builder, RPAREN);
e1 = builder.getTokenType();
} else if (expTopType instanceof Paren) {
consumeToken(builder, LPAREN);
e1 = builder.getTokenType();
parseExpTopType(builder, ((Paren) expTopType).exp, comments);
e1 = builder.getTokenType();
consumeToken(builder, RPAREN);
e1 = builder.getTokenType();
} else if (expTopType instanceof LeftSection) {
e1 = builder.getTokenType();
consumeToken(builder, LPAREN);
e1 = builder.getTokenType();
parseExpTopType(builder, ((LeftSection) expTopType).exp, comments);
e1 = builder.getTokenType();
parseQOp(builder, ((LeftSection) expTopType).qop, comments);
e1 = builder.getTokenType();
consumeToken(builder, RPAREN);
e1 = builder.getTokenType();
} else if (expTopType instanceof RightSection) {
e1 = builder.getTokenType();
consumeToken(builder, LPAREN);
parseQOp(builder, ((RightSection) expTopType).qop, comments);
parseExpTopType(builder, ((RightSection) expTopType).exp, comments);
e1 = builder.getTokenType();
consumeToken(builder, RPAREN);
e1 = builder.getTokenType();
} else if (expTopType instanceof RecConstr) {
e1 = builder.getTokenType();
parseQName(builder, ((RecConstr) expTopType).qName, comments);
e1 = builder.getTokenType();
consumeToken(builder, LBRACE);
parseFieldUpdateTopTypes(builder, ((RecConstr) expTopType).fieldUpdates, comments);
e1 = builder.getTokenType();
consumeToken(builder, RBRACE);
e1 = builder.getTokenType();
} else if (expTopType instanceof RecUpdate) {
e1 = builder.getTokenType();
parseExpTopType(builder, ((RecUpdate) expTopType).exp, comments);
e1 = builder.getTokenType();
consumeToken(builder, LBRACE);
parseFieldUpdateTopTypes(builder, ((RecUpdate) expTopType).fieldUpdates, comments);
e1 = builder.getTokenType();
consumeToken(builder, RBRACE);
e1 = builder.getTokenType();
} else if (expTopType instanceof EnumFrom) {
consumeToken(builder, LBRACKET);
e1 = builder.getTokenType();
parseExpTopType(builder, ((EnumFrom) expTopType).exp, comments);
e1 = builder.getTokenType();
consumeToken(builder, DOUBLEPERIOD);
e1 = builder.getTokenType();
consumeToken(builder, RBRACKET);
e1 = builder.getTokenType();
} else if (expTopType instanceof EnumFromTo) {
consumeToken(builder, LBRACKET);
e1 = builder.getTokenType();
parseExpTopType(builder, ((EnumFromTo) expTopType).from, comments);
e1 = builder.getTokenType();
consumeToken(builder, DOUBLEPERIOD);
e1 = builder.getTokenType();
parseExpTopType(builder, ((EnumFromTo) expTopType).to, comments);
consumeToken(builder, RBRACKET);
e1 = builder.getTokenType();
} else if (expTopType instanceof EnumFromThen) {
consumeToken(builder, LBRACKET);
e1 = builder.getTokenType();
parseExpTopType(builder, ((EnumFromThen) expTopType).from, comments);
e1 = builder.getTokenType();
consumeToken(builder, COMMA);
e1 = builder.getTokenType();
parseExpTopType(builder, ((EnumFromThen) expTopType).step, comments);
consumeToken(builder, DOUBLEPERIOD);
e1 = builder.getTokenType();
consumeToken(builder, RBRACKET);
e1 = builder.getTokenType();
} else if (expTopType instanceof EnumFromThenTo) {
consumeToken(builder, LBRACKET);
e1 = builder.getTokenType();
parseExpTopType(builder, ((EnumFromThenTo) expTopType).from, comments);
e1 = builder.getTokenType();
consumeToken(builder, COMMA);
e1 = builder.getTokenType();
parseExpTopType(builder, ((EnumFromThenTo) expTopType).step, comments);
consumeToken(builder, DOUBLEPERIOD);
e1 = builder.getTokenType();
parseExpTopType(builder, ((EnumFromThenTo) expTopType).to, comments);
e1 = builder.getTokenType();
consumeToken(builder, RBRACKET);
e1 = builder.getTokenType();
} else if (expTopType instanceof ListComp) {
consumeToken(builder, LBRACKET);
e1 = builder.getTokenType();
parseExpTopType(builder, ((ListComp) expTopType).exp, comments);
e1 = builder.getTokenType();
consumeToken(builder, PIPE);
e1 = builder.getTokenType();
parseQualStmtTopTypes(builder, ((ListComp) expTopType).qualStmts, comments);
e1 = builder.getTokenType();
consumeToken(builder, RBRACKET);
e1 = builder.getTokenType();
} else if (expTopType instanceof ParComp) {
ParComp p = (ParComp) expTopType;
consumeToken(builder, LBRACKET);
e1 = builder.getTokenType();
parseExpTopType(builder, ((ParComp) expTopType).exp, comments);
e1 = builder.getTokenType();
consumeToken(builder, PIPE);
e1 = builder.getTokenType();
int i = 0;
while (p.qualStmts != null && i < p.qualStmts.length) {
parseQualStmtTopTypes(builder, p.qualStmts[i], comments);
i++;
e1 = builder.getTokenType();
if (e1 == PIPE) consumeToken(builder, PIPE);
e1 = builder.getTokenType();
}
consumeToken(builder, RBRACKET);
e1 = builder.getTokenType();
} else if (expTopType instanceof ExpTypeSig) {
IElementType e = builder.getTokenType();
parseExpTopType(builder, ((ExpTypeSig) expTopType).exp, comments);
e = builder.getTokenType();
consumeToken(builder, DOUBLECOLON);
e = builder.getTokenType();
parseTypeTopType(builder, ((ExpTypeSig) expTopType).type, comments);
e = builder.getTokenType();
} else if (expTopType instanceof Let) {
builder.advanceLexer();
IElementType e = builder.getTokenType();
parseBindsTopType(builder, ((Let) expTopType).binds, comments);
e = builder.getTokenType();
consumeToken(builder, IN);
e = builder.getTokenType();
parseExpTopType(builder, ((Let) expTopType).exp, comments);
e = builder.getTokenType();
} else if (expTopType instanceof If) {
consumeToken(builder, IF);
IElementType e = builder.getTokenType();
parseExpTopType(builder, ((If) expTopType).cond, comments);
e = builder.getTokenType();
consumeToken(builder, THEN);
e = builder.getTokenType();
parseExpTopType(builder, ((If) expTopType).t, comments);
e = builder.getTokenType();
consumeToken(builder, ELSE);
e = builder.getTokenType();
parseExpTopType(builder, ((If) expTopType).f, comments);
e = builder.getTokenType();
} else if (expTopType instanceof MultiIf) {
consumeToken(builder, IF);
IElementType e = builder.getTokenType();
parseIfAlts(builder, ((MultiIf) expTopType).alts, comments);
e = builder.getTokenType();
} else if (expTopType instanceof QuasiQuote) {
IElementType e = builder.getTokenType();
consumeToken(builder, LBRACKET);
builder.advanceLexer();
e = builder.getTokenType();
consumeToken(builder, PIPE);
e = builder.getTokenType();
while (e != PIPE) {
builder.advanceLexer();
e = builder.getTokenType();
}
consumeToken(builder, PIPE);
consumeToken(builder, RBRACKET);
e = builder.getTokenType();
} else if (expTopType instanceof CorePragma) {
parseGenericPragma(builder, null, comments);
parseExpTopType(builder, ((CorePragma) expTopType).exp, comments);
} else if (expTopType instanceof SCCPragma) {
parseGenericPragma(builder, null, comments);
parseExpTopType(builder, ((SCCPragma) expTopType).exp, comments);
} else if (expTopType instanceof Proc) {
e1 = builder.getTokenType();
builder.advanceLexer(); // TODO: consumeToken(builder, PROCTOKEN);
e1 = builder.getTokenType();
parsePatTopType(builder, ((Proc) expTopType).pat, comments);
consumeToken(builder, RIGHTARROW);
parseExpTopType(builder, ((Proc) expTopType).exp, comments);
} else if (expTopType instanceof LeftArrApp) {
e1 = builder.getTokenType();
parseExpTopType(builder, ((LeftArrApp) expTopType).e1, comments);
builder.advanceLexer(); // TODO: consumeToken(builder, LeftArrApp);
e1 = builder.getTokenType();
builder.advanceLexer();
e1 = builder.getTokenType();
parseExpTopType(builder, ((LeftArrApp) expTopType).e2, comments);
e1 = builder.getTokenType();
} else if (expTopType instanceof RightArrApp) {
e1 = builder.getTokenType();
parseExpTopType(builder, ((RightArrApp) expTopType).e1, comments);
builder.advanceLexer(); // TODO: consumeToken(builder, RightArrApp);
e1 = builder.getTokenType();
builder.advanceLexer();
e1 = builder.getTokenType();
parseExpTopType(builder, ((RightArrApp) expTopType).e2, comments);
e1 = builder.getTokenType();
} else if (expTopType instanceof LeftArrHighApp) {
e1 = builder.getTokenType();
parseExpTopType(builder, ((LeftArrHighApp) expTopType).e1, comments);
builder.advanceLexer(); // TODO: consumeToken(builder, LeftArrHighApp);
e1 = builder.getTokenType();
builder.advanceLexer();
e1 = builder.getTokenType();
builder.advanceLexer();
e1 = builder.getTokenType();
parseExpTopType(builder, ((LeftArrHighApp) expTopType).e2, comments);
e1 = builder.getTokenType();
} else if (expTopType instanceof RightArrHighApp) {
e1 = builder.getTokenType();
parseExpTopType(builder, ((RightArrHighApp) expTopType).e1, comments);
builder.advanceLexer(); // TODO: consumeToken(builder, RightArrHighApp);
e1 = builder.getTokenType();
builder.advanceLexer();
e1 = builder.getTokenType();
builder.advanceLexer();
e1 = builder.getTokenType();
parseExpTopType(builder, ((RightArrHighApp) expTopType).e2, comments);
e1 = builder.getTokenType();
} else if (expTopType instanceof LCase) {
IElementType e = builder.getTokenType();
consumeToken(builder, BACKSLASH);
e = builder.getTokenType();
consumeToken(builder, CASE);
e = builder.getTokenType();
parseAlts(builder, ((LCase) expTopType).alts, comments);
e = builder.getTokenType();
} else {
throw new RuntimeException("parseExpTopType: " + expTopType.toString());
}
}
/**
* Parses a list of field patterns.
*/
private static void parsePatFieldTopTypes(PsiBuilder builder, PatFieldTopType[] fields, Comment[] comments) {
IElementType e = builder.getTokenType();
int i = 0;
while (fields != null && i < fields.length) {
parsePatFieldTopType(builder, fields[i], comments);
i++;
e = builder.getTokenType();
if (e == COMMA) consumeToken(builder, COMMA);
}
}
/**
* Parses a field pattern.
*/
private static void parsePatFieldTopType(PsiBuilder builder, PatFieldTopType field, Comment[] comments) {
IElementType e = builder.getTokenType();
if (field instanceof PFieldPat) {
parseQName(builder, ((PFieldPat) field).qName, comments);
e = builder.getTokenType();
consumeToken(builder, EQUALS);
e = builder.getTokenType();
parsePatTopType(builder, ((PFieldPat) field).pat, comments);
e = builder.getTokenType();
} else if (field instanceof PFieldPun) {
consumeToken(builder, VARIDREGEXP);
e = builder.getTokenType();
} else if (field instanceof PFieldWildcard) {
builder.advanceLexer(); // TODO: Token.UNDERSCORE?
e = builder.getTokenType();
}
}
/**
* Parses a list of field updates.
*/
private static void parseFieldUpdateTopTypes(PsiBuilder builder, FieldUpdateTopType[] fieldUpdateTopTypes, Comment[] comments) {
IElementType e = builder.getTokenType();
int i = 0;
while (fieldUpdateTopTypes != null && i < fieldUpdateTopTypes.length) {
parseFieldUpdateTopType(builder, fieldUpdateTopTypes[i], comments);
i++;
e = builder.getTokenType();
if (e == COMMA) consumeToken(builder, COMMA);
}
}
/**
* Parses a field update.
*/
private static void parseFieldUpdateTopType(PsiBuilder builder, FieldUpdateTopType fieldUpdate, Comment[] comments) {
IElementType e = builder.getTokenType();
if (fieldUpdate instanceof FieldUpdate) {
parseQName(builder, ((FieldUpdate) fieldUpdate).qName, comments);
e = builder.getTokenType();
consumeToken(builder, EQUALS);
e = builder.getTokenType();
parseExpTopType(builder, ((FieldUpdate) fieldUpdate).exp, comments);
e = builder.getTokenType();
} else if (fieldUpdate instanceof FieldPun) {
throw new RuntimeException("TODO: FieldPun not implemented");
} else if (fieldUpdate instanceof FieldWildcard) {
throw new RuntimeException("TODO: FieldWildcard not implemented");
}
}
/**
* Parses a list of alts.
*/
private static void parseAlts(PsiBuilder builder, Alt[] alts, Comment[] comments) {
IElementType e = builder.getTokenType();
int i = 0;
while (alts != null && i < alts.length) {
parseAlt(builder, alts[i], comments);
i++;
e = builder.getTokenType();
if (e == SEMICOLON) consumeToken(builder, SEMICOLON);
}
}
/**
* Parses a single alt.
*/
private static void parseAlt(PsiBuilder builder, Alt alt, Comment[] comments) {
IElementType e = builder.getTokenType();
parsePatTopType(builder, alt.pat, comments);
e = builder.getTokenType();
parseGuardedAltsTopType(builder, alt.guardedAlts, comments);
e = builder.getTokenType();
parseBindsTopType(builder, alt.bindsMaybe, comments);
e = builder.getTokenType();
}
/**
* Parses a list of IfAlts.
*/
private static void parseIfAlts(PsiBuilder builder, IfAlt[] alts, Comment[] comments) {
IElementType e = builder.getTokenType();
int i = 0;
while (alts != null && i < alts.length) {
parseIfAlt(builder, alts[i], comments);
i++;
e = builder.getTokenType();
if (e == PIPE) consumeToken(builder, PIPE);
}
}
/**
* Parses a single IfAlt
*/
private static void parseIfAlt(PsiBuilder builder, IfAlt alt, Comment[] comments) {
IElementType e = builder.getTokenType();
parseExpTopType(builder, alt.e1, comments);
e = builder.getTokenType();
consumeToken(builder, RIGHTARROW);
e = builder.getTokenType();
parseExpTopType(builder, alt.e2, comments);
e = builder.getTokenType();
}
/**
* Parses a single guarded alt.
*/
private static void parseGuardedAltsTopType(PsiBuilder builder, GuardedAltsTopType alt, Comment[] comments) {
IElementType e = builder.getTokenType();
if (alt instanceof UnGuardedAlt) {
consumeToken(builder, RIGHTARROW);
e = builder.getTokenType();
parseExpTopType(builder, ((UnGuardedAlt) alt).exp, comments);
e = builder.getTokenType();
} else if (alt instanceof GuardedAlts) {
parseGuardedAlts(builder, ((GuardedAlts) alt).alts, comments);
e = builder.getTokenType();
}
}
/**
* Parses a list of guarded alts.
*/
private static void parseGuardedAlts(PsiBuilder builder, GuardedAlt[] alts, Comment[] comments) {
IElementType e = builder.getTokenType();
int i = 0;
while (alts != null && i < alts.length) {
parseGuardedAlt(builder, alts[i], comments);
i++;
e = builder.getTokenType();
if (e == SEMICOLON) consumeToken(builder, SEMICOLON);
}
}
/**
* Parses a single guarded alt.
*/
private static void parseGuardedAlt(PsiBuilder builder, GuardedAlt alt, Comment[] comments) {
IElementType e = builder.getTokenType();
consumeToken(builder, PIPE);
e = builder.getTokenType();
parseStmtTopTypes(builder, alt.stmts, comments);
e = builder.getTokenType();
consumeToken(builder, RIGHTARROW);
e = builder.getTokenType();
parseExpTopType(builder, alt.exp, comments);
e = builder.getTokenType();
}
/**
* Parses a list of types.
*/
private static void parseTypeTopTypes(PsiBuilder builder, TypeTopType[] typeTopTypes, Comment[] comments) {
IElementType e = builder.getTokenType();
int i = 0;
while (typeTopTypes != null && i < typeTopTypes.length) {
parseTypeTopType(builder, typeTopTypes[i], comments);
i++;
e = builder.getTokenType();
if (e == COMMA) consumeToken(builder, COMMA);
}
}
/**
* Parses a type.
*/
private static void parseTypeTopType(PsiBuilder builder, TypeTopType typeTopType, Comment[] comments) {
IElementType e = builder.getTokenType();
if (typeTopType instanceof TyForall) { // FIXME: No forall lexeme.
TyForall t = (TyForall) typeTopType;
e = builder.getTokenType();
if (t.tyVarBinds != null) { // Implicit foralls for typeclasses.
builder.advanceLexer();
e = builder.getTokenType();
parseTyVarBinds(builder, t.tyVarBinds, comments);
e = builder.getTokenType();
consumeToken(builder, PERIOD);
}
parseContextTopType(builder, t.context, comments);
e = builder.getTokenType();
if (e == DOUBLEARROW) consumeToken(builder, DOUBLEARROW);
parseTypeTopType(builder, t.type, comments);
e = builder.getTokenType();
} else if (typeTopType instanceof TyFun) {
parseTypeTopType(builder, ((TyFun) typeTopType).t1, comments);
consumeToken(builder, RIGHTARROW);
parseTypeTopType(builder, ((TyFun) typeTopType).t2, comments);
} else if (typeTopType instanceof TyTuple) {
consumeToken(builder, LPAREN);
e = builder.getTokenType();
boolean unboxed = parseBoxed(builder, ((TyTuple) typeTopType).boxed, comments);
e = builder.getTokenType();
parseTypeTopTypes(builder, ((TyTuple) typeTopType).types, comments);
e = builder.getTokenType();
if (unboxed) {
consumeToken(builder, HASH);
e = builder.getTokenType();
}
consumeToken(builder, RPAREN);
e = builder.getTokenType();
} else if (typeTopType instanceof TyList) {
consumeToken(builder, LBRACKET);
e = builder.getTokenType();
parseTypeTopType(builder, ((TyList) typeTopType).t, comments);
e = builder.getTokenType();
consumeToken(builder, RBRACKET);
e = builder.getTokenType();
} else if (typeTopType instanceof TyApp) {
parseTypeTopType(builder, ((TyApp) typeTopType).t1, comments);
e = builder.getTokenType();
parseTypeTopType(builder, ((TyApp) typeTopType).t2, comments);
e = builder.getTokenType();
} else if (typeTopType instanceof TyVar) {
parseName(builder, ((TyVar) typeTopType).name, comments);
e = builder.getTokenType();
} else if (typeTopType instanceof TyCon) {
parseQName(builder, ((TyCon) typeTopType).qName, comments);
} else if (typeTopType instanceof TyParen) {
consumeToken(builder, LPAREN);
e = builder.getTokenType();
parseTypeTopType(builder, ((TyParen) typeTopType).type, comments);
e = builder.getTokenType();
consumeToken(builder, RPAREN);
e = builder.getTokenType();
} else if (typeTopType instanceof TyInfix) {
e = builder.getTokenType();
parseTypeTopType(builder, ((TyInfix) typeTopType).t1, comments);
e = builder.getTokenType();
parseQName(builder, ((TyInfix) typeTopType).qName, comments);
e = builder.getTokenType();
parseTypeTopType(builder, ((TyInfix) typeTopType).t2, comments);
e = builder.getTokenType();
} else if (typeTopType instanceof TyKind) {
e = builder.getTokenType();
consumeToken(builder, LPAREN);
e = builder.getTokenType();
parseTypeTopType(builder, ((TyKind) typeTopType).type, comments);
e = builder.getTokenType();
consumeToken(builder, DOUBLECOLON);
e = builder.getTokenType();
parseKindTopType(builder, ((TyKind) typeTopType).kind, comments);
e = builder.getTokenType();
consumeToken(builder, RPAREN);
e = builder.getTokenType();
} else if (typeTopType instanceof TyPromoted) {
parsePromotedTopType(builder, ((TyPromoted) typeTopType).promoted, comments);
e = builder.getTokenType();
} else {
throw new RuntimeException("parseTypeTopType: " + typeTopType.toString());
}
}
/**
* Parses a list of kinds.
*/
private static void parseKindTopTypes(PsiBuilder builder, KindTopType[] kinds, Comment[] comments) {
IElementType e = builder.getTokenType();
int i = 0;
while (kinds != null && i < kinds.length) {
parseKindTopType(builder, kinds[i], comments);
i++;
e = builder.getTokenType();
if (e == COMMA) consumeToken(builder, COMMA);
}
}
/**
* Parses a kind.
*/
private static void parseKindTopType(PsiBuilder builder, KindTopType kind, Comment[] comments) {
IElementType e = builder.getTokenType();
if (kind instanceof KindStar) {
consumeToken(builder, ASTERISK);
e = builder.getTokenType();
} else if (kind instanceof KindBang) {
consumeToken(builder, EXLAMATION);
e = builder.getTokenType();
} else if (kind instanceof KindFn) {
parseKindTopType(builder, ((KindFn) kind).k1, comments);
consumeToken(builder, RIGHTARROW);
parseKindTopType(builder, ((KindFn) kind).k2, comments);
} else if (kind instanceof KindParen) {
consumeToken(builder, LPAREN);
e = builder.getTokenType();
parseKindTopType(builder, ((KindParen) kind).kind, comments);
e = builder.getTokenType();
consumeToken(builder, RPAREN);
e = builder.getTokenType();
} else if (kind instanceof KindVar) {
parseQName(builder, ((KindVar) kind).qName, comments);
e = builder.getTokenType();
} else if (kind instanceof KindApp) {
parseKindTopType(builder, ((KindApp) kind).k1, comments);
e = builder.getTokenType();
parseKindTopType(builder, ((KindApp) kind).k2, comments);
e = builder.getTokenType();
} else if (kind instanceof KindTuple) {
e = builder.getTokenType();
if (e == SINGLEQUOTE) consumeToken(builder, SINGLEQUOTE);
e = builder.getTokenType();
consumeToken(builder, LPAREN);
e = builder.getTokenType();
parseKindTopTypes(builder, ((KindTuple) kind).kinds, comments);
consumeToken(builder, RPAREN);
e = builder.getTokenType();
} else if (kind instanceof KindList) {
e = builder.getTokenType();
if (e == SINGLEQUOTE) consumeToken(builder, SINGLEQUOTE);
e = builder.getTokenType();
consumeToken(builder, LBRACKET);
e = builder.getTokenType();
parseKindTopTypes(builder, ((KindList) kind).kinds, comments);
consumeToken(builder, RBRACKET);
e = builder.getTokenType();
}
}
/**
* Parses a list of promoted types.
*/
private static void parsePromotedTopTypes(PsiBuilder builder,PromotedTopType[] promotedTopTypes, Comment[] comments) {
IElementType e = builder.getTokenType();
int i = 0;
while (promotedTopTypes != null && i < promotedTopTypes.length) {
parsePromotedTopType(builder, promotedTopTypes[i], comments);
i++;
e = builder.getTokenType();
if (e == COMMA) consumeToken(builder, COMMA);
}
}
/**
* Parses one promoted type.
*/
private static void parsePromotedTopType(PsiBuilder builder, PromotedTopType promotedTopType, Comment[] comments) {
IElementType e = builder.getTokenType();
if (promotedTopType instanceof PromotedInteger) {
consumeToken(builder, INTEGERTOKEN);
e = builder.getTokenType();
} else if (promotedTopType instanceof PromotedString) {
parseStringLiteral(builder);
e = builder.getTokenType();
} else if (promotedTopType instanceof PromotedCon) {
parseQName(builder, ((PromotedCon) promotedTopType).qName, comments);
e = builder.getTokenType();
} else if (promotedTopType instanceof PromotedList) {
if (((PromotedList) promotedTopType).leadingQuote) consumeToken(builder, SINGLEQUOTE);
e = builder.getTokenType();
consumeToken(builder, LBRACKET);
parsePromotedTopTypes(builder, ((PromotedList) promotedTopType).promoteds, comments);
consumeToken(builder, RBRACKET);
e = builder.getTokenType();
} else if (promotedTopType instanceof PromotedTuple) {
e = builder.getTokenType();
if (e == SINGLEQUOTE) {
consumeToken(builder, SINGLEQUOTE);
e = builder.getTokenType();
}
consumeToken(builder, LPAREN);
parsePromotedTopTypes(builder, ((PromotedTuple) promotedTopType).promoteds, comments);
consumeToken(builder, RPAREN);
e = builder.getTokenType();
} else if (promotedTopType instanceof PromotedUnit) {
consumeToken(builder, SINGLEQUOTE);
e = builder.getTokenType();
consumeToken(builder, LPAREN);
e = builder.getTokenType();
consumeToken(builder, RPAREN);
e = builder.getTokenType();
}
}
/**
* Parses a list of qualified statements.
*/
private static void parseQualStmtTopTypes(PsiBuilder builder, QualStmtTopType[] qualStmtTopTypes, Comment[] comments) {
IElementType e = builder.getTokenType();
int i = 0;
while (qualStmtTopTypes != null && i < qualStmtTopTypes.length) {
parseQualStmtTopType(builder, qualStmtTopTypes[i], comments);
i++;
e = builder.getTokenType();
if (e == COMMA) consumeToken(builder, COMMA);
}
}
/**
* Parses one qualified statement.
*/
private static void parseQualStmtTopType(PsiBuilder builder, QualStmtTopType qualStmtTopType, Comment[] comments) {
IElementType e = builder.getTokenType();
if (qualStmtTopType instanceof QualStmt) {
parseStmtTopType(builder, ((QualStmt) qualStmtTopType).stmt, comments);
} else if (qualStmtTopType instanceof ThenTrans) {
consumeToken(builder, THEN);
e = builder.getTokenType();
parseExpTopType(builder, ((ThenTrans) qualStmtTopType).exp, comments);
e = builder.getTokenType();
} else if (qualStmtTopType instanceof ThenBy) {
consumeToken(builder, THEN);
e = builder.getTokenType();
parseExpTopType(builder, ((ThenBy) qualStmtTopType).e1, comments);
e = builder.getTokenType();
builder.advanceLexer(); // TODO: Add Token.BY
e = builder.getTokenType();
parseExpTopType(builder, ((ThenBy) qualStmtTopType).e2, comments);
e = builder.getTokenType();
} else if (qualStmtTopType instanceof GroupBy) {
consumeToken(builder, THEN);
e = builder.getTokenType();
builder.advanceLexer(); // TODO: Add Token.GROUP
e = builder.getTokenType();
builder.advanceLexer(); // TODO: Add Token.USING
e = builder.getTokenType();
parseExpTopType(builder, ((GroupBy) qualStmtTopType).exp, comments);
e = builder.getTokenType();
} else if (qualStmtTopType instanceof GroupUsing) {
consumeToken(builder, THEN);
e = builder.getTokenType();
builder.advanceLexer(); // TODO: Add Token.GROUP
e = builder.getTokenType();
builder.advanceLexer(); // TODO: Add Token.USING
e = builder.getTokenType();
parseExpTopType(builder, ((GroupUsing) qualStmtTopType).exp, comments);
e = builder.getTokenType();
} else if (qualStmtTopType instanceof GroupByUsing) {
consumeToken(builder, THEN);
e = builder.getTokenType();
builder.advanceLexer(); // TODO: Add Token.GROUP
e = builder.getTokenType();
builder.advanceLexer(); // TODO: Add Token.BY
e = builder.getTokenType();
parseExpTopType(builder, ((GroupByUsing) qualStmtTopType).e1, comments);
e = builder.getTokenType();
builder.advanceLexer(); // TODO: Add Token.USING.
parseExpTopType(builder, ((GroupByUsing) qualStmtTopType).e2, comments);
e = builder.getTokenType();
}
}
/**
* Parses contexts.
*/
private static void parseContextTopType(PsiBuilder builder, ContextTopType context, Comment[] comments) {
IElementType e = builder.getTokenType();
if (context instanceof CxSingle) {
parseAsstTopType(builder, ((CxSingle) context).asst, comments);
} else if (context instanceof CxTuple) {
consumeToken(builder, LPAREN);
e = builder.getTokenType();
parseAsstTopTypes(builder, ((CxTuple) context).assts, comments);
e = builder.getTokenType();
consumeToken(builder, RPAREN);
e = builder.getTokenType();
} else if (context instanceof CxParen) {
consumeToken(builder, LPAREN);
parseContextTopType(builder, ((CxParen) context).context, comments);
e = builder.getTokenType();
consumeToken(builder, RPAREN);
e = builder.getTokenType();
} else if (context instanceof CxEmpty) {
throw new RuntimeException("TODO: Implement CxEmpty");
}
}
/**
* Parses a list of Assts.
*/
private static void parseAsstTopTypes(PsiBuilder builder, AsstTopType[] assts, Comment[] comments) {
int i = 0;
IElementType e = builder.getTokenType();
while (assts != null && i < assts.length) {
parseAsstTopType(builder, assts[i], comments);
i++;
e = builder.getTokenType();
if (e == COMMA) {
consumeToken(builder, COMMA);
e = builder.getTokenType();
}
}
}
/**
* Parses Assts.
*/
private static void parseAsstTopType(PsiBuilder builder, AsstTopType asst, Comment[] comments) {
IElementType e = builder.getTokenType();
if (asst instanceof ClassA) {
parseQName(builder, ((ClassA) asst).qName, comments);
e = builder.getTokenType();
parseTypeTopTypes(builder, ((ClassA) asst).types, comments);
e = builder.getTokenType();
} else if (asst instanceof InfixA) {
parseTypeTopType(builder, ((InfixA) asst).t1, comments);
e = builder.getTokenType();
parseQName(builder, ((InfixA) asst).qName, comments);
e = builder.getTokenType();
parseTypeTopType(builder, ((InfixA) asst).t2, comments);
e = builder.getTokenType();
} else if (asst instanceof IParam) {
parseIPNameTopType(builder, ((IParam) asst).ipName, comments);
e = builder.getTokenType();
consumeToken(builder, DOUBLECOLON);
e = builder.getTokenType();
parseTypeTopType(builder, ((IParam) asst).type, comments);
e = builder.getTokenType();
} else if (asst instanceof EqualP) {
throw new RuntimeException("TODO: Parse EqualP");
/* Preliminary untested implementation:
parseTypeTopType(builder, ((EqualP) asst).t1, comments);
consumeToken(builder, TILDETOKENHERE);
e = builder.getTokenType();
parseTypeTopType(builder,((EqualP) asst).t2, comments);
e = builder.getTokenType();
*/
}
}
/**
* Parses Implicit parameter names.
*/
private static void parseIPNameTopType(PsiBuilder builder, IPNameTopType ipNameTopType, Comment[] comments) { // TODO: Improve granularity.
IElementType e = builder.getTokenType();
if (ipNameTopType instanceof IPDup) {
consumeToken(builder, QUESTION);
e = builder.getTokenType();
builder.advanceLexer();
e = builder.getTokenType();
} else if (ipNameTopType instanceof IPLin) {
consumeToken(builder, PERCENT);
e = builder.getTokenType();
builder.advanceLexer();
e = builder.getTokenType();
}
}
/**
* Parses box annotations.
*/
public static boolean parseBoxed(PsiBuilder builder, BoxedTopType boxedTopType, Comment[] comments) { // TODO: Improve granularity.
IElementType e = builder.getTokenType();
if (boxedTopType instanceof Boxed) {
return false;
} else if (boxedTopType instanceof Unboxed) {
consumeToken(builder, HASH);
return true;
}
throw new RuntimeException("Unexpected boxing: " + boxedTopType.toString());
}
/**
* Parses a generic pragma.
*/
public static void parseGenericPragma(PsiBuilder builder, DeclTopType annPragma, Comment[] comments) { // TODO: Improve granularity.
PsiBuilder.Marker pragmaMark = builder.mark();
IElementType e = builder.getTokenType();
chewPragma(builder);
consumeToken(builder, CLOSEPRAGMA);
pragmaMark.done(e);
}
/**
* Eats a complete pragma and leaves the builder at CLOSEPRAGMA token.
*/
public static void chewPragma(PsiBuilder builder) {
IElementType e = builder.getTokenType();
while (e != CLOSEPRAGMA) {
builder.advanceLexer();
e = builder.getTokenType();
}
}
public static boolean consumeToken(PsiBuilder builder_, IElementType token) {
if (nextTokenIsInner(builder_, token)) {
builder_.advanceLexer();
return true;
}
return false;
}
public static boolean nextTokenIsInner(PsiBuilder builder_, IElementType expectedToken) {
IElementType tokenType = builder_.getTokenType();
if (expectedToken != tokenType) {
System.out.println("Found token: " + tokenType + " vs expected: " + expectedToken);
}
return expectedToken == tokenType;
}
}
|
package com.irccloud.android;
import java.util.ArrayList;
import org.json.JSONException;
import org.json.JSONObject;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.google.android.gcm.GCMRegistrar;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.style.BackgroundColorSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.text.style.UnderlineSpan;
import android.text.util.Linkify;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.animation.AlphaAnimation;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
public class MessageActivity extends BaseActivity implements UsersListFragment.OnUserSelectedListener, BuffersListFragment.OnBufferSelectedListener, MessageViewFragment.MessageViewListener {
int cid = -1;
int bid;
String name;
String type;
TextView messageTxt;
View sendBtn;
int joined;
int archived;
String status;
UsersDataSource.User selected_user;
View userListView;
View buffersListView;
TextView title;
TextView subtitle;
LinearLayout messageContainer;
HorizontalScrollView scrollView;
NetworkConnection conn;
private boolean shouldFadeIn = false;
ImageView upView;
private RefreshUpIndicatorTask refreshUpIndicatorTask = null;
private ArrayList<Integer> backStack = new ArrayList<Integer>();
PowerManager.WakeLock screenLock = null;
@SuppressLint("NewApi")
@SuppressWarnings({ "deprecation", "unchecked" })
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message);
buffersListView = findViewById(R.id.BuffersList);
messageContainer = (LinearLayout)findViewById(R.id.messageContainer);
scrollView = (HorizontalScrollView)findViewById(R.id.scroll);
if(scrollView != null) {
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)messageContainer.getLayoutParams();
params.width = getWindowManager().getDefaultDisplay().getWidth();
messageContainer.setLayoutParams(params);
}
messageTxt = (TextView)findViewById(R.id.messageTxt);
messageTxt.setOnEditorActionListener(new OnEditorActionListener() {
public boolean onEditorAction(TextView exampleView, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_DOWN) {
new SendTask().execute((Void)null);
}
return true;
}
});
messageTxt.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
Object[] spans = s.getSpans(0, s.length(), Object.class);
for(Object o : spans) {
if(((s.getSpanFlags(o) & Spanned.SPAN_COMPOSING) != Spanned.SPAN_COMPOSING) && (o.getClass() == StyleSpan.class || o.getClass() == ForegroundColorSpan.class || o.getClass() == BackgroundColorSpan.class || o.getClass() == UnderlineSpan.class)) {
s.removeSpan(o);
}
}
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
});
sendBtn = findViewById(R.id.sendBtn);
sendBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
new SendTask().execute((Void)null);
}
});
userListView = findViewById(R.id.usersListFragment);
getSupportActionBar().setHomeButtonEnabled(false);
getSupportActionBar().setDisplayShowHomeEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayShowCustomEnabled(true);
View v = getLayoutInflater().inflate(R.layout.actionbar_messageview, null);
v.findViewById(R.id.actionTitleArea).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
ChannelsDataSource.Channel c = ChannelsDataSource.getInstance().getChannelForBuffer(bid);
if(c != null) {
AlertDialog.Builder builder = new AlertDialog.Builder(MessageActivity.this);
builder.setTitle("Channel Topic");
if(c.topic_text.length() > 0) {
final SpannableString s = new SpannableString(c.topic_text);
Linkify.addLinks(s, Linkify.WEB_URLS | Linkify.EMAIL_ADDRESSES);
builder.setMessage(s);
} else
builder.setMessage("No topic set.");
builder.setPositiveButton("Close", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.setNeutralButton("Edit", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
editTopic();
}
});
AlertDialog dialog = builder.create();
dialog.setOwnerActivity(MessageActivity.this);
dialog.show();
((TextView)dialog.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance());
} else if(archived == 0 && subtitle.getText().length() > 0){
AlertDialog.Builder builder = new AlertDialog.Builder(MessageActivity.this);
builder.setTitle(title.getText().toString());
final SpannableString s = new SpannableString(subtitle.getText().toString());
Linkify.addLinks(s, Linkify.WEB_URLS | Linkify.EMAIL_ADDRESSES);
builder.setMessage(s);
builder.setPositiveButton("Close", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.setOwnerActivity(MessageActivity.this);
dialog.show();
((TextView)dialog.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance());
}
}
});
upView = (ImageView)v.findViewById(R.id.upIndicator);
if(scrollView != null) {
upView.setVisibility(View.VISIBLE);
upView.setOnClickListener(upClickListener);
ImageView icon = (ImageView)v.findViewById(R.id.upIcon);
icon.setOnClickListener(upClickListener);
if(refreshUpIndicatorTask != null)
refreshUpIndicatorTask.cancel(true);
refreshUpIndicatorTask = new RefreshUpIndicatorTask();
refreshUpIndicatorTask.execute((Void)null);
} else {
upView.setVisibility(View.INVISIBLE);
}
title = (TextView)v.findViewById(R.id.title);
subtitle = (TextView)v.findViewById(R.id.subtitle);
getSupportActionBar().setCustomView(v);
if(savedInstanceState != null && savedInstanceState.containsKey("cid")) {
cid = savedInstanceState.getInt("cid");
bid = savedInstanceState.getInt("bid");
name = savedInstanceState.getString("name");
type = savedInstanceState.getString("type");
joined = savedInstanceState.getInt("joined");
archived = savedInstanceState.getInt("archived");
status = savedInstanceState.getString("status");
backStack = (ArrayList<Integer>) savedInstanceState.getSerializable("backStack");
}
GCMRegistrar.checkDevice(this);
GCMRegistrar.checkManifest(this);
final String regId = GCMRegistrar.getRegistrationId(this);
if (regId.equals("")) {
GCMRegistrar.register(this, "841915816917");
} else {
Log.v("IRCCloud", "Already registered");
}
}
@Override
public void onSaveInstanceState(Bundle state) {
super.onSaveInstanceState(state);
state.putInt("cid", cid);
state.putInt("bid", bid);
state.putString("name", name);
state.putString("type", type);
state.putInt("joined", joined);
state.putInt("archived", archived);
state.putString("status", status);
state.putSerializable("backStack", backStack);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) { //Back key pressed
if(backStack.size() > 0) {
Integer bid = backStack.get(0);
backStack.remove(0);
BuffersDataSource.Buffer buffer = BuffersDataSource.getInstance().getBuffer(bid);
onBufferSelected(buffer.cid, buffer.bid, buffer.name, buffer.last_seen_eid, buffer.min_eid,
buffer.type, 1, buffer.archived, status);
backStack.remove(0);
return true;
}
}
return super.onKeyDown(keyCode, event);
}
private class SendTask extends AsyncTaskEx<Void, Void, Void> {
@Override
protected void onPreExecute() {
sendBtn.setEnabled(false);
}
@Override
protected Void doInBackground(Void... arg0) {
if(conn.getState() == NetworkConnection.STATE_CONNECTED) {
conn.say(cid, name, messageTxt.getText().toString());
}
return null;
}
@Override
protected void onPostExecute(Void result) {
messageTxt.setText("");
sendBtn.setEnabled(true);
}
}
private class RefreshUpIndicatorTask extends AsyncTaskEx<Void, Void, Void> {
int unread = 0;
int highlights = 0;
@Override
protected Void doInBackground(Void... arg0) {
ArrayList<ServersDataSource.Server> servers = ServersDataSource.getInstance().getServers();
JSONObject disabledMap = null;
if(conn != null && conn.getUserInfo() != null && conn.getUserInfo().prefs != null && conn.getUserInfo().prefs.has("channel-disableTrackUnread")) {
try {
disabledMap = conn.getUserInfo().prefs.getJSONObject("channel-disableTrackUnread");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for(int i = 0; i < servers.size(); i++) {
ServersDataSource.Server s = servers.get(i);
ArrayList<BuffersDataSource.Buffer> buffers = BuffersDataSource.getInstance().getBuffersForServer(s.cid);
for(int j = 0; j < buffers.size(); j++) {
BuffersDataSource.Buffer b = buffers.get(j);
if(b.type == null)
Log.w("IRCCloud", "Buffer with null type: " + b.bid + " name: " + b.name);
if(b.bid != bid) {
if(unread == 0) {
int u = 0;
try {
u = EventsDataSource.getInstance().getUnreadCountForBuffer(b.bid, b.last_seen_eid, b.type);
if(disabledMap != null && disabledMap.has(String.valueOf(b.bid)) && disabledMap.getBoolean(String.valueOf(b.bid)))
u = 0;
} catch (JSONException e) {
e.printStackTrace();
}
unread += u;
}
if(highlights == 0)
highlights += EventsDataSource.getInstance().getHighlightCountForBuffer(b.bid, b.last_seen_eid, b.type);
}
}
}
return null;
}
@Override
protected void onPostExecute(Void result) {
if(!isCancelled()) {
if(highlights > 0) {
upView.setImageResource(R.drawable.up_highlight);
} else if(unread > 0) {
upView.setImageResource(R.drawable.up_unread);
} else {
upView.setImageResource(R.drawable.up);
}
refreshUpIndicatorTask = null;
}
}
}
private void setFromIntent(Intent intent) {
long min_eid = 0;
long last_seen_eid = 0;
cid = intent.getIntExtra("cid", 0);
bid = intent.getIntExtra("bid", 0);
name = intent.getStringExtra("name");
type = intent.getStringExtra("type");
joined = intent.getIntExtra("joined", 0);
archived = intent.getIntExtra("archived", 0);
status = intent.getStringExtra("status");
min_eid = intent.getLongExtra("min_eid", 0);
last_seen_eid = intent.getLongExtra("last_seen_eid", 0);
if(bid == -1) {
BuffersDataSource.Buffer b = BuffersDataSource.getInstance().getBufferByName(cid, name);
if(b != null) {
bid = b.bid;
last_seen_eid = b.last_seen_eid;
min_eid = b.min_eid;
archived = b.archived;
}
}
UsersListFragment ulf = (UsersListFragment)getSupportFragmentManager().findFragmentById(R.id.usersListFragment);
MessageViewFragment mvf = (MessageViewFragment)getSupportFragmentManager().findFragmentById(R.id.messageViewFragment);
Bundle b = new Bundle();
b.putInt("cid", cid);
b.putInt("bid", bid);
b.putLong("last_seen_eid", last_seen_eid);
b.putLong("min_eid", min_eid);
b.putString("name", name);
b.putString("type", type);
ulf.setArguments(b);
mvf.setArguments(b);
}
@Override
protected void onNewIntent(Intent intent) {
if(intent != null && intent.hasExtra("cid")) {
setFromIntent(intent);
}
}
@Override
public void onResume() {
super.onResume();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext());
if(prefs.getBoolean("screenlock", false)) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
conn = NetworkConnection.getInstance();
conn.addHandler(mHandler);
if(getIntent() != null && getIntent().hasExtra("cid") && cid == -1) {
setFromIntent(getIntent());
}
updateUsersListFragmentVisibility();
title.setText(name);
getSupportActionBar().setTitle(name);
update_subtitle();
if(getSupportFragmentManager().findFragmentById(R.id.BuffersList) != null)
((BuffersListFragment)getSupportFragmentManager().findFragmentById(R.id.BuffersList)).setSelectedBid(bid);
if(refreshUpIndicatorTask != null)
refreshUpIndicatorTask.cancel(true);
refreshUpIndicatorTask = new RefreshUpIndicatorTask();
refreshUpIndicatorTask.execute((Void)null);
invalidateOptionsMenu();
Notifications.getInstance().excludeBid(bid);
Notifications.getInstance().showNotifications(null);
}
@Override
public void onPause() {
super.onPause();
if(conn != null)
conn.removeHandler(mHandler);
Notifications.getInstance().excludeBid(-1);
}
private void update_subtitle() {
if(archived > 0 && !type.equalsIgnoreCase("console")) {
subtitle.setVisibility(View.VISIBLE);
subtitle.setText("(archived)");
} else {
if(type.equalsIgnoreCase("conversation")) {
UsersDataSource.User user = UsersDataSource.getInstance().getUser(cid, name);
BuffersDataSource.Buffer b = BuffersDataSource.getInstance().getBuffer(bid);
if(user != null && user.away > 0) {
subtitle.setVisibility(View.VISIBLE);
if(user.away_msg != null && user.away_msg.length() > 0) {
subtitle.setText("Away: " + user.away_msg);
} else if(b != null && b.away_msg != null && b.away_msg.length() > 0) {
subtitle.setText("Away: " + b.away_msg);
} else {
subtitle.setText("Away");
}
} else {
subtitle.setVisibility(View.GONE);
}
} else if(type.equalsIgnoreCase("channel")) {
ChannelsDataSource.Channel c = ChannelsDataSource.getInstance().getChannelForBuffer(bid);
if(c != null && c.topic_text.length() > 0) {
subtitle.setVisibility(View.VISIBLE);
subtitle.setText(c.topic_text);
} else {
subtitle.setVisibility(View.GONE);
}
} else if(type.equalsIgnoreCase("console")) {
ServersDataSource.Server s = ServersDataSource.getInstance().getServer(cid);
if(s != null) {
subtitle.setVisibility(View.VISIBLE);
subtitle.setText(s.hostname + ":" + s.port);
} else {
subtitle.setVisibility(View.GONE);
}
}
}
}
private void updateUsersListFragmentVisibility() {
boolean hide = false;
if(userListView != null) {
try {
if(conn != null && conn.getUserInfo() != null && conn.getUserInfo().prefs != null) {
JSONObject hiddenMap = conn.getUserInfo().prefs.getJSONObject("channel-hiddenMembers");
if(hiddenMap.has(String.valueOf(bid)) && hiddenMap.getBoolean(String.valueOf(bid)))
hide = true;
}
} catch (Exception e) {
e.printStackTrace();
}
if(hide || !type.equalsIgnoreCase("channel"))
userListView.setVisibility(View.GONE);
else
userListView.setVisibility(View.VISIBLE);
}
}
@SuppressLint("HandlerLeak")
private final Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
Integer event_bid = 0;
IRCCloudJSONObject event = null;
switch (msg.what) {
case NetworkConnection.EVENT_BANLIST:
event = (IRCCloudJSONObject)msg.obj;
if(event.getString("channel").equalsIgnoreCase(name)) {
Bundle args = new Bundle();
args.putInt("cid", cid);
args.putInt("bid", bid);
args.putString("event", event.toString());
BanListFragment banList = (BanListFragment)getSupportFragmentManager().findFragmentByTag("banlist");
if(banList == null) {
banList = new BanListFragment();
banList.setArguments(args);
banList.show(getSupportFragmentManager(), "banlist");
} else {
banList.setArguments(args);
}
}
break;
case NetworkConnection.EVENT_BACKLOG_END:
update_subtitle();
break;
case NetworkConnection.EVENT_USERINFO:
updateUsersListFragmentVisibility();
invalidateOptionsMenu();
if(refreshUpIndicatorTask != null)
refreshUpIndicatorTask.cancel(true);
refreshUpIndicatorTask = new RefreshUpIndicatorTask();
refreshUpIndicatorTask.execute((Void)null);
break;
case NetworkConnection.EVENT_STATUSCHANGED:
try {
event = (IRCCloudJSONObject)msg.obj;
if(event.cid() == cid) {
status = event.getString("new_status");
invalidateOptionsMenu();
}
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
break;
case NetworkConnection.EVENT_MAKESERVER:
ServersDataSource.Server server = (ServersDataSource.Server)msg.obj;
if(server.cid == cid) {
status = server.status;
invalidateOptionsMenu();
}
break;
case NetworkConnection.EVENT_MAKEBUFFER:
BuffersDataSource.Buffer buffer = (BuffersDataSource.Buffer)msg.obj;
if(bid == -1 && buffer.cid == cid && buffer.name.equalsIgnoreCase(name)) {
Log.i("IRCCloud", "Got my new buffer id: " + buffer.bid);
bid = buffer.bid;
if(getSupportFragmentManager().findFragmentById(R.id.BuffersList) != null)
((BuffersListFragment)getSupportFragmentManager().findFragmentById(R.id.BuffersList)).setSelectedBid(bid);
Notifications.getInstance().excludeBid(bid);
Notifications.getInstance().showNotifications(null);
}
break;
case NetworkConnection.EVENT_BUFFERARCHIVED:
event_bid = (Integer)msg.obj;
if(event_bid == bid) {
archived = 1;
invalidateOptionsMenu();
subtitle.setVisibility(View.VISIBLE);
subtitle.setText("(archived)");
}
break;
case NetworkConnection.EVENT_BUFFERUNARCHIVED:
event_bid = (Integer)msg.obj;
if(event_bid == bid) {
archived = 0;
invalidateOptionsMenu();
subtitle.setVisibility(View.GONE);
}
break;
case NetworkConnection.EVENT_JOIN:
event = (IRCCloudJSONObject)msg.obj;
if(event.bid() == bid && event.type().equalsIgnoreCase("you_joined_channel")) {
joined = 1;
invalidateOptionsMenu();
}
break;
case NetworkConnection.EVENT_PART:
event = (IRCCloudJSONObject)msg.obj;
if(event.bid() == bid && event.type().equalsIgnoreCase("you_parted_channel")) {
joined = 0;
invalidateOptionsMenu();
}
break;
case NetworkConnection.EVENT_CHANNELINIT:
ChannelsDataSource.Channel channel = (ChannelsDataSource.Channel)msg.obj;
if(channel.bid == bid) {
joined = 1;
archived = 0;
update_subtitle();
invalidateOptionsMenu();
}
break;
case NetworkConnection.EVENT_CONNECTIONDELETED:
case NetworkConnection.EVENT_DELETEBUFFER:
Integer id = (Integer)msg.obj;
if(id == ((msg.what==NetworkConnection.EVENT_CONNECTIONDELETED)?cid:bid)) {
Intent parentActivityIntent = new Intent(MessageActivity.this, MainActivity.class);
parentActivityIntent.addFlags(
Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(parentActivityIntent);
finish();
}
break;
case NetworkConnection.EVENT_CHANNELTOPIC:
event = (IRCCloudJSONObject)msg.obj;
if(event.bid() == bid) {
try {
if(event.getString("topic").length() > 0) {
subtitle.setVisibility(View.VISIBLE);
subtitle.setText(event.getString("topic"));
} else {
subtitle.setVisibility(View.GONE);
}
} catch (Exception e1) {
subtitle.setVisibility(View.GONE);
e1.printStackTrace();
}
}
break;
case NetworkConnection.EVENT_SELFBACK:
try {
event = (IRCCloudJSONObject)msg.obj;
if(event.cid() == cid && event.getString("nick").equalsIgnoreCase(name)) {
subtitle.setVisibility(View.GONE);
subtitle.setText("");
}
} catch (Exception e1) {
e1.printStackTrace();
}
break;
case NetworkConnection.EVENT_AWAY:
try {
event = (IRCCloudJSONObject)msg.obj;
if((event.bid() == bid || (event.type().equalsIgnoreCase("self_away") && event.cid() == cid)) && event.getString("nick").equalsIgnoreCase(name)) {
subtitle.setVisibility(View.VISIBLE);
if(event.has("away_msg"))
subtitle.setText("Away: " + event.getString("away_msg"));
else
subtitle.setText("Away: " + event.getString("msg"));
}
} catch (Exception e1) {
e1.printStackTrace();
}
break;
case NetworkConnection.EVENT_HEARTBEATECHO:
if(refreshUpIndicatorTask != null)
refreshUpIndicatorTask.cancel(true);
refreshUpIndicatorTask = new RefreshUpIndicatorTask();
refreshUpIndicatorTask.execute((Void)null);
break;
case NetworkConnection.EVENT_BUFFERMSG:
try {
EventsDataSource.Event e = (EventsDataSource.Event)msg.obj;
if(e.bid != bid && upView != null) {
if(refreshUpIndicatorTask != null)
refreshUpIndicatorTask.cancel(true);
refreshUpIndicatorTask = new RefreshUpIndicatorTask();
refreshUpIndicatorTask.execute((Void)null);
}
} catch (Exception e1) {
}
break;
}
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if(type.equalsIgnoreCase("channel")) {
getSupportMenuInflater().inflate(R.menu.activity_message_channel_userlist, menu);
getSupportMenuInflater().inflate(R.menu.activity_message_channel, menu);
} else if(type.equalsIgnoreCase("conversation"))
getSupportMenuInflater().inflate(R.menu.activity_message_conversation, menu);
else if(type.equalsIgnoreCase("console"))
getSupportMenuInflater().inflate(R.menu.activity_message_console, menu);
getSupportMenuInflater().inflate(R.menu.activity_message_archive, menu);
getSupportMenuInflater().inflate(R.menu.activity_main, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onPrepareOptionsMenu (Menu menu) {
if(archived == 0) {
menu.findItem(R.id.menu_archive).setTitle(R.string.menu_archive);
} else {
menu.findItem(R.id.menu_archive).setTitle(R.string.menu_unarchive);
}
if(type.equalsIgnoreCase("channel")) {
if(joined == 0) {
menu.findItem(R.id.menu_leave).setTitle(R.string.menu_rejoin);
menu.findItem(R.id.menu_archive).setVisible(true);
menu.findItem(R.id.menu_archive).setEnabled(true);
menu.findItem(R.id.menu_delete).setVisible(true);
menu.findItem(R.id.menu_delete).setEnabled(true);
if(menu.findItem(R.id.menu_userlist) != null) {
menu.findItem(R.id.menu_userlist).setEnabled(false);
menu.findItem(R.id.menu_userlist).setVisible(false);
}
} else {
menu.findItem(R.id.menu_leave).setTitle(R.string.menu_leave);
menu.findItem(R.id.menu_archive).setVisible(false);
menu.findItem(R.id.menu_archive).setEnabled(false);
menu.findItem(R.id.menu_delete).setVisible(false);
menu.findItem(R.id.menu_delete).setEnabled(false);
if(menu.findItem(R.id.menu_userlist) != null) {
boolean hide = false;
try {
if(conn != null && conn.getUserInfo() != null && conn.getUserInfo().prefs != null) {
JSONObject hiddenMap = conn.getUserInfo().prefs.getJSONObject("channel-hiddenMembers");
if(hiddenMap.has(String.valueOf(bid)) && hiddenMap.getBoolean(String.valueOf(bid)))
hide = true;
}
} catch (JSONException e) {
}
if(hide) {
menu.findItem(R.id.menu_userlist).setEnabled(false);
menu.findItem(R.id.menu_userlist).setVisible(false);
} else {
menu.findItem(R.id.menu_userlist).setEnabled(true);
menu.findItem(R.id.menu_userlist).setVisible(true);
}
}
}
} else if(type.equalsIgnoreCase("console")) {
menu.findItem(R.id.menu_archive).setVisible(false);
menu.findItem(R.id.menu_archive).setEnabled(false);
Log.i("IRCCloud", "Status: " + status);
if(status != null && status.contains("connected") && !status.startsWith("dis")) {
menu.findItem(R.id.menu_disconnect).setTitle(R.string.menu_disconnect);
menu.findItem(R.id.menu_delete).setVisible(false);
menu.findItem(R.id.menu_delete).setEnabled(false);
} else {
menu.findItem(R.id.menu_disconnect).setTitle(R.string.menu_reconnect);
menu.findItem(R.id.menu_delete).setVisible(true);
menu.findItem(R.id.menu_delete).setEnabled(true);
}
}
return super.onPrepareOptionsMenu(menu);
}
private OnClickListener upClickListener = new OnClickListener() {
@Override
public void onClick(View arg0) {
if(scrollView != null) {
if(scrollView.getScrollX() < buffersListView.getWidth() / 4) {
scrollView.smoothScrollTo(buffersListView.getWidth(), 0);
upView.setVisibility(View.VISIBLE);
} else {
scrollView.smoothScrollTo(0, 0);
upView.setVisibility(View.INVISIBLE);
}
}
}
};
@Override
public boolean onOptionsItemSelected(MenuItem item) {
AlertDialog.Builder builder;
AlertDialog dialog;
switch (item.getItemId()) {
case R.id.menu_add_network:
EditConnectionFragment connFragment = new EditConnectionFragment();
connFragment.show(getSupportFragmentManager(), "dialog");
break;
case R.id.menu_channel_options:
ChannelOptionsFragment newFragment = new ChannelOptionsFragment(cid, bid);
newFragment.show(getSupportFragmentManager(), "dialog");
break;
case R.id.menu_userlist:
if(scrollView != null) {
if(scrollView.getScrollX() > buffersListView.getWidth()) {
scrollView.smoothScrollTo(buffersListView.getWidth(), 0);
} else {
scrollView.smoothScrollTo(buffersListView.getWidth() + userListView.getWidth(), 0);
}
}
return true;
case R.id.menu_ignore_list:
Bundle args = new Bundle();
args.putInt("cid", cid);
IgnoreListFragment ignoreList = new IgnoreListFragment();
ignoreList.setArguments(args);
ignoreList.show(getSupportFragmentManager(), "ignorelist");
return true;
case R.id.menu_ban_list:
conn.mode(cid, name, "b");
return true;
case R.id.menu_leave:
if(joined == 0)
conn.join(cid, name, "");
else
conn.part(cid, name, "");
return true;
case R.id.menu_archive:
if(archived == 0)
conn.archiveBuffer(cid, bid);
else
conn.unarchiveBuffer(cid, bid);
return true;
case R.id.menu_delete:
builder = new AlertDialog.Builder(MessageActivity.this);
if(type.equalsIgnoreCase("console"))
builder.setTitle("Delete Connection");
else
builder.setTitle("Delete History");
if(type.equalsIgnoreCase("console"))
builder.setMessage("Are you sure you want to remove this connection?");
else if(type.equalsIgnoreCase("channel"))
builder.setMessage("Are you sure you want to clear your history in " + name + "?");
else
builder.setMessage("Are you sure you want to clear your history with " + name + "?");
builder.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.setNeutralButton("Delete", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if(type.equalsIgnoreCase("console")) {
conn.deleteServer(cid);
} else {
conn.deleteBuffer(cid, bid);
}
dialog.dismiss();
}
});
dialog = builder.create();
dialog.setOwnerActivity(MessageActivity.this);
dialog.show();
return true;
case R.id.menu_editconnection:
EditConnectionFragment editFragment = new EditConnectionFragment();
editFragment.setCid(cid);
editFragment.show(getSupportFragmentManager(), "editconnection");
return true;
case R.id.menu_disconnect:
if(status != null && status.contains("connected") && !status.startsWith("dis")) {
conn.disconnect(cid, "");
} else {
conn.reconnect(cid);
}
return true;
}
return super.onOptionsItemSelected(item);
}
void editTopic() {
ChannelsDataSource.Channel c = ChannelsDataSource.getInstance().getChannelForBuffer(bid);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.dialog_textprompt,null);
TextView prompt = (TextView)view.findViewById(R.id.prompt);
final EditText input = (EditText)view.findViewById(R.id.textInput);
input.setText(c.topic_text);
prompt.setVisibility(View.GONE);
builder.setTitle("Channel Topic");
builder.setView(view);
builder.setPositiveButton("Set Topic", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
conn.say(cid, name, "/topic " + input.getText().toString());
dialog.dismiss();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.setOwnerActivity(this);
dialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
dialog.show();
}
@Override
public void onMessageDoubleClicked(EventsDataSource.Event event) {
String from = event.from;
if(from == null || from.length() == 0)
from = event.nick;
if(messageTxt == null || event == null || from == null || from.length() == 0)
return;
if(messageTxt.getText().length() == 0)
messageTxt.append(from + ": ");
else
messageTxt.append(" " + from + " ");
}
@Override
public boolean onMessageLongClicked(EventsDataSource.Event event) {
String from = event.from;
if(from == null || from.length() == 0)
from = event.nick;
UsersDataSource.User user;
if(type.equals("channel"))
user = UsersDataSource.getInstance().getUser(cid, name, from);
else
user = UsersDataSource.getInstance().getUser(cid, from);
if(user == null && from != null && event.hostmask != null) {
user = UsersDataSource.getInstance().new User();
user.nick = from;
user.hostmask = event.hostmask;
user.mode = "";
}
if(user == null && event.html == null)
return false;
if(event.html != null)
showUserPopup(user, ColorFormatter.html_to_spanned(event.html));
else
showUserPopup(user, null);
return true;
}
@Override
public void onUserSelected(int c, String chan, String nick) {
UsersDataSource u = UsersDataSource.getInstance();
if(type.equals("channel"))
showUserPopup(u.getUser(cid, name, nick), null);
else
showUserPopup(u.getUser(cid, nick), null);
}
@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
private void showUserPopup(UsersDataSource.User user, Spanned message) {
ArrayList<String> itemList = new ArrayList<String>();
final String[] items;
final Spanned text_to_copy = message;
selected_user = user;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
if(message != null)
itemList.add("Copy Message");
if(selected_user != null) {
itemList.add("Open");
itemList.add("Invite to a channel");
itemList.add("Ignore");
if(type.equalsIgnoreCase("channel")) {
UsersDataSource.User self_user = UsersDataSource.getInstance().getUser(cid, name, ServersDataSource.getInstance().getServer(cid).nick);
if(self_user.mode.contains("q") || self_user.mode.contains("a") || self_user.mode.contains("o")) {
if(selected_user.mode.contains("o"))
itemList.add("Deop");
else
itemList.add("Op");
}
if(self_user.mode.contains("q") || self_user.mode.contains("a") || self_user.mode.contains("o") || self_user.mode.contains("h")) {
itemList.add("Kick");
itemList.add("Ban");
}
}
}
items = itemList.toArray(new String[itemList.size()]);
if(selected_user != null)
builder.setTitle(selected_user.nick + "\n(" + selected_user.hostmask + ")");
else
builder.setTitle("Message");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int item) {
AlertDialog.Builder builder = new AlertDialog.Builder(MessageActivity.this);
LayoutInflater inflater = getLayoutInflater();
ServersDataSource s = ServersDataSource.getInstance();
ServersDataSource.Server server = s.getServer(cid);
View view;
final TextView prompt;
final EditText input;
AlertDialog dialog;
if(items[item].equals("Copy Message")) {
if(Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) {
android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setText(text_to_copy);
} else {
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
android.content.ClipData clip = android.content.ClipData.newPlainText("IRCCloud Message",text_to_copy);
clipboard.setPrimaryClip(clip);
}
} else if(items[item].equals("Open")) {
BuffersDataSource b = BuffersDataSource.getInstance();
BuffersDataSource.Buffer buffer = b.getBufferByName(cid, selected_user.nick);
if(getSupportFragmentManager().findFragmentById(R.id.BuffersList) != null) {
if(buffer != null) {
onBufferSelected(buffer.cid, buffer.bid, buffer.name, buffer.last_seen_eid, buffer.min_eid,
buffer.type, 1, buffer.archived, status);
} else {
onBufferSelected(cid, -1, selected_user.nick, 0, 0, "conversation", 1, 0, status);
}
} else {
Intent i = new Intent(MessageActivity.this, MessageActivity.class);
if(buffer != null) {
i.putExtra("cid", buffer.cid);
i.putExtra("bid", buffer.bid);
i.putExtra("name", buffer.name);
i.putExtra("last_seen_eid", buffer.last_seen_eid);
i.putExtra("min_eid", buffer.min_eid);
i.putExtra("type", buffer.type);
i.putExtra("joined", 1);
i.putExtra("archived", buffer.archived);
i.putExtra("status", status);
} else {
i.putExtra("cid", cid);
i.putExtra("bid", -1);
i.putExtra("name", selected_user.nick);
i.putExtra("last_seen_eid", 0L);
i.putExtra("min_eid", 0L);
i.putExtra("type", "conversation");
i.putExtra("joined", 1);
i.putExtra("archived", 0);
i.putExtra("status", status);
}
startActivity(i);
}
} else if(items[item].equals("Invite to a channel")) {
view = inflater.inflate(R.layout.dialog_textprompt,null);
prompt = (TextView)view.findViewById(R.id.prompt);
input = (EditText)view.findViewById(R.id.textInput);
prompt.setText("Invite " + selected_user.nick + " to a channel");
builder.setTitle(server.name + " (" + server.hostname + ":" + (server.port) + ")");
builder.setView(view);
builder.setPositiveButton("Invite", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
conn.invite(cid, input.getText().toString(), selected_user.nick);
dialog.dismiss();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog = builder.create();
dialog.setOwnerActivity(MessageActivity.this);
dialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
dialog.show();
} else if(items[item].equals("Ignore")) {
view = inflater.inflate(R.layout.dialog_textprompt,null);
prompt = (TextView)view.findViewById(R.id.prompt);
input = (EditText)view.findViewById(R.id.textInput);
input.setText("*!"+selected_user.hostmask);
prompt.setText("Ignore messages for " + selected_user.nick + " at this hostmask");
builder.setTitle(server.name + " (" + server.hostname + ":" + (server.port) + ")");
builder.setView(view);
builder.setPositiveButton("Ignore", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
conn.ignore(cid, input.getText().toString());
dialog.dismiss();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog = builder.create();
dialog.setOwnerActivity(MessageActivity.this);
dialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
dialog.show();
} else if(items[item].equals("Op")) {
conn.mode(cid, name, "+o " + selected_user.nick);
} else if(items[item].equals("Deop")) {
conn.mode(cid, name, "-o " + selected_user.nick);
} else if(items[item].equals("Kick")) {
view = inflater.inflate(R.layout.dialog_textprompt,null);
prompt = (TextView)view.findViewById(R.id.prompt);
input = (EditText)view.findViewById(R.id.textInput);
prompt.setText("Give a reason for kicking");
builder.setTitle(server.name + " (" + server.hostname + ":" + (server.port) + ")");
builder.setView(view);
builder.setPositiveButton("Kick", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
conn.kick(cid, name, selected_user.nick, input.getText().toString());
dialog.dismiss();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog = builder.create();
dialog.setOwnerActivity(MessageActivity.this);
dialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
dialog.show();
} else if(items[item].equals("Ban")) {
view = inflater.inflate(R.layout.dialog_textprompt,null);
prompt = (TextView)view.findViewById(R.id.prompt);
input = (EditText)view.findViewById(R.id.textInput);
input.setText("*!"+selected_user.hostmask);
prompt.setText("Add a banmask for " + selected_user.nick);
builder.setTitle(server.name + " (" + server.hostname + ":" + (server.port) + ")");
builder.setView(view);
builder.setPositiveButton("Ban", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
conn.mode(cid, name, "+b " + input.getText().toString());
dialog.dismiss();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog = builder.create();
dialog.setOwnerActivity(MessageActivity.this);
dialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
dialog.show();
}
dialogInterface.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.setOwnerActivity(this);
dialog.show();
}
@Override
public void onBufferSelected(int cid, int bid, String name,
long last_seen_eid, long min_eid, String type, int joined,
int archived, String status) {
if(scrollView != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
scrollView.smoothScrollTo(buffersListView.getWidth(), 0);
upView.setVisibility(View.VISIBLE);
}
if(bid != this.bid) {
for(int i = 0; i < backStack.size(); i++) {
if(backStack.get(i) == this.bid)
backStack.remove(i);
}
backStack.add(0, this.bid);
this.cid = cid;
this.bid = bid;
this.name = name;
this.type = type;
this.joined = joined;
this.archived = archived;
this.status = status;
title.setText(name);
getSupportActionBar().setTitle(name);
update_subtitle();
Bundle b = new Bundle();
b.putInt("cid", cid);
b.putInt("bid", bid);
b.putLong("last_seen_eid", last_seen_eid);
b.putLong("min_eid", min_eid);
b.putString("name", name);
b.putString("type", type);
BuffersListFragment blf = (BuffersListFragment)getSupportFragmentManager().findFragmentById(R.id.BuffersList);
MessageViewFragment mvf = (MessageViewFragment)getSupportFragmentManager().findFragmentById(R.id.messageViewFragment);
UsersListFragment ulf = (UsersListFragment)getSupportFragmentManager().findFragmentById(R.id.usersListFragment);
if(blf != null)
blf.setSelectedBid(bid);
if(mvf != null)
mvf.setArguments(b);
if(ulf != null)
ulf.setArguments(b);
AlphaAnimation anim = new AlphaAnimation(1, 0);
anim.setDuration(100);
anim.setFillAfter(true);
mvf.getListView().startAnimation(anim);
ulf.getListView().startAnimation(anim);
shouldFadeIn = true;
updateUsersListFragmentVisibility();
invalidateOptionsMenu();
Notifications.getInstance().excludeBid(bid);
Notifications.getInstance().showNotifications(null);
}
}
public void showUpButton(boolean show) {
if(upView != null) {
if(show) {
upView.setVisibility(View.VISIBLE);
} else {
upView.setVisibility(View.INVISIBLE);
}
}
}
@Override
public void onMessageViewReady() {
if(shouldFadeIn) {
MessageViewFragment mvf = (MessageViewFragment)getSupportFragmentManager().findFragmentById(R.id.messageViewFragment);
UsersListFragment ulf = (UsersListFragment)getSupportFragmentManager().findFragmentById(R.id.usersListFragment);
AlphaAnimation anim = new AlphaAnimation(0, 1);
anim.setDuration(100);
anim.setFillAfter(true);
mvf.getListView().startAnimation(anim);
ulf.getListView().startAnimation(anim);
shouldFadeIn = false;
}
}
}
|
package com.kopysoft.chronos.content;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;
import com.kopysoft.chronos.enums.Defines;
import com.kopysoft.chronos.types.Day;
import com.kopysoft.chronos.types.HoldNote;
import com.kopysoft.chronos.types.Note;
import com.kopysoft.chronos.types.Punch;
public class Chronos extends SQLiteOpenHelper {
private static final String TAG = "Chronos - SQL";
//0.9 = 7
//1.0.1 = 10
private static final int DATABASE_VERSION = 10;
public static final String TABLE_NAME_CLOCK = "clockactions";
public static final String TABLE_NAME_NOTE = "notes";
public static final String TABLE_NAME_OTHER = "misc";
public static final String DATABASE_NAME = "Chronos";
String insertString = "INSERT INTO " + TABLE_NAME_CLOCK + "(punch_type, time, actionReason) VALUES (?, ?, ?)";
String insertNote = "INSERT INTO " + TABLE_NAME_NOTE + "(note_string, time) VALUES (?, ?)";
public static final String insertLunch = "INSERT INTO " +
TABLE_NAME_OTHER + "(day, lunchTaken) VALUES (?, ?)";
public Chronos(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME_CLOCK +
" ( _id INTEGER PRIMARY KEY NOT NULL, punch_type INTEGER NOT NULL, time LONG NOT NULL, actionReason INTEGER NOT NULL )");
db.execSQL("CREATE TABLE " + TABLE_NAME_NOTE +
" ( _id LONG PRIMARY KEY, note_string TEXT NOT NULL, time LONG NOT NULL )");
db.execSQL("CREATE TABLE " + TABLE_NAME_OTHER +
" ( _id INTEGER PRIMARY KEY NOT NULL, day LONG NOT NULL, lunchTaken INTEGER NOT NULL ) ");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database, this will drop tables and recreate.");
Log.w(TAG, "oldVerion: " + oldVersion + "\tnewVersion: " + newVersion);
if ( oldVersion == 3 ){
db.execSQL("CREATE TABLE " + TABLE_NAME_NOTE +
" ( _id INTEGER PRIMARY KEY, note_string TEXT NOT NULL, time LONG NOT NULL )");
}
Log.d(TAG, "Update");
ArrayList<HoldNote> Notes = null;
try{
Notes = getNotes(db);
} catch (SQLiteException e){
try{
Notes = getNotes(db);
} catch( SQLiteException e2){
throw(e2);
}
}
ArrayList<Punch> punches = new ArrayList<Punch>();
Cursor cursor = db.query(TABLE_NAME_CLOCK, new String[] { "_id","punch_type", "time" },
null, null, null, null, "_id desc");
final int colId = cursor.getColumnIndex("_id");
final int colTime = cursor.getColumnIndex("time");
final int colType = cursor.getColumnIndex("punch_type");
if (cursor.moveToFirst()) {
do {
long id = cursor.getLong(colId);
long time = cursor.getLong(colTime);
int type = cursor.getInt(colType);
Punch temp = new Punch(time, type, id, Defines.REGULAR_TIME);
punches.add(temp);
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
dropAll(db);
for(int i = 0; i < punches.size(); i++){
Punch temp = punches.get(i);
temp.setNeedToUpdate(true);
temp.removeId();
temp.commitToDb(db);
}
reloadNotes(db, Notes);
}
/**
* This method is intended to be used ONLY for testing purposes!!
*
*/
public void replacePunches(ArrayList<Punch> punches){
SQLiteDatabase db = getWritableDatabase();
for(int i = 0; i < punches.size(); i++){
Punch temp = punches.get(i);
temp.setNeedToUpdate(true);
temp.removeId();
temp.commitToDb(db);
}
db.close();
}
/**
* This method is intended to be used ONLY for testing purposes!!
*
* @return a list of the punches, so it is able to be restored
*/
public ArrayList<Punch> getPunces(){
SQLiteDatabase db = getReadableDatabase();
ArrayList<Punch> punches = new ArrayList<Punch>();
Cursor cursor = db.query(TABLE_NAME_CLOCK, new String[] { "_id","punch_type", "time" },
null, null, null, null, "_id desc");
final int colId = cursor.getColumnIndex("_id");
final int colTime = cursor.getColumnIndex("time");
final int colType = cursor.getColumnIndex("punch_type");
if (cursor.moveToFirst()) {
do {
long id = cursor.getLong(colId);
long time = cursor.getLong(colTime);
int type = cursor.getInt(colType);
Punch temp = new Punch(time, type, id, Defines.REGULAR_TIME);
punches.add(temp);
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
db.close();
return punches;
}
private void reloadNotes(SQLiteDatabase db, ArrayList<HoldNote> Notes){
for( int i = 0; i < Notes.size(); i++ ){
SQLiteStatement insertStmt = db.compileStatement(insertNote);
insertStmt.bindString(1, Notes.get(i).getText() );
insertStmt.bindLong(2, Notes.get(i).getTime() );
insertStmt.executeInsert();
Log.d(TAG, "Adding entry: " + i);
} //end loop
}
// SQL Section
/**
*
* @param xml_info List of XMLDay's from XML file
*
* @note This will destroy the DB. Use carefully!
*/
public void replaceFromXML(List<Day> xml_info, Object context){
SQLiteDatabase db = getWritableDatabase();
//delete DBgetApplicationContext
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_CLOCK);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_NOTE);
//Create DB
db.execSQL("CREATE TABLE " + TABLE_NAME_CLOCK +
" ( _id INTEGER PRIMARY KEY, punch_type INTEGER NOT NULL, time LONG NOT NULL )");
db.execSQL("CREATE TABLE " + TABLE_NAME_NOTE +
" ( _id INTEGER PRIMARY KEY, note_string TEXT NOT NULL, time LONG NOT NULL )");
for(int i = 0; i < xml_info.size(); i++){
Day workingDay = xml_info.get(i);
if(workingDay.getNote(false).trim() != ""){
int[] dayTime = { workingDay.getDay()[0],
workingDay.getDay()[1], workingDay.getDay()[2]};
Note newNote = null;
if(context.getClass().equals(Chronos.class) == true){
newNote = new Note(dayTime,(Chronos)context);
} else if(context.getClass().equals(Context.class) == true) {
newNote = new Note(dayTime,(Context)context);
} else {
return;
}
newNote.setNote(workingDay.getNote(true));
newNote.update();
}
workingDay.forceWrite();
}
}
/**
*
* @return Returns list of HoldNote's
*/
private ArrayList<HoldNote> getNotes(SQLiteDatabase db){
ArrayList<HoldNote> returnValue = new ArrayList<HoldNote>();
Cursor cursor = db.query(TABLE_NAME_NOTE, new String[] { "note_string", "time" },
null, null, null, null, "time ASC ");
long time_temp;
String text_temp;
HoldNote tempNote = null;
if (cursor.moveToFirst()) {
do {
final int colNote = cursor.getColumnIndex("note_string");
final int colTime = cursor.getColumnIndex("time");
text_temp = cursor.getString(colNote);
time_temp = cursor.getLong(colTime);
tempNote = new HoldNote(time_temp, text_temp);
returnValue.add(tempNote);
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return returnValue;
}
/**
* Checks to see if the user has stayed clocked in over midnight and will clock them out
*/
/*
public boolean checkForMidnight(){
GregorianCalendar cal = new GregorianCalendar();
SQLiteDatabase db = getWritableDatabase();
boolean returnValue = false;
int[] date1 = new int[2];
int[] date2 = new int[2];
date1[0] = cal.get(Calendar.DAY_OF_YEAR);
date1[1] = cal.get(Calendar.YEAR);
Cursor cursor = db.query(TABLE_NAME_CLOCK, new String[] { "punch_type", "time" },
null, null, null,
null, "time ASC "); //Get all time punches between today at midnight and midnight
if(cursor.moveToLast()){
int punch = (int)cursor.getLong(0);
long time = cursor.getLong(1);
if ( punch == Defines.IN ){
cal.setTimeInMillis(time);
date2[0] = cal.get(Calendar.DAY_OF_YEAR);
date2[1] = cal.get(Calendar.YEAR);
Punch newPunch = null;
//Check if they are the same
//if the day of year are not the same or years are not the same
if( ( date2[0] != date1[0]) || (date2[1] != date1[1]) ){
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
cal.set(Calendar.MILLISECOND, 0);
long temp = cal.getTimeInMillis();
newPunch = new Punch()
//insertTime(db, Defines.OUT, temp);
cal.add(Calendar.DAY_OF_YEAR, 1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 1);
cal.set(Calendar.MILLISECOND, 0);
date2[0] = cal.get(Calendar.DAY_OF_YEAR);
date2[1] = cal.get(Calendar.YEAR);
//check to see that the new day is todays
if( ( date2[0] == date1[0]) || (date2[1] == date1[1]) ){
temp = cal.getTimeInMillis();
//insertTime(db, Defines.IN, temp);
}
returnValue = true;
}
}
}
cursor.close();
db.close();
return returnValue;
}
*/
/**
* Drops TABLE_NAME and then recreates the database
*/
public void dropAll(){
SQLiteDatabase db = getWritableDatabase();
Log.w(TAG, "Dropping tables then recreate.");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_CLOCK);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_NOTE);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_OTHER);
onCreate(db);
db.close();
}
public void dropAll(SQLiteDatabase db){
Log.w(TAG, "Dropping tables then recreate.");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_CLOCK);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_NOTE);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_OTHER);
onCreate(db);
}
/**
* Prints all entries in the database
*/
public void printAll(){
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME_CLOCK, new String[] { "_id","punch_type", "time" },
null, null, null, null, "_id desc");
long arg1, arg2, arg3;
int hour, min, sec, month, day, year;
GregorianCalendar cal = new GregorianCalendar();
int colType = cursor.getColumnIndex("punch_type");
int colTime = cursor.getColumnIndex("time");
int colId = cursor.getColumnIndex("_id");
if ( Defines.DEBUG_PRINT )Log.d(TAG, "Print All: ");
if (cursor.moveToFirst()) {
do {
arg1 = cursor.getLong(colType);
arg2 = cursor.getLong(colTime);
arg3 = cursor.getLong(colId);
cal.setTimeInMillis(arg2);
hour = cal.get(Calendar.HOUR_OF_DAY);
min = cal.get(Calendar.MINUTE);
sec = cal.get(Calendar.SECOND);
day = cal.get(Calendar.DAY_OF_MONTH);
month = cal.get(Calendar.MONTH);
year = cal.get(Calendar.YEAR);
if ( Defines.DEBUG_PRINT )Log.d(TAG, "ID: " + arg3 + "\tTime:" + arg2 + "\tPunch Type: " +
arg1 + "\t" + month + "/" + day +
"/" + year + " - " + hour + ":" + min + ":" + sec);
} while (cursor.moveToNext());
cursor.close();
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
db.close();
}
/**
* Gets the start of the current pay period
* @param dateGiven The start date of any payperiod [year, month, day]
* @param weeks_in_pp number of weeks in the pay period
* @return [year, month, day] of the current pay period
*/
public static int[] getPP(int[] dateGiven, int weeks_in_pp){
int[] returnValue = new int[3];
GregorianCalendar cal1 = new GregorianCalendar();
GregorianCalendar cal2 = new GregorianCalendar(dateGiven[0], dateGiven[1], dateGiven[2]);
long time1 = cal1.getTimeInMillis();
long time2 = cal2.getTimeInMillis();
long diff = time1 - time2;
diff = diff / 1000; //convert ms to s
int weeks = (int) diff / 60 / 60 / 24 / 7;
int pp_diff = weeks / weeks_in_pp;
if ( Defines.DEBUG_PRINT )Log.d(TAG, "days to add: " + (pp_diff * weeks_in_pp * 7) );
cal2.add(Calendar.DAY_OF_YEAR, pp_diff * weeks_in_pp * 7);
returnValue[0] = cal2.get(Calendar.YEAR);
returnValue[1] = cal2.get(Calendar.MONTH);
returnValue[2] = cal2.get(Calendar.DAY_OF_MONTH);
if ( Defines.DEBUG_PRINT )Log.d(TAG, "Start of PP - Y: " + returnValue[0] + "\tM: " +
returnValue[1] + "\tD: " + returnValue[2]);
if ( Defines.DEBUG_PRINT )Log.d(TAG, "Origonal PP: - Y: " + dateGiven[0] + "\tM: " +
dateGiven[1] + "\tD: " + dateGiven[2]);
return returnValue;
}
public static int[] getDate(String date){
String temp[] = date.split("\\.");
int[] returnValue = new int[3];
returnValue[0] = Integer.parseInt(temp[0]);
returnValue[1] = Integer.parseInt(temp[1]) - 1;
returnValue[2] = Integer.parseInt(temp[2]);
return returnValue;
}
}
|
package com.novell.spsample.client;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.Widget;
import com.novell.spiffyui.client.MessageUtil;
import com.novell.spiffyui.client.widgets.FormFeedback;
import com.novell.spiffyui.client.widgets.button.FancyButton;
import com.novell.spiffyui.client.widgets.button.FancySaveButton;
/**
* This is the form sample panel
*
*/
public class FormPanel extends HTMLPanel implements KeyUpHandler
{
private static final SPSampleStrings STRINGS = (SPSampleStrings) GWT.create(SPSampleStrings.class);
private static final String CONTENTS =
"<fieldset id=\"Page2Fields\">" +
"<h2 class=\"sectionTitle\">Sample user form fieldset</h2>" +
"<ol class=\"dialogformsection\">" +
"<li id=\"firstNameRow\" class=\"dialogformrow\"><label class=\"dialogformlabel\" for=\"firstNameTxt\">First name: " +
"</label><div id=\"firstName\" class=\"formcontrolssection\"></div></li>" +
"<li id=\"lastNameRow\" class=\"dialogformrow\"><label class=\"dialogformlabel\" for=\"lastNameTxt\">Last name: " +
"</label><div id=\"lastName\" class=\"formcontrolssection\"></div></li>" +
"<li id=\"emailRow\" class=\"dialogformrow\"><label class=\"dialogformlabel\" for=\"emailTxt\">Email address: " +
"</label><div id=\"email\" class=\"formcontrolssection\"></div></li>" +
"<li id=\"passwordRow\" class=\"dialogformrow\"><label class=\"dialogformlabel\" for=\"passwordTxt\">Password: " +
"</label><div id=\"password\" class=\"formcontrolssection\"></div></li>" +
"<li id=\"passwordRepeatRow\" class=\"dialogformrow\"><label class=\"dialogformlabel\" for=\"passwordRepeatTxt\">Repeat password: " +
"</label><div id=\"passwordRepeat\" class=\"formcontrolssection\"></div></li>" +
"<li id=\"userDescRow\" class=\"extratallformrow\"><label class=\"dialogformlabel\" for=\"userDescTxt\">Short description: " +
"</label><div id=\"userDesc\" class=\"formcontrolssection\"></div></li>" +
"<li id=\"page2ButtonsRow\" class=\"dialogformrow\"><div id=\"page2Buttons\" class=\"formcontrolssection\"></div></li>" +
"</ol>" +
"</fieldset>";
private TextBox m_firstName;
private FormFeedback m_firstNameFeedback;
private TextBox m_lastName;
private FormFeedback m_lastNameFeedback;
private TextBox m_email;
private FormFeedback m_emailFeedback;
private TextBox m_password;
private FormFeedback m_passwordFeedback;
private TextBox m_passwordRepeat;
private FormFeedback m_passwordRepeatFeedback;
private TextArea m_userDesc;
private FormFeedback m_userDescFeedback;
private FancyButton m_save;
/**
* Creates a new import panel
*/
public FormPanel()
{
super("div", "<h1>Spiffy Forms</h1>" + STRINGS.FormPanel_html() + CONTENTS);
getElement().setId("formPanel");
RootPanel.get("mainContent").add(this);
setVisible(false);
/*
First name
*/
m_firstName = new TextBox();
m_firstName.addKeyUpHandler(this);
m_firstName.getElement().setId("firstNameTxt");
m_firstName.getElement().addClassName("wideTextField");
add(m_firstName, "firstName");
m_firstNameFeedback = new FormFeedback();
add(m_firstNameFeedback, "firstNameRow");
/*
Last name
*/
m_lastName = new TextBox();
m_lastName.addKeyUpHandler(this);
m_lastName.getElement().setId("lastNameTxt");
m_lastName.getElement().addClassName("wideTextField");
add(m_lastName, "lastName");
m_lastNameFeedback = new FormFeedback();
add(m_lastNameFeedback, "lastNameRow");
/*
email
*/
m_email = new TextBox();
m_email.addKeyUpHandler(this);
m_email.getElement().setId("emailTxt");
m_email.getElement().addClassName("wideTextField");
add(m_email, "email");
m_emailFeedback = new FormFeedback();
add(m_emailFeedback, "emailRow");
/*
Password
*/
m_password = new PasswordTextBox();
m_password.addKeyUpHandler(this);
m_password.getElement().setId("passwordTxt");
m_password.getElement().addClassName("slimTextField");
add(m_password, "password");
m_passwordFeedback = new FormFeedback();
add(m_passwordFeedback, "passwordRow");
/*
Password repeat
*/
m_passwordRepeat = new PasswordTextBox();
m_passwordRepeat.addKeyUpHandler(this);
m_passwordRepeat.getElement().setId("passwordRepeatTxt");
m_passwordRepeat.getElement().addClassName("slimTextField");
add(m_passwordRepeat, "passwordRepeat");
m_passwordRepeatFeedback = new FormFeedback();
add(m_passwordRepeatFeedback, "passwordRepeatRow");
/*
User description
*/
m_userDesc = new TextArea();
m_userDesc.addKeyUpHandler(this);
m_userDesc.getElement().setId("userDescTxt");
m_userDesc.getElement().addClassName("wideTextField");
add(m_userDesc, "userDesc");
m_userDescFeedback = new FormFeedback();
add(m_userDescFeedback, "userDescRow");
/*
The big save button
*/
m_save = new FancySaveButton("Save");
m_save.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event)
{
save();
}
});
add(m_save, "page2Buttons");
updateFormStatus(null);
}
@Override
public void onKeyUp(KeyUpEvent event)
{
if (event.getNativeKeyCode() != KeyCodes.KEY_TAB) {
updateFormStatus((Widget) event.getSource());
}
}
private void updateFormStatus(Widget w)
{
if (w == m_firstName) {
if (m_firstName.getText().length() > 2) {
m_firstNameFeedback.setStatus(FormFeedback.VALID);
} else {
m_firstNameFeedback.setStatus(FormFeedback.WARNING);
}
} else if (w == m_lastName) {
if (m_lastName.getText().length() > 2) {
m_lastNameFeedback.setStatus(FormFeedback.VALID);
} else {
m_lastNameFeedback.setStatus(FormFeedback.WARNING);
}
} else if (w == m_email) {
if (m_email.getText().length() > 2) {
m_emailFeedback.setStatus(FormFeedback.VALID);
} else {
m_emailFeedback.setStatus(FormFeedback.WARNING);
}
} else if (w == m_password) {
if (m_password.getText().length() > 2) {
m_passwordFeedback.setStatus(FormFeedback.VALID);
} else {
m_passwordFeedback.setStatus(FormFeedback.WARNING);
}
} else if (w == m_passwordRepeat) {
if (m_passwordRepeat.getText().length() > 2) {
if (m_passwordRepeat.getText().equals(m_password.getText())) {
m_passwordRepeatFeedback.setStatus(FormFeedback.VALID);
m_passwordRepeatFeedback.setTitle("");
} else {
m_passwordRepeatFeedback.setStatus(FormFeedback.ERROR);
m_passwordRepeatFeedback.setTitle("Make sure your two passwords match.");
}
} else {
m_passwordRepeatFeedback.setStatus(FormFeedback.WARNING);
m_passwordRepeatFeedback.setTitle("");
}
} else if (w == m_userDesc) {
if (m_userDesc.getText().length() > 8) {
m_userDescFeedback.setStatus(FormFeedback.VALID);
} else {
m_userDescFeedback.setStatus(FormFeedback.WARNING);
}
}
m_save.setEnabled(m_firstName.getText().length() > 2 &&
m_lastName.getText().length() > 2 &&
m_email.getText().length() > 2 &&
m_password.getText().length() > 2 &&
m_passwordRepeat.getText().length() > 2 &&
m_passwordRepeat.getText().equals(m_password.getText()) &&
m_userDesc.getText().length() > 8);
}
private void save()
{
MessageUtil.showMessage("This form doesn't save anything.");
}
}
|
package com.radans.TerrainTiler;
import com.jme3.app.Application;
import com.jme3.app.SimpleApplication;
import com.jme3.app.state.AppState;
import com.jme3.app.state.AppStateManager;
import com.jme3.asset.DesktopAssetManager;
import com.jme3.asset.ModelKey;
import com.jme3.asset.plugins.ClasspathLocator;
import com.jme3.asset.plugins.FileLocator;
import com.jme3.asset.plugins.ZipLocator;
import com.jme3.export.binary.BinaryImporter;
import com.jme3.font.plugins.BitmapFontLoader;
import com.jme3.material.Material;
import com.jme3.material.plugins.J3MLoader;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Vector2f;
import com.jme3.math.Vector3f;
import com.jme3.renderer.Camera;
import com.jme3.renderer.RenderManager;
import com.jme3.scene.Node;
import com.jme3.shader.plugins.GLSLLoader;
import com.jme3.terrain.ProgressMonitor;
import com.jme3.terrain.Terrain;
import com.jme3.terrain.geomipmap.MultiTerrainLodControl;
import com.jme3.terrain.geomipmap.NeighbourFinder;
import com.jme3.terrain.geomipmap.TerrainQuad;
import com.jme3.terrain.geomipmap.lodcalc.DistanceLodCalculator;
import com.jme3.texture.plugins.AWTLoader;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* TerrainTiler class for managing very large terrains over an array of tiles
* each being a TerrainQuad.
*
* @author Radan Vowles
*
*/
public class TerrainTiler extends Node implements Terrain, NeighbourFinder {
private static float version = 2013.1118f;
private static int maxTiles = 4096;
protected static final Logger tLog = Logger.getLogger(TerrainTiler.class.getCanonicalName());
private final DesktopAssetManager dAssetManager;
private volatile MultiTerrainLodControl terrainMLOD;
private volatile boolean terrainLocked; // disable editing if true
private volatile boolean useJars; // true if tiles packed into jars
private volatile TerrainState terrainState; // appState for updates
private ConcurrentHashMap<Integer, TerrainQuad> tileSet; // Array of tiles
private ConcurrentHashMap<Integer, Integer> tileFlag; // Array of tiles
private volatile terrainThread tThread; // Thread for tile updates
private volatile boolean threadState; // State of thread (running or not)
private volatile boolean newTile; // flag to alert to tile changes
private volatile Camera camera; // Referance to camera to track movement for updates
private volatile int numTilesX; // number of tiles in the X direction
private volatile int numTilesZ; // number of tiles in the Z direction
private volatile int tileSize; // size of each tile - power of 2
private volatile int tileScale; // scale of each tile for world view
private volatile int tileWSize; // world size (scaled) of each tile
private volatile String tileLocator; // Locator for asset loader to find tiles
private volatile String terrainMapFile; // location and name of map file
private volatile SimpleApplication app; // app calling hooks
private volatile int gridSize; // number of tiles viewable (3, 5, 7, 9);
private volatile int gridCenterX; // center of viewable grid
private volatile int gridCenterZ; // center of viewable grid
private Set<TerrainTilerAction> actionHooks = new HashSet<>();
public boolean valid = false; // true if terrain initialized, false if somethings wrong;
public int mapVersion = 0;
/**
* Constructor for new TerrainTiler object using a 3x3 tile grid as default
* Uses the new <tiledTerrain>.map file system for details on the map tile data.
*
* @param cam - Camera to track movement for tile load/unload.
* @param tLocator - Full pathname for the <tiledTerrain>.map file to load.
* This file containes all the details on the map tiles, size etc
* Should be absolute path and filename for loading.
* line 1: tiledTerrain : <version> // eg "tiledTerrain : 19
* line 2: useJars : <true|false> // are tiles packed into jars
* line 3: numTilesX : <16...4096> // number tiles in X direction
* line 4: numTilesZ : <16...4096> // number tiles in Z direction
* line 5: tileSize : <256...2048> // base size of each tile
* line 6: tileScale : <scale> // scale factors for each tile
* line 7: tileType : <image|terrain|node> // tile file type
* @param caller - SimpleApplication calling us to attach appState to
*/
public TerrainTiler(Camera cam, String tLocator, SimpleApplication caller) {
this.setName("TiledTerrainNode");
this.camera = cam;
this.app = caller;
this.terrainLocked = true; // by default lock out editing
this.gridSize = 3; // default to 3x3 grid
this.terrainMapFile = tLocator;
this.valid = false;
dAssetManager = new DesktopAssetManager();
dAssetManager.registerLocator("/", ClasspathLocator.class);
dAssetManager.registerLoader(J3MLoader.class, "j3md");
dAssetManager.registerLoader(GLSLLoader.class, "vert");
dAssetManager.registerLoader(GLSLLoader.class, "frag");
dAssetManager.registerLoader(GLSLLoader.class, "glsl");
dAssetManager.registerLoader(GLSLLoader.class, "glsllib");
dAssetManager.registerLoader(BinaryImporter.class, "j3o");
dAssetManager.registerLoader(BitmapFontLoader.class, "fnt");
dAssetManager.registerLoader(AWTLoader.class, "png");
// todo
/** load in <tiledTerrain>.map file and parse parameters....*/
File file = new File(tLocator);
if (file.exists()) {
try {
tileLocator = file.getParentFile().getCanonicalPath();
FileReader fRead = new FileReader(file);
BufferedReader bRead = new BufferedReader(fRead);
String rLine = bRead.readLine();
if (rLine.startsWith("tiledTerrain")) {
mapVersion = Integer.valueOf(rLine.substring(15));
rLine = bRead.readLine();
useJars = Boolean.valueOf(rLine.substring(12));
rLine = bRead.readLine();
numTilesX = Integer.valueOf(rLine.substring(12));
rLine = bRead.readLine();
numTilesZ = Integer.valueOf(rLine.substring(12));
rLine = bRead.readLine();
tileSize = Integer.valueOf(rLine.substring(12));
rLine = bRead.readLine();
tileScale = Integer.valueOf(rLine.substring(12));
rLine = bRead.readLine();
if (rLine.substring(12).startsWith("terrain")) {
this.valid = true;
if (numTilesX < 16 | numTilesX > 4096 | numTilesZ < 16 | numTilesZ > 4096) {
this.valid = false;
}
if (tileSize != 256 & tileSize != 512 & tileSize != 1024 & tileSize != 2048) {
this.valid = false;
}
if (tileScale == 0) {
this.valid = false;
}
}
bRead.close();
fRead.close();
}
} catch (IOException ex) {
Logger.getLogger(TerrainTiler.class.getName()).log(Level.SEVERE, "Error loading tiledTerrain.map {0}", ex);
}
}
if (!this.valid) {
Logger.getLogger(TerrainTiler.class.getName()).log(Level.SEVERE, "Cannot initialize tiledTerrain - tiledTerrain.map file does not exist at given location.");
return;
}
// we have a valid mapfile - initialise the tiledterrain
if (!this.useJars) {
dAssetManager.registerLocator(tileLocator, FileLocator.class);
} else {
for (int z = 0; z < (numTilesZ / 64) + 1; z++) {
for (int x = 0; x < (numTilesX / 64 + 1); x++) {
String jarFile = String.format("DIR-%02d%02d.jar", x, z);
tLog.log(Level.FINE, "Registering jar file: {0}{1}", new Object[]{tileLocator, jarFile});
dAssetManager.registerLocator(tileLocator + jarFile, ZipLocator.class);
}
}
}
// Check tile size by loading the origin one.
TerrainQuad tq = LoadTile(0, 0);
if (tq.getName().startsWith("OOB")) {
tLog.log(Level.SEVERE, "TerrainTiler: Origin Tile Not Found! Aborting...");
this.valid = false;
return;
}
if (this.tileSize != (tq.getTerrainSize() - 1)) {
tLog.log(Level.SEVERE, "TerrainTiler: Origin Tile size does not match mapfile! Aborting...");
this.valid = false;
return;
}
this.tileWSize = tileSize * tileScale;
int pSize = tileSize / 4;
// setup LOD system
terrainMLOD = new MultiTerrainLodControl(camera);
terrainMLOD.setLodCalculator(new DistanceLodCalculator(pSize + 1, 2.0f));
this.addControl(terrainMLOD);
// initialize our appState and attach it
terrainState = new TerrainState();
terrainState.initialize(app.getStateManager(), app);
app.getStateManager().attach(terrainState);
}
/**
* Constructor for new TerrainTiler object using a 3x3 tile grid as default
* manual way with no map file - restricted as follows:
*
* @param cam - Camera to track movement for tile load/unload.
* @param nTiles - Max number of tiles in the X & Z axis ( X==Z )
* @param uJars - Boolean true if tiles are packed into jars
* @param tScale - scale to apply to each tile to world size
* @param tLocator - Tile Locator - root directory for tile subfolders. -
* tiles loaded from <tLocator>/DIR-xxzz/TILE-xxzz.j3o - if useJars is true
* then load tiles from <tLocator>/DIR-xxzz.jar
* @param caller - SimpleApplication calling us to attach appState to
*/
public TerrainTiler(Camera cam, int nTiles, boolean uJars, int tScale, String tLocator, SimpleApplication caller) {
// Fill the local variables
this.setName("TerrainTilerNode");
this.camera = cam;
this.numTilesX = nTiles;
this.numTilesZ = nTiles;
this.useJars = uJars;
this.tileScale = tScale;
this.tileLocator = tLocator;
this.valid = false;
this.app = caller;
this.gridSize = 3; // default to 3x3 grid
this.terrainLocked = useJars;
this.tileSize = 128;
dAssetManager = new DesktopAssetManager();
dAssetManager.registerLocator("/", ClasspathLocator.class);
dAssetManager.registerLoader(J3MLoader.class, "j3md");
dAssetManager.registerLoader(GLSLLoader.class, "vert");
dAssetManager.registerLoader(GLSLLoader.class, "frag");
dAssetManager.registerLoader(GLSLLoader.class, "glsl");
dAssetManager.registerLoader(GLSLLoader.class, "glsllib");
dAssetManager.registerLoader(BinaryImporter.class, "j3o");
dAssetManager.registerLoader(BitmapFontLoader.class, "fnt");
dAssetManager.registerLoader(AWTLoader.class, "png");
if (!this.useJars) {
dAssetManager.registerLocator(tileLocator, FileLocator.class);
} else {
for (int z = 0; z < (numTilesZ / 64) + 1; z++) {
for (int x = 0; x < (numTilesX / 64 + 1); x++) {
String jarFile = String.format("DIR-%02d%02d.jar", x, z);
tLog.log(Level.FINE, "Registering jar file: {0}{1}", new Object[]{tileLocator, jarFile});
dAssetManager.registerLocator(tileLocator + jarFile, ZipLocator.class);
}
}
}
// Check tile size by loading the origin one.
TerrainQuad tq = LoadTile(0, 0);
if (tq.getName().startsWith("OOB")) {
tLog.log(Level.SEVERE, "TerrainTiler: Origin Tile Not Found! Aborting...");
return;
}
this.tileSize = tq.getTerrainSize() - 1;
this.tileWSize = tileSize * tileScale;
int pSize = tileSize / 4;
// setup LOD system
terrainMLOD = new MultiTerrainLodControl(camera);
terrainMLOD.setLodCalculator(new DistanceLodCalculator(pSize + 1, 2.0f));
this.addControl(terrainMLOD);
// initialize our appState and attach it
terrainState = new TerrainState();
terrainState.initialize(app.getStateManager(), app);
app.getStateManager().attach(terrainState);
this.valid = true;
}
/**
* Loads a tile from file and returns the TerrainQuad for it.
*
* @param tileX - Tile X location in grid
* @param tileZ - Tile Z location in grid
* @return TerrainQuad of loaded tile or null if OOB or no file found
*/
private synchronized TerrainQuad LoadTile(int tileX, int tileZ) {
try {
String tileName = String.format("TILE-%02d%02d.j3o", (tileX % 64), (tileZ % 64));
String dirName = String.format("DIR-%02d%02d/", (tileX / 64), (tileZ / 64));
tLog.log(Level.FINE, "Loading Tile: {0}{1}", new Object[]{dirName, tileName});
ModelKey mk = new ModelKey(dirName + tileName);
TerrainQuad tq = (TerrainQuad) dAssetManager.loadModel(mk);
tq.setLocalScale(tileScale, 1f, tileScale);
float ts = tileSize * tileScale;
float to = ts / 2;
tq.setLocalTranslation(new Vector3f(tileX * ts + to, 0f, tileZ * ts + to));
// this is needed as tiles come with separate materials for each
// patch so this makes the tile have one for all patches.
tq.setMaterial(tq.getMaterial());
// Debug LOD with wireframe: (if I dont do above only one patch will be wireframe!!)
//tq.getMaterial().getAdditionalRenderState().setWireframe(true);
tLog.log(Level.FINE, "Tile Loaded");
dAssetManager.deleteFromCache(mk);
return tq;
} catch (Exception ex) {
tLog.log(Level.WARNING, "Error loading tile!{0}", ex.getMessage());
float[] hMap = new float[(tileSize + 1) * (tileSize + 1)];
int pSize = tileSize / 4;
if (tileSize <= 64) {
pSize = tileSize;
} else if (tileSize == 128) {
pSize = 64;
}
String tileName = String.format("OOB%02d%02d%02d%02d",
(tileX / 64), (tileX % 64), (tileZ / 64), (tileZ % 64));
TerrainQuad oobQuad = new TerrainQuad(tileName, pSize + 1, tileSize + 1, hMap);
oobQuad.setLocalScale(tileScale);
float ts = tileSize * tileScale;
float to = ts / 2;
oobQuad.setLocalTranslation(new Vector3f(tileX * ts + to, 0f, tileZ * ts + to));
oobQuad.setNeighbourFinder(this);
Material mat = new Material(dAssetManager, "Common/MatDefs/Misc/Unshaded.j3md");
mat.setColor("Color", ColorRGBA.Green);
mat.getAdditionalRenderState().setWireframe(true);
oobQuad.setMaterial(mat);
return oobQuad;
}
}
/**
* return the library version
*/
public double getVersion() {
return version;
}
/**
* Set the camera we will track for loading tiles
*
* @param cam - Camera to track
*/
public void setCamera(Camera cam) {
this.camera = cam;
}
/**
* Gets the currently set root directory for finding the Tiles
*
* @return String containing the tile root directory
*/
public String getTileLocator() {
return this.tileLocator;
}
/**
* Sets the root directory in which to find the Tiles. Do not use while
* setEnabled(true)!
*
* @param directory - String with the root directory
*/
public void setTileLocator(String directory) {
dAssetManager.unregisterLocator(this.tileLocator, FileLocator.class);
this.tileLocator = directory;
dAssetManager.registerLocator(this.tileLocator, FileLocator.class);
}
/**
* Sets the size of the viewable grid Must be 3 or 5 or 7 or 9!
*
* @param size - int of size
*/
public void setGridSize(int size) {
if (size == 3 | size == 5 | size == 7 | size == 9) {
this.gridSize = size;
}
}
/**
* Get the current size of the viewable grid
*
* @return int of gridSize
*/
public int getGridSize() {
return gridSize;
}
/**
* Set the max number of terrain tiles to use in the X direction <16...4096>
* Do not set to less than current location or player will be plunged
* into the void!
*
* @param number
*/
public void setNumTilesX(int number) {
if (number > 4 & (number & (number - 1)) == 0) {
this.numTilesX = number;
}
}
/**
* Get the current max number of tiles in the X direction
*
* @return int number of tiles
*/
public int getNumTilesX() {
return numTilesX;
}
/**
* Set the max number of terrain tiles to use in the Z direction <16...4096>
* Do not set to less than current location or player will be plunged
* into the void!
*
* @param number
*/
public void setNumTilesZ(int number) {
if (number > 4 & (number & (number - 1)) == 0) {
this.numTilesZ = number;
}
}
/**
* Get the current max number of tiles in the Z direction
*
* @return int number of tiles
*/
public int getNumTilesZ() {
return numTilesZ;
}
/**
* Get the current tile size (unscaled)
*
* @return - int of size
*/
public int getTileSize() {
return tileSize;
}
/**
* Sets the scale to apply to each tile Do not use while setEnabled(true)!
*
* @param scale - int of scale factor
*/
public void setTileScale(int scale) {
if (scale > 0) {
this.tileScale = scale;
this.tileWSize = this.tileSize * this.tileScale;
}
}
/**
* Get the current tile scaling factor
*
* @return - int of scale
*/
public int getTileScale() {
return tileScale;
}
/**
* Enable the terrainState and run the tiler thread
*
* @param state - true to enable and start, false to disable and stop
*/
public void setEnabled(boolean state) {
terrainState.setEnabled(state);
}
/**
* Get the terrainState isEnabled state
*
* @return true|false
*/
public boolean getEnabled() {
return terrainState.isEnabled();
}
/**
* Adds a TerrainTilerAction Handler for parent program to handle events
* when new tiles and loaded or old tiles unloaded from the scene.
*
* @param handler TerrainTilerAction to add to action handlers
*/
public void addActionHandler(TerrainTilerAction handler) {
actionHooks.add(handler);
}
/**
* Removes a TerrainTilerAction handler from the list
*
* @param handler TerrainTilerAction to remove
*/
public void delActionHandler(TerrainTilerAction handler) {
actionHooks.remove(handler);
}
/**
* Get the interpolated height at the specified point
*
* @param xz = Vector2f of World Coordinate
* @return float of the height or NaN if tile not loaded
*/
@Override
public float getHeight(Vector2f xz) {
// work out which tile it is
int tx = (int) xz.x / tileWSize;
int tz = (int) xz.y / tileWSize;
int tk = tx + (tz * maxTiles);
if (tileSet.containsKey(tk)) {
return tileSet.get(tk).getHeight(xz);
} else {
return Float.NaN;
}
}
/**
* Return the normal for the specified point
*
* @param xz = Vector2f of World Coordinate
* @return Vector3f or the normal or .ZERO if tile not loaded
*/
@Override
public Vector3f getNormal(Vector2f xz) {
// work out which tile it is
int tx = (int) xz.x / tileWSize;
int tz = (int) xz.y / tileWSize;
int tk = tx + (tz * maxTiles);
if (tileSet.containsKey(tk)) {
return tileSet.get(tk).getNormal(xz);
} else {
return Vector3f.ZERO;
}
}
/**
* Get the unscaled HeightMap height at the specified point snapped to
* nearest grid point
*
* @param xz = Vector2f of World Coordinate
* @return float of the height or NaN if tile not loaded
*/
@Override
public float getHeightmapHeight(Vector2f xz) {
// work out which tile it is
int tx = (int) xz.x / tileWSize;
int tz = (int) xz.y / tileWSize;
int tk = tx + (tz * maxTiles);
if (tileSet.containsKey(tk)) {
return tileSet.get(tk).getHeightmapHeight(xz);
} else {
return Float.NaN;
}
}
/**
* Set the terrain Height at the specified World coordinate
*
* @param xzCoordinate - Vector2f World Coordinate x,z
* @param height - float of new height
*/
@Override
public void setHeight(Vector2f xzCoordinate, float height) {
if (!terrainLocked) {
int tx = (int) xzCoordinate.x / tileWSize;
int tz = (int) xzCoordinate.y / tileWSize;
int tk = tx + (tz * maxTiles);
if (tileSet.containsKey(tk)) {
tileSet.get(tk).setHeight(xzCoordinate, height);
}
}
}
/**
* Set the height of many points
*
* @param xz - List<Vector2f> of World Coordinates x,z
* @param height - List<Float> matching list of height values
*/
@Override
public void setHeight(List<Vector2f> xz, List<Float> height) {
if (!terrainLocked) {
Iterator it = tileFlag.keySet().iterator();
while (it.hasNext()) {
int ik = (Integer) it.next();
if (tileFlag.get(ik) == 3) {
tileSet.get(ik).setHeight(xz, height);
}
}
}
}
/**
* Adjust the height of a point up or down bu the amount specified
*
* @param xzCoordinate - Vector2f of the World Coordinate x,z
* @param delta - float to adjust the point by +/-
*/
@Override
public void adjustHeight(Vector2f xzCoordinate, float delta) {
if (!terrainLocked) {
int tx = (int) xzCoordinate.x / tileWSize;
int tz = (int) xzCoordinate.y / tileWSize;
int tk = tx + (tz * maxTiles);
if (tileSet.containsKey(tk)) {
tileSet.get(tk).adjustHeight(xzCoordinate, delta);
}
}
}
/**
* Adjust the height of many points
*
* @param xz - List<Vector2f> of World Coordinates x,z
* @param height - List<Float> matching list of height adjustment values
*/
@Override
public void adjustHeight(List<Vector2f> xz, List<Float> height) {
if (!terrainLocked) {
Iterator it = tileFlag.keySet().iterator();
while (it.hasNext()) {
int ik = (Integer) it.next();
if (tileFlag.get(ik) == 3) {
tileSet.get(ik).adjustHeight(xz, height);
}
}
}
}
/**
* Gets the heightmap of the terrain tile at the center of the current grid
*
* @return float array of the heightmap
*/
@Override
public float[] getHeightMap() {
int tk = gridCenterX + (gridCenterZ * maxTiles);
if (tileSet.containsKey(tk)) {
return tileSet.get(tk).getHeightMap();
} else {
return null;
}
}
/**
* Get the height map from the tile at the location in world coordinates.
*
* @param worldLocation in world coordinates
* @return float array of heightmap for tile at location
*/
public float[] getHeightMap(Vector3f worldLocation) {
// work out which tile it is
int tx = (int) worldLocation.x / tileWSize;
int tz = (int) worldLocation.z / tileWSize;
int tk = tx + (tz * maxTiles);
if (tileSet.containsKey(tk)) {
return tileSet.get(tk).getHeightMap();
} else {
return null;
}
}
/**
* Get the maximum LOD of the center terrain tile
*
* @return int of the current setting.
*/
@Override
public int getMaxLod() {
int tk = gridCenterX + (gridCenterZ * maxTiles);
if (tileSet.containsKey(tk)) {
return tileSet.get(tk).getMaxLod();
} else {
return 1;
}
}
/**
* Set locking of terrain changes
*
* @param locked - true to lock changes, false to allow. Note that if loading
* tiles from jars then terrain will always be locked
*/
@Override
public void setLocked(boolean locked) {
if (!useJars) {
terrainLocked = locked;
}
}
/**
* Check if terrain is locked from changes
* @return boolean
*/
public boolean isLocked() {
return terrainLocked;
}
/**
* Generate entropies
*
* @param monitor ProgressMonitor
*/
@Override
public void generateEntropy(ProgressMonitor monitor) {
if (!terrainLocked) {
Iterator it = tileFlag.keySet().iterator();
while (it.hasNext()) {
int ik = (Integer) it.next();
if (tileFlag.get(ik) == 3) {
tileSet.get(ik).generateEntropy(monitor);
}
}
}
}
/**
* Get the material that the current center tile uses
*
* @return Material of centered tile or null if no tile loaded
*/
@Override
public Material getMaterial() {
int tk = gridCenterX + (gridCenterZ * maxTiles);
if (tileSet.containsKey(tk)) {
return tileSet.get(tk).getMaterial();
} else {
return null;
}
}
/**
* Get the material of the terrain at the specified World location
*
* @param worldLocation - Vector3f of the World Coordinate x,y,z
* @return Material of tile at that location or null if no tile loaded
* there.
*/
@Override
public Material getMaterial(Vector3f worldLocation) {
int tx = (int) worldLocation.x / tileWSize;
int tz = (int) worldLocation.y / tileWSize;
int tk = tx + (tz * maxTiles);
if (tileSet.containsKey(tk)) {
return tileSet.get(tk).getMaterial();
} else {
return null;
}
}
/**
* Sets the material for the TerrainQuad tile at the given world location
* provided that tile has been loaded.
*
* @param worldLocation of tile to set
* @param mat material to place on tile
*/
public void setMaterial(Vector3f worldLocation, Material mat) {
int tx = (int) worldLocation.x / tileWSize;
int tz = (int) worldLocation.y / tileWSize;
int tk = tx + (tz * maxTiles);
if (tileSet.containsKey(tk)) {
tileSet.get(tk).setMaterial(mat);
}
}
/**
* Get the terrain size - number of vertices along the side of one tile
*
* @return int of terrain size
*/
@Override
public int getTerrainSize() {
return tileSize;
}
/**
*
* @return 1
*/
@Override
public int getNumMajorSubdivisions() {
return 1;
}
/*
* For NeigborFinder LOD routines
* gets the quad to centers right (+x)
*
* @param center TerrainQuad
* @return TerrainQuad to the right
*/
@Override
public TerrainQuad getRightQuad(TerrainQuad center) {
int tx = (int) center.getLocalTranslation().x / tileWSize;
int tz = (int) center.getLocalTranslation().z / tileWSize;
if (tx < numTilesX - 1) {
tx++;
int tk = tx + (tz * maxTiles);
if (tileSet.containsKey(tk)) {
return tileSet.get(tk);
}
}
return null;
}
/**
* For NeigborFinder LOD routines gets the quad to centers left (-x)
*
* @param center TerrainQuad
* @return TerrainQuad to the left
*/
@Override
public TerrainQuad getLeftQuad(TerrainQuad center) {
int tx = (int) center.getLocalTranslation().x / tileWSize;
int tz = (int) center.getLocalTranslation().z / tileWSize;
if (tx > 0) {
tx
int tk = tx + (tz * maxTiles);
if (tileSet.containsKey(tk)) {
return tileSet.get(tk);
}
}
return null;
}
/**
* For NeigborFinder LOD routines gets the quad to centers down (+z)
*
* @param center TerrainQuad
* @return TerrainQuad down
*/
@Override
public TerrainQuad getDownQuad(TerrainQuad center) {
int tx = (int) center.getLocalTranslation().x / tileWSize;
int tz = (int) center.getLocalTranslation().z / tileWSize;
if (tz < numTilesZ - 1) {
tz++;
int tk = tx + (tz * maxTiles);
if (tileSet.containsKey(tk)) {
return tileSet.get(tk);
}
}
return null;
}
/**
* For NeigborFinder LOD routines gets the quad to centers top (-z)
*
* @param center TerrainQuad
* @return TerrainQuad top
*/
@Override
public TerrainQuad getTopQuad(TerrainQuad center) {
int tx = (int) center.getLocalTranslation().x / tileWSize;
int tz = (int) center.getLocalTranslation().z / tileWSize;
if (tz > 0) {
tz
int tk = tx + (tz * maxTiles);
if (tileSet.containsKey(tk)) {
return tileSet.get(tk);
}
}
return null;
}
private class terrainThread extends Thread {
private boolean firstRun;
/*
* terrainThread constructor
*/
terrainThread() {
this.setName("Terrain Tiler Thread");
gridCenterX = (int) camera.getLocation().x / tileWSize;
gridCenterZ = (int) camera.getLocation().z / tileWSize;
tileSet = new ConcurrentHashMap<>(gridSize * gridSize);
tileFlag = new ConcurrentHashMap<>(gridSize * gridSize);
firstRun = true;
}
@Override
public void run() {
threadState = true;
tLog.log(Level.FINE, "Terrain Thread Started\n");
while (threadState) {
int cx = (int) camera.getLocation().x / tileWSize;
int cz = (int) camera.getLocation().z / tileWSize;
long time = System.nanoTime();
if (firstRun | cx != gridCenterX | cz != gridCenterZ) { // check if camera changed cells
gridCenterX = cx;
gridCenterZ = cz;
// iterrate tileSet to see if any tiles are now outside range
Iterator it = tileFlag.keySet().iterator();
while (it.hasNext()) {
int key = (Integer) it.next();
int kx = key % maxTiles;
int kz = key / maxTiles;
if (kx < (gridCenterX - (gridSize / 2)) | kx > (gridCenterX + (gridSize / 2))) {
tileFlag.replace(key, 4);
newTile = true;
}
if (kz < (gridCenterZ - (gridSize / 2)) | kz > (gridCenterZ + (gridSize / 2))) {
tileFlag.replace(key, 4);
newTile = true;
}
}
// Scan grid area for missing tiles
for (int z = 0; z < gridSize; z++) {
for (int x = 0; x < gridSize; x++) {
int tx = x - (gridSize / 2) + gridCenterX; // get tile absolute position
int tz = z - (gridSize / 2) + gridCenterZ;
if (tx >= 0 & tx < numTilesX & tz >= 0 & tz < numTilesZ) { // OOB check
int tk = tx + (tz * maxTiles);
if (!tileSet.containsKey(tk)) { // no tile loaded so...
tileSet.put(tk, LoadTile(tx, tz)); // Load it
tileFlag.put(tk, 2); // Flag for attaching
newTile = true;
}
}
}
}
firstRun = false;
}/*
time = System.nanoTime() - time;
time /= 1000000;
if (time > 90) {
time = 90;
}
try {
sleep(100 - time);
} catch (InterruptedException ex) {
tLog.log(Level.SEVERE, null, ex);
threadState = false;
}*/
}
// thread has been stopped so flag all tiles for removal
Iterator it = tileFlag.keySet().iterator();
while (it.hasNext()) {
int tk = (Integer) it.next();
tileFlag.replace(tk, 4);
}
}
}
private class TerrainState implements AppState {
private boolean isInit = false;
private boolean isEnable = false;
@Override
public void initialize(AppStateManager stateManager, Application app) {
// initialize terrainThread
if (!isInit) {
threadState = false;
tThread = new terrainThread();
isEnable = false;
isInit = true;
}
}
@Override
public boolean isInitialized() {
return isInit;
}
@Override
public void setEnabled(boolean state) {
if (!isEnable & state) {
tThread.start();
isEnable = true;
} else if (isEnable & !state) {
threadState = false;
// detach and remove all tiles
Iterator it = tileSet.keySet().iterator();
while (it.hasNext()) {
int key = (Integer) it.next();
terrainMLOD.removeTerrain(tileSet.get(key));
tileSet.get(key).setNeighbourFinder(null);
TerrainTiler.this.detachChild(tileSet.get(key));
tileSet.get(key).detachAllChildren();
tileSet.remove(key);
tileFlag.remove(key);
}
tileSet.clear();
tileFlag.clear();
while (tThread.isAlive()){
// wait for thread to stop.
}
TerrainTiler.this.detachAllChildren();
isEnable = false;
}
}
@Override
public boolean isEnabled() {
return isEnable;
}
@Override
public void stateAttached(AppStateManager stateManager) {
// do stuff when attached
}
@Override
public void stateDetached(AppStateManager stateManager) {
// do stuff when detached
}
@Override
public void update(float tpf) {
if (isEnable & newTile) {
// iterrate list and check if needs attaching or removing.
Iterator it = tileFlag.keySet().iterator();
boolean once = true; // only one remove/attach per update.
while (it.hasNext() & once) {
int key = (Integer) it.next();
if (tileFlag.get(key) == 2) {
// flagged to attach
TerrainTiler.this.attachChild(tileSet.get(key));
tileSet.get(key).setNeighbourFinder(TerrainTiler.this);
terrainMLOD.addTerrain(tileSet.get(key));
// run the actionHooks.tileAttached
for (TerrainTilerAction hooks : actionHooks) {
hooks.tileAttached(tileSet.get(key).getLocalTranslation(), tileSet.get(key));
}
tileFlag.replace(key, 3);
terrainMLOD.forceUpdate();
once = false;
} else if (tileFlag.get(key) == 4) {
// flagged for removal
terrainMLOD.removeTerrain(tileSet.get(key));
tileSet.get(key).setNeighbourFinder(null);
TerrainTiler.this.detachChild(tileSet.get(key));
// run the actionHooks.tileDetached
for (TerrainTilerAction hooks : actionHooks) {
hooks.tileDetached(tileSet.get(key).getLocalTranslation(), tileSet.get(key));
}
tileFlag.replace(key, 5); // Flag for deletion
once = false;
} else if (tileFlag.get(key) == 5) {
// flagged for deletion
tileSet.remove(key);
tileFlag.remove(key);
once = false;
}
}
if (!once) { // new tile attached/removed so reset neighbor caches
it = tileFlag.keySet().iterator();
while (it.hasNext()) {
int key = (Integer) it.next();
if (tileFlag.get(key) == 3) {
tileSet.get(key).resetCachedNeighbours();
}
}
} else {
// nothing changed so no new tiles to load
newTile = false;
}
}
}
@Override
public void render(RenderManager rm) {
}
@Override
public void postRender() {
}
@Override
public void cleanup() {
setEnabled(false);
isInit = false;
}
}
}
|
package com.sibisoft.faizaniftikhartdd;
public class Franc extends Money
{
public Franc()
{
}
public Franc(int amount)
{
this.amount= amount;
}
Franc times(int multiplier)
{
return new Franc(amount * multiplier);
}
public boolean equals(Object object)
{
Money franc= (Money) object;
return amount == franc.amount;
}
}
|
package be.ibridge.kettle.trans.step;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import org.w3c.dom.Node;
import be.ibridge.kettle.cluster.ClusterSchema;
import be.ibridge.kettle.core.Const;
import be.ibridge.kettle.core.GUIPositionInterface;
import be.ibridge.kettle.core.LogWriter;
import be.ibridge.kettle.core.Point;
import be.ibridge.kettle.core.Row;
import be.ibridge.kettle.core.SharedObjectBase;
import be.ibridge.kettle.core.SharedObjectInterface;
import be.ibridge.kettle.core.XMLHandler;
import be.ibridge.kettle.core.exception.KettleDatabaseException;
import be.ibridge.kettle.core.exception.KettleException;
import be.ibridge.kettle.core.exception.KettleStepLoaderException;
import be.ibridge.kettle.core.exception.KettleXMLException;
import be.ibridge.kettle.repository.Repository;
import be.ibridge.kettle.trans.StepLoader;
import be.ibridge.kettle.trans.StepPlugin;
/**
* This class contains everything that is needed to define a step.
*
* @since 27-mei-2003
* @author Matt
*
*/
public class StepMeta extends SharedObjectBase implements Cloneable, Comparable, GUIPositionInterface, SharedObjectInterface
{
public static final String XML_TAG = "step";
private String stepid; // --> StepPlugin.id
private String stepname;
private StepMetaInterface stepMetaInterface;
private boolean selected;
public boolean distributes;
private int copies;
private Point location;
private boolean drawstep;
private String description;
private boolean terminator;
private StepPartitioningMeta stepPartitioningMeta;
private ClusterSchema clusterSchema;
private String clusterSchemaName; // temporary to resolve later.
// private LogWriter log;
private long id;
/**
* @param stepid The ID of the step: this is derived information, you can also use the constructor without stepid.
* This constructor will be deprecated soon.
* @param stepname The name of the new step
* @param stepMetaInterface The step metadata interface to use (TextFileInputMeta, etc)
*/
public StepMeta(String stepid, String stepname, StepMetaInterface stepMetaInterface)
{
this(stepname, stepMetaInterface);
if (this.stepid==null) this.stepid = stepid;
}
/**
* @param stepname The name of the new step
* @param stepMetaInterface The step metadata interface to use (TextFileInputMeta, etc)
*/
public StepMeta(String stepname, StepMetaInterface stepMetaInterface)
{
if (stepMetaInterface!=null)
{
this.stepid = StepLoader.getInstance().getStepPluginID(stepMetaInterface);
}
this.stepname = stepname;
this.stepMetaInterface = stepMetaInterface;
selected = false;
distributes = true;
copies = 1;
location = new Point(0,0);
drawstep = false;
description = null;
stepPartitioningMeta = new StepPartitioningMeta();
clusterSchema = null; // non selected by default.
}
/**
* @deprecated The logging is now a singlton, use the constructor without it.
*
* @param log
* @param stepid
* @param stepname
* @param stepMetaInterface
*/
public StepMeta(LogWriter log, String stepid, String stepname, StepMetaInterface stepMetaInterface)
{
this(stepid, stepname, stepMetaInterface);
}
public StepMeta()
{
this((String)null, (String)null, (StepMetaInterface)null);
}
/**
* @deprecated The logging is now a singlton, use the constructor without it.
* @param log
*/
public StepMeta(LogWriter log)
{
this();
}
public String getXML()
{
StringBuffer retval=new StringBuffer(); //$NON-NLS-1$
retval.append(" <"+XML_TAG+">"+Const.CR); //$NON-NLS-1$
retval.append(" "+XMLHandler.addTagValue("name", getName()) ); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" "+XMLHandler.addTagValue("type", getStepID()) ); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" "+XMLHandler.addTagValue("description", description) ); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" "+XMLHandler.addTagValue("distribute", distributes) ); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" "+XMLHandler.addTagValue("copies", copies) ); //$NON-NLS-1$ //$NON-NLS-2$
retval.append( stepPartitioningMeta.getXML() );
retval.append( stepMetaInterface.getXML() );
retval.append(" "+XMLHandler.addTagValue("cluster_schema", clusterSchema==null?"":clusterSchema.getName()));
retval.append(" <GUI>"+Const.CR); //$NON-NLS-1$
retval.append(" <xloc>"+location.x+"</xloc>"+Const.CR); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" <yloc>"+location.y+"</yloc>"+Const.CR); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" <draw>"+(drawstep?"Y":"N")+"</draw>"+Const.CR); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
retval.append(" </GUI>"+Const.CR); //$NON-NLS-1$
retval.append(" </"+XML_TAG+">"+Const.CR+Const.CR); //$NON-NLS-1$
return retval.toString();
}
/**
* @deprecated The logging is now a singlton, use the constructor without it.
*
* Read the step data from XML
*
* @param stepnode The XML step node.
* @param databases A list of databases
* @param counters A hashtable with all defined counters.
*
*/
public StepMeta(LogWriter log, Node stepnode, ArrayList databases, Hashtable counters) throws KettleXMLException
{
this(stepnode, databases, counters);
}
/**
* Read the step data from XML
*
* @param stepnode The XML step node.
* @param databases A list of databases
* @param counters A hashtable with all defined counters.
*
*/
public StepMeta(Node stepnode, ArrayList databases, Hashtable counters) throws KettleXMLException
{
this();
LogWriter log = LogWriter.getInstance();
StepLoader steploader = StepLoader.getInstance();
try
{
stepname = XMLHandler.getTagValue(stepnode, "name"); //$NON-NLS-1$
stepid = XMLHandler.getTagValue(stepnode, "type"); //$NON-NLS-1$
log.logDebug("StepMeta()", Messages.getString("StepMeta.Log.LookingForTheRightStepNode",stepname)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
// Create a new StepMetaInterface object...
StepPlugin sp = steploader.findStepPluginWithID(stepid);
if (sp!=null)
{
stepMetaInterface = BaseStep.getStepInfo(sp, steploader);
}
else
{
throw new KettleStepLoaderException(Messages.getString("StepMeta.Exception.UnableToLoadClass",stepid)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
// Load the specifics from XML...
if (stepMetaInterface!=null)
{
stepMetaInterface.loadXML(stepnode, databases, counters);
}
log.logDebug("StepMeta()", Messages.getString("StepMeta.Log.SpecificLoadedStep",stepname)); //$NON-NLS-1$ //$NON-NLS-2$
/* Handle info general to all step types...*/
description = XMLHandler.getTagValue(stepnode, "description"); //$NON-NLS-1$
copies = Const.toInt(XMLHandler.getTagValue(stepnode, "copies"), 1); //$NON-NLS-1$
String sdistri = XMLHandler.getTagValue(stepnode, "distribute"); //$NON-NLS-1$
distributes = "Y".equalsIgnoreCase(sdistri); //$NON-NLS-1$
if (sdistri==null) distributes=true; // default=distribute
// Handle GUI information: location & drawstep?
String xloc, yloc;
int x,y;
xloc=XMLHandler.getTagValue(stepnode, "GUI", "xloc"); //$NON-NLS-1$ //$NON-NLS-2$
yloc=XMLHandler.getTagValue(stepnode, "GUI", "yloc"); //$NON-NLS-1$ //$NON-NLS-2$
try{ x=Integer.parseInt(xloc); } catch(Exception e) { x=0; }
try{ y=Integer.parseInt(yloc); } catch(Exception e) { y=0; }
location=new Point(x,y);
drawstep = "Y".equalsIgnoreCase(XMLHandler.getTagValue(stepnode, "GUI", "draw")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
// The partitioning information?
Node partNode = XMLHandler.getSubNode(stepnode, "partitioning");
stepPartitioningMeta = new StepPartitioningMeta(partNode);
clusterSchemaName = XMLHandler.getTagValue(stepnode, "cluster_schema"); // resolve to clusterSchema later
log.logDebug("StepMeta()", Messages.getString("StepMeta.Log.EndOfReadXML")); //$NON-NLS-1$ //$NON-NLS-2$
}
catch(Exception e)
{
throw new KettleXMLException(Messages.getString("StepMeta.Exception.UnableToLoadStepInfo"), e); //$NON-NLS-1$
}
}
/**
* Resolves the name of the cluster loaded from XML/Repository to the correct clusterSchema object
* @param clusterSchemas The list of clusterSchemas to reference.
*/
public void setClusterSchemaAfterLoading(List clusterSchemas)
{
if (clusterSchemaName==null) return;
for (int i=0;i<clusterSchemas.size();i++)
{
ClusterSchema look = (ClusterSchema) clusterSchemas.get(i);
if (look.getName().equals(clusterSchemaName)) clusterSchema=look;
}
}
public long getID()
{
return id;
}
public void setID(long id)
{
this.id = id;
}
/**
* See wether or not the step is drawn on the canvas.
*
* @return True if the step is drawn on the canvas.
*/
public boolean isDrawn()
{
return drawstep;
}
/**
* Sets the draw attribute of the step so that it will be drawn on the canvas.
*
* @param draw True if you want the step to show itself on the canvas, False if you don't.
*/
public void setDraw(boolean draw)
{
drawstep=draw;
setChanged();
}
/**
* Sets the number of parallel copies that this step will be launched with.
*
* @param c The number of copies.
*/
public void setCopies(int c)
{
if (copies!=c) setChanged();
copies=c;
}
public int getCopies()
{
// If the step is partitioned, that's going to determine the number of copies, nothing else...
if (isPartitioned() && getStepPartitioningMeta().getPartitionSchema()!=null)
{
String[] partitionIDs = getStepPartitioningMeta().getPartitionSchema().getPartitionIDs();
if (partitionIDs!=null && partitionIDs.length>0) // these are the partitions the step can "reach"
{
return partitionIDs.length;
}
}
return copies;
}
public void drawStep()
{
setDraw(true);
setChanged();
}
public void hideStep()
{
setDraw(false);
setChanged();
}
/**
* Two steps are equal if their names are equal.
* @return true if the two steps are equal.
*/
public boolean equals(Object obj)
{
if (obj==null) return false;
StepMeta stepMeta = (StepMeta)obj;
return getName().equalsIgnoreCase(stepMeta.getName());
}
public int hashCode()
{
return stepname.hashCode();
}
public int compareTo(Object o)
{
return toString().compareTo(((StepMeta)o).toString());
}
public boolean hasChanged()
{
BaseStepMeta bsi = (BaseStepMeta)this.getStepMetaInterface();
return bsi!=null?bsi.hasChanged():false;
}
public void setChanged(boolean ch)
{
BaseStepMeta bsi = (BaseStepMeta)this.getStepMetaInterface();
if (bsi!=null) bsi.setChanged(ch);
}
public void setChanged()
{
BaseStepMeta bsi = (BaseStepMeta)this.getStepMetaInterface();
if (bsi!=null) bsi.setChanged();
}
public boolean chosesTargetSteps()
{
if (getStepMetaInterface()!=null)
{
return getStepMetaInterface().getTargetSteps()!=null;
}
return false;
}
public Object clone()
{
try
{
StepMeta retval = (StepMeta)super.clone();
boolean changed = hasChanged();
retval.setLocation(getLocation().x, getLocation().y);
if (stepMetaInterface!=null) retval.stepMetaInterface = (StepMetaInterface)stepMetaInterface.clone();
else retval.stepMetaInterface=null;
retval.setChanged( changed );
setChanged(changed );
return retval;
}
catch(CloneNotSupportedException e)
{
return null;
}
}
public StepMetaInterface getStepMetaInterface()
{
return stepMetaInterface;
}
public String getStepID()
{
return stepid;
}
/*
public String getStepTypeDesc()
{
return BaseStep.type_desc[steptype];
}
*/
public String getName()
{
return stepname;
}
public void setName(String sname)
{
stepname=sname;
}
public String getDescription()
{
return description;
}
public void setDescription(String description)
{
this.description=description;
}
public void setSelected(boolean sel)
{
selected=sel;
}
public void flipSelected()
{
selected=!selected;
}
public boolean isSelected()
{
return selected;
}
public void setTerminator()
{
setTerminator(true);
}
public void setTerminator(boolean t)
{
terminator = t;
}
public boolean hasTerminator()
{
return terminator;
}
/**
* @deprecated The logging is now a singlton, use the constructor without it.
* @param log
* @param id_step
*/
public StepMeta(LogWriter log, long id_step)
{
this(log, (String)null, (String)null, (StepMetaInterface)null);
setID(id_step);
}
public StepMeta(long id_step)
{
this((String)null, (String)null, (StepMetaInterface)null);
setID(id_step);
}
/**
* @deprecated The logging is now a singlton, use the constructor without it.
*
* @param log
* @param rep
* @param id_step
* @param databases
* @param counters
* @param partitionSchemas
* @throws KettleException
*/
public StepMeta(LogWriter log, Repository rep, long id_step, ArrayList databases, Hashtable counters, List partitionSchemas) throws KettleException
{
this(rep, id_step, databases, counters, partitionSchemas);
}
/**
* Create a new step by loading the metadata from the specified repository.
* @param rep
* @param id_step
* @param databases
* @param counters
* @param partitionSchemas
* @throws KettleException
*/
public StepMeta(Repository rep, long id_step, ArrayList databases, Hashtable counters, List partitionSchemas) throws KettleException
{
this();
StepLoader steploader = StepLoader.getInstance();
try
{
Row r = rep.getStep(id_step);
if (r!=null)
{
setID(id_step);
stepname = r.searchValue("NAME").getString(); //$NON-NLS-1$
//System.out.println("stepname = "+stepname);
description = r.searchValue("DESCRIPTION").getString(); //$NON-NLS-1$
//System.out.println("description = "+description);
long id_step_type = r.searchValue("ID_STEP_TYPE").getInteger(); //$NON-NLS-1$
//System.out.println("id_step_type = "+id_step_type);
Row steptyperow = rep.getStepType(id_step_type);
stepid = steptyperow.searchValue("CODE").getString(); //$NON-NLS-1$
distributes = r.searchValue("DISTRIBUTE").getBoolean(); //$NON-NLS-1$
copies = (int)r.searchValue("COPIES").getInteger(); //$NON-NLS-1$
int x = (int)r.searchValue("GUI_LOCATION_X").getInteger(); //$NON-NLS-1$
int y = (int)r.searchValue("GUI_LOCATION_Y").getInteger(); //$NON-NLS-1$
location = new Point(x,y);
drawstep = r.searchValue("GUI_DRAW").getBoolean(); //$NON-NLS-1$
// Generate the appropriate class...
StepPlugin sp = steploader.findStepPluginWithID(stepid);
if (sp!=null)
{
stepMetaInterface = BaseStep.getStepInfo(sp, steploader);
}
else
{
throw new KettleStepLoaderException(Messages.getString("StepMeta.Exception.UnableToLoadClass",stepid+Const.CR)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
stepMetaInterface = BaseStep.getStepInfo(sp, steploader);
if (stepMetaInterface!=null)
{
// Read the step info from the repository!
stepMetaInterface.readRep(rep, getID(), databases, counters);
}
// Get the partitioning as well...
stepPartitioningMeta = new StepPartitioningMeta(rep, getID());
// Get the cluster schema name
clusterSchemaName = rep.getStepAttributeString(id_step, "cluster_schema");
}
else
{
throw new KettleException(Messages.getString("StepMeta.Exception.StepInfoCouldNotBeFound",String.valueOf(id_step))); //$NON-NLS-1$ //$NON-NLS-2$
}
}
catch(KettleDatabaseException dbe)
{
throw new KettleException(Messages.getString("StepMeta.Exception.StepCouldNotBeLoaded",String.valueOf(getID())), dbe); //$NON-NLS-1$ //$NON-NLS-2$
}
}
public void saveRep(Repository rep, long id_transformation)
throws KettleException
{
LogWriter log = LogWriter.getInstance();
try
{
log.logDebug(toString(), Messages.getString("StepMeta.Log.SaveNewStep")); //$NON-NLS-1$
// Insert new Step in repository
setID(rep.insertStep( id_transformation,
getName(),
getDescription(),
getStepID(),
distributes,
copies,
getLocation()==null?-1:getLocation().x,
getLocation()==null?-1:getLocation().y,
isDrawn()
)
);
// Save partitioning selection for the step
stepPartitioningMeta.saveRep(rep, id_transformation, getID());
// The id_step is known, as well as the id_transformation
// This means we can now save the attributes of the step...
log.logDebug(toString(), Messages.getString("StepMeta.Log.SaveStepDetails")); //$NON-NLS-1$
stepMetaInterface.saveRep(rep, id_transformation, getID());
// Save the clustering schema that was chosen.
rep.saveStepAttribute(id_transformation, getID(), "cluster_schema", clusterSchema==null?"":clusterSchema.getName());
}
catch(KettleException e)
{
throw new KettleException(Messages.getString("StepMeta.Exception.UnableToSaveStepInfo",String.valueOf(id_transformation)), e); //$NON-NLS-1$
}
}
public void setLocation(int x, int y)
{
int nx = (x>=0?x:0);
int ny = (y>=0?y:0);
Point loc = new Point(nx,ny);
if (!loc.equals(location)) setChanged();
location=loc;
}
public void setLocation(Point loc)
{
if (loc!=null && !loc.equals(location)) setChanged();
location = loc;
}
public Point getLocation()
{
return location;
}
public void check(ArrayList remarks, Row prev, String input[], String output[], Row info)
{
stepMetaInterface.check(remarks, this, prev, input, output, info);
}
public String toString()
{
if (getName()==null) return getClass().getName();
return getName();
}
/**
* @return true is the step is partitioned
*/
public boolean isPartitioned()
{
return stepPartitioningMeta.isPartitioned();
}
/**
* @return the stepPartitioningMeta
*/
public StepPartitioningMeta getStepPartitioningMeta()
{
return stepPartitioningMeta;
}
/**
* @param stepPartitioningMeta the stepPartitioningMeta to set
*/
public void setStepPartitioningMeta(StepPartitioningMeta stepPartitioningMeta)
{
this.stepPartitioningMeta = stepPartitioningMeta;
}
/**
* @return the clusterSchema
*/
public ClusterSchema getClusterSchema()
{
return clusterSchema;
}
/**
* @param clusterSchema the clusterSchema to set
*/
public void setClusterSchema(ClusterSchema clusterSchema)
{
this.clusterSchema = clusterSchema;
}
}
|
package com.web.javsterisk.server;
public class MainServer {
public static void main(String[] args) throws Exception {
;
}
}
|
package alluxio.client.file;
import alluxio.Constants;
import alluxio.annotation.PublicApi;
import alluxio.client.AlluxioStorageType;
import alluxio.client.BoundedStream;
import alluxio.client.Seekable;
import alluxio.client.block.BlockInStream;
import alluxio.client.block.BufferedBlockOutStream;
import alluxio.client.block.LocalBlockInStream;
import alluxio.client.block.RemoteBlockInStream;
import alluxio.client.block.UnderStoreBlockInStream;
import alluxio.client.file.options.InStreamOptions;
import alluxio.client.file.policy.FileWriteLocationPolicy;
import alluxio.exception.AlluxioException;
import alluxio.exception.BlockAlreadyExistsException;
import alluxio.exception.ExceptionMessage;
import alluxio.exception.PreconditionMessage;
import alluxio.master.block.BlockId;
import alluxio.wire.BlockInfo;
import alluxio.wire.BlockLocation;
import alluxio.wire.WorkerNetAddress;
import com.google.common.base.Preconditions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import javax.annotation.concurrent.NotThreadSafe;
/**
* A streaming API to read a file. This API represents a file as a stream of bytes and provides a
* collection of {@link #read} methods to access this stream of bytes. In addition, one can seek
* into a given offset of the stream to read.
* <p>
* This class wraps the {@link BlockInStream} for each of the blocks in the file and abstracts the
* switching between streams. The backing streams can read from Alluxio space in the local machine,
* remote machines, or the under storage system.
*/
@PublicApi
@NotThreadSafe
public class FileInStream extends InputStream implements BoundedStream, Seekable {
private static final Logger LOG = LoggerFactory.getLogger(Constants.LOGGER_TYPE);
/** How the data should be written into Alluxio space, if at all. */
protected final AlluxioStorageType mAlluxioStorageType;
/** Standard block size in bytes of the file, guaranteed for all but the last block. */
protected final long mBlockSize;
/** The location policy for CACHE type of read into Alluxio. */
protected final FileWriteLocationPolicy mLocationPolicy;
/** Total length of the file in bytes. */
protected final long mFileLength;
/** File System context containing the {@link FileSystemMasterClient} pool. */
protected final FileSystemContext mContext;
/** A 1-byte array for writing a single byte to the cache stream. */
protected final byte[] mSingleByte;
/** File information. */
protected URIStatus mStatus;
/** Constant error message for block ID not cached. */
protected static final String BLOCK_ID_NOT_CACHED =
"The block with ID {} could not be cached into Alluxio storage.";
/** Error message for cache collision. */
private static final String BLOCK_ID_EXISTS_SO_NOT_CACHED =
"The block with ID {} is already stored in the target worker, canceling the cache request.";
/** If the stream is closed, this can only go from false to true. */
protected boolean mClosed;
/** Whether or not the current block should be cached. */
protected boolean mShouldCacheCurrentBlock;
/** Include incomplete blocks if Alluxio is configured to store blocks in Alluxio storage. */
private boolean mShouldCacheIncompleteBlock;
/** Current position of the stream. */
protected long mPos;
/** Current {@link BlockInStream} backing this stream. */
protected BlockInStream mCurrentBlockInStream;
/** Current {@link BufferedBlockOutStream} writing the data into Alluxio, this may be null. */
protected BufferedBlockOutStream mCurrentCacheStream;
/** Block id for the current instream, {@link #mCurrentBlockInStream}. */
protected long mCurrentBlockId;
/**
* Creates a new file input stream.
*
* @param status the file status
* @param options the client options
* @return the created {@link FileInStream} instance
*/
public static FileInStream create(URIStatus status, InStreamOptions options) {
if (status.getLength() == Constants.UNKNOWN_SIZE) {
return new UnknownLengthFileInStream(status, options);
}
return new FileInStream(status, options);
}
/**
* Creates a new file input stream.
*
* @param status the file status
* @param options the client options
*/
protected FileInStream(URIStatus status, InStreamOptions options) {
mStatus = status;
mBlockSize = status.getBlockSizeBytes();
mFileLength = status.getLength();
mContext = FileSystemContext.INSTANCE;
mAlluxioStorageType = options.getAlluxioStorageType();
mShouldCacheCurrentBlock = mAlluxioStorageType.isStore();
mShouldCacheIncompleteBlock = options.getCacheIncompleteBlock();
mClosed = false;
mLocationPolicy = options.getLocationPolicy();
if (mShouldCacheCurrentBlock) {
Preconditions.checkNotNull(options.getLocationPolicy(),
PreconditionMessage.FILE_WRITE_LOCATION_POLICY_UNSPECIFIED);
}
mSingleByte = new byte[1];
}
@Override
public void close() throws IOException {
if (mClosed) {
return;
}
if (mShouldCacheCurrentBlock && mShouldCacheIncompleteBlock) {
readCurrentBlockTill(mFileLength);
}
if (mCurrentBlockInStream != null) {
mCurrentBlockInStream.close();
}
closeCacheStream();
mClosed = true;
}
@Override
public int read() throws IOException {
if (!validPosition(mPos)) {
return -1;
}
checkAndAdvanceBlockInStream();
int data = mCurrentBlockInStream.read();
if (data == -1) {
// The underlying stream is done.
return -1;
}
updatePosForRead(1);
if (mShouldCacheCurrentBlock) {
try {
// writeToCacheStream writes a byte array.
mSingleByte[0] = (byte) (0xFF & data);
writeToCacheStream(mSingleByte, 0, 1);
} catch (IOException e) {
logCacheStreamIOException(e);
mShouldCacheCurrentBlock = false;
}
}
return data;
}
@Override
public int read(byte[] b) throws IOException {
return read(b, 0, b.length);
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
Preconditions.checkArgument(b != null, PreconditionMessage.ERR_READ_BUFFER_NULL);
Preconditions.checkArgument(off >= 0 && len >= 0 && len + off <= b.length,
PreconditionMessage.ERR_BUFFER_STATE, b.length, off, len);
if (len == 0) {
return 0;
} else if (!validPosition(mPos)) {
return -1;
}
int currentOffset = off;
int bytesLeftToRead = len;
while (bytesLeftToRead > 0 && validPosition(mPos)) {
checkAndAdvanceBlockInStream();
int bytesToRead = (int) Math.min(bytesLeftToRead, mCurrentBlockInStream.remaining());
if (mCurrentBlockInStream.remaining() == 0) {
// The underlying stream is done.
break;
}
int bytesRead = mCurrentBlockInStream.read(b, currentOffset, bytesToRead);
if (bytesRead > 0) {
if (mShouldCacheCurrentBlock) {
try {
writeToCacheStream(b, currentOffset, bytesRead);
} catch (IOException e) {
logCacheStreamIOException(e);
mShouldCacheCurrentBlock = false;
}
}
updatePosForRead(bytesRead);
bytesLeftToRead -= bytesRead;
currentOffset += bytesRead;
}
}
if (bytesLeftToRead == len && mCurrentBlockInStream.remaining() == 0) {
// Nothing was read, and the underlying stream is done.
return -1;
}
return len - bytesLeftToRead;
}
@Override
public long remaining() {
return mFileLength - mPos;
}
@Override
public void seek(long pos) throws IOException {
if (mPos == pos) {
return;
}
Preconditions.checkArgument(pos >= 0, PreconditionMessage.ERR_SEEK_NEGATIVE, pos);
Preconditions.checkArgument(
pos < mFileLength, PreconditionMessage.ERR_SEEK_PAST_END_OF_FILE, pos);
if (!mShouldCacheIncompleteBlock) {
seekInternal(pos);
} else {
seekInternalWithCachingIncompleteBlock(pos);
}
}
@Override
public long skip(long n) throws IOException {
if (n <= 0) {
return 0;
}
long toSkip = Math.min(n, remaining());
long newPos = mPos + toSkip;
long toSkipInBlock = ((newPos / mBlockSize) > mPos / mBlockSize) ? newPos % mBlockSize : toSkip;
seekBlockInStream(newPos);
checkAndAdvanceBlockInStream();
if (toSkipInBlock != mCurrentBlockInStream.skip(toSkipInBlock)) {
throw new IOException(ExceptionMessage.INSTREAM_CANNOT_SKIP.getMessage(toSkip));
}
return toSkip;
}
/**
* Updates {@link #mPos} with the number of read bytes.
*
* @param bytesRead the number of bytes read, to increment {@link #mPos}
*/
protected void updatePosForRead(int bytesRead) {
mPos += bytesRead;
}
/**
* @param pos the position to check to validity
* @return true of the given pos is a valid position in the file
*/
protected boolean validPosition(long pos) {
return pos < mFileLength;
}
/**
* @param pos the position to check
* @return the block size in bytes for the gven pos, used for worker allocation
*/
protected long getBlockSizeAllocation(long pos) {
return getBlockSize(pos);
}
/**
* Creates and returns a {@link BlockInStream} for the UFS.
*
* @param blockStart the offset to start the block from
* @param length the length of the block
* @param path the UFS path
* @return the {@link BlockInStream} for the UFS
* @throws IOException if the stream cannot be created
*/
protected BlockInStream createUnderStoreBlockInStream(long blockStart, long length, String path)
throws IOException {
return new UnderStoreBlockInStream(blockStart, length, mBlockSize, path);
}
/**
* Writes data to the cache stream.
*
* @param buffer the data to write
* @param offset the start offset into the data
* @param length the number of bytes to write
* @throws IOException if the write failed
*/
protected void writeToCacheStream(byte[] buffer, int offset, int length) throws IOException {
mCurrentCacheStream.write(buffer, offset, length);
}
/**
* Creates and returns a {@link BufferedBlockOutStream} for caching a block.
*
* @param blockId the block id to cache
* @param length the length of the block to cache
* @param address the {@link WorkerNetAddress} to cache to
* @return the created {@link BufferedBlockOutStream} for caching a block
* @throws IOException if the stream cannot be created
*/
protected BufferedBlockOutStream createCacheStream(long blockId, long length,
WorkerNetAddress address) throws IOException {
return mContext.getAlluxioBlockStore().getOutStream(blockId, length, address);
}
/**
* @return true if the cache out stream is complete and should be closed, false otherwise
*/
protected boolean shouldCloseCacheStream() {
return mCurrentCacheStream.remaining() == 0;
}
/**
* Convenience method for updating {@link #mCurrentBlockInStream},
* {@link #mShouldCacheCurrentBlock}, and {@link #mCurrentCacheStream}. If the block boundary has
* been reached, the current {@link BlockInStream} is closed and a the next one is opened.
* {@link #mShouldCacheCurrentBlock} is set to {@link #mAlluxioStorageType}.isCache().
* {@link #mCurrentCacheStream} is also closed and a new one is created for the next block.
*
* @throws IOException if the next BlockInStream cannot be obtained
*/
private void checkAndAdvanceBlockInStream() throws IOException {
long currentBlockId = getCurrentBlockId();
if (mCurrentBlockInStream == null
|| (mCurrentBlockInStream.remaining() == 0 && currentBlockId != mCurrentBlockId)) {
closeCacheStream();
updateBlockInStream(currentBlockId);
mCurrentBlockId = currentBlockId;
if (mShouldCacheCurrentBlock) {
try {
WorkerNetAddress address = mLocationPolicy.getWorkerForNextBlock(
mContext.getAlluxioBlockStore().getWorkerInfoList(), getBlockSizeAllocation(mPos));
// Don't cache the block to somewhere that already has it.
// TODO(andrew): Filter the workers provided to the location policy to not include
// workers which already contain the block. See ALLUXIO-1816.
if (mCurrentBlockInStream instanceof RemoteBlockInStream) {
WorkerNetAddress readAddress =
((RemoteBlockInStream) mCurrentBlockInStream).getWorkerNetAddress();
// Try to avoid an RPC.
if (readAddress.equals(address)) {
mShouldCacheCurrentBlock = false;
} else {
BlockInfo blockInfo = mContext.getAlluxioBlockStore().getInfo(currentBlockId);
for (BlockLocation location : blockInfo.getLocations()) {
if (address.equals(location.getWorkerAddress())) {
mShouldCacheCurrentBlock = false;
}
}
}
}
if (mShouldCacheCurrentBlock) {
mCurrentCacheStream = createCacheStream(currentBlockId, getBlockSize(mPos), address);
}
} catch (IOException e) {
logCacheStreamIOException(e);
mShouldCacheCurrentBlock = false;
} catch (AlluxioException e) {
LOG.warn(BLOCK_ID_NOT_CACHED, currentBlockId, e);
mShouldCacheCurrentBlock = false;
}
}
}
}
/**
* Convenience method for checking if {@link #mCurrentCacheStream} is not null and closing it
* with the appropriate close or cancel command.
*
* @throws IOException if the close fails
*/
private void closeCacheStream() throws IOException {
if (mCurrentCacheStream == null) {
return;
}
if (shouldCloseCacheStream()) {
mCurrentCacheStream.close();
} else {
mCurrentCacheStream.cancel();
}
mShouldCacheCurrentBlock = false;
}
/**
* @return the current block id based on mPos, -1 if at the end of the file
*/
private long getCurrentBlockId() {
if (!validPosition(mPos)) {
return -1;
}
int index = (int) (mPos / mBlockSize);
Preconditions
.checkState(index < mStatus.getBlockIds().size(), PreconditionMessage.ERR_BLOCK_INDEX);
return mStatus.getBlockIds().get(index);
}
/**
* @param pos the position to get the block size for
* @return the size of the current block
*/
protected long getBlockSize(long pos) {
// The size of the last block, 0 if it is equal to the normal block size
long lastBlockSize = mFileLength % mBlockSize;
// If we are not in the last block or if the last block is equal to the normal block size,
// return the normal block size. Otherwise return the block size of the last block.
if (mFileLength - pos > lastBlockSize) {
return mBlockSize;
} else {
return lastBlockSize;
}
}
/**
* Logs IO exceptions thrown in response to the worker cache request. If the exception is not an
* expected exception, a warning will be logged with the stack trace.
*/
private void logCacheStreamIOException(IOException e) {
if (e.getCause() instanceof BlockAlreadyExistsException) {
LOG.warn(BLOCK_ID_EXISTS_SO_NOT_CACHED, getCurrentBlockId());
} else {
LOG.warn(BLOCK_ID_NOT_CACHED, getCurrentBlockId(), e);
}
}
/**
* Similar to {@link #checkAndAdvanceBlockInStream()}, but a specific position can be specified
* and the stream pointer will be at that offset after this method completes.
*
* @param newPos the new position to set the stream to
* @throws IOException if the stream at the specified position cannot be opened
*/
private void seekBlockInStream(long newPos) throws IOException {
long oldBlockId = getCurrentBlockId();
mPos = newPos;
closeCacheStream();
long currentBlockId = getCurrentBlockId();
if (oldBlockId != currentBlockId) {
updateBlockInStream(currentBlockId);
// Reading next block entirely.
if (mPos % mBlockSize == 0 && mShouldCacheCurrentBlock) {
try {
WorkerNetAddress address = mLocationPolicy.getWorkerForNextBlock(
mContext.getAlluxioBlockStore().getWorkerInfoList(), getBlockSizeAllocation(mPos));
mCurrentCacheStream = createCacheStream(currentBlockId, getBlockSize(mPos), address);
} catch (IOException e) {
logCacheStreamIOException(e);
mShouldCacheCurrentBlock = false;
} catch (AlluxioException e) {
LOG.warn(BLOCK_ID_NOT_CACHED, currentBlockId, e);
mShouldCacheCurrentBlock = false;
}
} else {
mShouldCacheCurrentBlock = false;
}
}
}
/**
* Helper method to {@link #checkAndAdvanceBlockInStream()} and {@link #seekBlockInStream(long)}.
* The current {@link BlockInStream} will be closed and a new {@link BlockInStream} for the given
* blockId will be opened at position 0.
*
* @param blockId blockId to set the {@link #mCurrentBlockInStream} to read
* @throws IOException if the next {@link BlockInStream} cannot be obtained
*/
private void updateBlockInStream(long blockId) throws IOException {
if (mCurrentBlockInStream != null) {
mCurrentBlockInStream.close();
}
try {
if (mAlluxioStorageType.isPromote()) {
try {
mContext.getAlluxioBlockStore().promote(blockId);
} catch (IOException e) {
// Failed to promote
LOG.warn("Promotion of block with ID {} failed.", blockId, e);
}
}
mCurrentBlockInStream = mContext.getAlluxioBlockStore().getInStream(blockId);
mShouldCacheCurrentBlock =
!(mCurrentBlockInStream instanceof LocalBlockInStream) && mAlluxioStorageType.isStore();
} catch (IOException e) {
LOG.debug("Failed to get BlockInStream for block with ID {}, using UFS instead. {}", blockId,
e);
if (!mStatus.isPersisted()) {
LOG.error("Could not obtain data for block with ID {} from Alluxio."
+ " The block is also not available in the under storage.", blockId);
throw e;
}
long blockStart = BlockId.getSequenceNumber(blockId) * mBlockSize;
mCurrentBlockInStream =
createUnderStoreBlockInStream(blockStart, getBlockSize(blockStart), mStatus.getUfsPath());
mShouldCacheCurrentBlock = mAlluxioStorageType.isStore();
}
}
/**
* Seeks to a file position. Blocks are not cached unless they are fully read. This is only called
* by {@link FileInStream#seek}.
*
* @param pos The position to seek to. It is guaranteed to be valid (pos >= 0 && pos != mPos &&
* pos <= mFileLength)
* @throws IOException if the seek fails due to an error accessing the stream at the position
*/
private void seekInternal(long pos) throws IOException {
seekBlockInStream(pos);
checkAndAdvanceBlockInStream();
mCurrentBlockInStream.seek(mPos % mBlockSize);
}
/**
* Seeks to a file position. Blocks are cached even if they are not fully read. This is only
* called by {@link FileInStream#seek}.
* Invariant: if the current block is to be cached, [0, mPos) should have been cached already.
*
* @param pos The position to seek to. It is guaranteed to be valid (pos >= 0 && pos != mPos &&
* pos <= mFileLength).
* @throws IOException if the seek fails due to an error accessing the stream at the position
*/
private void seekInternalWithCachingIncompleteBlock(long pos) throws IOException {
// Precompute this because mPos will be updated several times in this function.
boolean isInCurrentBlock = pos / mBlockSize == mPos / mBlockSize;
if (mShouldCacheCurrentBlock) {
// Cache till pos if seeking forward within the current block. Otheriwse cache the whole
// block.
readCurrentBlockTill(pos > mPos ? pos : mFileLength);
}
// The logic below:
// If seeks within the current block, directly seeks to pos if we are not yet there.
// If seeks outside the current block, seek to the beginning of that block first, then
// cache the prefix (pos % mBlockSize) of that block.
if (isInCurrentBlock) {
// We don't need to seek if we are at pos already. It won't work if you remove this early
// return because SeekBlockInStream closes the current cache stream.
if (mPos == pos) {
return;
}
seekBlockInStream(pos);
mCurrentBlockInStream.seek(mPos % mBlockSize);
} else {
seekBlockInStream(pos / mBlockSize * mBlockSize);
checkAndAdvanceBlockInStream();
readCurrentBlockTill(pos);
}
}
/**
* Reads till the file offset (mPos) equals pos or the end of the current block (whichever is
* met first) if pos > mPos. Otherwise no-op.
*
* @param pos file offset
* @throws IOException if read or cache write fails
*/
private void readCurrentBlockTill(long pos) throws IOException {
long len = Math.min(pos - mPos,
mCurrentBlockInStream == null ? mBlockSize : mCurrentBlockInStream.remaining());
if (len <= 0) {
return;
}
Preconditions.checkState(len <= Integer.MAX_VALUE);
byte[] buffer = new byte[(int) len];
read(buffer);
}
}
|
package me.nallar.patched;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.common.collect.ImmutableMultiset;
import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.Multiset;
import com.google.common.collect.Multisets;
import com.google.common.collect.Ordering;
import com.google.common.collect.SetMultimap;
import com.google.common.collect.TreeMultimap;
import cpw.mods.fml.common.DuplicateModsFoundException;
import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.ModContainer;
public abstract class PatchLoader extends Loader {
@Override
protected void identifyDuplicates(List<ModContainer> mods) {
Map<String, List<ModContainer>> modsMap = new HashMap<String, List<ModContainer>>();
for (ModContainer mc : mods) {
String source = mc.getSource().getAbsolutePath() + mc.getModId();
List<ModContainer> modsList = modsMap.get(source);
if (modsList == null) {
modsMap.put(source, modsList = new ArrayList<ModContainer>());
}
modsList.add(mc);
}
for (List<ModContainer> modContainers : modsMap.values()) {
if (modContainers.size() > 1) {
modContainers.remove(modContainers.size() - 1);
for (ModContainer modContainer : modContainers) {
mods.remove(modContainer);
}
}
}
TreeMultimap<ModContainer, File> dupsearch = TreeMultimap.create(new ModIdComparator(), Ordering.arbitrary());
for (ModContainer mc : mods) {
if (mc.getSource() != null) {
dupsearch.put(mc, mc.getSource());
}
}
ImmutableMultiset<ModContainer> duplist = Multisets.copyHighestCountFirst(dupsearch.keys());
SetMultimap<ModContainer, File> dupes = LinkedHashMultimap.create();
for (Multiset.Entry<ModContainer> e : duplist.entrySet()) {
if (e.getCount() > 1) {
FMLLog.severe("Found a duplicate mod %s at %s", e.getElement().getModId(), dupsearch.get(e.getElement()));
dupes.putAll(e.getElement(), dupsearch.get(e.getElement()));
}
}
if (!dupes.isEmpty()) {
throw new DuplicateModsFoundException(dupes);
}
}
}
|
package org.opencms.search.solr;
import org.opencms.file.CmsObject;
import org.opencms.i18n.CmsEncoder;
import org.opencms.search.CmsSearchResource;
import org.opencms.search.fields.CmsSearchField;
import org.opencms.test.OpenCmsTestProperties;
import org.opencms.util.CmsDateUtil;
import org.opencms.util.CmsStringUtil;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.apache.solr.client.solrj.response.FacetField;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
/**
* Main test suite for the package <code>{@link org.opencms.search.solr}</code>.<p>
*
* @since 8.5.0
*/
public final class AllTests {
/** Name of a search index created using API. */
public static final String INDEX_TEST = "Test new index";
/** Name of an index used for testing. */
public static final String SOLR_OFFLINE = "Solr Offline";
/** Name of an index used for testing. */
public static final String SOLR_ONLINE = "Solr Online";
/**
* Hide constructor to prevent generation of class instances.<p>
*/
private AllTests() {
// empty
}
/**
* Prints the results.<p>
*
* @param cms the current cms
* @param results the results
* @param countOnly signals if to print the counts only
*/
public static void printResults(CmsObject cms, CmsSolrResultList results, boolean countOnly) {
if (countOnly) {
printResultCount(results);
} else {
printResultCount(results);
printResults(results, cms);
}
}
/**
* Returns the JUnit test suite for this package.<p>
*
* @return the JUnit test suite for this package
*/
public static Test suite() {
TestSuite suite = new TestSuite("Tests for package " + AllTests.class.getPackage().getName());
OpenCmsTestProperties.initialize(org.opencms.test.AllTests.TEST_PROPERTIES_PATH);
//$JUnit-BEGIN$
suite.addTest(TestSolrConfiguration.suite());
suite.addTest(TestSolrFieldConfiguration.suite());
suite.addTest(TestSolrIndexing.suite());
suite.addTest(TestSolrSearch.suite());
// suite.addTest(TestSolrSearchAutoSuggeting.suite());
suite.addTest(TestSolrSearchFaceting.suite());
suite.addTest(TestSolrSearchFulltextSearching.suite());
// suite.addTest(TestSolrSearchHighlighting.suite());
// suite.addTest(TestSolrSearchMLTQuerying.suite());
// suite.addTest(TestSolrSearchPaging.suite());
suite.addTest(TestSolrSearchPermissionHandling.suite());
// suite.addTest(TestSolrSearchRanging.suite());
// suite.addTest(TestSolrSearchSorting.suite());
// suite.addTest(TestSolrSearchSpellchecking.suite());
suite.addTest(TestCmsSolrCollector.suite());
//$JUnit-END$
return suite;
}
/**
* Prints a Solr query response.<p>
*
* @param results the query result
*/
private static void printResultCount(CmsSolrResultList results) {
System.out.println("
System.out.println("Found: " + results.getNumFound());
System.out.println("Start: " + results.getStart());
System.out.println("Max Score: " + results.getMaxScore());
System.out.println("Query: " + CmsEncoder.decode(results.getQuery().toString()));
System.out.println("
}
/**
* Prints a Solr query response.<p>
*
* @param qr the query response
*/
@SuppressWarnings("unused")
private static void printResultDetails(QueryResponse qr) {
SolrDocumentList sdl = qr.getResults();
qr.getExplainMap();
// System.out.println(sdl.toString());
ArrayList<HashMap<String, Object>> hitsOnPage = new ArrayList<HashMap<String, Object>>();
for (SolrDocument d : sdl) {
HashMap<String, Object> values = new HashMap<String, Object>();
Iterator<Map.Entry<String, Object>> i = d.iterator();
while (i.hasNext()) {
Map.Entry<String, Object> e2 = i.next();
values.put(e2.getKey(), e2.getValue());
}
hitsOnPage.add(values);
System.out.println(values.get("path") + " (" + values.get("Title") + ")");
}
List<FacetField> facets = qr.getFacetFields();
if (facets != null) {
for (FacetField facet : facets) {
List<FacetField.Count> facetEntries = facet.getValues();
if (facetEntries != null) {
for (FacetField.Count fcount : facetEntries) {
System.out.println(fcount.getName() + ": " + fcount.getCount());
}
}
}
}
}
/**
* Prints the result.<p>
*
* @param results the results to print
* @param cms the cms object
*/
private static void printResults(CmsSolrResultList results, CmsObject cms) {
Iterator<CmsSearchResource> i = results.iterator();
int count = 0;
int colPath = 0;
int colTitle = 0;
while (i.hasNext()) {
CmsSearchResource res = i.next();
String path = res.getRootPath();
colPath = Math.max(colPath, path.length() + 3);
String title = res.getField(CmsSearchField.FIELD_TITLE
+ "_"
+ cms.getRequestContext().getLocale().toString());
if (title == null) {
title = "";
} else {
title = title.trim();
}
colTitle = Math.max(colTitle, title.length() + 3);
}
for (CmsSearchResource res : results) {
System.out.print(CmsStringUtil.padRight("" + ++count, 4));
System.out.print(CmsStringUtil.padRight(res.getRootPath(), colPath));
String title = res.getField(CmsSearchField.FIELD_TITLE
+ "_"
+ cms.getRequestContext().getLocale().toString());
if (title == null) {
title = "";
} else {
title = title.trim();
}
System.out.print(CmsStringUtil.padRight(title, colTitle));
String type = res.getField(CmsSearchField.FIELD_TYPE);
if (type == null) {
type = "";
}
System.out.print(CmsStringUtil.padRight(type, 10));
System.out.print(CmsStringUtil.padRight(
"" + CmsDateUtil.getDateTime(new Date(res.getDateLastModified()), DateFormat.SHORT, Locale.GERMAN),
17));
System.out.println("score: " + res.getScore(results.getMaxScore().floatValue()));
}
}
}
|
package org.jetel.graph;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jetel.exception.ComponentNotReadyException;
import org.jetel.exception.ConfigurationStatus;
import org.jetel.exception.GraphConfigurationException;
import org.jetel.graph.runtime.NodeTrackingDetail;
import org.jetel.graph.runtime.TrackingDetail;
/**
* A class that represents processing Phase of Transformation Graph
*
* @author D.Pavlis
* @since July 23, 2003
* @revision $Revision$
* @see OtherClasses
*/
public class Phase implements Comparable {
// Attributes
// Associations
/**
* @since April 2, 2002
*/
private List <Node> nodesInPhase;
private List <Edge> edgesInPhase;
private List <Node> leafNodes;
// specifies the order of this phase within graph
private int phaseNum;
private int phaseExecTime;
private int phaseMemUtilization;
private Result result;
private boolean isCheckPoint;
private Map<String,TrackingDetail> tracking;
protected TransformationGraph graph;
static Log logger = LogFactory.getLog(Phase.class);
// Operations
/**
*Constructor for the TransformationGraph object
*
* @param phaseNum Description of the Parameter
* @since April 2, 2002
*/
public Phase(int phaseNum) {
this.phaseNum = phaseNum;
nodesInPhase = new LinkedList<Node> ();
edgesInPhase = new LinkedList<Edge> ();
result=Result.N_A;
}
/**
* Sets the Graph attribute of the Phase object
*
* @param graph The new Graph value
* @since April 5, 2002
*/
public void setGraph(TransformationGraph graph) {
this.graph = graph;
}
/**
* Gets the phaseNum attribute of the Phase object
*
* @return The phaseNum value
*/
public int getPhaseNum() {
return phaseNum;
}
/**
* An operation that starts execution of graph
*
* @param out OutputStream - if defined, info messages are printed there
* @return True if all nodes successfully started, otherwise False
* @since April 2, 2002
*/
/**
* Description of the Method
*
* @param out OutputStream - if defined, info messages are printed thereDescription of Parameter
* @return returns TRUE if succeeded or FALSE if some Node or Edge failed initialization
* @since April 10, 2002
*/
public boolean init() {
Node node = null;
Edge edge;
Iterator nodeIterator = nodesInPhase.iterator();
Iterator edgeIterator = edgesInPhase.iterator();
phaseExecTime = phaseMemUtilization = 0;
// list of leaf nodes -will be filled later
leafNodes = new LinkedList<Node>();
// if the output stream is specified, create logging possibility information
logger.info("[Clover] Initializing phase: "
+ phaseNum);
// iterate through all edges and initialize them
logger.debug(" initializing edges: ");
while (edgeIterator.hasNext()) {
try {
edge = (Edge) edgeIterator.next();
edge.init();
} catch (ComponentNotReadyException ex) {
logger.error(ex);
return false;
}
}
// if logger exists, print some out information
logger.debug(" all edges initialized successfully... ");
// iterate through all nodes and initialize them
logger.debug(" initializing nodes: ");
while (nodeIterator.hasNext()) {
try {
node = (Node) nodeIterator.next();
// is it a leaf node ?
if (node.isLeaf() || node.isPhaseLeaf()) {
leafNodes.add(node);
}
// if logger exists, print some out information
node.init();
logger.debug("\t" + node.getId() + " ...OK");
} catch (ComponentNotReadyException ex) {
logger.error("\t" + node.getId() + " ...FAILED !", ex);
return false;
} catch (Exception ex) {
logger.error("\t" + node.getId() + " ...FATAL ERROR !", ex);
return false;
}
}
logger.info("[Clover] phase: "
+ phaseNum
+ " initialized successfully.");
result = Result.READY;
return true;
// initialized OK
}
/**
* Description of the Method
*
* @return Description of the Return Value
*/
public ConfigurationStatus checkConfig(ConfigurationStatus status) {
//check nodes configuration
for(Node node : getNodes()) {
node.checkConfig(status);
}
//check edges configuration
// for(Edge edge : getEdgesInPhase()) {
// edge.checkConfig(status);
return status;
}
/**
* An operation that registers Node within current Phase.
*
*
* @param node The feature to be added to the Node attribute
* @since April 2, 2002
*/
protected void assignNode(Node node) {
nodesInPhase.add(node);
node.setPhase(this);
}
/**
* Assigns Edge to belong (also) to this phase.<br> Needed
* for cross-phase edges mostly
*
* @param edge The feature to be added to the Edge attribute
*/
@Deprecated protected void assignEdge(Edge edge) {
edgesInPhase.add(edge);
}
/**
* Adds node to the graph (through this Phase).<br>
* Node is registered to belong to this phase and also
* is globally registered within graph
*
* @param node The feature to be added to the Node attribute
* @throws GraphConfigurationException in case node with the same ID has already
* been registered withing graph
*/
public void addNode(Node node) throws GraphConfigurationException{
assignNode(node);
graph.addNode(node,this);
}
/**
* Adds edge to the graph (through this Phase).<br>
* Edge is registered globally within Graph
*
* @param edge The feature to be added to the Edge attribute
* @throws GraphConfigurationException in case node with the same ID has already
* been registered withing graph
*/
public void addEdge(Edge edge) throws GraphConfigurationException {
graph.addEdge(edge);
}
/**
* Removes all Nodes from Phase
*
* @since April 2, 2002
* @deprecated please use free method instead
*/
@Deprecated
public void destroy() {
free();
}
/**
* Removes all Nodes from Phase
*
* @since April 2, 2002
*/
public void free() {
//free all nodes in this phase
for(Node node : nodesInPhase) {
node.free();
}
//free all edges in this phase
for(Edge edge : edgesInPhase) {
edge.free();
}
nodesInPhase.clear();
edgesInPhase.clear();
}
/**
* Returns reference to Nodes contained in this phase.
*
* @return The nodes value
* @since July 29, 2002
*/
public List<Node> getNodes() {
return nodesInPhase;
}
/**
* Gets the edges attribute of the Phase object
*
* @return The edges value
*/
@Deprecated public List<Edge> getEdges() {
return edgesInPhase;
}
/**
* Description of the Method
*
* @param to Description of the Parameter
* @return Description of the Return Value
*/
public int compareTo(Object to) {
int toPhaseNum = ((Phase) to).getPhaseNum();
if (phaseNum > toPhaseNum) {
return 1;
} else if (phaseNum < toPhaseNum) {
return -1;
} else {
return 0;
}
}
@Override public int hashCode(){
return phaseNum;
}
@Override public boolean equals(Object obj){
if (obj instanceof Phase){
return ((Phase)obj).getPhaseNum()==phaseNum;
}else{
return false;
}
}
/**
* Sets the phaseExecTime attribute of the Phase object
*
* @param time The new phaseExecTime value
*/
public void setPhaseExecTime(int time) {
phaseExecTime = time;
}
/**
* Sets the phaseMemUtilization attribute of the Phase object
*
* @param mem The new phaseMemUtilization value
*/
public void setPhaseMemUtilization(int mem) {
phaseMemUtilization = mem;
}
/**
* Gets the phaseExecTime attribute of the Phase object
*
* @return The phaseExecTime value
*/
public int getPhaseExecTime() {
return phaseExecTime;
}
/**
* Gets the phaseMemUtilization attribute of the Phase object
*
* @return The phaseMemUtilization value
*/
public int getPhaseMemUtilization() {
return phaseMemUtilization;
}
public Result getResult() {
return result;
}
public void setResult(Result result) {
this.result = result;
}
public boolean isCheckPoint() {
return isCheckPoint;
}
public void setCheckPoint(boolean isCheckPoint) {
this.isCheckPoint = isCheckPoint;
}
public List<Edge> getEdgesInPhase() {
return edgesInPhase;
}
public void setEdgesInPhase(List<Edge> edgesInPhase) {
this.edgesInPhase = edgesInPhase;
}
/**
* @return the leafNodes
* @since 10.1.2007
*/
public List<Node> getLeafNodes() {
return leafNodes;
}
/**
* @return the tracking
* @since 10.1.2007
*/
public Map<String, TrackingDetail> getTracking() {
return tracking;
}
/**
* @param tracking the tracking to set
* @since 10.1.2007
*/
public void setTracking(Map<String, TrackingDetail> tracking) {
this.tracking = tracking;
}
}
/*
* end class Phase
*/
|
package net.i2p.client;
import java.util.HashMap;
import java.util.Map;
import net.i2p.I2PAppContext;
import net.i2p.crypto.KeyGenerator;
import net.i2p.data.DataFormatException;
import net.i2p.data.DataHelper;
import net.i2p.data.Destination;
import net.i2p.data.Lease;
import net.i2p.data.LeaseSet;
import net.i2p.data.PrivateKey;
import net.i2p.data.PublicKey;
import net.i2p.data.SessionKey;
import net.i2p.data.SigningPrivateKey;
import net.i2p.data.SigningPublicKey;
import net.i2p.data.i2cp.I2CPMessage;
import net.i2p.data.i2cp.RequestLeaseSetMessage;
import net.i2p.util.Log;
/**
* Handle I2CP RequestLeaseSetMessage from the router by granting all leases
*
* @author jrandom
*/
class RequestLeaseSetMessageHandler extends HandlerImpl {
private Map _existingLeaseSets;
public RequestLeaseSetMessageHandler(I2PAppContext context) {
super(context, RequestLeaseSetMessage.MESSAGE_TYPE);
_existingLeaseSets = new HashMap(32);
}
public void handleMessage(I2CPMessage message, I2PSessionImpl session) {
if (_log.shouldLog(Log.DEBUG))
_log.debug("Handle message " + message);
RequestLeaseSetMessage msg = (RequestLeaseSetMessage) message;
LeaseSet leaseSet = new LeaseSet();
for (int i = 0; i < msg.getEndpoints(); i++) {
Lease lease = new Lease();
lease.setGateway(msg.getRouter(i));
lease.setTunnelId(msg.getTunnelId(i));
lease.setEndDate(msg.getEndDate());
//lease.setStartDate(msg.getStartDate());
leaseSet.addLease(lease);
}
// also, if this session is connected to multiple routers, include other leases here
leaseSet.setDestination(session.getMyDestination());
// reuse the old keys for the client
LeaseInfo li = null;
synchronized (_existingLeaseSets) {
if (_existingLeaseSets.containsKey(session.getMyDestination()))
li = (LeaseInfo) _existingLeaseSets.get(session.getMyDestination());
}
if (li == null) {
li = new LeaseInfo(session.getMyDestination());
synchronized (_existingLeaseSets) {
_existingLeaseSets.put(session.getMyDestination(), li);
}
if (_log.shouldLog(Log.DEBUG))
_log.debug("Creating new leaseInfo keys for "
+ session.getMyDestination().calculateHash().toBase64());
} else {
if (_log.shouldLog(Log.DEBUG))
_log.debug("Caching the old leaseInfo keys for "
+ session.getMyDestination().calculateHash().toBase64());
}
leaseSet.setEncryptionKey(li.getPublicKey());
leaseSet.setSigningKey(li.getSigningPublicKey());
boolean encrypt = Boolean.valueOf(session.getOptions().getProperty("i2cp.encryptLeaseSet")).booleanValue();
String sk = session.getOptions().getProperty("i2cp.leaseSetKey");
if (encrypt && sk != null) {
SessionKey key = new SessionKey();
try {
key.fromBase64(sk);
leaseSet.encrypt(key);
_context.keyRing().put(session.getMyDestination().calculateHash(), key);
} catch (DataFormatException dfe) {
_log.error("Bad leaseset key: " + sk);
}
}
try {
leaseSet.sign(session.getPrivateKey());
session.getProducer().createLeaseSet(session, leaseSet, li.getSigningPrivateKey(), li.getPrivateKey());
session.setLeaseSet(leaseSet);
} catch (DataFormatException dfe) {
session.propogateError("Error signing the leaseSet", dfe);
} catch (I2PSessionException ise) {
session.propogateError("Error sending the signed leaseSet", ise);
}
}
private static class LeaseInfo {
private PublicKey _pubKey;
private PrivateKey _privKey;
private SigningPublicKey _signingPubKey;
private SigningPrivateKey _signingPrivKey;
private Destination _dest;
public LeaseInfo(Destination dest) {
_dest = dest;
Object encKeys[] = KeyGenerator.getInstance().generatePKIKeypair();
Object signKeys[] = KeyGenerator.getInstance().generateSigningKeypair();
_pubKey = (PublicKey) encKeys[0];
_privKey = (PrivateKey) encKeys[1];
_signingPubKey = (SigningPublicKey) signKeys[0];
_signingPrivKey = (SigningPrivateKey) signKeys[1];
}
public PublicKey getPublicKey() {
return _pubKey;
}
public PrivateKey getPrivateKey() {
return _privKey;
}
public SigningPublicKey getSigningPublicKey() {
return _signingPubKey;
}
public SigningPrivateKey getSigningPrivateKey() {
return _signingPrivKey;
}
@Override
public int hashCode() {
return DataHelper.hashCode(_pubKey) + 7 * DataHelper.hashCode(_privKey) + 7 * 7
* DataHelper.hashCode(_signingPubKey) + 7 * 7 * 7 * DataHelper.hashCode(_signingPrivKey);
}
@Override
public boolean equals(Object obj) {
if ((obj == null) || !(obj instanceof LeaseInfo)) return false;
LeaseInfo li = (LeaseInfo) obj;
return DataHelper.eq(_pubKey, li.getPublicKey()) && DataHelper.eq(_privKey, li.getPrivateKey())
&& DataHelper.eq(_signingPubKey, li.getSigningPublicKey())
&& DataHelper.eq(_signingPrivKey, li.getSigningPrivateKey());
}
}
}
|
package bisq.core.btc.wallet;
import bisq.core.btc.exceptions.SigningException;
import bisq.core.btc.exceptions.TransactionVerificationException;
import bisq.core.btc.exceptions.WalletException;
import bisq.core.btc.model.AddressEntry;
import bisq.core.btc.model.InputsAndChangeOutput;
import bisq.core.btc.model.PreparedDepositTxAndMakerInputs;
import bisq.core.btc.model.RawTransactionInput;
import bisq.core.btc.setup.WalletConfig;
import bisq.core.btc.setup.WalletsSetup;
import bisq.core.locale.Res;
import bisq.core.user.Preferences;
import bisq.common.config.Config;
import org.bitcoinj.core.Address;
import org.bitcoinj.core.AddressFormatException;
import org.bitcoinj.core.Coin;
import org.bitcoinj.core.ECKey;
import org.bitcoinj.core.InsufficientMoneyException;
import org.bitcoinj.core.LegacyAddress;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.core.SegwitAddress;
import org.bitcoinj.core.Sha256Hash;
import org.bitcoinj.core.SignatureDecodeException;
import org.bitcoinj.core.Transaction;
import org.bitcoinj.core.TransactionInput;
import org.bitcoinj.core.TransactionOutPoint;
import org.bitcoinj.core.TransactionOutput;
import org.bitcoinj.core.TransactionWitness;
import org.bitcoinj.core.Utils;
import org.bitcoinj.crypto.DeterministicKey;
import org.bitcoinj.crypto.TransactionSignature;
import org.bitcoinj.script.Script;
import org.bitcoinj.script.ScriptBuilder;
import org.bitcoinj.script.ScriptPattern;
import org.bitcoinj.wallet.SendRequest;
import org.bitcoinj.wallet.Wallet;
import javax.inject.Inject;
import com.google.common.collect.ImmutableList;
import org.bouncycastle.crypto.params.KeyParameter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nullable;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
public class TradeWalletService {
private static final Logger log = LoggerFactory.getLogger(TradeWalletService.class);
private final WalletsSetup walletsSetup;
private final Preferences preferences;
private final NetworkParameters params;
@Nullable
private Wallet wallet;
@Nullable
private WalletConfig walletConfig;
@Nullable
private KeyParameter aesKey;
// Constructor, initialization
@Inject
public TradeWalletService(WalletsSetup walletsSetup, Preferences preferences) {
this.walletsSetup = walletsSetup;
this.preferences = preferences;
this.params = Config.baseCurrencyNetworkParameters();
walletsSetup.addSetupCompletedHandler(() -> {
walletConfig = walletsSetup.getWalletConfig();
wallet = walletsSetup.getBtcWallet();
});
}
// AesKey
void setAesKey(@Nullable KeyParameter newAesKey) {
this.aesKey = newAesKey;
}
@Nullable
public KeyParameter getAesKey() {
return aesKey;
}
// Trade fee
/**
* Create a BTC trading fee transaction for the maker or taker of an offer. The first output of the tx is for the
* fee receiver. The second output is the reserve of the trade. There is an optional third output for change.
*
* @param fundingAddress the provided source of funds in case the savings wallet is not used
* @param reservedForTradeAddress the address of the trade reserve
* @param changeAddress the change address to use in case of overpayment or use of the savings wallet
* @param reservedFundsForOffer the amount to reserve for the trade
* @param useSavingsWallet {@code true} to use the savings wallet, {@code false} to use the funding address
* @param tradingFee the amount of the trading fee
* @param txFee the mining fee for this transaction
* @param feeReceiverAddress the address of the receiver of the trading fee
* @param doBroadcast {@code true} to broadcast the transaction, {@code false} otherwise
* @param callback an optional callback to use when broadcasting the transaction
* @return the optionally broadcast transaction
* @throws InsufficientMoneyException if the request could not be completed due to not enough balance
* @throws AddressFormatException if the fee receiver base58 address doesn't parse or its checksum is invalid
*/
public Transaction createBtcTradingFeeTx(Address fundingAddress,
Address reservedForTradeAddress,
Address changeAddress,
Coin reservedFundsForOffer,
boolean useSavingsWallet,
Coin tradingFee,
Coin txFee,
String feeReceiverAddress,
boolean doBroadcast,
@Nullable TxBroadcaster.Callback callback) throws InsufficientMoneyException, AddressFormatException {
Transaction tradingFeeTx = new Transaction(params);
SendRequest sendRequest = null;
try {
tradingFeeTx.addOutput(tradingFee, Address.fromString(params, feeReceiverAddress));
// the reserved amount we need for the trade we send to our trade reservedForTradeAddress
tradingFeeTx.addOutput(reservedFundsForOffer, reservedForTradeAddress);
// we allow spending of unconfirmed tx (double spend risk is low and usability would suffer if we need to
// wait for 1 confirmation)
// In case of double spend we will detect later in the trade process and use a ban score to penalize bad behaviour (not impl. yet)
sendRequest = SendRequest.forTx(tradingFeeTx);
sendRequest.shuffleOutputs = false;
sendRequest.aesKey = aesKey;
if (useSavingsWallet) {
sendRequest.coinSelector = new BtcCoinSelector(walletsSetup.getAddressesByContext(AddressEntry.Context.AVAILABLE),
preferences.getIgnoreDustThreshold());
} else {
sendRequest.coinSelector = new BtcCoinSelector(fundingAddress, preferences.getIgnoreDustThreshold());
}
// We use a fixed fee
sendRequest.fee = txFee;
sendRequest.feePerKb = Coin.ZERO;
sendRequest.ensureMinRequiredFee = false;
// Change is optional in case of overpay or use of funds from savings wallet
sendRequest.changeAddress = changeAddress;
checkNotNull(wallet, "Wallet must not be null");
wallet.completeTx(sendRequest);
if (removeDust(tradingFeeTx)) {
wallet.signTransaction(sendRequest);
}
WalletService.printTx("tradingFeeTx", tradingFeeTx);
if (doBroadcast && callback != null) {
broadcastTx(tradingFeeTx, callback);
}
return tradingFeeTx;
} catch (Throwable t) {
if (wallet != null && sendRequest != null && sendRequest.coinSelector != null) {
log.warn("Balance = {}; CoinSelector = {}", wallet.getBalance(sendRequest.coinSelector), sendRequest.coinSelector);
}
log.warn("createBtcTradingFeeTx failed: tradingFeeTx={}, txOutputs={}", tradingFeeTx.toString(),
tradingFeeTx.getOutputs());
throw t;
}
}
public Transaction completeBsqTradingFeeTx(Transaction preparedBsqTx,
Address fundingAddress,
Address reservedForTradeAddress,
Address changeAddress,
Coin reservedFundsForOffer,
boolean useSavingsWallet,
Coin txFee)
throws TransactionVerificationException, WalletException, InsufficientMoneyException, AddressFormatException {
// preparedBsqTx has following structure:
// inputs [1-n] BSQ inputs
// outputs [0-1] BSQ change output
// mining fee: burned BSQ fee
// We add BTC mining fee. Result tx looks like:
// inputs [1-n] BSQ inputs
// inputs [1-n] BTC inputs
// outputs [0-1] BSQ change output
// outputs [1] BTC reservedForTrade output
// outputs [0-1] BTC change output
// mining fee: BTC mining fee + burned BSQ fee
// In case all BSQ were burnt as fees we have no receiver output and it might be that there are no change outputs
// We need to guarantee that min. 1 valid output is added (OP_RETURN does not count). So we use a higher input
// for BTC to force an additional change output.
final int preparedBsqTxInputsSize = preparedBsqTx.getInputs().size();
final boolean hasBsqOutputs = !preparedBsqTx.getOutputs().isEmpty();
// If there are no BSQ change outputs an output larger than the burnt BSQ amount has to be added as the first
// output to make sure the reserved funds are in output 1, deposit tx input creation depends on the reserve
// being output 1. The amount has to be larger than the BSQ input to make sure the inputs get burnt.
// The BTC changeAddress is used, so it might get used for both output 0 and output 2.
if (!hasBsqOutputs) {
var bsqInputValue = preparedBsqTx.getInputs().stream()
.map(TransactionInput::getValue)
.reduce(Coin.valueOf(0), Coin::add);
preparedBsqTx.addOutput(bsqInputValue.add(Coin.valueOf(1)), changeAddress);
}
// the reserved amount we need for the trade we send to our trade reservedForTradeAddress
preparedBsqTx.addOutput(reservedFundsForOffer, reservedForTradeAddress);
// we allow spending of unconfirmed tx (double spend risk is low and usability would suffer if we need to
// wait for 1 confirmation)
// In case of double spend we will detect later in the trade process and use a ban score to penalize bad behaviour (not impl. yet)
SendRequest sendRequest = SendRequest.forTx(preparedBsqTx);
sendRequest.shuffleOutputs = false;
sendRequest.aesKey = aesKey;
if (useSavingsWallet) {
sendRequest.coinSelector = new BtcCoinSelector(walletsSetup.getAddressesByContext(AddressEntry.Context.AVAILABLE),
preferences.getIgnoreDustThreshold());
} else {
sendRequest.coinSelector = new BtcCoinSelector(fundingAddress, preferences.getIgnoreDustThreshold());
}
// We use a fixed fee
sendRequest.fee = txFee;
sendRequest.feePerKb = Coin.ZERO;
sendRequest.ensureMinRequiredFee = false;
sendRequest.signInputs = false;
// Change is optional in case of overpay or use of funds from savings wallet
sendRequest.changeAddress = changeAddress;
checkNotNull(wallet, "Wallet must not be null");
wallet.completeTx(sendRequest);
Transaction resultTx = sendRequest.tx;
removeDust(resultTx);
// Sign all BTC inputs
for (int i = preparedBsqTxInputsSize; i < resultTx.getInputs().size(); i++) {
TransactionInput txIn = resultTx.getInputs().get(i);
checkArgument(txIn.getConnectedOutput() != null &&
txIn.getConnectedOutput().isMine(wallet),
"txIn.getConnectedOutput() is not in our wallet. That must not happen.");
WalletService.signTransactionInput(wallet, aesKey, resultTx, txIn, i);
WalletService.checkScriptSig(resultTx, txIn, i);
}
WalletService.checkWalletConsistency(wallet);
WalletService.verifyTransaction(resultTx);
WalletService.printTx(Res.getBaseCurrencyCode() + " wallet: Signed tx", resultTx);
return resultTx;
}
// Deposit tx
// We construct the deposit transaction in the way that the buyer is always the first entry (inputs, outputs, MS keys) and then the seller.
// In the creation of the deposit tx the taker/maker roles are the determining roles instead of buyer/seller.
// In the payout tx it is the buyer/seller role. We keep the buyer/seller ordering over all transactions to not get confusion with ordering,
// which is important to follow correctly specially for the order of the MS keys.
/**
* The taker creates a dummy transaction to get the input(s) and optional change output for the amount and the
* taker's address for that trade. That will be used to send to the maker for creating the deposit transaction.
*
* @param takeOfferFeeTx the take offer fee tx
* @param inputAmount amount of takers input
* @param txFee mining fee
* @return a data container holding the inputs, the output value and address
* @throws TransactionVerificationException if there was an unexpected problem with the created dummy tx
*/
public InputsAndChangeOutput takerCreatesDepositTxInputs(Transaction takeOfferFeeTx,
Coin inputAmount,
Coin txFee)
throws TransactionVerificationException {
// We add the mining fee 2 times to the deposit tx:
// 1. Will be spent when publishing the deposit tx (paid by buyer)
// 2. Will be added to the MS amount, so when publishing the payout tx the fee is already there and the outputs are not changed by fee reduction
// The fee for the payout will be paid by the seller.
/*
The tx we create has that structure:
IN[0] input from taker fee tx > inputAmount (including tx fee) (unsigned)
OUT[0] dummyOutputAmount (inputAmount - tx fee)
We are only interested in the inputs.
We get the exact input value from the taker fee tx so we don't create a change output.
*/
// inputAmount includes the tx fee. So we subtract the fee to get the dummyOutputAmount.
Coin dummyOutputAmount = inputAmount.subtract(txFee);
Transaction dummyTX = new Transaction(params);
// The output is just used to get the right inputs and change outputs, so we use an anonymous ECKey, as it will never be used for anything.
// We don't care about fee calculation differences between the real tx and that dummy tx as we use a static tx fee.
TransactionOutput dummyOutput = new TransactionOutput(params, dummyTX, dummyOutputAmount, SegwitAddress.fromKey(params, new ECKey()));
dummyTX.addOutput(dummyOutput);
// Find the needed inputs to pay the output, optionally add 1 change output.
// Normally only 1 input and no change output is used, but we support multiple inputs and 1 change output.
// Our spending transaction output is from the create offer fee payment.
// We created the take offer fee tx in the structure that the second output is for the funds for the deposit tx.
TransactionOutput reservedForTradeOutput = takeOfferFeeTx.getOutputs().get(1);
checkArgument(reservedForTradeOutput.getValue().equals(inputAmount),
"Reserve amount does not equal input amount");
dummyTX.addInput(reservedForTradeOutput);
WalletService.verifyTransaction(dummyTX);
//WalletService.printTx("dummyTX", dummyTX);
List<RawTransactionInput> rawTransactionInputList = dummyTX.getInputs().stream().map(e -> {
checkNotNull(e.getConnectedOutput(), "e.getConnectedOutput() must not be null");
checkNotNull(e.getConnectedOutput().getParentTransaction(),
"e.getConnectedOutput().getParentTransaction() must not be null");
checkNotNull(e.getValue(), "e.getValue() must not be null");
return getRawInputFromTransactionInput(e);
}).collect(Collectors.toList());
// TODO changeOutputValue and changeOutputAddress is not used as taker spends exact amount from fee tx.
// Change is handled already at the fee tx creation so the handling of a change output for the deposit tx
// can be removed here. We still keep it atm as we prefer to not introduce a larger
// refactoring. When new trade protocol gets implemented this can be cleaned.
// The maker though can have a change output if the taker takes less as the max. offer amount!
return new InputsAndChangeOutput(new ArrayList<>(rawTransactionInputList), 0, null);
}
public PreparedDepositTxAndMakerInputs sellerAsMakerCreatesDepositTx(byte[] contractHash,
Coin makerInputAmount,
Coin msOutputAmount,
List<RawTransactionInput> takerRawTransactionInputs,
long takerChangeOutputValue,
@Nullable String takerChangeAddressString,
Address makerAddress,
Address makerChangeAddress,
byte[] buyerPubKey,
byte[] sellerPubKey)
throws SigningException, TransactionVerificationException, WalletException, AddressFormatException {
return makerCreatesDepositTx(false,
contractHash,
makerInputAmount,
msOutputAmount,
takerRawTransactionInputs,
takerChangeOutputValue,
takerChangeAddressString,
makerAddress,
makerChangeAddress,
buyerPubKey,
sellerPubKey);
}
public PreparedDepositTxAndMakerInputs buyerAsMakerCreatesAndSignsDepositTx(byte[] contractHash,
Coin makerInputAmount,
Coin msOutputAmount,
List<RawTransactionInput> takerRawTransactionInputs,
long takerChangeOutputValue,
@Nullable String takerChangeAddressString,
Address makerAddress,
Address makerChangeAddress,
byte[] buyerPubKey,
byte[] sellerPubKey)
throws SigningException, TransactionVerificationException, WalletException, AddressFormatException {
return makerCreatesDepositTx(true,
contractHash,
makerInputAmount,
msOutputAmount,
takerRawTransactionInputs,
takerChangeOutputValue,
takerChangeAddressString,
makerAddress,
makerChangeAddress,
buyerPubKey,
sellerPubKey);
}
/**
* The maker creates the deposit transaction using the takers input(s) and optional output and signs his input(s).
*
* @param makerIsBuyer the flag indicating if we are in the maker as buyer role or the opposite
* @param contractHash the hash of the contract to be added to the OP_RETURN output
* @param makerInputAmount the input amount of the maker
* @param msOutputAmount the output amount to our MS output
* @param takerRawTransactionInputs raw data for the connected outputs for all inputs of the taker (normally 1 input)
* @param takerChangeOutputValue optional taker change output value
* @param takerChangeAddressString optional taker change address
* @param makerAddress the maker's address
* @param makerChangeAddress the maker's change address
* @param buyerPubKey the public key of the buyer
* @param sellerPubKey the public key of the seller
* @return a data container holding the serialized transaction and the maker raw inputs
* @throws SigningException if there was an unexpected problem signing (one of) the input(s) from the maker's wallet
* @throws AddressFormatException if the taker base58 change address doesn't parse or its checksum is invalid
* @throws TransactionVerificationException if there was an unexpected problem with the deposit tx or its signature(s)
* @throws WalletException if the maker's wallet is null or there was an error choosing deposit tx input(s) from it
*/
private PreparedDepositTxAndMakerInputs makerCreatesDepositTx(boolean makerIsBuyer,
byte[] contractHash,
Coin makerInputAmount,
Coin msOutputAmount,
List<RawTransactionInput> takerRawTransactionInputs,
long takerChangeOutputValue,
@Nullable String takerChangeAddressString,
Address makerAddress,
Address makerChangeAddress,
byte[] buyerPubKey,
byte[] sellerPubKey)
throws SigningException, TransactionVerificationException, WalletException, AddressFormatException {
checkArgument(!takerRawTransactionInputs.isEmpty());
// First we construct a dummy TX to get the inputs and outputs we want to use for the real deposit tx.
// Similar to the way we did in the createTakerDepositTxInputs method.
Transaction dummyTx = new Transaction(params);
TransactionOutput dummyOutput = new TransactionOutput(params, dummyTx, makerInputAmount, SegwitAddress.fromKey(params, new ECKey()));
dummyTx.addOutput(dummyOutput);
addAvailableInputsAndChangeOutputs(dummyTx, makerAddress, makerChangeAddress);
// Normally we have only 1 input but we support multiple inputs if the user has paid in with several transactions.
List<TransactionInput> makerInputs = dummyTx.getInputs();
TransactionOutput makerOutput = null;
// We don't support more than 1 optional change output
checkArgument(dummyTx.getOutputs().size() < 3, "dummyTx.getOutputs().size() >= 3");
// Only save change outputs, the dummy output is ignored (that's why we start with index 1)
if (dummyTx.getOutputs().size() > 1) {
makerOutput = dummyTx.getOutput(1);
}
// Now we construct the real deposit tx
Transaction preparedDepositTx = new Transaction(params);
ArrayList<RawTransactionInput> makerRawTransactionInputs = new ArrayList<>();
if (makerIsBuyer) {
// Add buyer inputs
for (TransactionInput input : makerInputs) {
preparedDepositTx.addInput(input);
makerRawTransactionInputs.add(getRawInputFromTransactionInput(input));
}
// Add seller inputs
// the seller's input is not signed so we attach empty script bytes
for (RawTransactionInput rawTransactionInput : takerRawTransactionInputs)
preparedDepositTx.addInput(getTransactionInput(preparedDepositTx, new byte[]{}, rawTransactionInput));
} else {
// taker is buyer role
// Add buyer inputs
// the seller's input is not signed so we attach empty script bytes
for (RawTransactionInput rawTransactionInput : takerRawTransactionInputs)
preparedDepositTx.addInput(getTransactionInput(preparedDepositTx, new byte[]{}, rawTransactionInput));
// Add seller inputs
for (TransactionInput input : makerInputs) {
preparedDepositTx.addInput(input);
makerRawTransactionInputs.add(getRawInputFromTransactionInput(input));
}
}
// Add MultiSig output
Script hashedMultiSigOutputScript = get2of2MultiSigOutputScript(buyerPubKey, sellerPubKey, false);
// Tx fee for deposit tx will be paid by buyer.
TransactionOutput hashedMultiSigOutput = new TransactionOutput(params, preparedDepositTx, msOutputAmount,
hashedMultiSigOutputScript.getProgram());
preparedDepositTx.addOutput(hashedMultiSigOutput);
// We add the hash ot OP_RETURN with a 0 amount output
TransactionOutput contractHashOutput = new TransactionOutput(params, preparedDepositTx, Coin.ZERO,
ScriptBuilder.createOpReturnScript(contractHash).getProgram());
preparedDepositTx.addOutput(contractHashOutput);
TransactionOutput takerTransactionOutput = null;
if (takerChangeOutputValue > 0 && takerChangeAddressString != null) {
takerTransactionOutput = new TransactionOutput(params, preparedDepositTx, Coin.valueOf(takerChangeOutputValue),
Address.fromString(params, takerChangeAddressString));
}
if (makerIsBuyer) {
// Add optional buyer outputs
if (makerOutput != null) {
preparedDepositTx.addOutput(makerOutput);
}
// Add optional seller outputs
if (takerTransactionOutput != null) {
preparedDepositTx.addOutput(takerTransactionOutput);
}
} else {
// taker is buyer role
// Add optional seller outputs
if (takerTransactionOutput != null) {
preparedDepositTx.addOutput(takerTransactionOutput);
}
// Add optional buyer outputs
if (makerOutput != null) {
preparedDepositTx.addOutput(makerOutput);
}
}
int start = makerIsBuyer ? 0 : takerRawTransactionInputs.size();
int end = makerIsBuyer ? makerInputs.size() : preparedDepositTx.getInputs().size();
for (int i = start; i < end; i++) {
TransactionInput input = preparedDepositTx.getInput(i);
signInput(preparedDepositTx, input, i);
WalletService.checkScriptSig(preparedDepositTx, input, i);
}
WalletService.printTx("makerCreatesDepositTx", preparedDepositTx);
WalletService.verifyTransaction(preparedDepositTx);
return new PreparedDepositTxAndMakerInputs(makerRawTransactionInputs, preparedDepositTx.bitcoinSerialize());
}
/**
* The taker signs the deposit transaction he received from the maker and publishes it.
*
* @param takerIsSeller the flag indicating if we are in the taker as seller role or the opposite
* @param contractHash the hash of the contract to be added to the OP_RETURN output
* @param makersDepositTxSerialized the prepared deposit transaction signed by the maker
* @param buyerInputs the connected outputs for all inputs of the buyer
* @param sellerInputs the connected outputs for all inputs of the seller
* @param buyerPubKey the public key of the buyer
* @param sellerPubKey the public key of the seller
* @throws SigningException if (one of) the taker input(s) was of an unrecognized type for signing
* @throws TransactionVerificationException if a maker input wasn't signed, their MultiSig script or contract hash
* doesn't match the taker's, or there was an unexpected problem with the final deposit tx or its signatures
* @throws WalletException if the taker's wallet is null or structurally inconsistent
*/
public Transaction takerSignsDepositTx(boolean takerIsSeller,
byte[] contractHash,
byte[] makersDepositTxSerialized,
List<RawTransactionInput> buyerInputs,
List<RawTransactionInput> sellerInputs,
byte[] buyerPubKey,
byte[] sellerPubKey)
throws SigningException, TransactionVerificationException, WalletException {
Transaction makersDepositTx = new Transaction(params, makersDepositTxSerialized);
checkArgument(!buyerInputs.isEmpty());
checkArgument(!sellerInputs.isEmpty());
// Check if maker's MultiSig script is identical to the takers
Script hashedMultiSigOutputScript = get2of2MultiSigOutputScript(buyerPubKey, sellerPubKey, false);
if (!makersDepositTx.getOutput(0).getScriptPubKey().equals(hashedMultiSigOutputScript)) {
throw new TransactionVerificationException("Maker's hashedMultiSigOutputScript does not match to takers hashedMultiSigOutputScript");
}
// The outpoints are not available from the serialized makersDepositTx, so we cannot use that tx directly, but we use it to construct a new
// depositTx
Transaction depositTx = new Transaction(params);
if (takerIsSeller) {
// Add buyer inputs and apply signature
// We grab the signature from the makersDepositTx and apply it to the new tx input
for (int i = 0; i < buyerInputs.size(); i++) {
TransactionInput makersInput = makersDepositTx.getInputs().get(i);
byte[] makersScriptSigProgram = getMakersScriptSigProgram(makersInput);
TransactionInput input = getTransactionInput(depositTx, makersScriptSigProgram, buyerInputs.get(i));
if (!TransactionWitness.EMPTY.equals(makersInput.getWitness())) {
input.setWitness(makersInput.getWitness());
}
depositTx.addInput(input);
}
// Add seller inputs
for (RawTransactionInput rawTransactionInput : sellerInputs) {
depositTx.addInput(getTransactionInput(depositTx, new byte[]{}, rawTransactionInput));
}
} else {
// taker is buyer
// Add buyer inputs and apply signature
for (RawTransactionInput rawTransactionInput : buyerInputs) {
depositTx.addInput(getTransactionInput(depositTx, new byte[]{}, rawTransactionInput));
}
// Add seller inputs
// We grab the signature from the makersDepositTx and apply it to the new tx input
for (int i = buyerInputs.size(), k = 0; i < makersDepositTx.getInputs().size(); i++, k++) {
TransactionInput transactionInput = makersDepositTx.getInputs().get(i);
// We get the deposit tx unsigned if maker is seller
depositTx.addInput(getTransactionInput(depositTx, new byte[]{}, sellerInputs.get(k)));
}
}
// Check if OP_RETURN output with contract hash matches the one from the maker
TransactionOutput contractHashOutput = new TransactionOutput(params, makersDepositTx, Coin.ZERO,
ScriptBuilder.createOpReturnScript(contractHash).getProgram());
log.debug("contractHashOutput {}", contractHashOutput);
TransactionOutput makersContractHashOutput = makersDepositTx.getOutputs().get(1);
log.debug("makersContractHashOutput {}", makersContractHashOutput);
if (!makersContractHashOutput.getScriptPubKey().equals(contractHashOutput.getScriptPubKey())) {
throw new TransactionVerificationException("Maker's transaction output for the contract hash is not matching takers version.");
}
// Add all outputs from makersDepositTx to depositTx
makersDepositTx.getOutputs().forEach(depositTx::addOutput);
WalletService.printTx("makersDepositTx", makersDepositTx);
// Sign inputs
int start = takerIsSeller ? buyerInputs.size() : 0;
int end = takerIsSeller ? depositTx.getInputs().size() : buyerInputs.size();
for (int i = start; i < end; i++) {
TransactionInput input = depositTx.getInput(i);
signInput(depositTx, input, i);
WalletService.checkScriptSig(depositTx, input, i);
}
WalletService.printTx("takerSignsDepositTx", depositTx);
WalletService.verifyTransaction(depositTx);
WalletService.checkWalletConsistency(wallet);
return depositTx;
}
public void sellerAsMakerFinalizesDepositTx(Transaction myDepositTx,
Transaction takersDepositTx,
int numTakersInputs)
throws TransactionVerificationException, AddressFormatException {
// We add takers signature from his inputs and add it to out tx which was already signed earlier.
for (int i = 0; i < numTakersInputs; i++) {
TransactionInput takersInput = takersDepositTx.getInput(i);
Script takersScriptSig = takersInput.getScriptSig();
TransactionInput txInput = myDepositTx.getInput(i);
txInput.setScriptSig(takersScriptSig);
TransactionWitness witness = takersInput.getWitness();
if (!TransactionWitness.EMPTY.equals(witness)) {
txInput.setWitness(witness);
}
}
WalletService.printTx("sellerAsMakerFinalizesDepositTx", myDepositTx);
WalletService.verifyTransaction(myDepositTx);
}
// Delayed payout tx
public Transaction createDelayedUnsignedPayoutTx(Transaction depositTx,
String donationAddressString,
Coin minerFee,
long lockTime)
throws AddressFormatException, TransactionVerificationException {
TransactionOutput hashedMultiSigOutput = depositTx.getOutput(0);
Transaction delayedPayoutTx = new Transaction(params);
delayedPayoutTx.addInput(hashedMultiSigOutput);
applyLockTime(lockTime, delayedPayoutTx);
Coin outputAmount = hashedMultiSigOutput.getValue().subtract(minerFee);
delayedPayoutTx.addOutput(outputAmount, Address.fromString(params, donationAddressString));
WalletService.printTx("Unsigned delayedPayoutTx ToDonationAddress", delayedPayoutTx);
WalletService.verifyTransaction(delayedPayoutTx);
return delayedPayoutTx;
}
public byte[] signDelayedPayoutTx(Transaction delayedPayoutTx,
Transaction preparedDepositTx,
DeterministicKey myMultiSigKeyPair,
byte[] buyerPubKey,
byte[] sellerPubKey)
throws AddressFormatException, TransactionVerificationException {
Script redeemScript = get2of2MultiSigRedeemScript(buyerPubKey, sellerPubKey);
Sha256Hash sigHash;
Coin delayedPayoutTxInputValue = preparedDepositTx.getOutput(0).getValue();
sigHash = delayedPayoutTx.hashForWitnessSignature(0, redeemScript,
delayedPayoutTxInputValue, Transaction.SigHash.ALL, false);
checkNotNull(myMultiSigKeyPair, "myMultiSigKeyPair must not be null");
if (myMultiSigKeyPair.isEncrypted()) {
checkNotNull(aesKey);
}
ECKey.ECDSASignature mySignature = myMultiSigKeyPair.sign(sigHash, aesKey).toCanonicalised();
WalletService.printTx("delayedPayoutTx for sig creation", delayedPayoutTx);
WalletService.verifyTransaction(delayedPayoutTx);
return mySignature.encodeToDER();
}
public Transaction finalizeDelayedPayoutTx(Transaction delayedPayoutTx,
byte[] buyerPubKey,
byte[] sellerPubKey,
byte[] buyerSignature,
byte[] sellerSignature)
throws AddressFormatException, TransactionVerificationException, WalletException, SignatureDecodeException {
Script redeemScript = get2of2MultiSigRedeemScript(buyerPubKey, sellerPubKey);
ECKey.ECDSASignature buyerECDSASignature = ECKey.ECDSASignature.decodeFromDER(buyerSignature);
ECKey.ECDSASignature sellerECDSASignature = ECKey.ECDSASignature.decodeFromDER(sellerSignature);
TransactionSignature buyerTxSig = new TransactionSignature(buyerECDSASignature, Transaction.SigHash.ALL, false);
TransactionSignature sellerTxSig = new TransactionSignature(sellerECDSASignature, Transaction.SigHash.ALL, false);
TransactionInput input = delayedPayoutTx.getInput(0);
input.setScriptSig(ScriptBuilder.createEmpty());
TransactionWitness witness = TransactionWitness.redeemP2WSH(redeemScript, sellerTxSig, buyerTxSig);
input.setWitness(witness);
WalletService.printTx("finalizeDelayedPayoutTx", delayedPayoutTx);
WalletService.verifyTransaction(delayedPayoutTx);
WalletService.checkWalletConsistency(wallet);
WalletService.checkScriptSig(delayedPayoutTx, input, 0);
checkNotNull(input.getConnectedOutput(), "input.getConnectedOutput() must not be null");
input.verify(input.getConnectedOutput());
return delayedPayoutTx;
}
// Standard payout tx
/**
* Seller signs payout transaction, buyer has not signed yet.
*
* @param depositTx deposit transaction
* @param buyerPayoutAmount payout amount for buyer
* @param sellerPayoutAmount payout amount for seller
* @param buyerPayoutAddressString address for buyer
* @param sellerPayoutAddressString address for seller
* @param multiSigKeyPair DeterministicKey for MultiSig from seller
* @param buyerPubKey the public key of the buyer
* @param sellerPubKey the public key of the seller
* @return DER encoded canonical signature
* @throws AddressFormatException if the buyer or seller base58 address doesn't parse or its checksum is invalid
* @throws TransactionVerificationException if there was an unexpected problem with the payout tx or its signature
*/
public byte[] buyerSignsPayoutTx(Transaction depositTx,
Coin buyerPayoutAmount,
Coin sellerPayoutAmount,
String buyerPayoutAddressString,
String sellerPayoutAddressString,
DeterministicKey multiSigKeyPair,
byte[] buyerPubKey,
byte[] sellerPubKey)
throws AddressFormatException, TransactionVerificationException {
Transaction preparedPayoutTx = createPayoutTx(depositTx, buyerPayoutAmount, sellerPayoutAmount,
buyerPayoutAddressString, sellerPayoutAddressString);
// MS redeemScript
Script redeemScript = get2of2MultiSigRedeemScript(buyerPubKey, sellerPubKey);
// MS output from prev. tx is index 0
Sha256Hash sigHash;
TransactionOutput hashedMultiSigOutput = depositTx.getOutput(0);
if (ScriptPattern.isP2SH(hashedMultiSigOutput.getScriptPubKey())) {
sigHash = preparedPayoutTx.hashForSignature(0, redeemScript, Transaction.SigHash.ALL, false);
} else {
Coin inputValue = hashedMultiSigOutput.getValue();
sigHash = preparedPayoutTx.hashForWitnessSignature(0, redeemScript,
inputValue, Transaction.SigHash.ALL, false);
}
checkNotNull(multiSigKeyPair, "multiSigKeyPair must not be null");
if (multiSigKeyPair.isEncrypted()) {
checkNotNull(aesKey);
}
ECKey.ECDSASignature buyerSignature = multiSigKeyPair.sign(sigHash, aesKey).toCanonicalised();
WalletService.printTx("prepared payoutTx", preparedPayoutTx);
WalletService.verifyTransaction(preparedPayoutTx);
return buyerSignature.encodeToDER();
}
/**
* Seller creates and signs payout transaction and adds signature of buyer to complete the transaction.
*
* @param depositTx deposit transaction
* @param buyerSignature DER encoded canonical signature of buyer
* @param buyerPayoutAmount payout amount for buyer
* @param sellerPayoutAmount payout amount for seller
* @param buyerPayoutAddressString address for buyer
* @param sellerPayoutAddressString address for seller
* @param multiSigKeyPair seller's key pair for MultiSig
* @param buyerPubKey the public key of the buyer
* @param sellerPubKey the public key of the seller
* @return the payout transaction
* @throws AddressFormatException if the buyer or seller base58 address doesn't parse or its checksum is invalid
* @throws TransactionVerificationException if there was an unexpected problem with the payout tx or its signatures
* @throws WalletException if the seller's wallet is null or structurally inconsistent
*/
public Transaction sellerSignsAndFinalizesPayoutTx(Transaction depositTx,
byte[] buyerSignature,
Coin buyerPayoutAmount,
Coin sellerPayoutAmount,
String buyerPayoutAddressString,
String sellerPayoutAddressString,
DeterministicKey multiSigKeyPair,
byte[] buyerPubKey,
byte[] sellerPubKey)
throws AddressFormatException, TransactionVerificationException, WalletException, SignatureDecodeException {
Transaction payoutTx = createPayoutTx(depositTx, buyerPayoutAmount, sellerPayoutAmount, buyerPayoutAddressString, sellerPayoutAddressString);
// MS redeemScript
Script redeemScript = get2of2MultiSigRedeemScript(buyerPubKey, sellerPubKey);
// MS output from prev. tx is index 0
TransactionOutput hashedMultiSigOutput = depositTx.getOutput(0);
boolean hashedMultiSigOutputIsLegacy = ScriptPattern.isP2SH(hashedMultiSigOutput.getScriptPubKey());
Sha256Hash sigHash;
if (hashedMultiSigOutputIsLegacy) {
sigHash = payoutTx.hashForSignature(0, redeemScript, Transaction.SigHash.ALL, false);
} else {
Coin inputValue = hashedMultiSigOutput.getValue();
sigHash = payoutTx.hashForWitnessSignature(0, redeemScript,
inputValue, Transaction.SigHash.ALL, false);
}
checkNotNull(multiSigKeyPair, "multiSigKeyPair must not be null");
if (multiSigKeyPair.isEncrypted()) {
checkNotNull(aesKey);
}
ECKey.ECDSASignature sellerSignature = multiSigKeyPair.sign(sigHash, aesKey).toCanonicalised();
TransactionSignature buyerTxSig = new TransactionSignature(ECKey.ECDSASignature.decodeFromDER(buyerSignature),
Transaction.SigHash.ALL, false);
TransactionSignature sellerTxSig = new TransactionSignature(sellerSignature, Transaction.SigHash.ALL, false);
// Take care of order of signatures. Need to be reversed here. See comment below at getMultiSigRedeemScript (seller, buyer)
TransactionInput input = payoutTx.getInput(0);
if (hashedMultiSigOutputIsLegacy) {
Script inputScript = ScriptBuilder.createP2SHMultiSigInputScript(ImmutableList.of(sellerTxSig, buyerTxSig),
redeemScript);
input.setScriptSig(inputScript);
} else {
input.setScriptSig(ScriptBuilder.createEmpty());
TransactionWitness witness = TransactionWitness.redeemP2WSH(redeemScript, sellerTxSig, buyerTxSig);
input.setWitness(witness);
}
WalletService.printTx("payoutTx", payoutTx);
WalletService.verifyTransaction(payoutTx);
WalletService.checkWalletConsistency(wallet);
WalletService.checkScriptSig(payoutTx, input, 0);
checkNotNull(input.getConnectedOutput(), "input.getConnectedOutput() must not be null");
input.verify(input.getConnectedOutput());
return payoutTx;
}
// Mediated payoutTx
public byte[] signMediatedPayoutTx(Transaction depositTx,
Coin buyerPayoutAmount,
Coin sellerPayoutAmount,
String buyerPayoutAddressString,
String sellerPayoutAddressString,
DeterministicKey myMultiSigKeyPair,
byte[] buyerPubKey,
byte[] sellerPubKey)
throws AddressFormatException, TransactionVerificationException {
Transaction preparedPayoutTx = createPayoutTx(depositTx, buyerPayoutAmount, sellerPayoutAmount, buyerPayoutAddressString, sellerPayoutAddressString);
// MS redeemScript
Script redeemScript = get2of2MultiSigRedeemScript(buyerPubKey, sellerPubKey);
// MS output from prev. tx is index 0
TransactionOutput hashedMultiSigOutput = depositTx.getOutput(0);
boolean hashedMultiSigOutputIsLegacy = ScriptPattern.isP2SH(hashedMultiSigOutput.getScriptPubKey());
Sha256Hash sigHash;
if (hashedMultiSigOutputIsLegacy) {
sigHash = preparedPayoutTx.hashForSignature(0, redeemScript, Transaction.SigHash.ALL, false);
} else {
Coin inputValue = hashedMultiSigOutput.getValue();
sigHash = preparedPayoutTx.hashForWitnessSignature(0, redeemScript,
inputValue, Transaction.SigHash.ALL, false);
}
checkNotNull(myMultiSigKeyPair, "myMultiSigKeyPair must not be null");
if (myMultiSigKeyPair.isEncrypted()) {
checkNotNull(aesKey);
}
ECKey.ECDSASignature mySignature = myMultiSigKeyPair.sign(sigHash, aesKey).toCanonicalised();
WalletService.printTx("prepared mediated payoutTx for sig creation", preparedPayoutTx);
WalletService.verifyTransaction(preparedPayoutTx);
return mySignature.encodeToDER();
}
public Transaction finalizeMediatedPayoutTx(Transaction depositTx,
byte[] buyerSignature,
byte[] sellerSignature,
Coin buyerPayoutAmount,
Coin sellerPayoutAmount,
String buyerPayoutAddressString,
String sellerPayoutAddressString,
DeterministicKey multiSigKeyPair,
byte[] buyerPubKey,
byte[] sellerPubKey)
throws AddressFormatException, TransactionVerificationException, WalletException, SignatureDecodeException {
Transaction payoutTx = createPayoutTx(depositTx, buyerPayoutAmount, sellerPayoutAmount, buyerPayoutAddressString, sellerPayoutAddressString);
// MS redeemScript
Script redeemScript = get2of2MultiSigRedeemScript(buyerPubKey, sellerPubKey);
// MS output from prev. tx is index 0
checkNotNull(multiSigKeyPair, "multiSigKeyPair must not be null");
TransactionSignature buyerTxSig = new TransactionSignature(ECKey.ECDSASignature.decodeFromDER(buyerSignature),
Transaction.SigHash.ALL, false);
TransactionSignature sellerTxSig = new TransactionSignature(ECKey.ECDSASignature.decodeFromDER(sellerSignature),
Transaction.SigHash.ALL, false);
// Take care of order of signatures. Need to be reversed here. See comment below at getMultiSigRedeemScript (seller, buyer)
TransactionOutput hashedMultiSigOutput = depositTx.getOutput(0);
boolean hashedMultiSigOutputIsLegacy = ScriptPattern.isP2SH(hashedMultiSigOutput.getScriptPubKey());
TransactionInput input = payoutTx.getInput(0);
if (hashedMultiSigOutputIsLegacy) {
Script inputScript = ScriptBuilder.createP2SHMultiSigInputScript(ImmutableList.of(sellerTxSig, buyerTxSig),
redeemScript);
input.setScriptSig(inputScript);
} else {
input.setScriptSig(ScriptBuilder.createEmpty());
TransactionWitness witness = TransactionWitness.redeemP2WSH(redeemScript, sellerTxSig, buyerTxSig);
input.setWitness(witness);
}
WalletService.printTx("mediated payoutTx", payoutTx);
WalletService.verifyTransaction(payoutTx);
WalletService.checkWalletConsistency(wallet);
WalletService.checkScriptSig(payoutTx, input, 0);
checkNotNull(input.getConnectedOutput(), "input.getConnectedOutput() must not be null");
input.verify(input.getConnectedOutput());
return payoutTx;
}
// Arbitrated payoutTx
// TODO: Once we have removed legacy arbitrator from dispute domain we can remove that method as well.
// Atm it is still used by ArbitrationManager.
/**
* A trader who got the signed tx from the arbitrator finalizes the payout tx.
*
* @param depositTxSerialized serialized deposit tx
* @param arbitratorSignature DER encoded canonical signature of arbitrator
* @param buyerPayoutAmount payout amount of the buyer
* @param sellerPayoutAmount payout amount of the seller
* @param buyerAddressString the address of the buyer
* @param sellerAddressString the address of the seller
* @param tradersMultiSigKeyPair the key pair for the MultiSig of the trader who calls that method
* @param buyerPubKey the public key of the buyer
* @param sellerPubKey the public key of the seller
* @param arbitratorPubKey the public key of the arbitrator
* @return the completed payout tx
* @throws AddressFormatException if the buyer or seller base58 address doesn't parse or its checksum is invalid
* @throws TransactionVerificationException if there was an unexpected problem with the payout tx or its signature
* @throws WalletException if the trade wallet is null or structurally inconsistent
*/
public Transaction traderSignAndFinalizeDisputedPayoutTx(byte[] depositTxSerialized,
byte[] arbitratorSignature,
Coin buyerPayoutAmount,
Coin sellerPayoutAmount,
String buyerAddressString,
String sellerAddressString,
DeterministicKey tradersMultiSigKeyPair,
byte[] buyerPubKey,
byte[] sellerPubKey,
byte[] arbitratorPubKey)
throws AddressFormatException, TransactionVerificationException, WalletException, SignatureDecodeException {
Transaction depositTx = new Transaction(params, depositTxSerialized);
TransactionOutput hashedMultiSigOutput = depositTx.getOutput(0);
Transaction payoutTx = new Transaction(params);
payoutTx.addInput(hashedMultiSigOutput);
if (buyerPayoutAmount.isPositive()) {
payoutTx.addOutput(buyerPayoutAmount, Address.fromString(params, buyerAddressString));
}
if (sellerPayoutAmount.isPositive()) {
payoutTx.addOutput(sellerPayoutAmount, Address.fromString(params, sellerAddressString));
}
// take care of sorting!
Script redeemScript = get2of3MultiSigRedeemScript(buyerPubKey, sellerPubKey, arbitratorPubKey);
Sha256Hash sigHash;
boolean hashedMultiSigOutputIsLegacy = !ScriptPattern.isP2SH(hashedMultiSigOutput.getScriptPubKey());
if (hashedMultiSigOutputIsLegacy) {
sigHash = payoutTx.hashForSignature(0, redeemScript, Transaction.SigHash.ALL, false);
} else {
Coin inputValue = hashedMultiSigOutput.getValue();
sigHash = payoutTx.hashForWitnessSignature(0, redeemScript,
inputValue, Transaction.SigHash.ALL, false);
}
checkNotNull(tradersMultiSigKeyPair, "tradersMultiSigKeyPair must not be null");
if (tradersMultiSigKeyPair.isEncrypted()) {
checkNotNull(aesKey);
}
ECKey.ECDSASignature tradersSignature = tradersMultiSigKeyPair.sign(sigHash, aesKey).toCanonicalised();
TransactionSignature tradersTxSig = new TransactionSignature(tradersSignature, Transaction.SigHash.ALL, false);
TransactionSignature arbitratorTxSig = new TransactionSignature(ECKey.ECDSASignature.decodeFromDER(arbitratorSignature),
Transaction.SigHash.ALL, false);
TransactionInput input = payoutTx.getInput(0);
// Take care of order of signatures. See comment below at getMultiSigRedeemScript (sort order needed here: arbitrator, seller, buyer)
if (hashedMultiSigOutputIsLegacy) {
Script inputScript = ScriptBuilder.createP2SHMultiSigInputScript(
ImmutableList.of(arbitratorTxSig, tradersTxSig),
redeemScript);
input.setScriptSig(inputScript);
} else {
input.setScriptSig(ScriptBuilder.createEmpty());
TransactionWitness witness = TransactionWitness.redeemP2WSH(redeemScript, arbitratorTxSig, tradersTxSig);
input.setWitness(witness);
}
WalletService.printTx("disputed payoutTx", payoutTx);
WalletService.verifyTransaction(payoutTx);
WalletService.checkWalletConsistency(wallet);
WalletService.checkScriptSig(payoutTx, input, 0);
checkNotNull(input.getConnectedOutput(), "input.getConnectedOutput() must not be null");
input.verify(input.getConnectedOutput());
return payoutTx;
}
// Emergency payoutTx
public void emergencySignAndPublishPayoutTxFrom2of2MultiSig(String depositTxHex,
Coin buyerPayoutAmount,
Coin sellerPayoutAmount,
Coin txFee,
String buyerAddressString,
String sellerAddressString,
String buyerPrivateKeyAsHex,
String sellerPrivateKeyAsHex,
String buyerPubKeyAsHex,
String sellerPubKeyAsHex,
boolean hashedMultiSigOutputIsLegacy,
TxBroadcaster.Callback callback)
throws AddressFormatException, TransactionVerificationException, WalletException {
byte[] buyerPubKey = ECKey.fromPublicOnly(Utils.HEX.decode(buyerPubKeyAsHex)).getPubKey();
byte[] sellerPubKey = ECKey.fromPublicOnly(Utils.HEX.decode(sellerPubKeyAsHex)).getPubKey();
Script hashedMultiSigOutputScript = get2of2MultiSigOutputScript(buyerPubKey, sellerPubKey,
hashedMultiSigOutputIsLegacy);
Coin msOutputValue = buyerPayoutAmount.add(sellerPayoutAmount).add(txFee);
TransactionOutput hashedMultiSigOutput = new TransactionOutput(params, null, msOutputValue, hashedMultiSigOutputScript.getProgram());
Transaction depositTx = new Transaction(params);
depositTx.addOutput(hashedMultiSigOutput);
Transaction payoutTx = new Transaction(params);
Sha256Hash spendTxHash = Sha256Hash.wrap(depositTxHex);
payoutTx.addInput(new TransactionInput(params, depositTx, null, new TransactionOutPoint(params, 0, spendTxHash), msOutputValue));
if (buyerPayoutAmount.isPositive()) {
payoutTx.addOutput(buyerPayoutAmount, Address.fromString(params, buyerAddressString));
}
if (sellerPayoutAmount.isPositive()) {
payoutTx.addOutput(sellerPayoutAmount, Address.fromString(params, sellerAddressString));
}
// take care of sorting!
Script redeemScript = get2of2MultiSigRedeemScript(buyerPubKey, sellerPubKey);
Sha256Hash sigHash;
if (hashedMultiSigOutputIsLegacy) {
sigHash = payoutTx.hashForSignature(0, redeemScript, Transaction.SigHash.ALL, false);
} else {
Coin inputValue = msOutputValue;
sigHash = payoutTx.hashForWitnessSignature(0, redeemScript,
inputValue, Transaction.SigHash.ALL, false);
}
ECKey buyerPrivateKey = ECKey.fromPrivate(Utils.HEX.decode(buyerPrivateKeyAsHex));
checkNotNull(buyerPrivateKey, "key must not be null");
ECKey.ECDSASignature buyerECDSASignature = buyerPrivateKey.sign(sigHash, aesKey).toCanonicalised();
ECKey sellerPrivateKey = ECKey.fromPrivate(Utils.HEX.decode(sellerPrivateKeyAsHex));
checkNotNull(sellerPrivateKey, "key must not be null");
ECKey.ECDSASignature sellerECDSASignature = sellerPrivateKey.sign(sigHash, aesKey).toCanonicalised();
TransactionSignature buyerTxSig = new TransactionSignature(buyerECDSASignature, Transaction.SigHash.ALL, false);
TransactionSignature sellerTxSig = new TransactionSignature(sellerECDSASignature, Transaction.SigHash.ALL, false);
TransactionInput input = payoutTx.getInput(0);
if (hashedMultiSigOutputIsLegacy) {
Script inputScript = ScriptBuilder.createP2SHMultiSigInputScript(ImmutableList.of(sellerTxSig, buyerTxSig),
redeemScript);
input.setScriptSig(inputScript);
} else {
input.setScriptSig(ScriptBuilder.createEmpty());
TransactionWitness witness = TransactionWitness.redeemP2WSH(redeemScript, sellerTxSig, buyerTxSig);
input.setWitness(witness);
}
WalletService.printTx("payoutTx", payoutTx);
WalletService.verifyTransaction(payoutTx);
WalletService.checkWalletConsistency(wallet);
broadcastTx(payoutTx, callback, 20);
}
// Broadcast tx
public void broadcastTx(Transaction tx, TxBroadcaster.Callback callback) {
checkNotNull(walletConfig);
TxBroadcaster.broadcastTx(wallet, walletConfig.peerGroup(), tx, callback);
}
public void broadcastTx(Transaction tx, TxBroadcaster.Callback callback, int timeoutInSec) {
checkNotNull(walletConfig);
TxBroadcaster.broadcastTx(wallet, walletConfig.peerGroup(), tx, callback, timeoutInSec);
}
// Misc
/**
* Returns the local existing wallet transaction with the given ID, or {@code null} if missing.
*
* @param txId the transaction ID of the transaction we want to lookup
*/
public Transaction getWalletTx(Sha256Hash txId) {
checkNotNull(wallet);
return wallet.getTransaction(txId);
}
public void commitTx(Transaction tx) {
checkNotNull(wallet);
wallet.commitTx(tx);
}
public Transaction getClonedTransaction(Transaction tx) {
return new Transaction(params, tx.bitcoinSerialize());
}
// Private methods
private RawTransactionInput getRawInputFromTransactionInput(@NotNull TransactionInput input) {
checkNotNull(input.getConnectedOutput(), "input.getConnectedOutput() must not be null");
checkNotNull(input.getConnectedOutput().getParentTransaction(),
"input.getConnectedOutput().getParentTransaction() must not be null");
checkNotNull(input.getValue(), "input.getValue() must not be null");
return new RawTransactionInput(input.getOutpoint().getIndex(),
input.getConnectedOutput().getParentTransaction().bitcoinSerialize(false),
input.getValue().value);
}
private byte[] getMakersScriptSigProgram(TransactionInput transactionInput) throws TransactionVerificationException {
byte[] scriptProgram = transactionInput.getScriptSig().getProgram();
if (scriptProgram.length == 0) {
throw new TransactionVerificationException("Inputs from maker not signed.");
}
return scriptProgram;
}
private TransactionInput getTransactionInput(Transaction depositTx,
byte[] scriptProgram,
RawTransactionInput rawTransactionInput) {
return new TransactionInput(params, depositTx, scriptProgram, new TransactionOutPoint(params,
rawTransactionInput.index, new Transaction(params, rawTransactionInput.parentTransaction)),
Coin.valueOf(rawTransactionInput.value));
}
// TODO: Once we have removed legacy arbitrator from dispute domain we can remove that method as well.
// Atm it is still used by traderSignAndFinalizeDisputedPayoutTx which is used by ArbitrationManager.
// Don't use ScriptBuilder.createRedeemScript and ScriptBuilder.createP2SHOutputScript as they use a sorting
// (Collections.sort(pubKeys, ECKey.PUBKEY_COMPARATOR);) which can lead to a non-matching list of signatures with pubKeys and the executeMultiSig does
// not iterate all possible combinations of sig/pubKeys leading to a verification fault. That nasty bug happens just randomly as the list after sorting
// might differ from the provided one or not.
// Changing the while loop in executeMultiSig to fix that does not help as the reference implementation seems to behave the same (not iterating all
// possibilities) .
// Furthermore the executed list is reversed to the provided.
// Best practice is to provide the list sorted by the least probable successful candidates first (arbitrator is first -> will be last in execution loop, so
// avoiding unneeded expensive ECKey.verify calls)
private Script get2of3MultiSigRedeemScript(byte[] buyerPubKey, byte[] sellerPubKey, byte[] arbitratorPubKey) {
ECKey buyerKey = ECKey.fromPublicOnly(buyerPubKey);
ECKey sellerKey = ECKey.fromPublicOnly(sellerPubKey);
ECKey arbitratorKey = ECKey.fromPublicOnly(arbitratorPubKey);
// Take care of sorting! Need to reverse to the order we use normally (buyer, seller, arbitrator)
List<ECKey> keys = ImmutableList.of(arbitratorKey, sellerKey, buyerKey);
return ScriptBuilder.createMultiSigOutputScript(2, keys);
}
private Script get2of2MultiSigRedeemScript(byte[] buyerPubKey, byte[] sellerPubKey) {
ECKey buyerKey = ECKey.fromPublicOnly(buyerPubKey);
ECKey sellerKey = ECKey.fromPublicOnly(sellerPubKey);
// Take care of sorting! Need to reverse to the order we use normally (buyer, seller)
List<ECKey> keys = ImmutableList.of(sellerKey, buyerKey);
return ScriptBuilder.createMultiSigOutputScript(2, keys);
}
private Script get2of2MultiSigOutputScript(byte[] buyerPubKey, byte[] sellerPubKey, boolean legacy) {
Script redeemScript = get2of2MultiSigRedeemScript(buyerPubKey, sellerPubKey);
if (legacy) {
return ScriptBuilder.createP2SHOutputScript(redeemScript);
} else {
return ScriptBuilder.createP2WSHOutputScript(redeemScript);
}
}
private Transaction createPayoutTx(Transaction depositTx,
Coin buyerPayoutAmount,
Coin sellerPayoutAmount,
String buyerAddressString,
String sellerAddressString) throws AddressFormatException {
TransactionOutput hashedMultiSigOutput = depositTx.getOutput(0);
Transaction transaction = new Transaction(params);
transaction.addInput(hashedMultiSigOutput);
if (buyerPayoutAmount.isPositive()) {
transaction.addOutput(buyerPayoutAmount, Address.fromString(params, buyerAddressString));
}
if (sellerPayoutAmount.isPositive()) {
transaction.addOutput(sellerPayoutAmount, Address.fromString(params, sellerAddressString));
}
checkArgument(transaction.getOutputs().size() >= 1, "We need at least one output.");
return transaction;
}
private void signInput(Transaction transaction, TransactionInput input, int inputIndex) throws SigningException {
checkNotNull(input.getConnectedOutput(), "input.getConnectedOutput() must not be null");
Script scriptPubKey = input.getConnectedOutput().getScriptPubKey();
checkNotNull(wallet);
ECKey sigKey = input.getOutpoint().getConnectedKey(wallet);
checkNotNull(sigKey, "signInput: sigKey must not be null. input.getOutpoint()=" +
input.getOutpoint().toString());
if (sigKey.isEncrypted()) {
checkNotNull(aesKey);
}
if (ScriptPattern.isP2PK(scriptPubKey) || ScriptPattern.isP2PKH(scriptPubKey)) {
Sha256Hash hash = transaction.hashForSignature(inputIndex, scriptPubKey, Transaction.SigHash.ALL, false);
ECKey.ECDSASignature signature = sigKey.sign(hash, aesKey);
TransactionSignature txSig = new TransactionSignature(signature, Transaction.SigHash.ALL, false);
if (ScriptPattern.isP2PK(scriptPubKey)) {
input.setScriptSig(ScriptBuilder.createInputScript(txSig));
} else if (ScriptPattern.isP2PKH(scriptPubKey)) {
input.setScriptSig(ScriptBuilder.createInputScript(txSig, sigKey));
}
} else if (ScriptPattern.isP2WPKH(scriptPubKey)) {
// TODO: Consider using this alternative way to build the scriptCode (taken from bitcoinj master)
// Script scriptCode = ScriptBuilder.createP2PKHOutputScript(sigKey)
Script scriptCode = new ScriptBuilder().data(
ScriptBuilder.createOutputScript(LegacyAddress.fromKey(transaction.getParams(), sigKey)).getProgram())
.build();
Coin value = input.getValue();
TransactionSignature txSig = transaction.calculateWitnessSignature(inputIndex, sigKey, scriptCode, value,
Transaction.SigHash.ALL, false);
input.setScriptSig(ScriptBuilder.createEmpty());
input.setWitness(TransactionWitness.redeemP2WPKH(txSig, sigKey));
} else {
throw new SigningException("Don't know how to sign for this kind of scriptPubKey: " + scriptPubKey);
}
}
private void addAvailableInputsAndChangeOutputs(Transaction transaction,
Address address,
Address changeAddress) throws WalletException {
SendRequest sendRequest = null;
try {
// Let the framework do the work to find the right inputs
sendRequest = SendRequest.forTx(transaction);
sendRequest.shuffleOutputs = false;
sendRequest.aesKey = aesKey;
// We use a fixed fee
sendRequest.fee = Coin.ZERO;
sendRequest.feePerKb = Coin.ZERO;
sendRequest.ensureMinRequiredFee = false;
// we allow spending of unconfirmed tx (double spend risk is low and usability would suffer if we need to wait for 1 confirmation)
sendRequest.coinSelector = new BtcCoinSelector(address, preferences.getIgnoreDustThreshold());
// We use always the same address in a trade for all transactions
sendRequest.changeAddress = changeAddress;
// With the usage of completeTx() we get all the work done with fee calculation, validation and coin selection.
// We don't commit that tx to the wallet as it will be changed later and it's not signed yet.
// So it will not change the wallet balance.
checkNotNull(wallet, "wallet must not be null");
wallet.completeTx(sendRequest);
} catch (Throwable t) {
if (sendRequest != null && sendRequest.tx != null) {
log.warn("addAvailableInputsAndChangeOutputs: sendRequest.tx={}, sendRequest.tx.getOutputs()={}",
sendRequest.tx, sendRequest.tx.getOutputs());
}
throw new WalletException(t);
}
}
private void applyLockTime(long lockTime, Transaction tx) {
checkArgument(!tx.getInputs().isEmpty(), "The tx must have inputs. tx={}", tx);
tx.getInputs().forEach(input -> input.setSequenceNumber(TransactionInput.NO_SEQUENCE - 1));
tx.setLockTime(lockTime);
}
// BISQ issue #4039: prevent dust outputs from being created.
// check all the outputs in a proposed transaction, if any are below the dust threshold
// remove them, noting the details in the log. returns 'true' to indicate if any dust was
// removed.
private boolean removeDust(Transaction transaction) {
List<TransactionOutput> originalTransactionOutputs = transaction.getOutputs();
List<TransactionOutput> keepTransactionOutputs = new ArrayList<>();
for (TransactionOutput transactionOutput : originalTransactionOutputs) {
if (transactionOutput.getValue().isLessThan(Restrictions.getMinNonDustOutput())) {
log.info("your transaction would have contained a dust output of {}", transactionOutput.toString());
} else {
keepTransactionOutputs.add(transactionOutput);
}
}
// if dust was detected, keepTransactionOutputs will have fewer elements than originalTransactionOutputs
// set the transaction outputs to what we saved in keepTransactionOutputs, thus discarding dust.
if (keepTransactionOutputs.size() != originalTransactionOutputs.size()) {
log.info("dust output was detected and removed, the new output is as follows:");
transaction.clearOutputs();
for (TransactionOutput transactionOutput : keepTransactionOutputs) {
transaction.addOutput(transactionOutput);
log.info("{}", transactionOutput.toString());
}
return true; // dust was removed
}
return false; // no action necessary
}
}
|
package me.dkzwm.widget.srl;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.SystemClock;
import android.support.annotation.ColorInt;
import android.support.annotation.FloatRange;
import android.support.annotation.IdRes;
import android.support.annotation.IntRange;
import android.support.annotation.LayoutRes;
import android.support.annotation.MainThread;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.NestedScrollingChild;
import android.support.v4.view.NestedScrollingChildHelper;
import android.support.v4.view.NestedScrollingParent;
import android.support.v4.view.NestedScrollingParentHelper;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import android.widget.Scroller;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import me.dkzwm.widget.srl.annotation.Action;
import me.dkzwm.widget.srl.annotation.Mode;
import me.dkzwm.widget.srl.annotation.State;
import me.dkzwm.widget.srl.config.Constants;
import me.dkzwm.widget.srl.extra.IRefreshView;
import me.dkzwm.widget.srl.gesture.GestureDetector;
import me.dkzwm.widget.srl.gesture.IGestureDetector;
import me.dkzwm.widget.srl.gesture.OnGestureListener;
import me.dkzwm.widget.srl.indicator.DefaultIndicator;
import me.dkzwm.widget.srl.indicator.IIndicator;
import me.dkzwm.widget.srl.utils.BoundaryUtil;
import me.dkzwm.widget.srl.utils.SRLog;
import me.dkzwm.widget.srl.utils.SRReflectUtil;
import me.dkzwm.widget.srl.utils.ScrollCompat;
public class SmoothRefreshLayout extends ViewGroup implements OnGestureListener, NestedScrollingChild,
NestedScrollingParent, ViewTreeObserver.OnScrollChangedListener {
//status
public static final byte SR_STATUS_INIT = 1;
public static final byte SR_STATUS_PREPARE = 2;
public static final byte SR_STATUS_REFRESHING = 3;
public static final byte SR_STATUS_LOADING_MORE = 4;
public static final byte SR_STATUS_COMPLETE = 5;
//fresh view status
public static final byte SR_VIEW_STATUS_INIT = 21;
public static final byte SR_VIEW_STATUS_HEADER_IN_PROCESSING = 22;
public static final byte SR_VIEW_STATUS_FOOTER_IN_PROCESSING = 23;
protected static final String TAG = "SmoothRefreshLayout";
protected static final Interpolator sQuinticInterpolator = new Interpolator() {
@Override
public float getInterpolation(float t) {
t -= 1.0f;
return t * t * t * t * t + 1.0f;
}
};
protected static final Interpolator sLinearInterpolator = new LinearInterpolator();
private static final byte FLAG_AUTO_REFRESH_AT_ONCE = 0x01;
private static final byte FLAG_AUTO_REFRESH_BUT_LATER = 0x01 << 1;
private static final byte FLAG_ENABLE_NEXT_AT_ONCE = 0x01 << 2;
private static final byte FLAG_ENABLE_OVER_SCROLL = 0x01 << 3;
private static final byte FLAG_ENABLE_KEEP_REFRESH_VIEW = 0x01 << 4;
private static final byte FLAG_ENABLE_PIN_CONTENT_VIEW = 0x01 << 5;
private static final byte FLAG_ENABLE_PULL_TO_REFRESH = 0x01 << 6;
private static final int FLAG_ENABLE_PIN_REFRESH_VIEW_WHILE_LOADING = 0x01 << 7;
private static final int FLAG_ENABLE_HEADER_DRAWER_STYLE = 0x01 << 8;
private static final int FLAG_ENABLE_FOOTER_DRAWER_STYLE = 0x01 << 9;
private static final int FLAG_DISABLE_PERFORM_LOAD_MORE = 0x01 << 10;
private static final int FLAG_ENABLE_NO_MORE_DATA = 0x01 << 11;
private static final int FLAG_DISABLE_LOAD_MORE = 0x01 << 12;
private static final int FLAG_DISABLE_PERFORM_REFRESH = 0x01 << 13;
private static final int FLAG_DISABLE_REFRESH = 0x01 << 14;
private static final int FLAG_ENABLE_AUTO_PERFORM_LOAD_MORE = 0x01 << 15;
private static final int FLAG_ENABLE_AUTO_PERFORM_REFRESH = 0x01 << 16;
private static final int FLAG_ENABLE_INTERCEPT_EVENT_WHILE_LOADING = 0x01 << 17;
private static final int FLAG_DISABLE_WHEN_ANOTHER_DIRECTION_MOVE = 0x01 << 18;
private static final int FLAG_ENABLE_HIDE_HEADER_VIEW = 0x01 << 19;
private static final int FLAG_ENABLE_HIDE_FOOTER_VIEW = 0x01 << 20;
private static final int FLAG_ENABLE_CHECK_FINGER_INSIDE = 0x01 << 21;
private static final int FLAG_ENABLE_NO_MORE_DATA_NO_BACK = 0x01 << 22;
private static final int FLAG_ENABLE_SMOOTH_ROLLBACK_WHEN_COMPLETED = 0x01 << 23;
private static final int FLAG_DISABLE_LOAD_MORE_WHEN_CONTENT_NOT_FULL = 0x01 << 24;
private static final byte MASK_AUTO_REFRESH = 0x03;
private static final int MASK_DISABLE_PERFORM_LOAD_MORE = 0x07 << 10;
private static final int MASK_DISABLE_PERFORM_REFRESH = 0x03 << 13;
private static final int[] LAYOUT_ATTRS = new int[]{
android.R.attr.enabled
};
protected static boolean sDebug = false;
private static IRefreshViewCreator sCreator;
protected final int[] mParentScrollConsumed = new int[2];
protected final int[] mParentOffsetInWindow = new int[2];
private final NestedScrollingParentHelper mNestedScrollingParentHelper;
private final NestedScrollingChildHelper mNestedScrollingChildHelper;
private final List<View> mCachedViews = new ArrayList<>(1);
@Mode
protected int mMode = Constants.MODE_DEFAULT;
@State
protected int mState = Constants.STATE_CONTENT;
@State
protected int mPreviousState = Constants.STATE_NONE;
protected IRefreshView<IIndicator> mHeaderView;
protected IRefreshView<IIndicator> mFooterView;
protected IIndicator mIndicator;
protected OnRefreshListener mRefreshListener;
protected OnStateChangedListener mStateChangedListener;
protected byte mStatus = SR_STATUS_INIT;
protected byte mViewStatus = SR_VIEW_STATUS_INIT;
protected boolean mNeedNotifyRefreshComplete = true;
protected boolean mDelayedRefreshComplete = false;
protected boolean mAutomaticActionUseSmoothScroll = false;
protected boolean mAutomaticActionInScrolling = false;
protected boolean mAutomaticActionTriggered = true;
protected boolean mDelayedNestedFling = false;
protected boolean mIsSpringBackCanNotBeInterrupted = false;
protected boolean mHasSendCancelEvent = false;
protected boolean mHasSendDownEvent = false;
protected boolean mDealAnotherDirectionMove = false;
protected boolean mPreventForAnotherDirection = false;
protected boolean mBeenSendTouchEvent = false;
protected boolean mIsInterceptTouchEventInOnceTouch = false;
protected boolean mIsLastOverScrollCanNotAbort = false;
protected boolean mIsFingerInsideAnotherDirectionView = false;
protected boolean mNestedScrollInProgress = false;
protected boolean mNeedNotifyRefreshListener = true;
protected long mLoadingMinTime = 500;
protected long mLoadingStartTime = 0;
protected int mDurationToCloseHeader = 500;
protected int mDurationToCloseFooter = 500;
protected View mTargetView;
protected View mContentView;
protected View mEmptyView;
protected View mErrorView;
protected View mCustomView;
protected View mScrollTargetView;
protected View mStickyHeaderView;
protected LayoutInflater mInflater;
protected int mContentResId = View.NO_ID;
protected int mErrorLayoutResId = View.NO_ID;
protected int mEmptyLayoutResId = View.NO_ID;
protected int mCustomLayoutResId = View.NO_ID;
protected int mStickyHeaderResId = View.NO_ID;
protected ScrollChecker mScrollChecker;
protected OverScrollChecker mOverScrollChecker;
protected DelayedScrollChecker mDelayedScrollChecker;
protected int mTouchSlop;
protected int mTouchPointerId;
protected int mHeaderBackgroundColor = -1;
protected int mFooterBackgroundColor = -2;
protected int mMinimumFlingVelocity;
protected Paint mBackgroundPaint;
protected MotionEvent mLastMoveEvent;
protected OnFingerDownListener mFingerDownListener;
protected OnHeaderEdgeDetectCallBack mInEdgeCanMoveHeaderCallBack;
protected OnFooterEdgeDetectCallBack mInEdgeCanMoveFooterCallBack;
protected OnInsideAnotherDirectionViewCallback mFingerInsideAnotherDirectionViewCallback;
protected OnLoadMoreScrollCallback mLoadMoreScrollCallback;
protected ValueAnimator mChangeStateAnimator;
private int mFlag = FLAG_DISABLE_LOAD_MORE;
private ILifecycleObserver mLifecycleObserver;
private Interpolator mSpringInterpolator;
private Interpolator mOverScrollInterpolator;
private IGestureDetector mGestureDetector;
private IChangeStateAnimatorCreator mAnimatorCreator;
private OnPerformAutoLoadMoreCallBack mAutoLoadMoreCallBack;
private List<OnUIPositionChangedListener> mUIPositionChangedListeners;
private DelayToRefreshComplete mDelayToRefreshComplete;
private RefreshCompleteHook mHeaderRefreshCompleteHook;
private RefreshCompleteHook mFooterRefreshCompleteHook;
private ViewTreeObserver mTargetViewTreeObserver;
private boolean mIsLastRefreshSuccessful = true;
private boolean mViewsZAxisNeedReset = true;
private boolean mNeedFilterScrollEvent = false;
private boolean mCompatLoadMoreScroll = true;
private int mMaxOverScrollDuration = 500;
private int mMinOverScrollDuration = 150;
private int mDurationOfBackToHeaderHeight = 200;
private int mDurationOfBackToFooterHeight = 200;
public SmoothRefreshLayout(Context context) {
this(context, null);
}
public SmoothRefreshLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public SmoothRefreshLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
createIndicator();
if (mIndicator == null)
throw new IllegalArgumentException("You must create a IIndicator, current indicator is null");
mInflater = LayoutInflater.from(context);
TypedArray arr = context.obtainStyledAttributes(attrs, R.styleable.SmoothRefreshLayout,
0, 0);
if (arr != null) {
mContentResId = arr.getResourceId(R.styleable.SmoothRefreshLayout_sr_content, mContentResId);
float resistance = arr.getFloat(R.styleable
.SmoothRefreshLayout_sr_resistance, IIndicator.DEFAULT_RESISTANCE);
mIndicator.setResistance(resistance);
mIndicator.setResistanceOfHeader(arr.getFloat(R.styleable
.SmoothRefreshLayout_sr_resistanceOfHeader, resistance));
mIndicator.setResistanceOfFooter(arr.getFloat(R.styleable
.SmoothRefreshLayout_sr_resistanceOfFooter, resistance));
mDurationOfBackToHeaderHeight = arr.getInt(R.styleable
.SmoothRefreshLayout_sr_backToKeepDuration, mDurationOfBackToHeaderHeight);
mDurationOfBackToFooterHeight = arr.getInt(R.styleable
.SmoothRefreshLayout_sr_backToKeepDuration, mDurationOfBackToFooterHeight);
mDurationOfBackToHeaderHeight = arr.getInt(R.styleable
.SmoothRefreshLayout_sr_backToKeepHeaderDuration, mDurationOfBackToHeaderHeight);
mDurationOfBackToFooterHeight = arr.getInt(R.styleable
.SmoothRefreshLayout_sr_backToKeepFooterDuration, mDurationOfBackToFooterHeight);
mDurationToCloseHeader = arr.getInt(R.styleable
.SmoothRefreshLayout_sr_closeDuration, mDurationToCloseHeader);
mDurationToCloseFooter = arr.getInt(R.styleable
.SmoothRefreshLayout_sr_closeDuration, mDurationToCloseFooter);
mDurationToCloseHeader = arr.getInt(R.styleable
.SmoothRefreshLayout_sr_closeHeaderDuration, mDurationToCloseHeader);
mDurationToCloseFooter = arr.getInt(R.styleable
.SmoothRefreshLayout_sr_closeFooterDuration, mDurationToCloseFooter);
float ratio = arr.getFloat(R.styleable.
SmoothRefreshLayout_sr_ratioToRefresh, IIndicator.DEFAULT_RATIO_TO_REFRESH);
mIndicator.setRatioToRefresh(ratio);
mIndicator.setRatioOfHeaderToRefresh(arr.getFloat(R.styleable
.SmoothRefreshLayout_sr_ratioOfHeaderToRefresh, ratio));
mIndicator.setRatioOfFooterToRefresh(arr.getFloat(R.styleable
.SmoothRefreshLayout_sr_ratioOfFooterToRefresh, ratio));
ratio = arr.getFloat(R.styleable.
SmoothRefreshLayout_sr_ratioToKeep, IIndicator.DEFAULT_RATIO_TO_REFRESH);
mIndicator.setRatioToKeepHeader(ratio);
mIndicator.setRatioToKeepFooter(ratio);
mIndicator.setRatioToKeepHeader(arr.getFloat(R.styleable
.SmoothRefreshLayout_sr_ratioToKeepHeader, ratio));
mIndicator.setRatioToKeepFooter(arr.getFloat(R.styleable
.SmoothRefreshLayout_sr_ratioToKeepFooter, ratio));
ratio = arr.getFloat(R.styleable.
SmoothRefreshLayout_sr_maxMoveRatio, IIndicator.DEFAULT_MAX_MOVE_RATIO);
mIndicator.setMaxMoveRatio(ratio);
mIndicator.setMaxMoveRatioOfHeader(arr.getFloat(R.styleable
.SmoothRefreshLayout_sr_maxMoveRatioOfHeader, ratio));
mIndicator.setMaxMoveRatioOfFooter(arr.getFloat(R.styleable
.SmoothRefreshLayout_sr_maxMoveRatioOfFooter, ratio));
setEnableKeepRefreshView(arr.getBoolean(R.styleable
.SmoothRefreshLayout_sr_enableKeep, true));
setEnablePinContentView(arr.getBoolean(R.styleable
.SmoothRefreshLayout_sr_enablePinContent, false));
setEnableOverScroll(arr.getBoolean(R.styleable
.SmoothRefreshLayout_sr_enableOverScroll, true));
setEnablePullToRefresh(arr.getBoolean(R.styleable
.SmoothRefreshLayout_sr_enablePullToRefresh, false));
setDisableRefresh(!arr.getBoolean(R.styleable.SmoothRefreshLayout_sr_enableRefresh,
true));
setDisableLoadMore(!arr.getBoolean(R.styleable
.SmoothRefreshLayout_sr_enableLoadMore, false));
mErrorLayoutResId = arr.getResourceId(R.styleable.SmoothRefreshLayout_sr_errorLayout,
NO_ID);
mEmptyLayoutResId = arr.getResourceId(R.styleable.SmoothRefreshLayout_sr_emptyLayout,
NO_ID);
mCustomLayoutResId = arr.getResourceId(R.styleable.SmoothRefreshLayout_sr_customLayout,
NO_ID);
mStickyHeaderResId = arr.getResourceId(R.styleable.SmoothRefreshLayout_sr_stickyHeader,
NO_ID);
mHeaderBackgroundColor = arr.getColor(R.styleable
.SmoothRefreshLayout_sr_headerBackgroundColor, -1);
mFooterBackgroundColor = arr.getColor(R.styleable
.SmoothRefreshLayout_sr_footerBackgroundColor, -1);
if (mHeaderBackgroundColor != -1 || mFooterBackgroundColor != -1) {
preparePaint();
}
@State
int state = arr.getInt(R.styleable.SmoothRefreshLayout_sr_state, Constants
.STATE_CONTENT);
mState = state;
@Mode
int mode = arr.getInt(R.styleable.SmoothRefreshLayout_sr_mode, Constants.MODE_DEFAULT);
mMode = mode;
arr.recycle();
arr = context.obtainStyledAttributes(attrs, LAYOUT_ATTRS, 0, 0);
setEnabled(arr.getBoolean(0, true));
arr.recycle();
} else {
setEnablePullToRefresh(true);
setEnableKeepRefreshView(true);
}
ViewConfiguration viewConfiguration = ViewConfiguration.get(getContext());
mTouchSlop = viewConfiguration.getScaledTouchSlop();
mMinimumFlingVelocity = viewConfiguration.getScaledMinimumFlingVelocity();
mGestureDetector = new GestureDetector(context, this);
mScrollChecker = new ScrollChecker();
mOverScrollChecker = new OverScrollChecker();
mSpringInterpolator = sQuinticInterpolator;
mOverScrollInterpolator = new DecelerateInterpolator(1.18f);
//Nested scrolling
mNestedScrollingChildHelper = new NestedScrollingChildHelper(this);
mNestedScrollingParentHelper = new NestedScrollingParentHelper(this);
setNestedScrollingEnabled(true);
}
public static void debug(boolean debug) {
sDebug = debug;
}
public static boolean isDebug() {
return sDebug;
}
/**
* Set the static refresh view creator, if the refresh view is null and the frame be
* needed the refresh view,frame will use this creator to create refresh view.
* <p>nullFrame</p>
*
* @param creator The static refresh view creator
*/
public static void setDefaultCreator(IRefreshViewCreator creator) {
sCreator = creator;
}
protected void createIndicator() {
mIndicator = new DefaultIndicator();
}
@Override
public void addView(View child, int index, ViewGroup.LayoutParams params) {
if (params == null)
params = generateDefaultLayoutParams();
else if (!checkLayoutParams(params))
params = generateLayoutParams(params);
super.addView(child, index, params);
ensureFreshView(child);
}
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
if (!enabled)
reset();
}
@Override
protected void onDetachedFromWindow() {
if (mLifecycleObserver != null)
mLifecycleObserver.onDetached(this);
super.onDetachedFromWindow();
destroy();
}
@Override
protected void onAttachedToWindow() {
if (mLifecycleObserver != null)
mLifecycleObserver.onAttached(this);
super.onAttachedToWindow();
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int count = getChildCount();
if (count == 0)
return;
ensureTargetView();
int maxHeight = 0;
int maxWidth = 0;
int childState = 0;
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() == GONE)
continue;
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (mHeaderView != null && child == mHeaderView.getView()) {
measureHeader(child, lp, widthMeasureSpec, heightMeasureSpec);
} else if (mFooterView != null && child == mFooterView.getView()) {
measureFooter(child, lp, widthMeasureSpec, heightMeasureSpec);
} else {
measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
}
maxWidth = Math.max(maxWidth, child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin);
maxHeight = Math.max(maxHeight, child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin);
childState = combineMeasuredStates(childState, child.getMeasuredState());
}
maxWidth += getPaddingLeft() + getPaddingRight();
maxHeight += getPaddingTop() + getPaddingBottom();
maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight());
maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());
setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
resolveSizeAndState(maxHeight, heightMeasureSpec, childState <<
MEASURED_HEIGHT_STATE_SHIFT));
}
protected void measureHeader(View child, LayoutParams lp, int widthMeasureSpec, int heightMeasureSpec) {
if (isDisabledRefresh() || isEnabledHideHeaderView())
return;
int height = mHeaderView.getCustomHeight();
if (mHeaderView.getStyle() == IRefreshView.STYLE_DEFAULT
|| mHeaderView.getStyle() == IRefreshView.STYLE_PIN
|| mHeaderView.getStyle() == IRefreshView.STYLE_FOLLOW_CENTER
|| mHeaderView.getStyle() == IRefreshView.STYLE_FOLLOW_PIN) {
if (height <= 0) {
if (height == LayoutParams.MATCH_PARENT) lp.height = LayoutParams.MATCH_PARENT;
} else lp.height = height;
measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
mIndicator.setHeaderHeight(child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin);
} else {
if (height <= 0 && height != LayoutParams.MATCH_PARENT) {
throw new IllegalArgumentException("If header view type is " +
"STYLE_SCALE or STYLE_FOLLOW_SCALE, you must set a accurate height");
} else {
if (height == LayoutParams.MATCH_PARENT) {
int specSize = MeasureSpec.getSize(heightMeasureSpec);
height = Math.max(0, specSize - (getPaddingTop() + getPaddingBottom()
+ lp.topMargin + lp.bottomMargin));
mIndicator.setHeaderHeight(height);
} else {
mIndicator.setHeaderHeight(height + lp.topMargin + lp.bottomMargin);
}
}
if (mHeaderView.getStyle() == IRefreshView.STYLE_FOLLOW_SCALE) {
if (mIndicator.getCurrentPos() <= mIndicator.getHeaderHeight()) {
lp.height = height;
measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
return;
}
}
final int childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec,
getPaddingLeft() + getPaddingRight() + lp.leftMargin + lp.rightMargin, lp
.width);
final int childHeightMeasureSpec;
if (isMovingHeader()) {
final int maxHeight = MeasureSpec.getSize(heightMeasureSpec) - getPaddingTop()
- getPaddingBottom() - lp.topMargin - lp.bottomMargin;
int realHeight = Math.min(mIndicator.getCurrentPos() - lp.topMargin - lp.bottomMargin,
maxHeight);
childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(realHeight > 0 ? realHeight : 0,
MeasureSpec.EXACTLY);
} else {
childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.EXACTLY);
}
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
}
protected void measureFooter(View child, LayoutParams lp, int widthMeasureSpec, int heightMeasureSpec) {
if (isDisabledLoadMore() || isEnabledHideFooterView())
return;
int height = mFooterView.getCustomHeight();
if (mFooterView.getStyle() == IRefreshView.STYLE_DEFAULT
|| mFooterView.getStyle() == IRefreshView.STYLE_PIN
|| mFooterView.getStyle() == IRefreshView.STYLE_FOLLOW_CENTER
|| mFooterView.getStyle() == IRefreshView.STYLE_FOLLOW_PIN) {
if (height <= 0) {
if (height == LayoutParams.MATCH_PARENT) lp.height = LayoutParams.MATCH_PARENT;
} else lp.height = height;
measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
mIndicator.setFooterHeight(child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin);
} else {
if (height <= 0 && height != LayoutParams.MATCH_PARENT) {
throw new IllegalArgumentException("If footer view type is " +
"STYLE_SCALE or STYLE_FOLLOW_SCALE, you must set a accurate height");
} else {
if (height == LayoutParams.MATCH_PARENT) {
int specSize = MeasureSpec.getSize(heightMeasureSpec);
height = Math.max(0, specSize - (getPaddingTop() + getPaddingBottom()
+ lp.topMargin + lp.bottomMargin));
mIndicator.setFooterHeight(height);
} else {
mIndicator.setFooterHeight(height + lp.topMargin + lp.bottomMargin);
}
}
if (mFooterView.getStyle() == IRefreshView.STYLE_FOLLOW_SCALE) {
if (mIndicator.getCurrentPos() <= mIndicator.getFooterHeight()) {
lp.height = height;
measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
return;
}
}
final int childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec,
getPaddingLeft() + getPaddingRight() + lp.leftMargin + lp.rightMargin, lp
.width);
final int childHeightMeasureSpec;
if (isMovingFooter()) {
final int maxHeight = MeasureSpec.getSize(heightMeasureSpec) - getPaddingTop()
- getPaddingBottom() - lp.topMargin - lp.bottomMargin;
int realHeight = Math.min(mIndicator.getCurrentPos() - lp.topMargin - lp
.bottomMargin, maxHeight);
childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(realHeight > 0 ? realHeight : 0,
MeasureSpec.EXACTLY);
} else {
childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.EXACTLY);
}
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
final int count = getChildCount();
if (count == 0)
return;
checkViewsZAxisNeedReset();
final int paddingLeft = getPaddingLeft();
final int paddingTop = getPaddingTop();
final int parentRight = r - l - getPaddingRight();
final int parentBottom = b - t - getPaddingBottom();
final boolean isMovingHeader = isMovingHeader();
final boolean isMovingFooter = isMovingFooter();
int offsetHeaderY = 0;
int offsetFooterY = 0;
if (isMovingHeader) {
offsetHeaderY = mIndicator.getCurrentPos();
} else if (isMovingFooter) {
offsetFooterY = mIndicator.getCurrentPos();
}
int contentBottom = 0;
boolean pin = (mScrollTargetView != null && !isMovingHeader) || isEnabledPinContentView();
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() == GONE)
continue;
if (mHeaderView != null && child == mHeaderView.getView()) {
layoutHeaderView(child, offsetHeaderY);
} else if (mTargetView != null && child == mTargetView
|| (mPreviousState != Constants.STATE_NONE && mChangeStateAnimator != null
&& mChangeStateAnimator.isRunning() && getView(mPreviousState) == child)
|| (mStickyHeaderView != null && child == mStickyHeaderView)) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final int left = paddingLeft + lp.leftMargin;
final int right = left + child.getMeasuredWidth();
int top, bottom;
if (mMode == Constants.MODE_DEFAULT && isMovingHeader) {
top = paddingTop + lp.topMargin + (pin ? 0 : offsetHeaderY);
bottom = top + child.getMeasuredHeight();
child.layout(left, top, right, bottom);
} else if (mMode == Constants.MODE_DEFAULT && isMovingFooter
&& mStickyHeaderView != child) {
top = paddingTop + lp.topMargin - (pin ? 0 : offsetFooterY);
bottom = top + child.getMeasuredHeight();
child.layout(left, top, right, bottom);
} else {
top = paddingTop + lp.topMargin;
bottom = top + child.getMeasuredHeight();
child.layout(left, top, right, bottom);
}
if (sDebug) {
SRLog.d(TAG, "onLayout(): content: %s %s %s %s", left, top, right, bottom);
}
if (mTargetView == child) contentBottom = bottom + lp.bottomMargin;
} else if (mFooterView == null || mFooterView.getView() != child) {
layoutOtherViewUseGravity(child, parentRight, parentBottom);
}
}
if (mFooterView != null && mFooterView.getView().getVisibility() != GONE) {
layoutFooterView(mFooterView.getView(), offsetFooterY, pin, contentBottom);
}
tryToPerformAutoRefresh();
}
protected void layoutHeaderView(View child, int offsetHeader) {
if (mMode != Constants.MODE_DEFAULT || isDisabledRefresh() || isEnabledHideHeaderView() || child
.getMeasuredHeight() == 0) {
child.layout(0, 0, 0, 0);
if (sDebug) {
SRLog.d(TAG, "onLayout(): header: %s %s %s %s", 0, 0, 0, 0);
}
return;
}
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
@IRefreshView.RefreshViewStyle final int type = mHeaderView.getStyle();
int left, right, top = 0, bottom;
switch (type) {
case IRefreshView.STYLE_DEFAULT:
int offset = offsetHeader - child.getMeasuredHeight();
top = getPaddingTop() + offset - lp.bottomMargin;
break;
case IRefreshView.STYLE_PIN:
case IRefreshView.STYLE_SCALE:
top = getPaddingTop() + lp.topMargin;
break;
case IRefreshView.STYLE_FOLLOW_PIN:
case IRefreshView.STYLE_FOLLOW_SCALE:
if (offsetHeader <= mIndicator.getHeaderHeight()) {
top = getPaddingTop() + offsetHeader - child.getMeasuredHeight() - lp
.bottomMargin;
} else {
top = getPaddingTop() + lp.topMargin;
}
break;
case IRefreshView.STYLE_FOLLOW_CENTER:
if (offsetHeader <= mIndicator.getHeaderHeight()) {
top = getPaddingTop() + offsetHeader - child.getMeasuredHeight() - lp
.bottomMargin;
} else {
top = getPaddingTop() + lp.topMargin + (offsetHeader - mIndicator
.getHeaderHeight()) / 2;
}
break;
}
left = getPaddingLeft() + lp.leftMargin;
right = left + child.getMeasuredWidth();
bottom = top + child.getMeasuredHeight();
child.layout(left, top, right, bottom);
if (sDebug) {
SRLog.d(TAG, "onLayout(): header: %s %s %s %s", left, top, right, bottom);
}
}
protected void layoutFooterView(View child, int offsetFooter, boolean pin, int contentBottom) {
if (mMode != Constants.MODE_DEFAULT || isDisabledLoadMore() || isEnabledHideFooterView() || child
.getMeasuredHeight() == 0) {
child.layout(0, 0, 0, 0);
if (sDebug) {
SRLog.d(TAG, "onLayout(): footer: %s %s %s %s", 0, 0, 0, 0);
}
return;
}
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
@IRefreshView.RefreshViewStyle final int type = mFooterView.getStyle();
int left, right, top = 0, bottom;
switch (type) {
case IRefreshView.STYLE_DEFAULT:
case IRefreshView.STYLE_SCALE:
top = lp.topMargin + contentBottom - (pin ? offsetFooter : 0);
break;
case IRefreshView.STYLE_PIN:
top = getMeasuredHeight() - child.getMeasuredHeight() - lp.bottomMargin
- getPaddingBottom();
break;
case IRefreshView.STYLE_FOLLOW_PIN:
case IRefreshView.STYLE_FOLLOW_SCALE:
if (offsetFooter <= mIndicator.getFooterHeight()) {
top = lp.topMargin + contentBottom - (pin ? offsetFooter : 0);
} else {
top = getMeasuredHeight() - child.getMeasuredHeight() - lp.bottomMargin
- getPaddingBottom();
}
break;
case IRefreshView.STYLE_FOLLOW_CENTER:
if (offsetFooter <= mIndicator.getFooterHeight()) {
top = lp.topMargin + contentBottom - (pin ? offsetFooter : 0);
} else {
top = lp.topMargin + contentBottom - (pin ? offsetFooter : 0)
+ (offsetFooter - mIndicator.getFooterHeight()) / 2;
}
break;
}
left = getPaddingLeft() + lp.leftMargin;
right = left + child.getMeasuredWidth();
bottom = top + child.getMeasuredHeight();
child.layout(left, top, right, bottom);
if (sDebug) {
SRLog.d(TAG, "onLayout(): footer: %s %s %s %s", left, top, right, bottom);
}
}
@SuppressLint({"RtlHardcpded", "RtlHardcoded"})
protected void layoutOtherViewUseGravity(View child, int parentRight, int parentBottom) {
final int width = child.getMeasuredWidth();
final int height = child.getMeasuredHeight();
int childLeft, childTop;
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
int gravity = lp.mGravity;
final int layoutDirection = ViewCompat.getLayoutDirection(this);
final int absoluteGravity = GravityCompat.getAbsoluteGravity(gravity, layoutDirection);
final int verticalGravity = gravity & Gravity.VERTICAL_GRAVITY_MASK;
switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
case Gravity.CENTER_HORIZONTAL:
childLeft = getPaddingLeft() + (parentRight - getPaddingLeft() - width) / 2
+ lp.leftMargin - lp.rightMargin;
break;
case Gravity.RIGHT:
childLeft = parentRight - width - lp.rightMargin;
break;
default:
childLeft = getPaddingLeft() + lp.leftMargin;
}
switch (verticalGravity) {
case Gravity.CENTER_VERTICAL:
childTop = getPaddingTop() + (parentBottom - getPaddingTop() - height) / 2
+ lp.topMargin - lp.bottomMargin;
break;
case Gravity.BOTTOM:
childTop = parentBottom - height - lp.bottomMargin;
break;
default:
childTop = getPaddingTop() + lp.topMargin;
}
child.layout(childLeft, childTop, childLeft + width, childTop + height);
if (sDebug) {
SRLog.d(TAG, "onLayout(): child: %s %s %s %s", childLeft, childTop, childLeft
+ width, childTop + height);
}
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
ensureTargetView();
if (mState != Constants.STATE_CONTENT) {
ensureContentView();
if (mContentView != null)
mContentView.setVisibility(GONE);
}
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (!isEnabled() || mTargetView == null) {
return super.dispatchTouchEvent(ev);
}
if (mFingerDownListener != null && ev.getActionMasked() == MotionEvent.ACTION_DOWN)
mFingerDownListener.onFingerDown();
if ((isEnabledPinRefreshViewWhileLoading() && ((isRefreshing() && isMovingHeader())
|| (isLoadingMore() && isMovingFooter())))
|| mNestedScrollInProgress || (isDisabledLoadMore() && isDisabledRefresh())) {
return super.dispatchTouchEvent(ev);
}
mGestureDetector.onTouchEvent(ev);
return processDispatchTouchEvent(ev);
}
protected boolean dispatchTouchEventSuper(MotionEvent ev) {
return super.dispatchTouchEvent(ev);
}
@Override
protected void dispatchDraw(Canvas canvas) {
if (mMode == Constants.MODE_DEFAULT) drawRefreshViewBackground(canvas);
super.dispatchDraw(canvas);
}
protected void drawRefreshViewBackground(Canvas canvas) {
if (mBackgroundPaint != null && !isEnabledPinContentView() && !mIndicator.isInStartPosition()) {
if (!isDisabledRefresh() && isMovingHeader() && mHeaderBackgroundColor != -1) {
mBackgroundPaint.setColor(mHeaderBackgroundColor);
final int bottom = Math.min(getPaddingTop() + mIndicator.getCurrentPos(),
getHeight() - getPaddingTop());
canvas.drawRect(getPaddingLeft(), getPaddingTop(), getWidth() - getPaddingRight(),
bottom, mBackgroundPaint);
} else if (!isDisabledLoadMore() && isMovingFooter() && mFooterBackgroundColor != -1) {
mBackgroundPaint.setColor(mFooterBackgroundColor);
final int top = Math.max(getHeight() - getPaddingBottom() - mIndicator
.getCurrentPos(), getPaddingTop());
canvas.drawRect(getPaddingLeft(), top, getWidth() - getPaddingRight(),
getHeight() - getPaddingBottom(), mBackgroundPaint);
}
}
}
@ViewCompat.ScrollAxis
public int getSupportScrollAxis() {
return ViewCompat.SCROLL_AXIS_VERTICAL;
}
public void setLifecycleObserver(ILifecycleObserver observer) {
mLifecycleObserver = observer;
}
@Nullable
public View getLoadMoreScrollTargetView() {
return mScrollTargetView;
}
/**
* Set loadMore scroll target view,For example the content view is a FrameLayout,with a
* listView in it.You can call this method,set the listView as load more scroll target view.
* Load more compat will try to make it smooth scrolling.
* <p><br/>
* SmoothRefreshLayoutCoordinatorLayout,
* CoordinatorLayoutAppbarLayoutRecyclerViewRecyclerVieW
* CoordinatorLayout,RecyclerViewTargetView</p>
*
* @param view Target view
*/
public void setLoadMoreScrollTargetView(@NonNull View view) {
mScrollTargetView = view;
}
/**
* Whether to enable the synchronous scroll when load more completed.
* <p></p>
*
* @param enable enable
*/
public void setEnableCompatLoadMoreScroll(boolean enable) {
mCompatLoadMoreScroll = enable;
}
/**
* Set the background color of the height of the Header view.
* <p>HeaderHeader</p>
*
* @param headerBackgroundColor Color
*/
public void setHeaderBackgroundColor(@ColorInt int headerBackgroundColor) {
mHeaderBackgroundColor = headerBackgroundColor;
preparePaint();
}
/**
* Set the background color of the height of the Footer view.
* <p>FooterFooter</p>
*
* @param footerBackgroundColor Color
*/
public void setFooterBackgroundColor(int footerBackgroundColor) {
mFooterBackgroundColor = footerBackgroundColor;
preparePaint();
}
/**
* Set the custom offset calculator.
* <p></p>
*
* @param calculator Offset calculator
*/
public void setIndicatorOffsetCalculator(IIndicator.IOffsetCalculator calculator) {
mIndicator.setOffsetCalculator(calculator);
}
/**
* Set the listener to be notified when a refresh is triggered.
* <p></p>
*
* @param listener Listener
*/
public <T extends OnRefreshListener> void setOnRefreshListener(T listener) {
mRefreshListener = listener;
}
/**
* Set the listener to be notified when the state changed.
* <p></p>
*
* @param listener Listener
*/
public void setOnStateChangedListener(OnStateChangedListener listener) {
mStateChangedListener = listener;
}
/**
* Add a listener to listen the views position change event.
* <p>UI</p>
*
* @param listener Listener
*/
public void addOnUIPositionChangedListener(OnUIPositionChangedListener listener) {
if (mUIPositionChangedListeners == null)
mUIPositionChangedListeners = new ArrayList<>();
mUIPositionChangedListeners.add(listener);
}
/**
* remove the listener.
* <p>UI</p>
*
* @param listener Listener
*/
public void removeOnUIPositionChangedListener(OnUIPositionChangedListener listener) {
if (mUIPositionChangedListeners != null && !mUIPositionChangedListeners.isEmpty())
mUIPositionChangedListeners.remove(listener);
}
/**
* Set a scrolling callback when loading more.
* <p>ListView
* FooterListView</p>
*
* @param callback Callback that should be called when scrolling on loading more.
*/
public void setOnLoadMoreScrollCallback(OnLoadMoreScrollCallback callback) {
mLoadMoreScrollCallback = callback;
}
/**
* Set a callback to override
* {@link SmoothRefreshLayout#isNotYetInEdgeCannotMoveHeader()} method. Non-null
* callback will return the value provided by the callback and ignore all internal logic.
* <p>{@link SmoothRefreshLayout#isNotYetInEdgeCannotMoveHeader()}</p>
*
* @param callback Callback that should be called when isChildNotYetInEdgeCannotMoveHeader() is called.
*/
public void setOnHeaderEdgeDetectCallBack(OnHeaderEdgeDetectCallBack callback) {
mInEdgeCanMoveHeaderCallBack = callback;
}
/**
* Set a callback to override
* {@link SmoothRefreshLayout#isNotYetInEdgeCannotMoveFooter()} method. Non-null
* callback will return the value provided by the callback and ignore all internal logic.
* <p>{@link SmoothRefreshLayout#isNotYetInEdgeCannotMoveFooter()}</p>
*
* @param callback Callback that should be called when isChildNotYetInEdgeCannotMoveFooter() is called.
*/
public void setOnFooterEdgeDetectCallBack(OnFooterEdgeDetectCallBack callback) {
mInEdgeCanMoveFooterCallBack = callback;
}
/**
* Set a callback to make sure you need to customize the specified trigger the auto load more rule.
* <p></p>
*
* @param callBack Customize the specified triggered rule
*/
public void setOnPerformAutoLoadMoreCallBack(OnPerformAutoLoadMoreCallBack callBack) {
mAutoLoadMoreCallBack = callBack;
}
/**
* Set a hook callback when the refresh complete event be triggered. Only can be called on
* refreshing.
* <p>Hook</p>
*
* @param callback Callback that should be called when refreshComplete() is called.
*/
public void setOnHookHeaderRefreshCompleteCallback(OnHookUIRefreshCompleteCallBack callback) {
if (mHeaderRefreshCompleteHook == null)
mHeaderRefreshCompleteHook = new RefreshCompleteHook();
mHeaderRefreshCompleteHook.mLayout = this;
mHeaderRefreshCompleteHook.setHookCallBack(callback);
}
/**
* Set a hook callback when the refresh complete event be triggered. Only can be called on
* loading more.
* <p>Hook</p>
*
* @param callback Callback that should be called when refreshComplete() is called.
*/
public void setOnHookFooterRefreshCompleteCallback(OnHookUIRefreshCompleteCallBack callback) {
if (mFooterRefreshCompleteHook == null)
mFooterRefreshCompleteHook = new RefreshCompleteHook();
mFooterRefreshCompleteHook.mLayout = this;
mFooterRefreshCompleteHook.setHookCallBack(callback);
}
public boolean equalsOnHookHeaderRefreshCompleteCallback(OnHookUIRefreshCompleteCallBack callBack) {
return mHeaderRefreshCompleteHook != null && mHeaderRefreshCompleteHook.mCallBack == callBack;
}
public boolean equalsOnHookFooterRefreshCompleteCallback(OnHookUIRefreshCompleteCallBack callBack) {
return mFooterRefreshCompleteHook != null && mFooterRefreshCompleteHook.mCallBack == callBack;
}
/**
* Set a callback to override
* {@link SmoothRefreshLayout#isInsideAnotherDirectionView(float, float)}} method.
* Non-null callback will return the value provided by the callback and ignore all internal
* logic.
* <p>{@link SmoothRefreshLayout#isInsideAnotherDirectionView(float, float)}
* </p>
*
* @param callback Callback that should be called when isFingerInsideAnotherDirectionView(float,
* float) is called.
*/
public void setOnInsideAnotherDirectionViewCallback(OnInsideAnotherDirectionViewCallback callback) {
mFingerInsideAnotherDirectionViewCallback = callback;
}
/**
* Set the change state animator creator.
* <p></p>
*
* @param creator The change state animator creator
*/
public void setChangeStateAnimatorCreator(IChangeStateAnimatorCreator creator) {
mAnimatorCreator = creator;
}
/**
* Whether it is refreshing state.
* <p></p>
*
* @return Refreshing
*/
public boolean isRefreshing() {
return mStatus == SR_STATUS_REFRESHING;
}
/**
* Whether it is loading more state.
* <p></p>
*
* @return Loading
*/
public boolean isLoadingMore() {
return mStatus == SR_STATUS_LOADING_MORE;
}
/**
* Whether it is in start position.
* <p></p>
*
* @return Is
*/
public boolean isInStartPosition() {
return mIndicator.isInStartPosition();
}
/**
* Whether it is refresh successful.
* <p></p>
*
* @return Is
*/
public boolean isRefreshSuccessful() {
return mIsLastRefreshSuccessful;
}
/**
* Perform refresh complete, to reset the state to {@link SmoothRefreshLayout#SR_STATUS_INIT}
* and set the last refresh operation successfully.
* <p></p>
*/
final public void refreshComplete() {
refreshComplete(true);
}
/**
* Perform refresh complete, to reset the state to {@link SmoothRefreshLayout#SR_STATUS_INIT}.
* <p>`isSuccessful`</p>
*
* @param isSuccessful Set the last refresh operation status
*/
final public void refreshComplete(boolean isSuccessful) {
refreshComplete(isSuccessful, 0);
}
/**
* Perform refresh complete, delay to reset the state to
* {@link SmoothRefreshLayout#SR_STATUS_INIT} and set the last refresh operation successfully.
* <p>`delayDurationToChangeState`</p>
*
* @param delayDurationToChangeState Delay to change the state to
* {@link SmoothRefreshLayout#SR_STATUS_COMPLETE}
*/
final public void refreshComplete(long delayDurationToChangeState) {
refreshComplete(true, delayDurationToChangeState);
}
/**
* Perform refresh complete, delay to reset the state to
* {@link SmoothRefreshLayout#SR_STATUS_INIT} and set the last refresh operation.
* <p>`isSuccessful``delayDurationToChangeState`</p>
*
* @param delayDurationToChangeState Delay to change the state to
* {@link SmoothRefreshLayout#SR_STATUS_INIT}
* @param isSuccessful Set the last refresh operation
*/
final public void refreshComplete(boolean isSuccessful, long delayDurationToChangeState) {
if (sDebug) {
SRLog.d(TAG, "refreshComplete(): isSuccessful: %s", isSuccessful);
}
mIsLastRefreshSuccessful = isSuccessful;
if (!isRefreshing() && !isLoadingMore())
return;
mIsSpringBackCanNotBeInterrupted = isEnabledSmoothRollbackWhenCompleted();
long delay = mLoadingMinTime - (SystemClock.uptimeMillis() - mLoadingStartTime);
if (delayDurationToChangeState <= 0) {
if (delay <= 0) {
performRefreshComplete(true);
} else {
if (mDelayToRefreshComplete == null)
mDelayToRefreshComplete = new DelayToRefreshComplete(this);
else
mDelayToRefreshComplete.mLayoutWeakRf = new WeakReference<>(this);
postDelayed(mDelayToRefreshComplete, delay);
}
} else {
if (isRefreshing() && mHeaderView != null) {
mHeaderView.onRefreshComplete(this, isSuccessful);
mNeedNotifyRefreshComplete = false;
} else if (isLoadingMore() && mFooterView != null) {
mFooterView.onRefreshComplete(this, isSuccessful);
mNeedNotifyRefreshComplete = false;
}
mDelayedRefreshComplete = true;
if (delayDurationToChangeState < delay)
delayDurationToChangeState = delay;
if (mDelayToRefreshComplete == null)
mDelayToRefreshComplete = new DelayToRefreshComplete(this);
else
mDelayToRefreshComplete.mLayoutWeakRf = new WeakReference<>(this);
postDelayed(mDelayToRefreshComplete, delayDurationToChangeState);
}
}
/**
* Set the loading min time.
* <p></p>
*
* @param time Millis
*/
public void setLoadingMinTime(long time) {
mLoadingMinTime = time;
}
/**
* Get the Header height, after the measurement is completed, the height will have value.
* <p>Header</p>
*
* @return Height default is -1
*/
public int getHeaderHeight() {
return mIndicator.getHeaderHeight();
}
/**
* Get the Footer height, after the measurement is completed, the height will have value.
* <p>Footer</p>
*
* @return Height default is -1
*/
public int getFooterHeight() {
return mIndicator.getFooterHeight();
}
/**
* Perform auto refresh at once.
* <p></p>
*/
public void autoRefresh() {
autoRefresh(Constants.ACTION_NOTIFY, true);
}
/**
* If @param atOnce has been set to true. Auto perform refresh at once.
* <p>`atOnce`</p>
*
* @param atOnce Auto refresh at once
*/
@Deprecated
public void autoRefresh(boolean atOnce) {
autoRefresh(atOnce ? Constants.ACTION_AT_ONCE : Constants.ACTION_NOTIFY, true);
}
/**
* If @param atOnce has been set to true. Auto perform refresh at once.
* If @param smooth has been set to true. Auto perform refresh will using smooth scrolling.
* <p>`atOnce``smooth`</p>
*
* @param atOnce Auto refresh at once
* @param smoothScroll Auto refresh use smooth scrolling
*/
@Deprecated
public void autoRefresh(boolean atOnce, boolean smoothScroll) {
autoRefresh(atOnce ? Constants.ACTION_AT_ONCE : Constants.ACTION_NOTIFY, smoothScroll);
}
/**
* The @param action can be used to specify the action to trigger refresh. If the `action` been
* set to `SR_ACTION_NOTHING`, we will not notify the refresh listener when in refreshing. If
* the `action` been set to `SR_ACTION_AT_ONCE`, we will notify the refresh listener at once. If
* the `action` been set to `SR_ACTION_NOTIFY`, we will notify the refresh listener when in
* refreshing be later
* If @param smooth has been set to true. Auto perform refresh will using smooth scrolling.
* listener
* <p>`action``smooth`</p>
*
* @param action Auto refresh use action.{@link Constants#ACTION_NOTIFY},
* {@link Constants#ACTION_AT_ONCE},{@link Constants#ACTION_NOTHING}
* @param smoothScroll Auto refresh use smooth scrolling
*/
public void autoRefresh(@Action int action, boolean smoothScroll) {
if (mStatus != SR_STATUS_INIT && mMode != Constants.MODE_DEFAULT) {
return;
}
if (sDebug) {
SRLog.d(TAG, "autoRefresh(): action: %s, smoothScroll: %s", action, smoothScroll);
}
mStatus = SR_STATUS_PREPARE;
if (mHeaderView != null)
mHeaderView.onRefreshPrepare(this);
mIndicator.setMovingStatus(Constants.MOVING_HEADER);
mViewStatus = SR_VIEW_STATUS_HEADER_IN_PROCESSING;
mAutomaticActionUseSmoothScroll = smoothScroll;
switch (action) {
case Constants.ACTION_NOTHING:
mFlag |= FLAG_AUTO_REFRESH_AT_ONCE;
mNeedNotifyRefreshListener = false;
triggeredRefresh(false);
break;
case Constants.ACTION_NOTIFY:
mFlag |= FLAG_AUTO_REFRESH_BUT_LATER;
mNeedNotifyRefreshListener = true;
break;
case Constants.ACTION_AT_ONCE:
mFlag |= FLAG_AUTO_REFRESH_AT_ONCE;
mNeedNotifyRefreshListener = true;
triggeredRefresh(true);
break;
}
int offsetToRefresh = mIndicator.getOffsetToRefresh();
if (offsetToRefresh <= 0) {
mAutomaticActionInScrolling = false;
mAutomaticActionTriggered = false;
} else {
mAutomaticActionTriggered = true;
mScrollChecker.tryToScrollTo(offsetToRefresh, smoothScroll ? mDurationToCloseHeader : 0);
mAutomaticActionInScrolling = smoothScroll;
}
}
/**
* Perform auto load more at once.
* <p></p>
*/
public void autoLoadMore() {
autoLoadMore(Constants.ACTION_NOTIFY, true);
}
/**
* If @param atOnce has been set to true. Auto perform load more at once.
* <p>`atOnce`</p>
*
* @param atOnce Auto load more at once
*/
@Deprecated
public void autoLoadMore(boolean atOnce) {
autoLoadMore(atOnce ? Constants.ACTION_AT_ONCE : Constants.ACTION_NOTIFY, true);
}
/**
* If @param atOnce has been set to true. Auto perform load more at once.
* If @param smooth has been set to true. Auto perform load more will using smooth scrolling.
* <p>`atOnce``smooth`</p>
*
* @param atOnce Auto load more at once
* @param smoothScroll Auto load more use smooth scrolling
*/
@Deprecated
public void autoLoadMore(boolean atOnce, boolean smoothScroll) {
autoLoadMore(atOnce ? Constants.ACTION_AT_ONCE : Constants.ACTION_NOTIFY,
smoothScroll);
}
/**
* The @param action can be used to specify the action to trigger refresh. If the `action` been
* set to `SR_ACTION_NOTHING`, we will not notify the refresh listener when in refreshing. If
* the `action` been set to `SR_ACTION_AT_ONCE`, we will notify the refresh listener at once. If
* the `action` been set to `SR_ACTION_NOTIFY`, we will notify the refresh listener when in
* refreshing be later
* If @param smooth has been set to true. Auto perform load more will using smooth scrolling.
* <p>`action``smooth`</p>
*
* @param action Auto load more use action.{@link Constants#ACTION_NOTIFY},
* {@link Constants#ACTION_AT_ONCE},{@link Constants#ACTION_NOTHING}
* @param smoothScroll Auto load more use smooth scrolling
*/
public void autoLoadMore(@Action int action, boolean smoothScroll) {
if (mStatus != SR_STATUS_INIT && mMode != Constants.MODE_DEFAULT) {
return;
}
if (sDebug) {
SRLog.d(TAG, "autoLoadMore(): action: %s, smoothScroll: %s", action, smoothScroll);
}
mStatus = SR_STATUS_PREPARE;
if (mFooterView != null)
mFooterView.onRefreshPrepare(this);
mIndicator.setMovingStatus(Constants.MOVING_FOOTER);
mViewStatus = SR_VIEW_STATUS_FOOTER_IN_PROCESSING;
mAutomaticActionUseSmoothScroll = smoothScroll;
switch (action) {
case Constants.ACTION_NOTHING:
mFlag |= FLAG_AUTO_REFRESH_AT_ONCE;
mNeedNotifyRefreshListener = false;
triggeredLoadMore(false);
break;
case Constants.ACTION_NOTIFY:
mFlag |= FLAG_AUTO_REFRESH_BUT_LATER;
mNeedNotifyRefreshListener = true;
break;
case Constants.ACTION_AT_ONCE:
mFlag |= FLAG_AUTO_REFRESH_AT_ONCE;
mNeedNotifyRefreshListener = true;
triggeredLoadMore(true);
break;
}
int offsetToLoadMore = mIndicator.getOffsetToLoadMore();
if (offsetToLoadMore <= 0) {
mAutomaticActionInScrolling = false;
mAutomaticActionTriggered = false;
} else {
mAutomaticActionTriggered = true;
mScrollChecker.tryToScrollTo(offsetToLoadMore, smoothScroll ? mDurationToCloseFooter : 0);
mAutomaticActionInScrolling = smoothScroll;
}
}
/**
* Set the resistance while you are moving.
* <p></p>
*
* @param resistance Resistance
*/
public void setResistance(@FloatRange(from = 0, to = Float.MAX_VALUE) float resistance) {
mIndicator.setResistance(resistance);
}
/**
* Set the resistance while you are moving Footer.
* <p>Footer</p>
*
* @param resistance Resistance
*/
public void setResistanceOfFooter(@FloatRange(from = 0, to = Float.MAX_VALUE) float resistance) {
mIndicator.setResistanceOfFooter(resistance);
}
/**
* Set the resistance while you are moving Header.
* <p>Header</p>
*
* @param resistance Resistance
*/
public void setResistanceOfHeader(@FloatRange(from = 0, to = Float.MAX_VALUE) float resistance) {
mIndicator.setResistanceOfHeader(resistance);
}
/**
* Set the height ratio of the trigger refresh.
* <p></p>
*
* @param ratio Height ratio
*/
public void setRatioToRefresh(@FloatRange(from = 0, to = Float.MAX_VALUE) float ratio) {
mIndicator.setRatioToRefresh(ratio);
}
/**
* Set the Header height ratio of the trigger refresh.
* <p>Header</p>
*
* @param ratio Height ratio
*/
public void setRatioOfHeaderToRefresh(@FloatRange(from = 0, to = Float.MAX_VALUE) float ratio) {
mIndicator.setRatioOfHeaderToRefresh(ratio);
}
/**
* Set the Footer height ratio of the trigger refresh.
* <p>Footer</p>
*
* @param ratio Height ratio
*/
public void setRatioOfFooterToRefresh(@FloatRange(from = 0, to = Float.MAX_VALUE) float ratio) {
mIndicator.setRatioOfFooterToRefresh(ratio);
}
/**
* Set the offset of keep view in refreshing occupies the height ratio of the refresh view.
* <p>:`1f`,
* {@link SmoothRefreshLayout#isEnabledKeepRefreshView}</p>
*
* @param ratio Height ratio
*/
public void setRatioToKeep(@FloatRange(from = 0, to = Float.MAX_VALUE) float ratio) {
mIndicator.setRatioToKeepHeader(ratio);
mIndicator.setRatioToKeepFooter(ratio);
}
/**
* Set the offset of keep Header in refreshing occupies the height ratio of the Header.
* <p>Header:`1f`,</p>
*
* @param ratio Height ratio
*/
public void setRatioToKeepHeader(@FloatRange(from = 0, to = Float.MAX_VALUE) float ratio) {
mIndicator.setRatioToKeepHeader(ratio);
}
/**
* Set the offset of keep Footer in refreshing occupies the height ratio of the Footer.
* <p>Header:`1f`,</p>
*
* @param ratio Height ratio
*/
public void setRatioToKeepFooter(@FloatRange(from = 0, to = Float.MAX_VALUE) float ratio) {
mIndicator.setRatioToKeepFooter(ratio);
}
/**
* Set the max duration for Cross-Boundary-Rebound(OverScroll).
* <p>:`500`</p>
*
* @param duration Duration
*/
public void setMaxOverScrollDuration(@IntRange(from = 0, to = Integer.MAX_VALUE) int duration) {
mMaxOverScrollDuration = duration;
}
/**
* Set the min duration for Cross-Boundary-Rebound(OverScroll).
* <p>:`150`</p>
*
* @param duration Duration
*/
public void setMinOverScrollDuration(@IntRange(from = 0, to = Integer.MAX_VALUE) int duration) {
mMinOverScrollDuration = duration;
}
/**
* Set the duration of return back to the start position.
* <p></p>
*
* @param duration Millis
*/
public void setDurationToClose(@IntRange(from = 0, to = Integer.MAX_VALUE) int duration) {
mDurationToCloseHeader = duration;
mDurationToCloseFooter = duration;
}
/**
* Get the duration of Header return to the start position.
*
* @return mDuration
*/
public int getDurationToCloseHeader() {
return mDurationToCloseHeader;
}
/**
* Set the duration of Header return to the start position.
* <p>Header</p>
*
* @param duration Millis
*/
public void setDurationToCloseHeader(@IntRange(from = 0, to = Integer.MAX_VALUE) int duration) {
mDurationToCloseHeader = duration;
}
/**
* Get the duration of Footer return to the start position.
*
* @return mDuration
*/
public int getDurationToCloseFooter() {
return mDurationToCloseFooter;
}
/**
* Set the duration of Footer return to the start position.
* <p>Footer</p>
*
* @param duration Millis
*/
public void setDurationToCloseFooter(@IntRange(from = 0, to = Integer.MAX_VALUE) int duration) {
mDurationToCloseFooter = duration;
}
/**
* Set the duration of return to the keep refresh view position.
* <p></p>
*
* @param duration Millis
*/
public void setDurationOfBackToKeep(@IntRange(from = 0, to = Integer.MAX_VALUE) int duration) {
mDurationOfBackToHeaderHeight = duration;
mDurationOfBackToFooterHeight = duration;
}
/**
* Get the duration of return to the keep refresh view position when Header moves.
*
* @return Duration
*/
public int getDurationOfBackToKeepHeader() {
return mDurationOfBackToHeaderHeight;
}
/**
* Set the duration of return to the keep refresh view position when Header moves.
* <p>Header</p>
*
* @param duration Millis
*/
public void setDurationOfBackToKeepHeader(@IntRange(from = 0, to = Integer.MAX_VALUE) int duration) {
this.mDurationOfBackToHeaderHeight = duration;
}
/**
* Get the duration of return to the keep refresh view position when Footer moves.
*
* @return mDuration
*/
public int getDurationOfBackToKeepFooter() {
return mDurationOfBackToFooterHeight;
}
/**
* Set the duration of return to the keep refresh view position when Footer moves.
* <p>Footer</p>
*
* @param duration Millis
*/
public void setDurationOfBackToKeepFooter(@IntRange(from = 0, to = Integer.MAX_VALUE) int duration) {
this.mDurationOfBackToFooterHeight = duration;
}
/**
* Set the max can move offset occupies the height ratio of the refresh view.
* <p></p>
*
* @param ratio The max ratio of refresh view
*/
public void setMaxMoveRatio(@FloatRange(from = 0, to = Float.MAX_VALUE) float ratio) {
mIndicator.setMaxMoveRatio(ratio);
}
/**
* Set the max can move offset occupies the height ratio of the Header.
* <p>Header</p>
*
* @param ratio The max ratio of Header view
*/
public void setMaxMoveRatioOfHeader(@FloatRange(from = 0, to = Float.MAX_VALUE) float ratio) {
mIndicator.setMaxMoveRatioOfHeader(ratio);
}
/**
* Set the max can move offset occupies the height ratio of the Footer.
* <p>Footer</p>
*
* @param ratio The max ratio of Footer view
*/
public void setMaxMoveRatioOfFooter(@FloatRange(from = 0, to = Float.MAX_VALUE) float ratio) {
mIndicator.setMaxMoveRatioOfFooter(ratio);
}
/**
* The flag has set to autoRefresh.
* <p></p>
*
* @return Enabled
*/
public boolean isAutoRefresh() {
return (mFlag & MASK_AUTO_REFRESH) > 0;
}
/**
* If enable has been set to true. The user can immediately perform next refresh.
* <p></p>
*
* @return Is enable
*/
public boolean isEnabledNextPtrAtOnce() {
return (mFlag & FLAG_ENABLE_NEXT_AT_ONCE) > 0;
}
/**
* If @param enable has been set to true. The user can immediately perform next refresh.
* <p></p>
*
* @param enable Enable
*/
public void setEnableNextPtrAtOnce(boolean enable) {
if (enable) {
mFlag = mFlag | FLAG_ENABLE_NEXT_AT_ONCE;
} else {
mFlag = mFlag & ~FLAG_ENABLE_NEXT_AT_ONCE;
}
}
/**
* The flag has set enabled overScroll.
* <p></p>
*
* @return Enabled
*/
public boolean isEnabledOverScroll() {
return (mFlag & FLAG_ENABLE_OVER_SCROLL) > 0;
}
/**
* If @param enable has been set to true. Will supports over scroll.
* <p></p>
*
* @param enable Enable
*/
public void setEnableOverScroll(boolean enable) {
if (enable) {
mFlag = mFlag | FLAG_ENABLE_OVER_SCROLL;
} else {
mFlag = mFlag & ~FLAG_ENABLE_OVER_SCROLL;
}
}
/**
* The flag has set enabled to intercept the touch event while loading.
* <p></p>
*
* @return Enabled
*/
public boolean isEnabledInterceptEventWhileLoading() {
return (mFlag & FLAG_ENABLE_INTERCEPT_EVENT_WHILE_LOADING) > 0;
}
/**
* If @param enable has been set to true. Will intercept the touch event while loading.
* <p></p>
*
* @param enable Enable
*/
public void setEnableInterceptEventWhileLoading(boolean enable) {
if (enable) {
mFlag = mFlag | FLAG_ENABLE_INTERCEPT_EVENT_WHILE_LOADING;
} else {
mFlag = mFlag & ~FLAG_ENABLE_INTERCEPT_EVENT_WHILE_LOADING;
}
}
/**
* The flag has been set to pull to refresh.
* <p></p>
*
* @return Enabled
*/
public boolean isEnabledPullToRefresh() {
return (mFlag & FLAG_ENABLE_PULL_TO_REFRESH) > 0;
}
/**
* If @param enable has been set to true. When the current pos >= refresh offsets perform
* refresh.
* <p>,</p>
*
* @param enable Pull to refresh
*/
public void setEnablePullToRefresh(boolean enable) {
if (enable) {
mFlag = mFlag | FLAG_ENABLE_PULL_TO_REFRESH;
} else {
mFlag = mFlag & ~FLAG_ENABLE_PULL_TO_REFRESH;
}
}
/**
* The flag has been set to check whether the finger pressed point is inside horizontal view.
* <p></p>
*
* @return Enabled
*/
public boolean isEnableCheckInsideAnotherDirectionView() {
return (mFlag & FLAG_ENABLE_CHECK_FINGER_INSIDE) > 0;
}
/**
* If @param enable has been set to true. Touch event handling will be check whether the finger
* pressed point is inside horizontal view.
* <p></p>
*
* @param enable Pull to refresh
*/
public void setEnableCheckInsideAnotherDirectionView(boolean enable) {
if (enable) {
mFlag = mFlag | FLAG_ENABLE_CHECK_FINGER_INSIDE;
} else {
mFlag = mFlag & ~FLAG_ENABLE_CHECK_FINGER_INSIDE;
}
}
/**
* The flag has been set to enabled Header drawerStyle.
* <p>HeaderHeaderContent</p>
*
* @return Enabled
*/
public boolean isEnabledHeaderDrawerStyle() {
return (mFlag & FLAG_ENABLE_HEADER_DRAWER_STYLE) > 0;
}
/**
* If @param enable has been set to true.Enable Header drawerStyle.
* <p>HeaderHeaderContent,</p>
*
* @param enable enable Header drawerStyle
*/
public void setEnableHeaderDrawerStyle(boolean enable) {
if (enable) {
mFlag = mFlag | FLAG_ENABLE_HEADER_DRAWER_STYLE;
} else {
mFlag = mFlag & ~FLAG_ENABLE_HEADER_DRAWER_STYLE;
}
mViewsZAxisNeedReset = true;
requestLayout();
}
/**
* The flag has been set to enabled Footer drawerStyle.
* <p>FooterFooterContent</p>
*
* @return Enabled
*/
public boolean isEnabledFooterDrawerStyle() {
return (mFlag & FLAG_ENABLE_FOOTER_DRAWER_STYLE) > 0;
}
/**
* If @param enable has been set to true.Enable Footer drawerStyle.
* <p>FooterFooterContent,</p>
*
* @param enable enable Footer drawerStyle
*/
public void setEnableFooterDrawerStyle(boolean enable) {
if (enable) {
mFlag = mFlag | FLAG_ENABLE_FOOTER_DRAWER_STYLE;
} else {
mFlag = mFlag & ~FLAG_ENABLE_FOOTER_DRAWER_STYLE;
}
mViewsZAxisNeedReset = true;
requestLayout();
}
/**
* The flag has been set to disabled perform refresh.
* <p></p>
*
* @return Disabled
*/
public boolean isDisabledPerformRefresh() {
return (mFlag & MASK_DISABLE_PERFORM_REFRESH) > 0;
}
/**
* If @param disable has been set to true. Will never perform refresh.
* <p></p>
*
* @param disable Disable perform refresh
*/
public void setDisablePerformRefresh(boolean disable) {
if (disable) {
mFlag = mFlag | FLAG_DISABLE_PERFORM_REFRESH;
} else {
mFlag = mFlag & ~FLAG_DISABLE_PERFORM_REFRESH;
}
}
/**
* The flag has been set to disabled refresh.
* <p></p>
*
* @return Disabled
*/
public boolean isDisabledRefresh() {
return (mFlag & FLAG_DISABLE_REFRESH) > 0;
}
/**
* If @param disable has been set to true.Will disable refresh.
* <p></p>
*
* @param disable Disable refresh
*/
public void setDisableRefresh(boolean disable) {
if (disable) {
mFlag = mFlag | FLAG_DISABLE_REFRESH;
if (isRefreshing()) reset();
} else {
mFlag = mFlag & ~FLAG_DISABLE_REFRESH;
}
requestLayout();
}
/**
* The flag has been set to disabled perform load more.
* <p></p>
*
* @return Disabled
*/
public boolean isDisabledPerformLoadMore() {
return (mFlag & MASK_DISABLE_PERFORM_LOAD_MORE) > 0;
}
/**
* If @param disable has been set to true.Will never perform load more.
* <p></p>
*
* @param disable Disable perform load more
*/
public void setDisablePerformLoadMore(boolean disable) {
if (disable) {
mFlag = mFlag | FLAG_DISABLE_PERFORM_LOAD_MORE;
} else {
mFlag = mFlag & ~FLAG_DISABLE_PERFORM_LOAD_MORE;
}
}
/**
* The flag has been set to disabled load more.
* <p></p>
*
* @return Disabled
*/
public boolean isDisabledLoadMore() {
return (mFlag & FLAG_DISABLE_LOAD_MORE) > 0;
}
/**
* If @param disable has been set to true.Will disable load more.
* <p></p>
*
* @param disable Disable load more
*/
public void setDisableLoadMore(boolean disable) {
if (disable) {
mFlag = mFlag | FLAG_DISABLE_LOAD_MORE;
if (isLoadingMore()) reset();
} else {
mFlag = mFlag & ~FLAG_DISABLE_LOAD_MORE;
}
requestLayout();
}
/**
* The flag has been set to hided Header view.
* <p>Header</p>
*
* @return hided
*/
public boolean isEnabledHideHeaderView() {
return (mFlag & FLAG_ENABLE_HIDE_HEADER_VIEW) > 0;
}
/**
* If @param enable has been set to true.Will hide the Header.
* <p>Header</p>
*
* @param enable Enable hide the Header
*/
public void setEnableHideHeaderView(boolean enable) {
if (enable) {
mFlag = mFlag | FLAG_ENABLE_HIDE_HEADER_VIEW;
} else {
mFlag = mFlag & ~FLAG_ENABLE_HIDE_HEADER_VIEW;
}
requestLayout();
}
/**
* The flag has been set to hided Footer view.
* <p>Footer</p>
*
* @return hided
*/
public boolean isEnabledHideFooterView() {
return (mFlag & FLAG_ENABLE_HIDE_FOOTER_VIEW) > 0;
}
/**
* If @param enable has been set to true.Will hide the Footer.
* <p>Footer</p>
*
* @param enable Enable hide the Footer
*/
public void setEnableHideFooterView(boolean enable) {
if (enable) {
mFlag = mFlag | FLAG_ENABLE_HIDE_FOOTER_VIEW;
} else {
mFlag = mFlag & ~FLAG_ENABLE_HIDE_FOOTER_VIEW;
}
requestLayout();
}
/**
* The flag has been set to disabled when horizontal move.
* <p></p>
*
* @return Disabled
*/
public boolean isDisabledWhenAnotherDirectionMove() {
return (mFlag & FLAG_DISABLE_WHEN_ANOTHER_DIRECTION_MOVE) > 0;
}
/**
* Set whether to filter the horizontal moves.
* <p></p>
*
* @param disable Enable
*/
public void setDisableWhenAnotherDirectionMove(boolean disable) {
if (disable) {
mFlag = mFlag | FLAG_DISABLE_WHEN_ANOTHER_DIRECTION_MOVE;
} else {
mFlag = mFlag & ~FLAG_DISABLE_WHEN_ANOTHER_DIRECTION_MOVE;
}
}
/**
* The flag has been set to enabled load more has no more data.
* <p>Footer</p>
*
* @return Enabled
*/
public boolean isEnabledNoMoreData() {
return (mFlag & FLAG_ENABLE_NO_MORE_DATA) > 0;
}
/**
* If @param enable has been set to true. The Footer will show no more data and will never
* trigger load more.
* <p>`true`</p>
*
* @param enable Enable no more data
*/
public void setEnableNoMoreData(boolean enable) {
if (enable) {
mFlag = mFlag | FLAG_ENABLE_NO_MORE_DATA;
} else {
mFlag = mFlag & ~FLAG_ENABLE_NO_MORE_DATA;
}
}
/**
* The flag has been set to enabled. The scroller rollback can not be interrupted when
* refresh completed.
* <p></p>
*
* @return Enabled
*/
public boolean isEnabledSmoothRollbackWhenCompleted() {
return (mFlag & FLAG_ENABLE_SMOOTH_ROLLBACK_WHEN_COMPLETED) > 0;
}
/**
* If @param enable has been set to true. The rollback can not be interrupted when refresh
* completed.
* <p></p>
*
* @param enable Enable no more data
*/
public void setEnableSmoothRollbackWhenCompleted(boolean enable) {
if (enable) {
mFlag = mFlag | FLAG_ENABLE_SMOOTH_ROLLBACK_WHEN_COMPLETED;
} else {
mFlag = mFlag & ~FLAG_ENABLE_SMOOTH_ROLLBACK_WHEN_COMPLETED;
}
}
/**
* The flag has been set to enabled. Load more will be disabled when the content is not
* full.
* <p></p>
*
* @return Disabled
*/
public boolean isDisabledLoadMoreWhenContentNotFull() {
return (mFlag & FLAG_DISABLE_LOAD_MORE_WHEN_CONTENT_NOT_FULL) > 0;
}
/**
* If @param disable has been set to true.Load more will be disabled when the content is not
* full.
* <p></p>
*
* @param disable Disable load more when the content is not full
*/
public void setDisableLoadMoreWhenContentNotFull(boolean disable) {
if (disable) {
mFlag = mFlag | FLAG_DISABLE_LOAD_MORE_WHEN_CONTENT_NOT_FULL;
} else {
mFlag = mFlag & ~FLAG_DISABLE_LOAD_MORE_WHEN_CONTENT_NOT_FULL;
}
}
/**
* The flag has been set to enabled when Footer has no more data to no longer need spring back.
* <p></p>
*
* @return Enabled
*/
public boolean isEnabledNoSpringBackWhenNoMoreData() {
return (mFlag & FLAG_ENABLE_NO_MORE_DATA_NO_BACK) > 0;
}
/**
* If @param enable has been set to true. When there is no more data will no longer spring back.
* <p>`true`</p>
*
* @param enable Enable no more data
*/
public void setEnableNoSpringBackWhenNoMoreData(boolean enable) {
if (enable) {
mFlag = mFlag | FLAG_ENABLE_NO_MORE_DATA_NO_BACK;
} else {
mFlag = mFlag & ~FLAG_ENABLE_NO_MORE_DATA_NO_BACK;
}
}
/**
* The flag has been set to keep refresh view while loading.
* <p></p>
*
* @return Enabled
*/
public boolean isEnabledKeepRefreshView() {
return (mFlag & FLAG_ENABLE_KEEP_REFRESH_VIEW) > 0;
}
/**
* If @param enable has been set to true.When the current pos> = keep refresh view pos,
* it rolls back to the keep refresh view pos to perform refresh and remains until the refresh
* completed.
* <p></p>
*
* @param enable Keep refresh view
*/
public void setEnableKeepRefreshView(boolean enable) {
if (enable) {
mFlag = mFlag | FLAG_ENABLE_KEEP_REFRESH_VIEW;
} else {
mFlag = mFlag & ~FLAG_ENABLE_KEEP_REFRESH_VIEW;
setEnablePinRefreshViewWhileLoading(false);
}
}
/**
* The flag has been set to perform load more when the content view scrolling to bottom.
* <p></p>
*
* @return Enabled
*/
public boolean isEnabledAutoLoadMore() {
return (mFlag & FLAG_ENABLE_AUTO_PERFORM_LOAD_MORE) > 0;
}
/**
* If @param enable has been set to true.When the content view scrolling to bottom, it will
* be perform load more.
* <p></p>
*
* @param enable Enable
*/
public void setEnableAutoLoadMore(boolean enable) {
if (enable) {
mFlag = mFlag | FLAG_ENABLE_AUTO_PERFORM_LOAD_MORE;
} else {
mFlag = mFlag & ~FLAG_ENABLE_AUTO_PERFORM_LOAD_MORE;
}
}
/**
* The flag has been set to perform refresh when the content view scrolling to top.
* <p></p>
*
* @return Enabled
*/
public boolean isEnabledAutoRefresh() {
return (mFlag & FLAG_ENABLE_AUTO_PERFORM_REFRESH) > 0;
}
/**
* If @param enable has been set to true.When the content view scrolling to top, it will be
* perform refresh.
* <p></p>
*
* @param enable Enable
*/
public void setEnableAutoRefresh(boolean enable) {
if (enable) {
mFlag = mFlag | FLAG_ENABLE_AUTO_PERFORM_REFRESH;
} else {
mFlag = mFlag & ~FLAG_ENABLE_AUTO_PERFORM_REFRESH;
}
}
/**
* The flag has been set to pinned refresh view while loading.
* <p></p>
*
* @return Enabled
*/
public boolean isEnabledPinRefreshViewWhileLoading() {
return (mFlag & FLAG_ENABLE_PIN_REFRESH_VIEW_WHILE_LOADING) > 0;
}
/**
* If @param enable has been set to true.The refresh view will pinned at the keep refresh
* position.
* <p>
* {@link SmoothRefreshLayout#setEnablePinContentView(boolean)}
* {@link SmoothRefreshLayout#setEnableKeepRefreshView(boolean)}2`true`</p>
*
* @param enable Pin content view
*/
public void setEnablePinRefreshViewWhileLoading(boolean enable) {
if (enable) {
if (isEnabledPinContentView() && isEnabledKeepRefreshView()) {
mFlag = mFlag | FLAG_ENABLE_PIN_REFRESH_VIEW_WHILE_LOADING;
} else {
throw new IllegalArgumentException("This method can only be enabled if setEnablePinContentView" +
" and setEnableKeepRefreshView are set be true");
}
} else {
mFlag = mFlag & ~FLAG_ENABLE_PIN_REFRESH_VIEW_WHILE_LOADING;
}
}
/**
* The flag has been set to pinned content view while loading.
* <p></p>
*
* @return Enabled
*/
public boolean isEnabledPinContentView() {
return (mFlag & FLAG_ENABLE_PIN_CONTENT_VIEW) > 0;
}
/**
* If @param enable has been set to true. The content view will be pinned in the start pos.
* <p></p>
*
* @param enable Pin content view
*/
public void setEnablePinContentView(boolean enable) {
if (enable) {
mFlag = mFlag | FLAG_ENABLE_PIN_CONTENT_VIEW;
} else {
mFlag = mFlag & ~FLAG_ENABLE_PIN_CONTENT_VIEW;
setEnablePinRefreshViewWhileLoading(false);
}
}
/**
* Set the Footer view.
* <p>Footer</p>
*
* @param footer Footer view
*/
public void setFooterView(@NonNull IRefreshView footer) {
if (mFooterView != null) {
removeView(mFooterView.getView());
mFooterView = null;
}
if (footer.getType() != IRefreshView.TYPE_FOOTER)
throw new IllegalArgumentException("Wrong type,FooterView type must be " +
"TYPE_FOOTER");
View view = footer.getView();
addFreshViewLayoutParams(view);
mViewsZAxisNeedReset = true;
addView(view);
}
/**
* Set the Header view.
* <p>Header</p>
*
* @param header Header view
*/
public void setHeaderView(@NonNull IRefreshView header) {
if (mHeaderView != null) {
removeView(mHeaderView.getView());
mHeaderView = null;
}
if (header.getType() != IRefreshView.TYPE_HEADER)
throw new IllegalArgumentException("Wrong type,HeaderView type must be " +
"TYPE_HEADER");
View view = header.getView();
addFreshViewLayoutParams(view);
mViewsZAxisNeedReset = true;
addView(view);
}
/**
* Set the content view.
* <p>`state``content`</p>
*
* @param state The state of content view
* @param content Content view
*/
public void setContentView(@State int state, @NonNull View content) {
switch (state) {
case Constants.STATE_NONE:
throw new IllegalArgumentException("STATE_NONE can not be used, It only can be " +
"used as an initial value");
case Constants.STATE_CONTENT:
if (mContentView != null) {
removeView(mContentView);
}
mContentResId = View.NO_ID;
mContentView = content;
break;
case Constants.STATE_EMPTY:
if (mEmptyView != null) {
removeView(mEmptyView);
}
mEmptyLayoutResId = View.NO_ID;
mEmptyView = content;
break;
case Constants.STATE_ERROR:
if (mErrorView != null) {
removeView(mErrorView);
}
mErrorLayoutResId = View.NO_ID;
mErrorView = content;
break;
case Constants.STATE_CUSTOM:
default:
if (mCustomView != null) {
removeView(mCustomView);
}
mCustomLayoutResId = View.NO_ID;
mCustomView = content;
break;
}
addStateViewLayoutParams(content);
if (mState != state) {
content.setVisibility(GONE);
}
mViewsZAxisNeedReset = true;
addView(content);
}
/**
* Update scroller interpolator.
* <p>Scroller</p>
*
* @param interpolator Scroller interpolator
*/
public void updateScrollerInterpolator(Interpolator interpolator) {
mScrollChecker.updateInterpolator(interpolator);
}
/**
* Reset scroller interpolator.
* <p>Scroller</p>
*/
public void resetScrollerInterpolator() {
mScrollChecker.updateInterpolator(mSpringInterpolator);
}
/**
* Set the scroller default interpolator.
* <p>Scroller</p>
*
* @param interpolator Scroller interpolator
*/
public void setSpringInterpolator(Interpolator interpolator) {
mSpringInterpolator = interpolator;
mScrollChecker.updateInterpolator(interpolator);
}
/**
* Set the scroller interpolator when in cross boundary rebound.
* <p>Scroller</p>
*
* @param interpolator Scroller interpolator
*/
public void setOverScrollInterpolator(Interpolator interpolator) {
mOverScrollInterpolator = interpolator;
}
/**
* Is in over scrolling
*
* @return Is
*/
public boolean isOverScrolling() {
return mOverScrollChecker.mIsScrolling;
}
@Override
protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
return p != null && p instanceof LayoutParams;
}
@Override
protected ViewGroup.LayoutParams generateDefaultLayoutParams() {
return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
}
@Override
protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
return new LayoutParams(p);
}
@Override
public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
return new LayoutParams(getContext(), attrs);
}
/**
* Returns the {@link View} associated with the {@link State}.
* <p></p>
*
* @param state The view
*/
public View getView(@State int state) {
switch (state) {
case Constants.STATE_NONE:
throw new IllegalArgumentException("STATE_NONE can not be used, It only can be " +
"used as an initial value");
case Constants.STATE_CONTENT:
ensureContentView();
return mContentView;
case Constants.STATE_ERROR:
ensureErrorView();
return mErrorView;
case Constants.STATE_EMPTY:
ensureEmptyView();
return mEmptyView;
case Constants.STATE_CUSTOM:
default:
ensureCustomView();
return mCustomView;
}
}
/**
* Set the pinned header view resource id
*
* @param resId Resource id
*/
public void setStickyHeaderResId(@IdRes int resId) {
if (mStickyHeaderResId != resId) {
mStickyHeaderResId = resId;
requestLayout();
}
}
/**
* Set layout resource id when the state is Empty state
*
* @param resId Resource id
*/
public void setEmptyLayoutResId(@LayoutRes int resId) {
if (mEmptyLayoutResId != resId) {
if (mEmptyLayoutResId != NO_ID && mEmptyView != null) {
removeViewInLayout(mEmptyView);
mEmptyView = null;
}
mEmptyLayoutResId = resId;
if (mState == Constants.STATE_EMPTY)
ensureEmptyView();
}
}
/**
* Set layout resource id when the state is Error state
*
* @param resId Resource id
*/
public void setErrorLayoutResId(@LayoutRes int resId) {
if (mErrorLayoutResId != resId) {
if (mErrorLayoutResId != NO_ID && mErrorView != null) {
removeViewInLayout(mErrorView);
mErrorView = null;
}
mErrorLayoutResId = resId;
if (mState == Constants.STATE_ERROR)
ensureErrorView();
}
}
/**
* Set layout resource id when the state is Custom state
*
* @param resId Resource id
*/
public void setCustomLayoutResId(@LayoutRes int resId) {
if (mCustomLayoutResId != resId) {
if (mCustomLayoutResId != NO_ID && mCustomView != null) {
removeViewInLayout(mCustomView);
mErrorView = null;
}
mCustomLayoutResId = resId;
if (mState == Constants.STATE_CUSTOM)
ensureCustomView();
}
}
public void setOnFingerDownListener(OnFingerDownListener listener) {
mFingerDownListener = listener;
}
public void setMode(@Mode int mode) {
mMode = mode;
requestLayout();
}
/**
* Returns the current state.
* <p></p>
*
* @return Current state
*/
@State
public int getState() {
return mState;
}
/**
* Set the current state.
* <p></p>
*
* @param state Current state
*/
public void setState(@State int state) {
setState(state, false);
}
/**
* Set the current state.
* <p>`state``animate`</p>
*
* @param state Current state
* @param animate Use animation
*/
public void setState(@State final int state, final boolean animate) {
if (state != mState) {
if (mChangeStateAnimator != null && mChangeStateAnimator.isRunning()) {
mChangeStateAnimator.cancel();
mChangeStateAnimator = null;
}
final View previousView = getView(mState);
final View currentView = getView(state);
if (animate && previousView != null && currentView != null) {
if (mAnimatorCreator != null)
mChangeStateAnimator = mAnimatorCreator.create(previousView, currentView);
else
createDefaultChangeStateAnimator(previousView, currentView);
mChangeStateAnimator.start();
} else {
if (previousView != null)
previousView.setVisibility(GONE);
if (currentView != null)
currentView.setVisibility(VISIBLE);
}
mPreviousState = mState;
mState = state;
mTargetView = currentView;
if (mStateChangedListener != null)
mStateChangedListener.onStateChanged(mPreviousState, mState);
}
}
private void createDefaultChangeStateAnimator(final View previous, final View current) {
mChangeStateAnimator = ObjectAnimator.ofFloat(1.0f, 0.0f).setDuration(250L);
mChangeStateAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
current.setVisibility(View.VISIBLE);
current.setAlpha(0);
}
@Override
public void onAnimationEnd(Animator animation) {
previous.setVisibility(View.GONE);
previous.setAlpha(1);
current.setAlpha(1);
}
@Override
public void onAnimationCancel(Animator animation) {
previous.setVisibility(View.GONE);
previous.setAlpha(1);
}
});
mChangeStateAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float value = (float) animation.getAnimatedValue();
previous.setAlpha(value);
current.setAlpha(1f - value);
invalidate();
}
});
}
@Override
public boolean onFling(float vx, final float vy) {
if ((isDisabledLoadMore() && isDisabledRefresh())
|| (!isAutoRefresh() && (isNeedInterceptTouchEvent() ||
isCanNotAbortOverScrolling()))) {
return mNestedScrollInProgress && dispatchNestedPreFling(-vx, -vy);
}
if ((!isNotYetInEdgeCannotMoveHeader() && vy > 0)
|| (!isNotYetInEdgeCannotMoveFooter() && vy < 0)) {
return mNestedScrollInProgress && dispatchNestedPreFling(-vx, -vy);
}
if (!mIndicator.isInStartPosition()) {
if (!isEnabledPinRefreshViewWhileLoading()) {
if (Math.abs(vy) > mMinimumFlingVelocity * 2) {
mDelayedNestedFling = true;
mOverScrollChecker.preFling(vy);
}
return true;
}
} else {
if (isEnabledOverScroll()) {
if (!isEnabledPinRefreshViewWhileLoading()
|| ((vy >= 0 || !isDisabledLoadMore())
&& (vy <= 0 || !isDisabledRefresh()))) {
mOverScrollChecker.fling(vy);
}
}
mDelayedNestedFling = true;
if (mDelayedScrollChecker == null)
mDelayedScrollChecker = new DelayedScrollChecker();
mDelayedScrollChecker.updateVelocity((int) vy);
}
return mNestedScrollInProgress && dispatchNestedPreFling(-vx, -vy);
}
@Override
public boolean onStartNestedScroll(View child, View target, int nestedScrollAxes) {
if (sDebug) {
SRLog.d(TAG, "onStartNestedScroll(): nestedScrollAxes: %s", nestedScrollAxes);
}
return isEnabled() && isNestedScrollingEnabled() && mTargetView != null
&& (nestedScrollAxes & getSupportScrollAxis()) != 0;
}
@Override
public void onNestedScrollAccepted(View child, View target, int axes) {
if (sDebug) {
SRLog.d(TAG, "onNestedScrollAccepted(): axes: %s", axes);
}
// Reset the counter of how much leftover scroll needs to be consumed.
mNestedScrollingParentHelper.onNestedScrollAccepted(child, target, axes);
mIndicator.onFingerDown();
// Dispatch up to the nested parent
startNestedScroll(axes & getSupportScrollAxis());
mNestedScrollInProgress = true;
if (!isNeedFilterTouchEvent()) {
mScrollChecker.abortIfWorking();
mOverScrollChecker.abortIfWorking();
}
}
@Override
public void onNestedPreScroll(@NonNull View target, int dx, int dy, @NonNull int[] consumed) {
if (sDebug) {
SRLog.d(TAG, "onNestedPreScroll(): dx: %s, dy: %s, consumed: %s",
dx, dy, Arrays.toString(consumed));
}
if (isNeedFilterTouchEvent()) {
consumed[1] = dy;
onNestedPreScroll(dx, dy, consumed);
return;
}
if (!mIndicator.hasTouched()) {
if (sDebug) {
SRLog.w(TAG, "onNestedPreScroll(): There was an exception in touch event handling" +
"This method should be performed after the onNestedScrollAccepted() " +
"method is called");
}
onNestedPreScroll(dx, dy, consumed);
return;
}
if (dy > 0 && !isDisabledRefresh() && !isNotYetInEdgeCannotMoveHeader()
&& !(isEnabledPinRefreshViewWhileLoading() && isRefreshing()
&& mIndicator.isOverOffsetToKeepHeaderWhileLoading())) {
if (!mIndicator.isInStartPosition() && isMovingHeader()) {
mIndicator.onFingerMove(mIndicator.getLastMovePoint()[0] - dx,
mIndicator.getLastMovePoint()[1] - dy);
moveHeaderPos(mIndicator.getOffset());
consumed[1] = dy;
} else {
mIndicator.onFingerMove(mIndicator.getLastMovePoint()[0] - dx,
mIndicator.getLastMovePoint()[1]);
}
}
if (dy < 0 && !isDisabledLoadMore() && !isNotYetInEdgeCannotMoveFooter()
&& !(isEnabledPinRefreshViewWhileLoading() && isLoadingMore()
&& mIndicator.isOverOffsetToKeepFooterWhileLoading())) {
if (!mIndicator.isInStartPosition() && isMovingFooter()) {
mIndicator.onFingerMove(mIndicator.getLastMovePoint()[0] - dx,
mIndicator.getLastMovePoint()[1] - dy);
moveFooterPos(mIndicator.getOffset());
consumed[1] = dy;
} else {
mIndicator.onFingerMove(mIndicator.getLastMovePoint()[0] - dx,
mIndicator.getLastMovePoint()[1]);
}
}
if (dy == 0) {
mIndicator.onFingerMove(mIndicator.getLastMovePoint()[0] - dx,
mIndicator.getLastMovePoint()[1]);
updateAnotherDirectionPos();
} else if (isMovingFooter() && isFooterInProcessing() && mStatus == SR_STATUS_COMPLETE
&& mIndicator.hasLeftStartPosition() && isNotYetInEdgeCannotMoveFooter()) {
mScrollChecker.tryToScrollTo(IIndicator.START_POS, 0);
consumed[1] = dy;
}
tryToResetMovingStatus();
onNestedPreScroll(dx, dy, consumed);
}
protected void onNestedPreScroll(int dx, int dy, int[] consumed) {
// Now let our nested parent consume the leftovers
final int[] parentConsumed = mParentScrollConsumed;
if (dispatchNestedPreScroll(dx - consumed[0], dy - consumed[1], parentConsumed, null)) {
consumed[0] += parentConsumed[0];
consumed[1] += parentConsumed[1];
}
}
@Override
public int getNestedScrollAxes() {
return mNestedScrollingParentHelper.getNestedScrollAxes();
}
@Override
public void onStopNestedScroll(View target) {
if (sDebug) {
SRLog.d(TAG, "onStopNestedScroll()");
}
mNestedScrollingParentHelper.onStopNestedScroll(target);
if (mNestedScrollInProgress) {
mIndicator.onFingerUp();
}
mNestedScrollInProgress = false;
mIsInterceptTouchEventInOnceTouch = isNeedInterceptTouchEvent();
mIsLastOverScrollCanNotAbort = isCanNotAbortOverScrolling();
// Dispatch up our nested parent
stopNestedScroll();
if (isAutoRefresh() && mScrollChecker.mIsRunning)
return;
if (mIndicator.hasLeftStartPosition()) {
onFingerUp(false);
} else {
notifyFingerUp();
}
}
@Override
public void onNestedScroll(final View target, final int dxConsumed, final int dyConsumed,
final int dxUnconsumed, final int dyUnconsumed) {
if (sDebug) {
SRLog.d(TAG, "onNestedScroll(): dxConsumed: %s, dyConsumed: %s, dxUnconsumed: %s" +
" dyUnconsumed: %s", dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed);
}
if (isNeedFilterTouchEvent())
return;
// Dispatch up to the nested parent first
dispatchNestedScroll(dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, mParentOffsetInWindow);
if (!mIndicator.hasTouched()) {
if (sDebug) {
SRLog.w(TAG, "onNestedScroll(): There was an exception in touch event handling" +
"This method should be performed after the onNestedScrollAccepted() " +
"method is called");
}
return;
}
final int dy = dyUnconsumed + mParentOffsetInWindow[1];
final boolean canNotChildScrollDown = !isNotYetInEdgeCannotMoveFooter();
final boolean canNotChildScrollUp = !isNotYetInEdgeCannotMoveHeader();
if (dy < 0 && !isDisabledRefresh() && canNotChildScrollUp
&& !(isEnabledPinRefreshViewWhileLoading() && isRefreshing()
&& mIndicator.isOverOffsetToKeepHeaderWhileLoading())) {
float distance = mIndicator.getCanMoveTheMaxDistanceOfHeader();
if (distance > 0 && mIndicator.getCurrentPos() >= distance)
return;
mIndicator.onFingerMove(mIndicator.getLastMovePoint()[0],
mIndicator.getLastMovePoint()[1] - dy);
if (distance > 0 && (mIndicator.getCurrentPos() + mIndicator.getOffset() > distance))
moveHeaderPos(distance - mIndicator.getCurrentPos());
else
moveHeaderPos(mIndicator.getOffset());
} else if (dy > 0 && !isDisabledLoadMore() && canNotChildScrollDown
&& !(isDisabledLoadMoreWhenContentNotFull() && canNotChildScrollUp
&& mIndicator.isInStartPosition())
&& !(isEnabledPinRefreshViewWhileLoading() && isLoadingMore()
&& mIndicator.isOverOffsetToKeepFooterWhileLoading())) {
float distance = mIndicator.getCanMoveTheMaxDistanceOfFooter();
if (distance > 0 && mIndicator.getCurrentPos() > distance)
return;
mIndicator.onFingerMove(mIndicator.getLastMovePoint()[0],
mIndicator.getLastMovePoint()[1] - dy);
if (distance > 0 && (mIndicator.getCurrentPos() - mIndicator.getOffset() > distance))
moveFooterPos(mIndicator.getCurrentPos() - distance);
else
moveFooterPos(mIndicator.getOffset());
}
tryToResetMovingStatus();
}
@Override
public boolean isNestedScrollingEnabled() {
return mNestedScrollingChildHelper.isNestedScrollingEnabled();
}
@Override
public void setNestedScrollingEnabled(boolean enabled) {
mNestedScrollingChildHelper.setNestedScrollingEnabled(enabled);
}
@Override
public boolean startNestedScroll(int axes) {
return mNestedScrollingChildHelper.startNestedScroll(axes);
}
@Override
public void stopNestedScroll() {
mNestedScrollingChildHelper.stopNestedScroll();
}
@Override
public boolean hasNestedScrollingParent() {
return mNestedScrollingChildHelper.hasNestedScrollingParent();
}
@Override
public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, int dxUnconsumed,
int dyUnconsumed, int[] offsetInWindow) {
return mNestedScrollingChildHelper.dispatchNestedScroll(dxConsumed, dyConsumed,
dxUnconsumed, dyUnconsumed, offsetInWindow);
}
@Override
public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed,
int[] offsetInWindow) {
return mNestedScrollingChildHelper.dispatchNestedPreScroll(
dx, dy, consumed, offsetInWindow);
}
@Override
public boolean onNestedPreFling(View target, float velocityX,
float velocityY) {
return onFling(-velocityX, -velocityY);
}
@Override
public boolean onNestedFling(View target, float velocityX, float velocityY,
boolean consumed) {
return dispatchNestedFling(velocityX, velocityY, consumed);
}
@Override
public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
return mNestedScrollingChildHelper.dispatchNestedFling(velocityX, velocityY, consumed);
}
@Override
public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
return mNestedScrollingChildHelper.dispatchNestedPreFling(velocityX, velocityY);
}
@Override
public void onScrollChanged() {
if (mNeedFilterScrollEvent) {
mNeedFilterScrollEvent = false;
return;
}
mDelayedNestedFling = false;
if (mDelayedScrollChecker != null) {
mDelayedScrollChecker.abortIfWorking();
}
checkAnotherDirectionViewUnInterceptedEvent();
tryToPerformScrollToBottomToLoadMore();
tryToPerformScrollToTopToRefresh();
mOverScrollChecker.computeScrollOffset();
}
private void checkAnotherDirectionViewUnInterceptedEvent() {
if (mIndicator.hasTouched() && mIndicator.hasMoved() && mPreventForAnotherDirection
&& isDisabledWhenAnotherDirectionMove() && mIsFingerInsideAnotherDirectionView) {
if (isMovingHeader() && isNotYetInEdgeCannotMoveHeader()) {
mPreventForAnotherDirection = false;
} else if (isMovingFooter() && isNotYetInEdgeCannotMoveFooter()) {
mPreventForAnotherDirection = false;
}
}
}
/**
* Check the Z-Axis relationships of the views need to be rearranged
*/
protected void checkViewsZAxisNeedReset() {
final int count = getChildCount();
if (mViewsZAxisNeedReset && count > 0) {
mCachedViews.clear();
final boolean isEnabledHeaderDrawer = isEnabledHeaderDrawerStyle();
final boolean isEnabledFooterDrawer = isEnabledFooterDrawerStyle();
if (isEnabledHeaderDrawer && isEnabledFooterDrawer) {
for (int i = count - 1; i >= 0; i
View view = getChildAt(i);
if (view != mHeaderView.getView() && view != mFooterView.getView())
mCachedViews.add(view);
}
} else if (isEnabledHeaderDrawer) {
for (int i = count - 1; i >= 0; i
View view = getChildAt(i);
if (view != mHeaderView.getView())
mCachedViews.add(view);
}
} else if (isEnabledFooterDrawer) {
for (int i = count - 1; i >= 0; i
View view = getChildAt(i);
if (view != mFooterView.getView())
mCachedViews.add(view);
}
} else {
for (int i = count - 1; i >= 0; i
View view = getChildAt(i);
if (view != mTargetView)
mCachedViews.add(view);
}
}
final int viewCount = mCachedViews.size();
if (viewCount > 0) {
for (int i = viewCount - 1; i >= 0; i
mCachedViews.get(i).bringToFront();
}
}
mCachedViews.clear();
if (sDebug) {
SRLog.d(TAG, "checkViewsZAxisNeedReset()");
}
}
mViewsZAxisNeedReset = false;
}
protected void destroy() {
reset();
mPreviousState = Constants.STATE_NONE;
if (mHeaderRefreshCompleteHook != null)
mHeaderRefreshCompleteHook.mLayout = null;
mHeaderRefreshCompleteHook = null;
if (mFooterRefreshCompleteHook != null)
mFooterRefreshCompleteHook.mLayout = null;
mFooterRefreshCompleteHook = null;
if (mUIPositionChangedListeners != null)
mUIPositionChangedListeners.clear();
if (sDebug) {
SRLog.i(TAG, "destroy()");
}
}
protected void reset() {
if (!mIndicator.isInStartPosition()) {
mScrollChecker.tryToScrollTo(IIndicator.START_POS, 0);
}
if (mChangeStateAnimator != null && mChangeStateAnimator.isRunning())
mChangeStateAnimator.cancel();
mChangeStateAnimator = null;
if (isRefreshing() || isLoadingMore()) {
mStatus = SR_STATUS_COMPLETE;
notifyUIRefreshComplete(false);
}
mScrollChecker.destroy();
if (mDelayToRefreshComplete != null)
removeCallbacks(mDelayToRefreshComplete);
mDelayToRefreshComplete = null;
mDelayedNestedFling = false;
if (mDelayedScrollChecker != null)
mDelayedScrollChecker.abortIfWorking();
if (sDebug) {
SRLog.i(TAG, "reset()");
}
}
protected void tryToPerformAutoRefresh() {
if (isAutoRefresh() && !mAutomaticActionTriggered) {
if (sDebug) {
SRLog.d(TAG, "tryToPerformAutoRefresh()");
}
if (isHeaderInProcessing()) {
if (mHeaderView == null || mIndicator.getHeaderHeight() <= 0)
return;
mAutomaticActionTriggered = true;
mScrollChecker.tryToScrollTo(mIndicator.getOffsetToRefresh(),
mAutomaticActionUseSmoothScroll ? mDurationToCloseHeader : 0);
mAutomaticActionInScrolling = mAutomaticActionUseSmoothScroll;
} else if (isFooterInProcessing()) {
if (mFooterView == null || mIndicator.getFooterHeight() <= 0)
return;
mAutomaticActionTriggered = true;
mScrollChecker.tryToScrollTo(mIndicator.getOffsetToLoadMore(),
mAutomaticActionUseSmoothScroll ? mDurationToCloseFooter : 0);
mAutomaticActionInScrolling = mAutomaticActionUseSmoothScroll;
}
}
}
protected void ensureFreshView(View child) {
if (child instanceof IRefreshView) {
IRefreshView<IIndicator> view = (IRefreshView<IIndicator>) child;
switch (view.getType()) {
case IRefreshView.TYPE_HEADER:
if (mHeaderView != null)
throw new IllegalArgumentException("Unsupported operation , " +
"HeaderView only can be add once !!");
mHeaderView = view;
break;
case IRefreshView.TYPE_FOOTER:
if (mFooterView != null)
throw new IllegalArgumentException("Unsupported operation , " +
"FooterView only can be add once !!");
mFooterView = view;
break;
}
}
}
protected void ensureContentView() {
if (mContentView == null) {
if (mContentResId != View.NO_ID) {
for (int i = getChildCount() - 1; i >= 0; i
View child = getChildAt(i);
if (!(child instanceof IRefreshView) && mContentResId == child.getId()) {
mContentView = child;
break;
}
}
} else {
for (int i = getChildCount() - 1; i >= 0; i
View child = getChildAt(i);
if ((mEmptyView != null && child == mEmptyView)
|| (mErrorView != null && child == mErrorView)
|| (mCustomView != null && child == mCustomView))
continue;
if (child.getVisibility() != GONE && !(child instanceof IRefreshView)) {
mContentView = child;
break;
}
}
}
}
if (mStickyHeaderView == null && mStickyHeaderResId != NO_ID) {
mStickyHeaderView = findViewById(mStickyHeaderResId);
}
}
private void ensureErrorView() {
if (mErrorView == null && mErrorLayoutResId != NO_ID) {
mErrorView = mInflater.inflate(mErrorLayoutResId, null, false);
addStateViewLayoutParams(mErrorView);
addView(mErrorView);
} else if (mErrorView == null)
throw new IllegalArgumentException("Error view must be not null");
}
private void ensureEmptyView() {
if (mEmptyView == null && mEmptyLayoutResId != NO_ID) {
mEmptyView = mInflater.inflate(mEmptyLayoutResId, null, false);
addStateViewLayoutParams(mEmptyView);
addView(mEmptyView);
} else if (mEmptyView == null)
throw new IllegalArgumentException("Empty view must be not null");
}
private void ensureCustomView() {
if (mCustomView == null && mCustomLayoutResId != NO_ID) {
mCustomView = mInflater.inflate(mCustomLayoutResId, null, false);
addStateViewLayoutParams(mCustomView);
addView(mCustomView);
} else if (mCustomView == null)
throw new IllegalArgumentException("Custom view must be not null");
}
protected void addFreshViewLayoutParams(View view) {
ViewGroup.LayoutParams lp = view.getLayoutParams();
if (lp == null) {
lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
view.setLayoutParams(lp);
}
}
protected void addStateViewLayoutParams(View view) {
ViewGroup.LayoutParams lp = view.getLayoutParams();
if (lp == null) {
lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
view.setLayoutParams(lp);
}
}
private void ensureTargetView() {
if (mTargetView == null) {
switch (mState) {
case Constants.STATE_NONE:
break;
case Constants.STATE_CONTENT:
ensureContentView();
mTargetView = mContentView;
break;
case Constants.STATE_EMPTY:
ensureEmptyView();
mTargetView = mEmptyView;
break;
case Constants.STATE_ERROR:
ensureErrorView();
mTargetView = mErrorView;
break;
case Constants.STATE_CUSTOM:
ensureCustomView();
mTargetView = mCustomView;
break;
}
if (mTargetView != null && isEnabledOverScroll())
mTargetView.setOverScrollMode(OVER_SCROLL_NEVER);
}
if (mTargetView != null) {
ViewTreeObserver observer;
if (mScrollTargetView == null) {
observer = mTargetView.getViewTreeObserver();
} else {
observer = mScrollTargetView.getViewTreeObserver();
if (isEnabledOverScroll())
mScrollTargetView.setOverScrollMode(OVER_SCROLL_NEVER);
}
if (observer != mTargetViewTreeObserver && observer.isAlive()) {
safelyRemoveListeners();
mTargetViewTreeObserver = observer;
mTargetViewTreeObserver.addOnScrollChangedListener(this);
}
}
//Use the static default creator to create the Header view
if (!isDisabledRefresh() && !isEnabledHideHeaderView() && mHeaderView == null &&
sCreator != null && mMode == Constants.MODE_DEFAULT) {
sCreator.createHeader(this);
}
//Use the static default creator to create the Footer view
if (!isDisabledLoadMore() && !isEnabledHideFooterView() && mFooterView == null &&
sCreator != null && mMode == Constants.MODE_DEFAULT) {
sCreator.createFooter(this);
}
}
protected boolean processDispatchTouchEvent(MotionEvent ev) {
final int action = ev.getAction() & MotionEvent.ACTION_MASK;
if (sDebug) {
SRLog.d(TAG, "processDispatchTouchEvent(): action: %s", action);
}
switch (action) {
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
mPreventForAnotherDirection = false;
mDealAnotherDirectionMove = false;
mIsFingerInsideAnotherDirectionView = false;
mBeenSendTouchEvent = false;
mIndicator.onFingerUp();
if (isNeedFilterTouchEvent()) {
mIsInterceptTouchEventInOnceTouch = false;
if (mIsLastOverScrollCanNotAbort && mIndicator.isInStartPosition()) {
mOverScrollChecker.abortIfWorking();
}
mIsLastOverScrollCanNotAbort = false;
float offsetX, offsetY;
float[] pressDownPoint = mIndicator.getFingerDownPoint();
offsetX = ev.getX() - pressDownPoint[0];
offsetY = ev.getY() - pressDownPoint[1];
if (Math.abs(offsetX) > mTouchSlop || Math.abs(offsetY) > mTouchSlop) {
sendCancelEvent();
return true;
} else {
return super.dispatchTouchEvent(ev);
}
} else {
mIsInterceptTouchEventInOnceTouch = false;
mIsLastOverScrollCanNotAbort = false;
if (mIndicator.hasLeftStartPosition()) {
onFingerUp(false);
if (mIndicator.hasMovedAfterPressedDown()) {
sendCancelEvent();
return true;
}
return super.dispatchTouchEvent(ev);
} else {
notifyFingerUp();
return super.dispatchTouchEvent(ev);
}
}
case MotionEvent.ACTION_POINTER_UP:
final int actionIndex = ev.getActionIndex();
if (ev.getPointerId(actionIndex) == mTouchPointerId) {
// Pick a new pointer to pick up the slack.
final int newIndex = actionIndex == 0 ? 1 : 0;
mTouchPointerId = ev.getPointerId(newIndex);
mIndicator.onFingerMove(ev.getX(newIndex), ev.getY(newIndex));
}
break;
case MotionEvent.ACTION_POINTER_DOWN:
mTouchPointerId = ev.getPointerId(ev.getActionIndex());
mIndicator.onFingerMove(ev.getX(ev.getActionIndex()), ev.getY(ev.getActionIndex()));
break;
case MotionEvent.ACTION_DOWN:
mIndicator.onFingerUp();
mHasSendDownEvent = false;
mTouchPointerId = ev.getPointerId(0);
mIndicator.onFingerDown(ev.getX(), ev.getY());
mIsFingerInsideAnotherDirectionView = isDisabledWhenAnotherDirectionMove()
&& (!isEnableCheckInsideAnotherDirectionView()
|| isInsideAnotherDirectionView(ev.getRawX(), ev.getRawY()));
mIsInterceptTouchEventInOnceTouch = isNeedInterceptTouchEvent();
mIsLastOverScrollCanNotAbort = isCanNotAbortOverScrolling();
if (!isNeedFilterTouchEvent()) {
mScrollChecker.abortIfWorking();
mOverScrollChecker.abortIfWorking();
}
mDelayedNestedFling = false;
if (mDelayedScrollChecker != null)
mDelayedScrollChecker.abortIfWorking();
mHasSendCancelEvent = false;
mPreventForAnotherDirection = false;
super.dispatchTouchEvent(ev);
return true;
case MotionEvent.ACTION_MOVE:
if (!mIndicator.hasTouched()) {
return super.dispatchTouchEvent(ev);
}
final int index = ev.findPointerIndex(mTouchPointerId);
if (index < 0) {
Log.e(TAG, "Error processing scroll; pointer index for id " +
mTouchPointerId + " not found. Did any MotionEvents get skipped?");
return super.dispatchTouchEvent(ev);
}
mLastMoveEvent = ev;
if (tryToFilterTouchEventInDispatchTouchEvent(ev))
return true;
tryToResetMovingStatus();
mIndicator.onFingerMove(ev.getX(index), ev.getY(index));
float offsetX, offsetY;
final float[] pressDownPoint = mIndicator.getFingerDownPoint();
offsetX = ev.getX(index) - pressDownPoint[0];
offsetY = ev.getY(index) - pressDownPoint[1];
final boolean canNotChildScrollDown = !isNotYetInEdgeCannotMoveFooter();
final boolean canNotChildScrollUp = !isNotYetInEdgeCannotMoveHeader();
if (isDisabledWhenAnotherDirectionMove() && mIsFingerInsideAnotherDirectionView) {
if (!mDealAnotherDirectionMove) {
if ((Math.abs(offsetX) >= mTouchSlop
&& Math.abs(offsetX) > Math.abs(offsetY))) {
mPreventForAnotherDirection = true;
mDealAnotherDirectionMove = true;
} else if (Math.abs(offsetX) < mTouchSlop
&& Math.abs(offsetY) < mTouchSlop) {
mDealAnotherDirectionMove = false;
mPreventForAnotherDirection = true;
} else {
mDealAnotherDirectionMove = true;
mPreventForAnotherDirection = false;
}
}
} else {
if (Math.abs(offsetX) < mTouchSlop
&& Math.abs(offsetY) < mTouchSlop) {
return super.dispatchTouchEvent(ev);
}
}
if (mPreventForAnotherDirection) {
return super.dispatchTouchEvent(ev);
}
offsetY = mIndicator.getOffset();
int currentY = mIndicator.getCurrentPos();
boolean movingDown = offsetY > 0;
if (isMovingFooter() && isFooterInProcessing() && mStatus == SR_STATUS_COMPLETE
&& mIndicator.hasLeftStartPosition() && !canNotChildScrollDown) {
mScrollChecker.tryToScrollTo(IIndicator.START_POS, 0);
return super.dispatchTouchEvent(ev);
}
if (movingDown) {
final float maxHeaderDistance = mIndicator.getCanMoveTheMaxDistanceOfHeader();
if (isMovingHeader() && !mIndicator.isInStartPosition()
&& maxHeaderDistance > 0) {
if (currentY >= maxHeaderDistance) {
updateAnotherDirectionPos();
return super.dispatchTouchEvent(ev);
} else if (currentY + offsetY > maxHeaderDistance) {
moveHeaderPos(maxHeaderDistance - currentY);
return true;
}
}
} else {
final float maxFooterDistance = mIndicator.getCanMoveTheMaxDistanceOfFooter();
if (isMovingFooter() && !mIndicator.isInStartPosition()
&& maxFooterDistance > 0) {
if (currentY >= maxFooterDistance) {
updateAnotherDirectionPos();
return super.dispatchTouchEvent(ev);
} else if (currentY - offsetY > maxFooterDistance) {
moveFooterPos(currentY - maxFooterDistance);
return true;
}
} else if (isDisabledLoadMoreWhenContentNotFull() && mIndicator
.isInStartPosition() && canNotChildScrollDown && canNotChildScrollUp) {
return true;
}
}
boolean canMoveUp = isMovingHeader() && mIndicator.hasLeftStartPosition();
boolean canMoveDown = isMovingFooter() && mIndicator.hasLeftStartPosition();
boolean canHeaderMoveDown = canNotChildScrollUp && !isDisabledRefresh();
boolean canFooterMoveUp = canNotChildScrollDown && !isDisabledLoadMore();
if (!canMoveUp && !canMoveDown) {
if ((movingDown && !canHeaderMoveDown) || (!movingDown && !canFooterMoveUp)) {
if (isLoadingMore() && mIndicator.hasLeftStartPosition()) {
moveFooterPos(offsetY);
return true;
} else if (isRefreshing() && mIndicator.hasLeftStartPosition()) {
moveHeaderPos(offsetY);
return true;
} else if ((isAutoRefresh() || mIndicator.getCurrentPos() < IIndicator.START_POS)
&& !mBeenSendTouchEvent) {
makeNewTouchDownEvent(ev);
mBeenSendTouchEvent = true;
}
return super.dispatchTouchEvent(ev);
}
// should show up Header
if (movingDown) {
if (isDisabledRefresh())
return super.dispatchTouchEvent(ev);
moveHeaderPos(offsetY);
return true;
}
if (isDisabledLoadMore())
return super.dispatchTouchEvent(ev);
moveFooterPos(offsetY);
return true;
}
if (canMoveUp) {
if (isDisabledRefresh())
return super.dispatchTouchEvent(ev);
if ((!canHeaderMoveDown && movingDown)) {
sendDownEvent();
return super.dispatchTouchEvent(ev);
}
moveHeaderPos(offsetY);
return true;
}
if (isDisabledLoadMore())
return super.dispatchTouchEvent(ev);
if ((!canFooterMoveUp && !movingDown)) {
sendDownEvent();
return super.dispatchTouchEvent(ev);
}
moveFooterPos(offsetY);
return true;
}
return super.dispatchTouchEvent(ev);
}
protected boolean tryToFilterTouchEventInDispatchTouchEvent(MotionEvent ev) {
if (mIsInterceptTouchEventInOnceTouch) {
mOverScrollChecker.abortIfWorking();
if (mIndicator.isInStartPosition() && !mScrollChecker.mIsRunning) {
makeNewTouchDownEvent(ev);
mIsInterceptTouchEventInOnceTouch = false;
}
return true;
}
if (mIsLastOverScrollCanNotAbort) {
if (mIndicator.isInStartPosition() && !mOverScrollChecker.mIsScrolling) {
makeNewTouchDownEvent(ev);
mIsLastOverScrollCanNotAbort = false;
}
return true;
}
if (mIsSpringBackCanNotBeInterrupted) {
if (mIndicator.isInStartPosition() && !mScrollChecker.mIsRunning
&& !mOverScrollChecker.mIsScrolling) {
makeNewTouchDownEvent(ev);
mIsSpringBackCanNotBeInterrupted = false;
}
return true;
}
return false;
}
protected void preparePaint() {
if (mBackgroundPaint == null) {
mBackgroundPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mBackgroundPaint.setStyle(Paint.Style.FILL);
}
}
protected boolean isNeedInterceptTouchEvent() {
return (isEnabledInterceptEventWhileLoading() && (isRefreshing() || isLoadingMore()))
|| mChangeStateAnimator != null && mChangeStateAnimator.isRunning()
|| (isAutoRefresh() && mAutomaticActionInScrolling);
}
protected boolean isNeedFilterTouchEvent() {
return mIsLastOverScrollCanNotAbort || mIsSpringBackCanNotBeInterrupted
|| mIsInterceptTouchEventInOnceTouch;
}
protected boolean isCanNotAbortOverScrolling() {
return (mOverScrollChecker.mIsScrolling
&& (((isMovingHeader() && isDisabledRefresh()))
|| (isMovingFooter() && isDisabledLoadMore())));
}
public boolean isNotYetInEdgeCannotMoveHeader() {
if (mInEdgeCanMoveHeaderCallBack != null)
return mInEdgeCanMoveHeaderCallBack.isNotYetInEdgeCannotMoveHeader(this,
mTargetView, mHeaderView);
return ScrollCompat.canChildScrollUp(mTargetView);
}
public boolean isNotYetInEdgeCannotMoveFooter() {
if (mInEdgeCanMoveFooterCallBack != null)
return mInEdgeCanMoveFooterCallBack.isNotYetInEdgeCannotMoveFooter(this,
mTargetView, mFooterView);
return ScrollCompat.canChildScrollDown(mTargetView);
}
protected boolean isInsideAnotherDirectionView(final float x, final float y) {
if (mFingerInsideAnotherDirectionViewCallback != null)
return mFingerInsideAnotherDirectionViewCallback.isInside(x, y, mTargetView);
return BoundaryUtil.isInsideHorizontalView(x, y, mTargetView);
}
protected void makeNewTouchDownEvent(MotionEvent ev) {
sendCancelEvent();
sendDownEvent();
mIndicator.onFingerUp();
mIndicator.onFingerDown(ev.getX(), ev.getY());
}
protected void sendCancelEvent() {
if (mHasSendCancelEvent || mLastMoveEvent == null) return;
if (sDebug) {
SRLog.i(TAG, "sendCancelEvent()");
}
final MotionEvent last = mLastMoveEvent;
MotionEvent ev = MotionEvent.obtain(last.getDownTime(), last.getEventTime() +
ViewConfiguration.getLongPressTimeout(),
MotionEvent.ACTION_CANCEL, last.getX(), last.getY(), last.getMetaState());
mHasSendCancelEvent = true;
mHasSendDownEvent = false;
super.dispatchTouchEvent(ev);
}
protected void sendDownEvent() {
if (mHasSendDownEvent || mLastMoveEvent == null) return;
if (sDebug) {
SRLog.i(TAG, "sendDownEvent()");
}
final MotionEvent last = mLastMoveEvent;
MotionEvent ev = MotionEvent.obtain(last.getDownTime(), last.getEventTime(),
MotionEvent.ACTION_DOWN, last.getX(), last.getY(), last.getMetaState());
mHasSendCancelEvent = false;
mHasSendDownEvent = true;
super.dispatchTouchEvent(ev);
}
protected void notifyFingerUp() {
if (sDebug) {
SRLog.i(TAG, "notifyFingerUp()");
}
if (mHeaderView != null && isHeaderInProcessing() && !isDisabledRefresh()) {
mHeaderView.onFingerUp(this, mIndicator);
} else if (mFooterView != null && isFooterInProcessing() && !isDisabledLoadMore()) {
mFooterView.onFingerUp(this, mIndicator);
}
}
protected void onFingerUp(boolean stayForLoading) {
if (sDebug) {
SRLog.d(TAG, "onFingerUp(): stayForLoading: %s", stayForLoading);
}
notifyFingerUp();
if (!stayForLoading && isEnabledKeepRefreshView() && mStatus != SR_STATUS_COMPLETE
&& !isRefreshing() && !isLoadingMore() && mMode == Constants.MODE_DEFAULT) {
if (isHeaderInProcessing() && !isDisabledRefresh()
&& mIndicator.isOverOffsetToKeepHeaderWhileLoading()) {
if (mIndicator.isAlreadyHere(mIndicator.getOffsetToKeepHeaderWhileLoading())
|| isDisabledPerformRefresh()) {
onRelease();
return;
}
mScrollChecker.tryToScrollTo(mIndicator.getOffsetToKeepHeaderWhileLoading(),
mDurationOfBackToHeaderHeight);
} else if (isFooterInProcessing() && !isDisabledLoadMore()
&& mIndicator.isOverOffsetToKeepFooterWhileLoading()) {
if (mIndicator.isAlreadyHere(mIndicator.getOffsetToKeepFooterWhileLoading())
|| isDisabledPerformLoadMore()) {
onRelease();
return;
}
mScrollChecker.tryToScrollTo(mIndicator.getOffsetToKeepFooterWhileLoading(),
mDurationOfBackToFooterHeight);
} else {
onRelease();
}
} else {
onRelease();
}
}
protected void onRelease() {
if (sDebug) {
SRLog.d(TAG, "onRelease()");
}
mAutomaticActionInScrolling = false;
if (canInterceptRelease() || (isEnabledNoMoreData() && isMovingFooter()
&& isEnabledNoSpringBackWhenNoMoreData()))
return;
tryToPerformRefresh();
if (mStatus == SR_STATUS_REFRESHING || mStatus == SR_STATUS_LOADING_MORE) {
if (isEnabledKeepRefreshView()) {
if (isHeaderInProcessing()) {
if (isMovingHeader() && mIndicator.isOverOffsetToKeepHeaderWhileLoading()) {
mScrollChecker.tryToScrollTo(mIndicator.getOffsetToKeepHeaderWhileLoading(),
mDurationOfBackToHeaderHeight);
} else if (isMovingFooter()) {
tryScrollBackToTopByPercentDuration();
}
} else if (isFooterInProcessing()) {
if (isMovingFooter() && mIndicator.isOverOffsetToKeepFooterWhileLoading()) {
mScrollChecker.tryToScrollTo(mIndicator.getOffsetToKeepFooterWhileLoading(),
mDurationOfBackToFooterHeight);
} else if (isMovingHeader()) {
tryScrollBackToTopByPercentDuration();
}
}
} else {
tryScrollBackToTopByPercentDuration();
}
} else if (mStatus == SR_STATUS_COMPLETE) {
notifyUIRefreshComplete(true);
} else {
tryScrollBackToTopByPercentDuration();
}
}
protected void springBack() {
mAutomaticActionInScrolling = false;
mOverScrollChecker.mIsClamped = false;
if (isEnabledNoMoreData() && isMovingFooter()
&& isEnabledNoSpringBackWhenNoMoreData())
return;
tryToPerformRefresh();
if (mStatus == SR_STATUS_REFRESHING || mStatus == SR_STATUS_LOADING_MORE) {
if (isEnabledKeepRefreshView()) {
if (isHeaderInProcessing()) {
if (isMovingHeader() && mIndicator.isOverOffsetToKeepHeaderWhileLoading()) {
mScrollChecker.tryToScrollTo(mIndicator.getOffsetToKeepHeaderWhileLoading(),
mOverScrollChecker.mDuration);
} else if (isMovingFooter()) {
tryScrollBackToTop(mOverScrollChecker.mDuration);
}
} else if (isFooterInProcessing()) {
if (isMovingFooter() && mIndicator.isOverOffsetToKeepFooterWhileLoading()) {
mScrollChecker.tryToScrollTo(mIndicator.getOffsetToKeepFooterWhileLoading(),
mOverScrollChecker.mDuration);
} else if (isMovingHeader()) {
tryScrollBackToTop(mOverScrollChecker.mDuration);
}
}
} else {
tryScrollBackToTop(mOverScrollChecker.mDuration);
}
} else if (mStatus == SR_STATUS_COMPLETE) {
notifyUIRefreshComplete(true);
} else {
tryScrollBackToTop(mOverScrollChecker.mDuration);
}
}
protected void tryScrollBackToTopByPercentDuration() {
//Use the current percentage duration of the current position to scroll back to the top
float percent;
if (isMovingHeader()) {
percent = mIndicator.getCurrentPercentOfRefreshOffset();
percent = percent > 1 || percent <= 0 ? 1 : percent;
tryScrollBackToTop(Math.round(mDurationToCloseHeader * percent));
} else if (isMovingFooter()) {
percent = mIndicator.getCurrentPercentOfLoadMoreOffset();
percent = percent > 1 || percent <= 0 ? 1 : percent;
tryScrollBackToTop(Math.round(mDurationToCloseFooter * percent));
} else {
tryScrollBackToTop(0);
}
}
protected void tryScrollBackToTop(int duration) {
if (sDebug) {
SRLog.d(TAG, "tryScrollBackToTop(): duration: %s", duration);
}
if (mIndicator.hasLeftStartPosition() && (!mIndicator.hasTouched() || !mIndicator.hasMoved())) {
mScrollChecker.tryToScrollTo(IIndicator.START_POS, duration);
return;
}
if (isNeedFilterTouchEvent() && mIndicator.hasLeftStartPosition()) {
mScrollChecker.tryToScrollTo(IIndicator.START_POS, duration);
return;
}
if (isMovingFooter() && mStatus == SR_STATUS_COMPLETE
&& mIndicator.hasJustBackToStartPosition()) {
mScrollChecker.tryToScrollTo(IIndicator.START_POS, duration);
return;
}
tryToNotifyReset();
}
protected void notifyUIRefreshComplete(boolean useScroll) {
if (sDebug) {
SRLog.i(TAG, "notifyUIRefreshComplete()");
}
mIndicator.onRefreshComplete();
if (mNeedNotifyRefreshComplete) {
if (isHeaderInProcessing() && mHeaderView != null) {
mHeaderView.onRefreshComplete(this, mIsLastRefreshSuccessful);
} else if (isFooterInProcessing() && mFooterView != null) {
mFooterView.onRefreshComplete(this, mIsLastRefreshSuccessful);
}
if (mNeedNotifyRefreshListener && mRefreshListener != null) {
mRefreshListener.onRefreshComplete(mIsLastRefreshSuccessful);
}
mNeedNotifyRefreshComplete = false;
} else if (mDelayedRefreshComplete && mNeedNotifyRefreshListener && mRefreshListener != null) {
mRefreshListener.onRefreshComplete(mIsLastRefreshSuccessful);
}
if (useScroll) tryScrollBackToTopByPercentDuration();
tryToNotifyReset();
}
protected void moveHeaderPos(float delta) {
if (sDebug) {
SRLog.d(TAG, "moveHeaderPos(): delta: %s", delta);
}
mIndicator.setMovingStatus(Constants.MOVING_HEADER);
// to keep the consistence with refresh, need to converse the deltaY
movePos(delta);
}
protected void moveFooterPos(float delta) {
if (sDebug) {
SRLog.d(TAG, "moveFooterPos(): delta: %s", delta);
}
mIndicator.setMovingStatus(Constants.MOVING_FOOTER);
//check if it is needed to compatible scroll
if (mCompatLoadMoreScroll && !isEnabledPinContentView() && mIsLastRefreshSuccessful
&& (mStatus == SR_STATUS_COMPLETE
|| (isEnabledNextPtrAtOnce() && mStatus == SR_STATUS_PREPARE
&& !mOverScrollChecker.mIsScrolling && !mIndicator.hasTouched()))) {
if (sDebug) {
SRLog.d(TAG, "moveFooterPos(): compatible scroll delta: %s", delta);
}
mNeedFilterScrollEvent = true;
compatLoadMoreScroll(delta);
}
movePos(-delta);
}
protected void compatLoadMoreScroll(float delta) {
if (mLoadMoreScrollCallback == null) {
if (mScrollTargetView != null) {
try {
ScrollCompat.scrollCompat(mScrollTargetView, delta);
} catch (Exception ignored) {//ignored
}
} else if (mTargetView != null)
try {
ScrollCompat.scrollCompat(mTargetView, delta);
} catch (Exception ignored) {//ignored
}
} else {
mLoadMoreScrollCallback.onScroll(mTargetView, delta);
}
}
protected void movePos(float delta) {
if (delta == 0f) {
if (sDebug) {
SRLog.d(TAG, "movePos(): delta is zero");
}
return;
}
if (delta > 0) {
delta = tryToFilterMovePos(delta);
if (delta <= 0)
return;
}
if (delta > 0 && mMode == Constants.MODE_SCALE && calculateScale() >= 1.2f) {
return;
}
int to = mIndicator.getCurrentPos() + Math.round(delta);
// over top
if ((mMode == Constants.MODE_DEFAULT || mOverScrollChecker.mIsFling) && mIndicator.willOverTop(to)) {
to = IIndicator.START_POS;
if (sDebug) {
SRLog.d(TAG, "movePos(): over top");
}
}
mBeenSendTouchEvent = false;
mIndicator.setCurrentPos(to);
int change = to - mIndicator.getLastPos();
if (getParent() != null && !mNestedScrollInProgress && mIndicator.hasTouched()
&& mIndicator.hasJustLeftStartPosition())
getParent().requestDisallowInterceptTouchEvent(true);
if (isMovingHeader())
updatePos(change);
else if (isMovingFooter())
updatePos(-change);
}
protected float tryToFilterMovePos(float deltaY) {
if (isMovingHeader() && !isDisabledRefresh() && mHeaderView != null) {
int style = mHeaderView.getStyle();
if (style != IRefreshView.STYLE_DEFAULT && style != IRefreshView.STYLE_FOLLOW_CENTER) {
final int maxHeight = getHeight() - getPaddingTop() - getPaddingBottom();
if (mIndicator.getCurrentPos() + Math.round(deltaY) > maxHeight) {
return maxHeight - mIndicator.getCurrentPos();
}
}
} else if (isMovingFooter() && !isDisabledLoadMore() && mFooterView != null) {
int style = mFooterView.getStyle();
if (style != IRefreshView.STYLE_DEFAULT && style != IRefreshView.STYLE_FOLLOW_CENTER) {
final int maxHeight = getHeight() - getPaddingTop() - getPaddingBottom();
if (mIndicator.getCurrentPos() + Math.round(deltaY) > maxHeight) {
return maxHeight - mIndicator.getCurrentPos();
}
}
}
return deltaY;
}
/**
* Update view's Y position
*
* @param change The changed value
*/
protected void updatePos(int change) {
// once moved, cancel event will be sent to child
if (mIndicator.hasTouched() && !mNestedScrollInProgress
&& mIndicator.hasMovedAfterPressedDown()) {
sendCancelEvent();
}
final boolean isMovingHeader = isMovingHeader();
final boolean isMovingFooter = isMovingFooter();
// leave initiated position or just refresh complete
if (mMode == Constants.MODE_DEFAULT && ((mIndicator.hasJustLeftStartPosition()
|| mViewStatus == SR_VIEW_STATUS_INIT) && mStatus == SR_STATUS_INIT)
|| (mStatus == SR_STATUS_COMPLETE && isEnabledNextPtrAtOnce()
&& ((isHeaderInProcessing() && isMovingHeader && change > 0)
|| (isFooterInProcessing() && isMovingFooter && change < 0)))) {
mStatus = SR_STATUS_PREPARE;
if (isMovingHeader()) {
mViewStatus = SR_VIEW_STATUS_HEADER_IN_PROCESSING;
if (mHeaderView != null)
mHeaderView.onRefreshPrepare(this);
} else if (isMovingFooter()) {
mViewStatus = SR_VIEW_STATUS_FOOTER_IN_PROCESSING;
if (mFooterView != null)
mFooterView.onRefreshPrepare(this);
}
}
tryToDispatchNestedFling();
// back to initiated position
if (!(isAutoRefresh() && mStatus != SR_STATUS_COMPLETE)
&& mIndicator.hasJustBackToStartPosition()) {
tryToNotifyReset();
// recover event to children
if (mIndicator.hasTouched() && !mNestedScrollInProgress && mHasSendCancelEvent) {
sendDownEvent();
}
}
tryToPerformRefreshWhenMoved();
if (sDebug) {
SRLog.d(TAG, "updatePos(): change: %s, current: %s last: %s",
change, mIndicator.getCurrentPos(), mIndicator.getLastPos());
}
notifyUIPositionChanged();
boolean needRequestLayout = offsetChild(change, isMovingHeader, isMovingFooter);
if (needRequestLayout || (!mOverScrollChecker.mIsScrolling && mIndicator
.isInStartPosition())) {
requestLayout();
} else {
invalidate();
}
}
protected boolean offsetChild(int change, boolean isMovingHeader, boolean isMovingFooter) {
boolean needRequestLayout = false;
if (mMode == Constants.MODE_DEFAULT) {
if (mHeaderView != null && !isDisabledRefresh() && isMovingHeader
&& !isEnabledHideHeaderView()) {
final int type = mHeaderView.getStyle();
switch (type) {
case IRefreshView.STYLE_DEFAULT:
mHeaderView.getView().offsetTopAndBottom(change);
break;
case IRefreshView.STYLE_SCALE:
needRequestLayout = true;
break;
case IRefreshView.STYLE_PIN:
break;
case IRefreshView.STYLE_FOLLOW_PIN:
if (mIndicator.getCurrentPos() <= mIndicator.getHeaderHeight())
mHeaderView.getView().offsetTopAndBottom(change);
break;
case IRefreshView.STYLE_FOLLOW_SCALE:
case IRefreshView.STYLE_FOLLOW_CENTER:
if (mIndicator.getCurrentPos() > mIndicator.getHeaderHeight())
needRequestLayout = true;
else
mHeaderView.getView().offsetTopAndBottom(change);
break;
}
if (!isEnabledPinContentView() && mStickyHeaderView != null)
mStickyHeaderView.offsetTopAndBottom(change);
if (isHeaderInProcessing())
mHeaderView.onRefreshPositionChanged(this, mStatus, mIndicator);
else
mHeaderView.onPureScrollPositionChanged(this, mStatus, mIndicator);
} else if (mFooterView != null && !isDisabledLoadMore() && isMovingFooter
&& !isEnabledHideFooterView()) {
final int type = mFooterView.getStyle();
switch (type) {
case IRefreshView.STYLE_DEFAULT:
mFooterView.getView().offsetTopAndBottom(change);
break;
case IRefreshView.STYLE_SCALE:
needRequestLayout = true;
break;
case IRefreshView.STYLE_PIN:
break;
case IRefreshView.STYLE_FOLLOW_PIN:
if (mIndicator.getCurrentPos() <= mIndicator.getFooterHeight())
mFooterView.getView().offsetTopAndBottom(change);
break;
case IRefreshView.STYLE_FOLLOW_SCALE:
case IRefreshView.STYLE_FOLLOW_CENTER:
if (mIndicator.getCurrentPos() > mIndicator.getFooterHeight())
needRequestLayout = true;
else
mFooterView.getView().offsetTopAndBottom(change);
break;
}
if (isFooterInProcessing())
mFooterView.onRefreshPositionChanged(this, mStatus, mIndicator);
else
mFooterView.onPureScrollPositionChanged(this, mStatus, mIndicator);
}
if (!isEnabledPinContentView()) {
if (mScrollTargetView != null && isMovingFooter && !isDisabledLoadMore()) {
mScrollTargetView.setTranslationY(-mIndicator.getCurrentPos());
} else {
if (mTargetView != null) mTargetView.offsetTopAndBottom(change);
}
}
} else {
if (mTargetView != null) {
if (isMovingHeader) {
mTargetView.setPivotY(0);
mTargetView.setScaleY(calculateScale());
} else if (isMovingFooter) {
if (mScrollTargetView != null) {
mScrollTargetView.setPivotY(getHeight());
mScrollTargetView.setScaleY(calculateScale());
} else {
mTargetView.setPivotY(getHeight());
mTargetView.setScaleY(calculateScale());
}
} else {
mTargetView.setPivotY(0);
mTargetView.setScaleY(1);
if (mScrollTargetView != null) {
mScrollTargetView.setPivotY(0);
mScrollTargetView.setScaleY(1);
}
}
mTargetView.setScaleX(1);
mTargetView.setPivotX(0);
if (mScrollTargetView != null) {
mScrollTargetView.setScaleX(0);
mScrollTargetView.setPivotX(1);
}
}
}
return needRequestLayout;
}
protected float calculateScale() {
if (mIndicator.getCurrentPos() >= 0)
return 1 + (float) Math.min(.2f, Math.pow(mIndicator.getCurrentPos(), .72f) / 1000f);
else
return 1 - (float) Math.min(.2f, Math.pow(-mIndicator.getCurrentPos(), .72f) / 1000f);
}
protected void tryToPerformRefreshWhenMoved() {
// try to perform refresh
if (mMode == Constants.MODE_DEFAULT && !mOverScrollChecker.mIsScrolling && mStatus == SR_STATUS_PREPARE) {
// reach fresh height while moving from top to bottom or reach load more height while
// moving from bottom to top
if (mIndicator.hasTouched() && !isAutoRefresh() && isEnabledPullToRefresh()
&& ((isHeaderInProcessing() && isMovingHeader() && mIndicator
.crossRefreshLineFromTopToBottom())
|| (isFooterInProcessing() && isMovingFooter() && mIndicator
.crossRefreshLineFromBottomToTop()))) {
tryToPerformRefresh();
}
// reach Header height while auto refresh or reach Footer height while auto refresh
if (!isRefreshing() && !isLoadingMore() && isPerformAutoRefreshButLater()
&& ((isHeaderInProcessing() && isMovingHeader())
|| (isFooterInProcessing() && isMovingFooter()))) {
tryToPerformRefresh();
}
}
}
/**
* We need to notify the X pos changed
*/
protected void updateAnotherDirectionPos() {
if (mMode == Constants.MODE_DEFAULT) {
if (mHeaderView != null && !isDisabledRefresh() && isMovingHeader()
&& !isEnabledHideHeaderView()) {
if (isHeaderInProcessing())
mHeaderView.onRefreshPositionChanged(this, mStatus, mIndicator);
else
mHeaderView.onPureScrollPositionChanged(this, mStatus, mIndicator);
} else if (mFooterView != null && !isDisabledLoadMore() && isMovingFooter()
&& !isEnabledHideFooterView()) {
if (isFooterInProcessing())
mFooterView.onRefreshPositionChanged(this, mStatus, mIndicator);
else
mFooterView.onPureScrollPositionChanged(this, mStatus, mIndicator);
}
}
}
public boolean isMovingHeader() {
return mIndicator.getMovingStatus() == Constants.MOVING_HEADER;
}
public boolean isMovingContent() {
return mIndicator.getMovingStatus() == Constants.MOVING_CONTENT;
}
public boolean isMovingFooter() {
return mIndicator.getMovingStatus() == Constants.MOVING_FOOTER;
}
public boolean isHeaderInProcessing() {
return mViewStatus == SR_VIEW_STATUS_HEADER_IN_PROCESSING;
}
public boolean isFooterInProcessing() {
return mViewStatus == SR_VIEW_STATUS_FOOTER_IN_PROCESSING;
}
/**
* Check in over scrolling needs to scroll back to the start position
*
* @return Is
*/
private boolean canSpringBack() {
if (mOverScrollChecker.mIsClamped && !mIndicator.isInStartPosition()) {
if (sDebug) {
SRLog.i(TAG, "canSpringBack()");
}
mScrollChecker.updateInterpolator(mSpringInterpolator);
springBack();
return true;
} else {
return false;
}
}
private void tryToDispatchNestedFling() {
if (mDelayedNestedFling && mIndicator.isInStartPosition()) {
mDelayedNestedFling = false;
mScrollChecker.abortIfWorking();
if (mDelayedScrollChecker != null)
mDelayedScrollChecker.abortIfWorking();
int v = (int) mOverScrollChecker.calculateVelocity();
dispatchNestedFling(v);
}
}
protected boolean tryToNotifyReset() {
if (sDebug) {
SRLog.i(TAG, "tryToNotifyReset()");
}
if ((mStatus == SR_STATUS_COMPLETE || mStatus == SR_STATUS_PREPARE)
&& mIndicator.isInStartPosition()) {
if (mHeaderView != null)
mHeaderView.onReset(this);
if (mFooterView != null)
mFooterView.onReset(this);
mStatus = SR_STATUS_INIT;
mViewStatus = SR_VIEW_STATUS_INIT;
mIsSpringBackCanNotBeInterrupted = false;
mNeedNotifyRefreshComplete = true;
mDelayedRefreshComplete = false;
mScrollChecker.destroy();
mFlag = mFlag & ~MASK_AUTO_REFRESH;
mAutomaticActionTriggered = false;
tryToResetMovingStatus();
resetScrollerInterpolator();
if (mMode == Constants.MODE_SCALE && mTargetView != null) {
mTargetView.setPivotX(0);
mTargetView.setPivotY(0);
mTargetView.setScaleX(1);
mTargetView.setScaleY(1);
if (mScrollTargetView != null) {
mScrollTargetView.setPivotX(0);
mScrollTargetView.setPivotY(0);
mScrollTargetView.setScaleX(1);
mScrollTargetView.setScaleY(1);
}
}
if (getParent() != null)
getParent().requestDisallowInterceptTouchEvent(false);
return true;
}
return false;
}
protected void performRefreshComplete(boolean hook) {
if (sDebug) {
SRLog.i(TAG, "performRefreshComplete()");
}
if (isRefreshing() && hook && mHeaderRefreshCompleteHook != null
&& mHeaderRefreshCompleteHook.mCallBack != null) {
mHeaderRefreshCompleteHook.mLayout = this;
mHeaderRefreshCompleteHook.doHook();
return;
}
if (isLoadingMore() && hook && mFooterRefreshCompleteHook != null
&& mFooterRefreshCompleteHook.mCallBack != null) {
mFooterRefreshCompleteHook.mLayout = this;
mFooterRefreshCompleteHook.doHook();
return;
}
mStatus = SR_STATUS_COMPLETE;
notifyUIRefreshComplete(true);
}
/**
* try to perform refresh or loading , if performed return true
*/
protected void tryToPerformRefresh() {
// status not be prepare or over scrolling or moving content go to break;
if (mMode != Constants.MODE_DEFAULT || mStatus != SR_STATUS_PREPARE || !canPerformRefresh()) {
return;
}
if (sDebug) {
SRLog.i(TAG, "tryToPerformRefresh()");
}
if (isHeaderInProcessing() && !isDisabledRefresh() && !isDisabledPerformRefresh()
&& ((mIndicator.isOverOffsetToKeepHeaderWhileLoading() && isAutoRefresh())
|| (isEnabledKeepRefreshView() && mIndicator.isOverOffsetToKeepHeaderWhileLoading())
|| mIndicator.isOverOffsetToRefresh())) {
triggeredRefresh(true);
return;
}
if (isFooterInProcessing() && !isDisabledLoadMore() && !isDisabledPerformLoadMore()
&& ((mIndicator.isOverOffsetToKeepFooterWhileLoading() && isAutoRefresh())
|| (isEnabledKeepRefreshView() && mIndicator.isOverOffsetToKeepFooterWhileLoading())
|| mIndicator.isOverOffsetToLoadMore())) {
triggeredLoadMore(true);
}
}
protected void tryToPerformScrollToBottomToLoadMore() {
if (isEnabledAutoLoadMore() && !isDisabledPerformLoadMore() && mMode ==
Constants.MODE_DEFAULT && (mStatus == SR_STATUS_INIT || mStatus == SR_STATUS_PREPARE)) {
if (mAutoLoadMoreCallBack != null && mAutoLoadMoreCallBack.canAutoLoadMore(this,
mTargetView)) {
triggeredLoadMore(true);
} else if (mAutoLoadMoreCallBack == null) {
if (isMovingFooter() && mScrollTargetView != null
&& ScrollCompat.canAutoLoadMore(mScrollTargetView)) {
triggeredLoadMore(true);
} else if (ScrollCompat.canAutoLoadMore(mTargetView)) {
triggeredLoadMore(true);
}
}
}
}
protected void tryToPerformScrollToTopToRefresh() {
if (isEnabledAutoRefresh() && !isDisabledPerformRefresh() && mMode == Constants.MODE_DEFAULT
&& (mStatus == SR_STATUS_INIT || mStatus == SR_STATUS_PREPARE)
&& ScrollCompat.canAutoRefresh(mTargetView)) {
triggeredRefresh(true);
}
}
protected void triggeredRefresh(boolean notify) {
mNeedNotifyRefreshListener = notify;
mStatus = SR_STATUS_REFRESHING;
mViewStatus = SR_VIEW_STATUS_HEADER_IN_PROCESSING;
mDelayedRefreshComplete = false;
mIsSpringBackCanNotBeInterrupted = false;
performRefresh();
}
protected void triggeredLoadMore(boolean notify) {
mNeedNotifyRefreshListener = notify;
mStatus = SR_STATUS_LOADING_MORE;
mViewStatus = SR_VIEW_STATUS_FOOTER_IN_PROCESSING;
mDelayedRefreshComplete = false;
mIsSpringBackCanNotBeInterrupted = false;
performRefresh();
}
protected void tryToResetMovingStatus() {
if (mIndicator.isInStartPosition() && !isMovingContent()
&& mStatus == SR_STATUS_INIT) {
mIndicator.setMovingStatus(Constants.MOVING_CONTENT);
notifyUIPositionChanged();
}
}
protected boolean canPerformRefresh() {
return !(mOverScrollChecker.mIsClamped || mOverScrollChecker.mIsScrolling
|| isMovingContent());
}
/**
* Try check auto refresh later flag
*
* @return Is
*/
protected boolean isPerformAutoRefreshButLater() {
return (mFlag & MASK_AUTO_REFRESH) == FLAG_AUTO_REFRESH_BUT_LATER;
}
protected void performRefresh() {
//loading start milliseconds since boot
mLoadingStartTime = SystemClock.uptimeMillis();
mNeedNotifyRefreshComplete = true;
if (sDebug) {
SRLog.d(TAG, "onRefreshBegin systemTime: %s", mLoadingStartTime);
}
if (isRefreshing()) {
if (mHeaderView != null)
mHeaderView.onRefreshBegin(this, mIndicator);
} else if (isLoadingMore()) {
if (mFooterView != null)
mFooterView.onRefreshBegin(this, mIndicator);
}
if (mNeedNotifyRefreshListener && mRefreshListener != null)
mRefreshListener.onRefreshBegin(isRefreshing());
}
protected void dispatchNestedFling(int velocity) {
if (mScrollTargetView != null)
ScrollCompat.flingCompat(mScrollTargetView, -velocity);
else
ScrollCompat.flingCompat(mTargetView, -velocity);
}
private void notifyUIPositionChanged() {
if (mUIPositionChangedListeners != null && !mUIPositionChangedListeners.isEmpty()) {
for (OnUIPositionChangedListener listener : mUIPositionChangedListeners) {
listener.onChanged(mStatus, mIndicator);
}
}
}
/**
* Safely remove the onScrollChangedListener from target ViewTreeObserver
*/
private void safelyRemoveListeners() {
if (mTargetViewTreeObserver != null) {
if (mTargetViewTreeObserver.isAlive())
mTargetViewTreeObserver.removeOnScrollChangedListener(this);
else {
SRReflectUtil.safelyRemoveListeners(mTargetViewTreeObserver, this);
}
}
}
private boolean canInterceptRelease() {
return mOverScrollChecker.mMode == OverScrollChecker.MODE_PRE_FLING
&& mOverScrollChecker.mIsScrolling;
}
/**
* Classes that wish to override {@link SmoothRefreshLayout#isNotYetInEdgeCannotMoveHeader()} method
* behavior should implement this interface.
*/
public interface OnHeaderEdgeDetectCallBack {
/**
* Callback that will be called when {@link SmoothRefreshLayout#isNotYetInEdgeCannotMoveHeader()} method
* is called to allow the implementer to override its behavior.
*
* @param parent SmoothRefreshLayout that this callback is overriding.
* @param child The child view.
* @param header The Header view.
* @return Whether it is possible for the child view of parent layout to scroll up.
*/
boolean isNotYetInEdgeCannotMoveHeader(SmoothRefreshLayout parent, @Nullable View child,
@Nullable IRefreshView header);
}
/**
* Classes that wish to override {@link SmoothRefreshLayout#isNotYetInEdgeCannotMoveFooter()} method
* behavior should implement this interface.
*/
public interface OnFooterEdgeDetectCallBack {
/**
* Callback that will be called when {@link SmoothRefreshLayout#isNotYetInEdgeCannotMoveFooter()} method
* is called to allow the implementer to override its behavior.
*
* @param parent SmoothRefreshLayout that this callback is overriding.
* @param child The child view.
* @param footer The Footer view.
* @return Whether it is possible for the child view of parent layout to scroll down.
*/
boolean isNotYetInEdgeCannotMoveFooter(SmoothRefreshLayout parent, @Nullable View child,
@Nullable IRefreshView footer);
}
/**
* Classes that wish to override {@link SmoothRefreshLayout#isInsideAnotherDirectionView(float, float)}}
* method behavior should implement this interface.
*/
public interface OnInsideAnotherDirectionViewCallback {
/**
* Callback that will be called when
* {@link SmoothRefreshLayout#isInsideAnotherDirectionView(float, float)}} method
* is called to allow the implementer to override its behavior.
*
* @param x The finger pressed x of the screen.
* @param y The finger pressed y of the screen.
* @param view The target view.
* @return Whether the finger pressed point is inside horizontal view
*/
boolean isInside(float x, float y, View view);
}
/**
* Classes that wish to be notified when the swipe gesture correctly triggers a refresh
* should implement this interface.
*/
public interface OnRefreshListener {
/**
* Called when a swipe gesture triggers a refresh.
*
* @param isRefresh Refresh is true , load more is false
*/
void onRefreshBegin(boolean isRefresh);
/**
* Called when refresh completed.
*
* @param isSuccessful refresh state
*/
void onRefreshComplete(boolean isSuccessful);
}
/**
* Classes that wish to be notified when the state changes should implement this interface.
*/
public interface OnStateChangedListener {
/**
* Called when the state changes
*
* @param previous The previous state @see {@link State}
* @param current The current state @see {@link State}
*/
void onStateChanged(@State int previous, @State int current);
}
/**
* Classes that wish to be notified when the views position changes should implement this
* interface
*/
public interface OnUIPositionChangedListener {
/**
* UI position changed
*
* @param status {@link #SR_STATUS_INIT}, {@link #SR_STATUS_PREPARE},
* {@link #SR_STATUS_REFRESHING},{@link #SR_STATUS_LOADING_MORE},{@link #SR_STATUS_COMPLETE}.
* @param indicator @see {@link IIndicator}
*/
void onChanged(byte status, IIndicator indicator);
}
/**
* Classes that wish to be called when load more completed spring back to start position
*/
public interface OnLoadMoreScrollCallback {
/**
* Called when load more completed spring back to start position, each move triggers a
* callback once
*
* @param content The content view
* @param delta The scroll distance in current axis
*/
void onScroll(View content, float delta);
}
public interface OnHookUIRefreshCompleteCallBack {
@MainThread
void onHook(RefreshCompleteHook hook);
}
/**
* Classes that wish to be called when {@link SmoothRefreshLayout#setEnableAutoLoadMore(boolean)}
* has been set true and {@link SmoothRefreshLayout#isDisabledLoadMore()} not be true and
* sure you need to customize the specified trigger rule
*/
public interface OnPerformAutoLoadMoreCallBack {
/**
* Whether need trigger auto load more
*
* @param parent The frame
* @param child the child view
* @return whether need trigger
*/
boolean canAutoLoadMore(SmoothRefreshLayout parent, @Nullable View child);
}
public interface OnFingerDownListener {
void onFingerDown();
}
public static class LayoutParams extends MarginLayoutParams {
private static final int[] LAYOUT_ATTRS = new int[]{android.R.attr.layout_gravity};
private int mGravity = Gravity.TOP | Gravity.START;
public LayoutParams(Context c, AttributeSet attrs) {
super(c, attrs);
final TypedArray a = c.obtainStyledAttributes(attrs, LAYOUT_ATTRS);
mGravity = a.getInt(0, mGravity);
a.recycle();
}
public LayoutParams(int width, int height, int gravity) {
super(width, height);
this.mGravity = gravity;
}
public LayoutParams(int width, int height) {
super(width, height);
}
public LayoutParams(MarginLayoutParams source) {
super(source);
}
public LayoutParams(ViewGroup.LayoutParams source) {
super(source);
}
public LayoutParams(LayoutParams source) {
super(source);
mGravity = source.mGravity;
}
public int getGravity() {
return mGravity;
}
}
public static class RefreshCompleteHook {
private SmoothRefreshLayout mLayout;
private OnHookUIRefreshCompleteCallBack mCallBack;
public void onHookComplete() {
if (mLayout != null) {
if (SmoothRefreshLayout.sDebug) {
SRLog.i(SmoothRefreshLayout.TAG, "RefreshCompleteHook: onHookComplete()");
}
mLayout.performRefreshComplete(false);
}
}
private void setHookCallBack(OnHookUIRefreshCompleteCallBack callBack) {
mCallBack = callBack;
}
private void doHook() {
if (mCallBack != null) {
if (SmoothRefreshLayout.sDebug) {
SRLog.i(SmoothRefreshLayout.TAG, "RefreshCompleteHook: doHook()");
}
mCallBack.onHook(this);
}
}
}
/**
* Delayed completion of loading
*/
private static class DelayToRefreshComplete implements Runnable {
private WeakReference<SmoothRefreshLayout> mLayoutWeakRf;
private DelayToRefreshComplete(SmoothRefreshLayout layout) {
mLayoutWeakRf = new WeakReference<>(layout);
}
@Override
public void run() {
if (mLayoutWeakRf.get() != null) {
if (SmoothRefreshLayout.sDebug) {
SRLog.i(SmoothRefreshLayout.TAG, "DelayToRefreshComplete: run()");
}
mLayoutWeakRf.get().performRefreshComplete(true);
}
}
}
class DelayedScrollChecker implements Runnable {
private int mVelocity;
private boolean mRunning = false;
void abortIfWorking() {
if (mRunning) {
SmoothRefreshLayout.this.removeCallbacks(this);
mRunning = false;
}
}
void updateVelocity(int velocity) {
mVelocity = velocity;
abortIfWorking();
mRunning = true;
SmoothRefreshLayout.this.postDelayed(this, 25);
}
@Override
public void run() {
if (mRunning) {
SmoothRefreshLayout.this.dispatchNestedFling(mVelocity);
mRunning = false;
}
}
}
/**
* Support over Scroll feature
* The Over Scroll checker
*/
class OverScrollChecker implements Runnable {
private static final byte MODE_NONE = -1;
private static final byte MODE_PRE_FLING = 0;
private static final byte MODE_FLING = 1;
final int mMaxDistance;
Scroller mScroller;
int mDuration = 0;
int mLastY = 0;
float mVelocity = -1;
boolean mIsScrolling = false;
boolean mIsClamped = false;
boolean mIsFling = false;
private byte mMode = MODE_NONE;
OverScrollChecker() {
DisplayMetrics dm = SmoothRefreshLayout.this.getContext().getResources()
.getDisplayMetrics();
mMaxDistance = dm.heightPixels / 8;
mScroller = new Scroller(SmoothRefreshLayout.this.getContext(),
SmoothRefreshLayout.sLinearInterpolator, false);
}
void fling(float v) {
destroy();
mMode = MODE_FLING;
mIsFling = true;
mVelocity = v;
mScroller.fling(0, 0, 0, (int) v, Integer.MIN_VALUE, Integer.MAX_VALUE,
Integer.MIN_VALUE, Integer.MAX_VALUE);
final int finalY = mScroller.getFinalY();
final int duration = mScroller.getDuration();
if (SmoothRefreshLayout.sDebug) {
SRLog.d(SmoothRefreshLayout.TAG, "OverScrollChecker: fling(): v: %s, finalY: %s," +
" duration: %s", v, finalY, duration);
}
mScroller.startScroll(0, 0, 0, finalY, duration);
}
void preFling(float v) {
destroy();
mMode = MODE_PRE_FLING;
mIsFling = true;
mVelocity = v;
mScroller.fling(0, 0, 0, (int) v, Integer.MIN_VALUE, Integer.MAX_VALUE,
Integer.MIN_VALUE, Integer.MAX_VALUE);
final int finalY = mScroller.getFinalY();
final int duration = mScroller.getDuration();
if (SmoothRefreshLayout.sDebug) {
SRLog.d(SmoothRefreshLayout.TAG, "OverScrollChecker: preFling(): v: %s, finalY: %s," +
" duration: %s", v, finalY, duration);
}
mScroller.startScroll(0, 0, 0, finalY, duration);
run();
}
float calculateVelocity() {
final float percent = (mScroller.getDuration() - mScroller.timePassed())
/ (float) mScroller.getDuration();
float velocity = mVelocity * percent * percent / 2;
if (SmoothRefreshLayout.sDebug) {
SRLog.i(SmoothRefreshLayout.TAG, "OverScrollChecker: calculateVelocity(): " +
"velocity: %s", velocity);
}
return velocity;
}
private void reset() {
mIsFling = false;
mMode = MODE_NONE;
if (SmoothRefreshLayout.sDebug) {
SRLog.i(SmoothRefreshLayout.TAG, "OverScrollChecker: reset()");
}
SmoothRefreshLayout.this.removeCallbacks(this);
mScroller.forceFinished(true);
}
void destroy() {
reset();
mIsScrolling = false;
mIsClamped = false;
mDuration = 0;
mLastY = 0;
SmoothRefreshLayout.this.resetScrollerInterpolator();
if (SmoothRefreshLayout.sDebug) {
SRLog.i(SmoothRefreshLayout.TAG, "OverScrollChecker: destroy()");
}
}
void abortIfWorking() {
if (SmoothRefreshLayout.sDebug) {
SRLog.d(SmoothRefreshLayout.TAG, "OverScrollChecker: abortIfWorking(): scrolling: %s",
mIsScrolling);
}
if (mIsScrolling) {
destroy();
}
}
void computeScrollOffset() {
if (mMode == MODE_FLING && mIsFling && mScroller.computeScrollOffset()) {
SmoothRefreshLayout.this.removeCallbacks(this);
SmoothRefreshLayout.this.postDelayed(this, 25);
} else {
mIsFling = false;
}
if (SmoothRefreshLayout.sDebug) {
SRLog.d(SmoothRefreshLayout.TAG, "OverScrollChecker: computeScrollOffset(): fling: %s, " +
"finished: %s", mIsFling, mScroller.isFinished());
}
}
@Override
public void run() {
if (!mIsFling)
return;
if (SmoothRefreshLayout.sDebug) {
SRLog.d(SmoothRefreshLayout.TAG, "OverScrollChecker: run()");
}
if (mMode == MODE_FLING) {
checkFling();
} else {
checkPreFling();
}
}
private void checkPreFling() {
boolean finished = !mScroller.computeScrollOffset() || mScroller.isFinished();
final int currY = mScroller.getCurrY();
int deltaY = currY - mLastY;
if (SmoothRefreshLayout.sDebug) {
SRLog.d(SmoothRefreshLayout.TAG,
"OverScrollChecker: checkPreFling(): finished: %s, currentPos: %s, " +
"currentY:%s, lastY: %s, delta: %s",
finished, SmoothRefreshLayout.this.mIndicator.getCurrentPos(), currY,
mLastY, deltaY);
}
if (!finished) {
mLastY = currY;
mIsScrolling = true;
if (SmoothRefreshLayout.this.isMovingHeader()) {
SmoothRefreshLayout.this.moveHeaderPos(deltaY);
} else if (SmoothRefreshLayout.this.isMovingFooter()) {
SmoothRefreshLayout.this.moveFooterPos(deltaY);
}
ViewCompat.postOnAnimation(SmoothRefreshLayout.this, this);
} else {
destroy();
SmoothRefreshLayout.this.mDelayedNestedFling = false;
SmoothRefreshLayout.this.onRelease();
}
}
private void checkFling() {
if (!mScroller.isFinished()) {
final int currY = mScroller.getCurrY();
if (currY > 0 && SmoothRefreshLayout.this.isInStartPosition()
&& !SmoothRefreshLayout.this.isNotYetInEdgeCannotMoveHeader()
&& !SmoothRefreshLayout.this.mScrollChecker.mIsRunning) {
int to = calculate(true);
if (SmoothRefreshLayout.this.isEnabledAutoRefresh()
&& !SmoothRefreshLayout.this.isDisabledPerformRefresh()) {
int offsetToKeepHeaderWhileLoading = SmoothRefreshLayout.this.mIndicator
.getOffsetToKeepHeaderWhileLoading();
if (to > offsetToKeepHeaderWhileLoading) {
to = offsetToKeepHeaderWhileLoading;
}
mDuration = Math.max(mDuration, SmoothRefreshLayout.this
.getDurationToCloseFooter());
mIsClamped = false;
}
if (SmoothRefreshLayout.sDebug) {
SRLog.d(SmoothRefreshLayout.TAG, "OverScrollChecker: checkFling(): to: %s, duration: %s",
to, mDuration);
}
SmoothRefreshLayout.this.mIndicator.setMovingStatus(Constants.MOVING_HEADER);
SmoothRefreshLayout.this.updateScrollerInterpolator(SmoothRefreshLayout
.this.mOverScrollInterpolator);
SmoothRefreshLayout.this.mScrollChecker.tryToScrollTo(to, mDuration);
//Add a buffer value
mDuration = (int) (mDuration * 1.25f);
mIsScrolling = true;
reset();
return;
} else if (currY < 0 && SmoothRefreshLayout.this.isInStartPosition()
&& !SmoothRefreshLayout.this.isNotYetInEdgeCannotMoveFooter()
&& !SmoothRefreshLayout.this.mScrollChecker.mIsRunning) {
int to = calculate(false);
if (SmoothRefreshLayout.this.isEnabledAutoLoadMore()
&& !SmoothRefreshLayout.this.isDisabledPerformLoadMore()) {
int offsetToKeepFooterWhileLoading = SmoothRefreshLayout.this.mIndicator
.getOffsetToKeepFooterWhileLoading();
if (to > offsetToKeepFooterWhileLoading) {
to = offsetToKeepFooterWhileLoading;
}
mDuration = Math.max(mDuration, SmoothRefreshLayout.this
.getDurationToCloseFooter());
mIsClamped = false;
}
if (SmoothRefreshLayout.sDebug) {
SRLog.d(SmoothRefreshLayout.TAG, "OverScrollChecker: checkFling(): to: %s, duration: %s",
-to, mDuration);
}
SmoothRefreshLayout.this.mIndicator.setMovingStatus(Constants.MOVING_FOOTER);
SmoothRefreshLayout.this.updateScrollerInterpolator(SmoothRefreshLayout
.this.mOverScrollInterpolator);
SmoothRefreshLayout.this.mScrollChecker.tryToScrollTo(to, mDuration);
//Add a buffer value
mDuration = (int) (mDuration * 1.25f);
mIsScrolling = true;
reset();
return;
}
}
mIsScrolling = false;
mIsClamped = false;
}
private int calculate(boolean isMovingHeader) {
mDuration = Math.max(mScroller.getDuration() - mScroller.timePassed(),
SmoothRefreshLayout.this.mMinOverScrollDuration);
mDuration = Math.min(mDuration, SmoothRefreshLayout.this.mMaxOverScrollDuration);
if (SmoothRefreshLayout.sDebug) {
SRLog.d(SmoothRefreshLayout.TAG, "OverScrollChecker: calculate(): " +
"originalDuration: %s", mDuration);
}
final int optimizedDistance = Math.min((int) Math.pow(Math.abs(calculateVelocity()),
.58f), mMaxDistance);
final float maxViewDistance;
final int viewHeight;
if (isMovingHeader) {
maxViewDistance = SmoothRefreshLayout.this.mIndicator
.getCanMoveTheMaxDistanceOfHeader();
viewHeight = SmoothRefreshLayout.this.getHeaderHeight();
} else {
maxViewDistance = SmoothRefreshLayout.this.mIndicator
.getCanMoveTheMaxDistanceOfFooter();
viewHeight = SmoothRefreshLayout.this.getFooterHeight();
}
int to = viewHeight > 0 ? Math.min(viewHeight, optimizedDistance) : optimizedDistance;
if (maxViewDistance > 0 && to > maxViewDistance) {
to = Math.round(maxViewDistance);
}
to = Math.max(to, SmoothRefreshLayout.this.mTouchSlop);
if (SmoothRefreshLayout.sDebug) {
SRLog.d(SmoothRefreshLayout.TAG, "OverScrollChecker: calculate(): " +
"isMovingHeader: %s, duration: %s, optimizedDistance: %s, " +
"maxViewDistance: %s, viewHeight: %s, to: %s",
isMovingHeader, mDuration, optimizedDistance, maxViewDistance,
viewHeight, to);
}
mIsClamped = true;
return to;
}
}
class ScrollChecker implements Runnable {
int mLastY;
int mLastStart;
int mLastTo;
boolean mIsRunning = false;
Scroller mScroller;
Interpolator mInterpolator;
ScrollChecker() {
mInterpolator = SmoothRefreshLayout.this.mSpringInterpolator;
mScroller = new Scroller(SmoothRefreshLayout.this.getContext(), mInterpolator);
}
@Override
public void run() {
boolean finished = !mScroller.computeScrollOffset() || mScroller.isFinished();
int curY = mScroller.getCurrY();
int deltaY = curY - mLastY;
if (SmoothRefreshLayout.sDebug) {
SRLog.d(SmoothRefreshLayout.TAG,
"ScrollChecker: run(): finished: %s, start: %s, to: %s, currentPos: %s, " +
"currentY:%s, last: %s, delta: %s",
finished, mLastStart, mLastTo, SmoothRefreshLayout.this.mIndicator
.getCurrentPos(), curY, mLastY, deltaY);
}
if (!finished) {
mLastY = curY;
if (SmoothRefreshLayout.this.isMovingHeader()) {
SmoothRefreshLayout.this.moveHeaderPos(deltaY);
} else if (SmoothRefreshLayout.this.isMovingFooter()) {
SmoothRefreshLayout.this.moveFooterPos(-deltaY);
}
ViewCompat.postOnAnimation(SmoothRefreshLayout.this, this);
} else {
if (!SmoothRefreshLayout.this.canSpringBack()) {
checkInStartPosition();
reset(true);
SmoothRefreshLayout.this.onRelease();
}
}
}
void updateInterpolator(Interpolator interpolator) {
if (SmoothRefreshLayout.sDebug) {
SRLog.d(SmoothRefreshLayout.TAG, "ScrollChecker: updateInterpolator()");
}
if (mInterpolator == interpolator)
return;
mInterpolator = interpolator;
if (mIsRunning) {
int timePassed = mScroller.timePassed();
int duration = mScroller.getDuration();
reset(false);
mLastStart = mIndicator.getCurrentPos();
int distance = mLastTo - mLastStart;
mScroller = new Scroller(getContext(), interpolator);
mScroller.startScroll(0, 0, 0, distance, duration - timePassed);
ViewCompat.postOnAnimation(SmoothRefreshLayout.this, this);
} else {
reset(false);
mScroller = SRReflectUtil.setScrollerInterpolatorOrReCreateScroller
(SmoothRefreshLayout.this.getContext(), mScroller, interpolator);
}
}
private void checkInStartPosition() {
//It should have scrolled to the specified location, but it has not scrolled
if (mLastTo == IIndicator.START_POS
&& !SmoothRefreshLayout.this.mIndicator.isInStartPosition()) {
int currentPos = SmoothRefreshLayout.this.mIndicator.getCurrentPos();
int deltaY = IIndicator.START_POS - currentPos;
if (SmoothRefreshLayout.sDebug) {
SRLog.d(SmoothRefreshLayout.TAG, "ScrollChecker: checkInStartPosition(): deltaY: %s",
deltaY);
}
if (SmoothRefreshLayout.this.isMovingHeader()) {
SmoothRefreshLayout.this.moveHeaderPos(deltaY);
} else if (SmoothRefreshLayout.this.isMovingFooter()) {
SmoothRefreshLayout.this.moveFooterPos(-deltaY);
}
}
}
private void reset(boolean stopOverScrollCheck) {
if (SmoothRefreshLayout.sDebug) {
SRLog.i(SmoothRefreshLayout.TAG, "ScrollChecker: reset()");
}
mIsRunning = false;
mLastY = 0;
if (stopOverScrollCheck)
mOverScrollChecker.abortIfWorking();
SmoothRefreshLayout.this.removeCallbacks(this);
}
void destroy() {
if (SmoothRefreshLayout.sDebug) {
SRLog.i(SmoothRefreshLayout.TAG, "ScrollChecker: destroy()");
}
reset(true);
mScroller.forceFinished(true);
}
void abortIfWorking() {
if (SmoothRefreshLayout.sDebug) {
SRLog.i(SmoothRefreshLayout.TAG, "ScrollChecker: abortIfWorking()");
}
if (mIsRunning) {
mScroller.forceFinished(true);
reset(true);
}
}
void tryToScrollTo(int to, int duration) {
if (SmoothRefreshLayout.sDebug) {
SRLog.i(SmoothRefreshLayout.TAG, "ScrollChecker: tryToScrollTo(): to: %s, " +
"duration: %s", to, duration);
}
mLastStart = SmoothRefreshLayout.this.mIndicator.getCurrentPos();
if (SmoothRefreshLayout.this.mIndicator.isAlreadyHere(to)) {
SmoothRefreshLayout.this.mOverScrollChecker.abortIfWorking();
return;
}
mLastTo = to;
int distance = to - mLastStart;
mLastY = 0;
if (SmoothRefreshLayout.sDebug) {
SRLog.d(SmoothRefreshLayout.TAG, "ScrollChecker: tryToScrollTo(): start: %s, to:%s, duration:%s",
mLastStart, to, duration);
}
if (duration > 0) {
mScroller.startScroll(0, 0, 0, distance, duration);
SmoothRefreshLayout.this.removeCallbacks(this);
SmoothRefreshLayout.this.post(this);
mIsRunning = true;
} else {
if (SmoothRefreshLayout.this.isMovingHeader()) {
SmoothRefreshLayout.this.moveHeaderPos(distance);
} else if (SmoothRefreshLayout.this.isMovingFooter()) {
SmoothRefreshLayout.this.moveFooterPos(-distance);
}
destroy();
}
}
}
}
|
package org.smoothbuild.builtin.java.javac;
import static com.google.common.truth.Truth.assertThat;
import static okio.Okio.buffer;
import static okio.Okio.sink;
import java.io.IOException;
import org.junit.jupiter.api.Test;
import org.smoothbuild.io.fs.base.Path;
import org.smoothbuild.lang.object.base.ArrayBuilder;
import org.smoothbuild.lang.object.base.Struct;
import org.smoothbuild.testing.TestingContext;
import okio.BufferedSink;
import okio.ByteString;
public class OutputClassFileTest extends TestingContext {
private final Path path = Path.path("my/path");
private final ByteString bytes = ByteString.encodeUtf8("abc");
@Test
public void open_output_stream() throws IOException {
ArrayBuilder fileArrayBuilder = arrayBuilder(nativeApi().factory().fileType());
OutputClassFile outputClassFile = new OutputClassFile(fileArrayBuilder, path, nativeApi());
try (BufferedSink sink = buffer(sink(outputClassFile.openOutputStream()))) {
sink.write(bytes);
}
assertThat(fileArrayBuilder.build().asIterable(Struct.class))
.containsExactly(file(path, bytes));
}
@Test
public void get_name_returns_file_path() {
OutputClassFile outputClassFile =
new OutputClassFile(arrayBuilder(fileType()), path, nativeApi());
assertThat(outputClassFile.getName())
.isEqualTo("/" + path.value());
}
}
|
package org.bitcoinj.quorums;
import org.bitcoinj.core.*;
import org.bitcoinj.core.listeners.NewBestBlockListener;
import org.bitcoinj.core.listeners.OnTransactionBroadcastListener;
import org.bitcoinj.core.listeners.TransactionReceivedInBlockListener;
import org.bitcoinj.crypto.BLSBatchVerifier;
import org.bitcoinj.quorums.listeners.RecoveredSignatureListener;
import org.bitcoinj.quorums.listeners.ChainLockListener;
import org.bitcoinj.store.BlockStore;
import org.bitcoinj.store.BlockStoreException;
import org.bitcoinj.store.FullPrunedBlockStore;
import org.bitcoinj.utils.Pair;
import org.bitcoinj.utils.Threading;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;
public class InstantSendManager implements RecoveredSignatureListener {
Context context;
SigningManager quorumSigningManager;
private static final Logger log = LoggerFactory.getLogger(InstantSendManager.class);
ReentrantLock lock = Threading.lock("InstantSendManager");
InstantSendDatabase db;
Thread workThread;
public boolean runWithoutThread;
AbstractBlockChain blockChain;
//Keep track of when the ISLOCK arrived
HashMap<InstantSendLock, Long> invalidInstantSendLocks;
// Incoming and not verified yet
HashMap<Sha256Hash, Pair<Long, InstantSendLock>> pendingInstantSendLocks;
public InstantSendManager(Context context, InstantSendDatabase db) {
this.context = context;
this.db = db;
this.quorumSigningManager = context.signingManager;
pendingInstantSendLocks = new HashMap<Sha256Hash, Pair<Long, InstantSendLock>>();
invalidInstantSendLocks = new HashMap<InstantSendLock, Long>();
}
@Override
public String toString() {
return String.format("InstantSendManager: pendingInstantSendLocks %d, DB: %s", pendingInstantSendLocks.size(), db);
}
public InstantSendManager(Context context, InstantSendDatabase db, boolean runWithoutThread) {
this(context, db);
this.runWithoutThread = runWithoutThread;
}
public void setBlockChain(AbstractBlockChain blockChain, @Nullable PeerGroup peerGroup) {
this.blockChain = blockChain;
this.blockChain.addTransactionReceivedListener(this.transactionReceivedInBlockListener);
this.blockChain.addNewBestBlockListener(Threading.SAME_THREAD, this.newBestBlockListener);
if (peerGroup != null) {
peerGroup.addOnTransactionBroadcastListener(this.transactionBroadcastListener);
}
context.chainLockHandler.addChainLockListener(this.chainLockListener, Threading.SAME_THREAD);
}
public void close(PeerGroup peerGroup) {
blockChain.removeTransactionReceivedListener(this.transactionReceivedInBlockListener);
blockChain.removeNewBestBlockListener(this.newBestBlockListener);
peerGroup.removeOnTransactionBroadcastListener(this.transactionBroadcastListener);
context.chainLockHandler.removeChainLockListener(this.chainLockListener);
}
@Deprecated
public boolean isOldInstantSendEnabled()
{
return false;
}
@Deprecated
public boolean isNewInstantSendEnabled()
{
return isInstantSendEnabled();
}
public boolean isInstantSendEnabled()
{
return context.sporkManager.isSporkActive(SporkManager.SPORK_2_INSTANTSEND_ENABLED);
}
public void processInstantSendLock(Peer peer, InstantSendLock isLock) {
if(!isInstantSendEnabled())
return;
if (!preVerifyInstantSendLock(peer.hashCode(), isLock)) {
return;
}
context.getConfidenceTable().seen(isLock.txid, peer.getAddress());
TransactionConfidence confidence = context.getConfidenceTable().get(isLock.txid);
if(confidence != null) {
if (confidence.getIXType() != TransactionConfidence.IXType.IX_NONE) {
return;
}
confidence.setIXType(TransactionConfidence.IXType.IX_REQUEST);
confidence.queueListeners(TransactionConfidence.Listener.ChangeReason.IX_TYPE);
}
Sha256Hash hash = isLock.getHash();
lock.lock();
try {
//TODO: how to handle this!
if (db.getInstantSendLockByHash(hash) != null) {
return;
}
if (pendingInstantSendLocks.containsKey(hash)) {
return;
}
log.info("received islock: txid={}, islock={} , peer={}",
isLock.txid.toString(), hash.toString(), peer.hashCode());
pendingInstantSendLocks.put(hash, new Pair((long)peer.hashCode(), isLock));
if(runWithoutThread) {
try {
processPendingInstantSendLocks();
} catch (BlockStoreException x) {
throw new VerificationException(x.getMessage());
}
}
} finally {
lock.unlock();
}
}
boolean preVerifyInstantSendLock(int nodeId, InstantSendLock islock)
{
if (islock.txid.equals(Sha256Hash.ZERO_HASH) || islock.inputs.isEmpty()) {
return false;
}
HashSet<TransactionOutPoint> dups = new HashSet<TransactionOutPoint>();
for (TransactionOutPoint o : islock.inputs) {
if (!dups.add(o)) {
return false;
}
}
return true;
}
public boolean alreadyHave(InventoryItem inv)
{
if (!isInstantSendEnabled()) {
return true;
}
lock.lock();
try {
boolean haslock = db.getInstantSendLockByHash(inv.hash) != null || pendingInstantSendLocks.containsKey(inv.hash);
TransactionConfidence confidence = context.getConfidenceTable().get(inv.hash);
if(confidence != null) {
if(confidence.getIXType() != TransactionConfidence.IXType.IX_NONE)
return true;
}
if(!invalidInstantSendLocks.isEmpty()) {
for(InstantSendLock islock : invalidInstantSendLocks.keySet()) {
if(inv.hash.equals(islock.getHash()))
return true;
}
}
return haslock;
} finally {
lock.unlock();
}
}
Runnable workerMainThread = new Runnable() {
@Override
public void run() {
try {
while (!workThread.isInterrupted()) {
boolean didWork = false;
didWork |= processPendingInstantSendLocks();
if (!didWork) {
Thread.sleep(100);
}
}
} catch (InterruptedException x) {
//let the thread stop
} catch (BlockStoreException x) {
}
}
};
public void start() {
if(!runWithoutThread) {
if (workThread != null)
throw new IllegalThreadStateException("Thread is already running");
workThread = new Thread(workerMainThread);
workThread.start();
}
quorumSigningManager.addRecoveredSignatureListener(this);
}
public void stop() {
quorumSigningManager.removeRecoveredSignatureListener(this);
if(runWithoutThread)
return;
if(workThread == null)
throw new IllegalThreadStateException("Thread is not running");
try {
if (!workThread.isInterrupted()) {
workThread.join();
workThread = null;
} else {
throw new IllegalThreadStateException("Thread was not interrupted");
}
} catch (InterruptedException x) {
throw new IllegalThreadStateException("Thread was interrupted while waiting for it to die");
}
}
void interuptWorkerThread() {
workThread.interrupt();
}
public boolean checkCanLock(Transaction tx) {
return checkCanLock(tx, false);
}
public boolean checkCanLock(Transaction tx, boolean printDebug)
{
if (tx.getInputs().isEmpty()) {
// can't lock TXs without inputs (e.g. quorum commitments)
return false;
}
BlockStore blockStore = blockChain.getBlockStore();
Coin value = Coin.valueOf(0);
for (TransactionInput in : tx.getInputs()) {
if (!checkCanLock(in.getOutpoint(), printDebug, tx.getHash())) {
return false;
}
if(blockStore instanceof FullPrunedBlockStore) {
// this relies on enabled txindex and won't work if we ever try to remove the requirement for txindex for masternodes
try {
UTXO utxo = ((FullPrunedBlockStore) blockStore).getTransactionOutput(in.getOutpoint().getHash(), in.getOutpoint().getIndex());
value = value.add(utxo.getValue());
} catch (BlockStoreException x) {
log.error("BlockStoreException: "+ x.getMessage());
}
} else {
if(in.getValue() != null)
value = value.add(in.getValue());
}
}
return true;
}
boolean checkCanLock(TransactionOutPoint outpoint, boolean printDebug, Sha256Hash txHash)
{
int nInstantSendConfirmationsRequired = context.getParams().getInstantSendConfirmationsRequired();
if (isLocked(outpoint.getHash())) {
// if prevout was ix locked, allow locking of descendants (no matter if prevout is in mempool or already mined)
return true;
}
TxConfidenceTable mempool = context.getConfidenceTable();
TransactionConfidence mempoolTx = mempool.get(outpoint.getHash());
if (mempoolTx != null) {
if (printDebug) {
log.info("txid={}: parent mempool TX {} is not locked",
txHash.toString(), outpoint.getHash().toString());
}
return false;
}
Transaction tx;
Sha256Hash hashBlock = null;
BlockStore blockStore = blockChain.getBlockStore();
UTXO utxo;
if(blockStore instanceof FullPrunedBlockStore) {
// this relies on enabled txindex and won't work if we ever try to remove the requirement for txindex for masternodes
try {
utxo = ((FullPrunedBlockStore) blockStore).getTransactionOutput(outpoint.getHash(), outpoint.getIndex());
StoredBlock block = blockStore.get(utxo.getHeight());
if(block != null)
hashBlock = block.getHeader().getHash();
if (printDebug) {
log.info("txid={}: failed to find parent TX {}",
txHash.toString(), outpoint.getHash().toString());
return false;
}
} catch (BlockStoreException x) {
log.error("BlockStoreException: "+ x.getMessage());
return false;
}
try {
if(hashBlock == null)
return false;
StoredUndoableBlock block = ((FullPrunedBlockStore) blockStore).getUndoBlock(hashBlock);
int txAge = blockChain.getBestChainHeight() - utxo.getHeight();
if (txAge < nInstantSendConfirmationsRequired) {
if (context.chainLockHandler.hasChainLock(utxo.getHeight(), block.getHash())) {
if (printDebug) {
log.info("txid={}: outpoint {} too new and not ChainLocked. nTxAge={}, nInstantSendConfirmationsRequired={}",
txHash.toString(), outpoint.toStringShort(), txAge, nInstantSendConfirmationsRequired);
}
return false;
}
}
} catch (BlockStoreException x) {
//swallow
return false;
}
} else {
try {
TransactionOutput output = outpoint.getConnectedOutput();
if(output != null) {
Transaction parent = output.getParentTransaction();
TransactionConfidence confidence = parent.getConfidence();
if(confidence != null) {
if (confidence.getDepthInBlocks() < nInstantSendConfirmationsRequired) {
StoredBlock block = blockStore.get(confidence.getAppearedAtChainHeight());
if (context.chainLockHandler.hasChainLock(confidence.getAppearedAtChainHeight(), block.getHeader().getHash()))
{
if (printDebug) {
log.info("txid={}: outpoint {} too new and not ChainLocked. nTxAge={}, nInstantSendConfirmationsRequired={}",
txHash.toString(), outpoint.toStringShort(), confidence.getDepthInBlocks(), nInstantSendConfirmationsRequired);
}
return false;
}
}
}
}
} catch (BlockStoreException x) {
return false;
}
}
return true;
}
boolean processPendingInstantSendLocks() throws BlockStoreException
{
LLMQParameters.LLMQType llmqType = context.getParams().getLlmqForInstantSend();
HashMap<Sha256Hash, Pair<Long, InstantSendLock>> pend;
lock.lock();
try {
if(pendingInstantSendLocks.isEmpty())
return false;
pend = new HashMap<Sha256Hash, Pair<Long, InstantSendLock>>(pendingInstantSendLocks);
pendingInstantSendLocks = new HashMap<Sha256Hash, Pair<Long, InstantSendLock>>();
//try to process the invalidInstantSendLocks again
for(InstantSendLock isLock : invalidInstantSendLocks.keySet())
pendingInstantSendLocks.put(isLock.getHash(), new Pair(Long.valueOf(0L), isLock));
} finally {
lock.unlock();
}
if (pend.isEmpty()) {
return false;
}
if (!isInstantSendEnabled()) {
return false;
}
int tipHeight;
tipHeight = blockChain.getBestChainHeight();
BLSBatchVerifier<Long, Sha256Hash> batchVerifier = new BLSBatchVerifier<Long, Sha256Hash>(false, true, 8);
HashMap<Sha256Hash, Pair<Quorum, RecoveredSignature>> recSigs = new HashMap<Sha256Hash, Pair<Quorum, RecoveredSignature>>();
for (Map.Entry<Sha256Hash, Pair<Long, InstantSendLock>> p : pend.entrySet()) {
Sha256Hash hash = p.getKey();
if(!context.masternodeSync.hasVerifyFlag(MasternodeSync.VERIFY_FLAGS.INSTANTSENDLOCK)) {
//If we don't verify the instantsendlock as being signed by a quorum...
processInstantSendLock(p.getValue().getFirst(), hash, p.getValue().getSecond());
continue;
}
long nodeId = p.getValue().getFirst().longValue();
InstantSendLock islock = p.getValue().getSecond();
if (batchVerifier.getBadSources().contains(nodeId)) {
log.info("islock: bad sources contains this node: " + nodeId);
continue;
}
if (!islock.signature.getSignature().isValid()) {
log.info("islock: signature is not valid: " + islock.signature);
batchVerifier.getBadSources().add(nodeId);
continue;
}
Sha256Hash id = islock.getRequestId();
// no need to verify an ISLOCK if we already have verified the recovered sig that belongs to it
if (quorumSigningManager.hasRecoveredSig(llmqType, id, islock.txid)) {
log.info("islock: signature has already been verified: " + islock.txid);
continue;
}
Quorum quorum = quorumSigningManager.selectQuorumForSigning(llmqType, tipHeight, id);
if (quorum == null) {
// should not happen, but if one fails to select, all others will also fail to select
log.info("islock: quorum not found to verify signature [tipHeight: " + tipHeight + " vs " + context.masternodeListManager.getQuorumListAtTip().getHeight() + "]");
invalidInstantSendLocks.put(islock, Utils.currentTimeSeconds());
return false;
}
Sha256Hash signHash = LLMQUtils.buildSignHash(llmqType, quorum.commitment.quorumHash, id, islock.txid);
batchVerifier.pushMessage(nodeId, hash, signHash, islock.signature.getSignature(), quorum.commitment.quorumPublicKey);
quorumSigningManager.logSignature("ISLOCK", quorum.commitment.quorumPublicKey, signHash, islock.signature.getSignature());
// We can reconstruct the RecoveredSignature objects from the islock and pass it to the signing manager, which
// avoids unnecessary double-verification of the signature. We however only do this when verification here
// turns out to be good (which is checked further down)
if (!quorumSigningManager.hasRecoveredSigForId(llmqType, id)) {
RecoveredSignature recSig = new RecoveredSignature();
recSig.llmqType = llmqType.getValue();
recSig.quorumHash = quorum.commitment.quorumHash;
recSig.id = id;
recSig.msgHash = islock.txid;
recSig.signature = islock.signature;
recSigs.put(hash, new Pair(quorum, recSig));
}
}
if(context.masternodeSync.hasVerifyFlag(MasternodeSync.VERIFY_FLAGS.BLS_SIGNATURES))
batchVerifier.verify();
if (!batchVerifier.getBadSources().isEmpty()) {
log.warn("islock: bad sources: " + batchVerifier.getBadSources());
for (Long nodeId : batchVerifier.getBadSources()) {
// Let's not be too harsh, as the peer might simply be unlucky and might have sent us an old lock which
// does not validate anymore due to changed quorums
//Misbehaving(nodeId, 20);
}
}
for (Map.Entry<Sha256Hash, Pair<Long, InstantSendLock>> p : pend.entrySet()) {
Sha256Hash hash = p.getKey();
long nodeId = p.getValue().getFirst();
InstantSendLock islock = p.getValue().getSecond();
if (batchVerifier.getBadMessages().contains(hash)) {
log.info("-- txid={}, islock={}: invalid sig in islock, peer={}",
islock.txid.toString(), hash.toString(), nodeId);
invalidInstantSendLocks.put(islock, Utils.currentTimeSeconds());
TransactionConfidence confidence = context.getConfidenceTable().get(islock.txid);
if(confidence != null) {
log.info("InstantSend: set to IX_LOCK_FAILED for {}", islock.txid);
confidence.setIXType(TransactionConfidence.IXType.IX_LOCK_FAILED);
confidence.queueListeners(TransactionConfidence.Listener.ChangeReason.IX_TYPE);
}
continue;
}
processInstantSendLock(nodeId, hash, islock);
// See comment further on top. We pass a reconstructed recovered sig to the signing manager to avoid
// double-verification of the sig.
Pair<Quorum, RecoveredSignature> it = recSigs.get(hash);
if (it != null) {
Quorum quorum = it.getFirst();
RecoveredSignature recSig = it.getSecond();
if (!quorumSigningManager.hasRecoveredSigForId(llmqType, recSig.id)) {
recSig.updateHash();
log.info("passing reconstructed recSig to signing mgr -- txid={}, islock={}: peer={}",
islock.txid.toString(), hash.toString(), nodeId);
quorumSigningManager.pushReconstructedRecoveredSig(recSig, quorum);
}
}
}
return true;
}
void processInstantSendLock(long from, Sha256Hash hash, InstantSendLock islock)
{
StoredBlock minedBlock = null;
TransactionConfidence confidence = context.getConfidenceTable().get(hash);
if(confidence != null) {
if(confidence.getConfidenceType() == TransactionConfidence.ConfidenceType.BUILDING)
{
long height = confidence.getAppearedAtChainHeight();
try {
StoredBlock block = blockChain.getBlockStore().get((int)height);
if(block != null) {
// Let's see if the TX that was locked by this islock is already mined in a ChainLocked block. If yes,
// we can simply ignore the islock, as the ChainLock implies locking of all TXs in that chain
if (context.chainLockHandler.hasChainLock(height, block.getHeader().getHash())) {
log.info("txlock={}, islock={}: dropping islock as it already got a ChainLock in block {}, peer={}",
islock.txid.toString(), hash.toString(), block.getHeader().getHash().toString(), from);
return;
}
}
} catch (BlockStoreException x) {
//swallow
}
}
}
lock.lock();
try
{
log.info("processing islock txid={}, islock={}: peer={}",
islock.txid.toString(), hash.toString(), from);
InstantSendLock otherIsLock;
if (db.getInstantSendLockByHash(hash) != null) {
return;
}
otherIsLock = db.getInstantSendLockByTxid(islock.txid);
if (otherIsLock != null) {
log.info("duplicate islock: txid={}, islock={}: other islock={}, peer={}",
islock.txid.toString(), hash.toString(),otherIsLock.getHash().toString(), from);
}
for (TransactionOutPoint in : islock.inputs) {
otherIsLock = db.getInstantSendLockByInput(in);
if (otherIsLock != null) {
log.info("CInstantSendManager::{} -- txid={}, islock={}: conflicting input in islock. input={}, other islock={}, peer={}",
islock.txid.toString(), hash.toString(), in.toStringShort(), otherIsLock.getHash().toString(), from);
}
}
db.writeNewInstantSendLock(hash, islock);
if (minedBlock != null) {
db.writeInstantSendLockMined(hash, minedBlock.getHeight());
}
// If an ISLOCK was originally invalid, but was later validated
// remove it here
if(invalidInstantSendLocks.containsKey(islock))
invalidInstantSendLocks.remove(islock);
} finally {
lock.unlock();
}
removeMempoolConflictsForLock(hash, islock);
updateWalletTransaction(islock.txid, null);
}
void updateWalletTransaction(Sha256Hash txid, Transaction tx) {
TransactionConfidence confidence = tx != null ? tx.getConfidence() : context.getConfidenceTable().get(txid);
if(confidence != null) {
confidence.setIXType(TransactionConfidence.IXType.IX_LOCKED);
confidence.queueListeners(TransactionConfidence.Listener.ChangeReason.IX_TYPE);
} else {
log.info("Can't find {} in mempool", txid);
}
}
public void syncTransaction(Transaction tx, StoredBlock block, int posInBlock)
{
if (!isInstantSendEnabled()) {
return;
}
if (tx.isCoinBase() || tx.getInputs().isEmpty()) {
// coinbase can't and TXs with no inputs be locked
return;
}
boolean isDisconnect = block != null && posInBlock == -1;
Sha256Hash islockHash;
lock.lock();
try {
islockHash = db.getInstantSendLockHashByTxid(tx.getHash());
// update DB about when an IS lock was mined
if (islockHash != null && !islockHash.equals(Sha256Hash.ZERO_HASH) && block != null) {
if (isDisconnect) {
db.removeInstantSendLockMined(islockHash, block.getHeight());
} else {
db.writeInstantSendLockMined(islockHash, block.getHeight());
}
}
} finally {
lock.unlock();
}
}
ChainLockListener chainLockListener = new ChainLockListener() {
public void onNewChainLock(StoredBlock block) {
handleFullyConfirmedBlock(block.getHeight());
}
};
NewBestBlockListener newBestBlockListener = new NewBestBlockListener() {
@Override
public void notifyNewBestBlock(StoredBlock block) throws VerificationException {
// TODO remove this after DIP8 has activated
//boolean fDIP0008Active = VersionBitsState(pindexNew.pprev, Params().GetConsensus(), Consensus::DEPLOYMENT_DIP0008, versionbitscache) == THRESHOLD_ACTIVE;
if (context.sporkManager.isSporkActive(SporkManager.SPORK_19_CHAINLOCKS_ENABLED) /*&& fDIP0008Active*/) {
// Nothing to do here. We should keep all islocks and let chainlocks handle them.
return;
}
int confirmedHeight = block.getHeight() - context.getParams().getInstantSendKeepLock();
handleFullyConfirmedBlock(confirmedHeight);
}
};
void handleFullyConfirmedBlock(int height)
{
HashMap<Sha256Hash, InstantSendLock> removeISLocks;
lock.lock();
try {
removeISLocks = db.removeConfirmedInstantSendLocks(height);
for (Map.Entry<Sha256Hash, InstantSendLock> p : removeISLocks.entrySet()) {
Sha256Hash islockHash = p.getKey();
InstantSendLock islock = p.getValue();
log.info("removed islock as it got fully confirmed -- txid={}, islock={}",
islock.txid.toString(), islockHash.toString());
}
} finally {
lock.unlock();
}
for (Map.Entry<Sha256Hash, InstantSendLock> p : removeISLocks.entrySet()) {
updateWalletTransaction(p.getValue().txid, null);
}
// Keep invalid ISLocks for 1 hour
for(Map.Entry<InstantSendLock, Long> entry : invalidInstantSendLocks.entrySet()) {
if(entry.getValue() < Utils.currentTimeSeconds() - context.getParams().getInstantSendKeepLock())
invalidInstantSendLocks.remove(entry.getKey());
}
}
static final String INPUTLOCK_REQUESTID_PREFIX = "inlock";
Sha256Hash getRequestId(TransactionOutPoint outpoint) {
try {
UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(40);
Utils.stringToByteStream(INPUTLOCK_REQUESTID_PREFIX, bos);
outpoint.bitcoinSerialize(bos);
return Sha256Hash.wrap(Sha256Hash.hashTwice(bos.toByteArray()));
} catch (IOException x) {
throw new RuntimeException(x);
}
}
void removeMempoolConflictsForLock(Sha256Hash hash, InstantSendLock islock)
{
//TODO: should full verification mode have this?
}
public InstantSendLock getInstantSendLockByHash(Sha256Hash hash)
{
if (!isInstantSendEnabled()) {
return null;
}
lock.lock();
try {
InstantSendLock islock = db.getInstantSendLockByHash(hash);
return islock;
} finally {
lock.unlock();
}
}
public InstantSendLock getInstantSendLockByTxId(Sha256Hash hash)
{
if (!isInstantSendEnabled()) {
return null;
}
lock.lock();
try {
InstantSendLock islock = db.getInstantSendLockByTxid(hash);
if (islock == null) {
for (InstantSendLock invalidLock : invalidInstantSendLocks.keySet()) {
if (invalidLock.txid.equals(hash)) {
islock = invalidLock;
break;
}
}
for (Pair<Long, InstantSendLock> entry : pendingInstantSendLocks.values()) {
if (entry.getSecond().txid.equals(hash)) {
islock = entry.getSecond();
break;
}
}
}
return islock;
} finally {
lock.unlock();
}
}
boolean isLocked(Sha256Hash txHash)
{
if (!isInstantSendEnabled()) {
return false;
}
lock.lock();
try {
return db.getInstantSendLockByTxid(txHash) != null;
} finally {
lock.unlock();
}
}
public boolean isConflicted(Transaction tx)
{
lock.lock();
try {
Sha256Hash dummy;
return getConflictingTx(tx) != null;
} finally {
lock.unlock();
}
}
public Sha256Hash getConflictingTx(Transaction tx)
{
if (!isInstantSendEnabled()) {
return null;
}
lock.lock();
try {
for (TransactionInput in :tx.getInputs()){
InstantSendLock otherIsLock = db.getInstantSendLockByInput(in.getOutpoint());
if (otherIsLock == null) {
continue;
}
if (otherIsLock.txid.equals(tx.getHash())) {
return otherIsLock.txid;
}
}
return null;
} finally {
lock.unlock();
}
}
@Override
public void onNewRecoveredSignature(RecoveredSignature recoveredSig) {
if (!isInstantSendEnabled()) {
return;
}
LLMQParameters.LLMQType llmqType = context.getParams().getLlmqForInstantSend();
if (llmqType == LLMQParameters.LLMQType.LLMQ_NONE) {
return;
}
}
TransactionReceivedInBlockListener transactionReceivedInBlockListener = new TransactionReceivedInBlockListener() {
@Override
public void receiveFromBlock(Transaction tx, StoredBlock block, BlockChain.NewBlockType blockType, int relativityOffset) throws VerificationException {
// Call syncTransaction to update lock candidates and votes
if(blockType == AbstractBlockChain.NewBlockType.BEST_CHAIN) {
syncTransaction(tx, block, relativityOffset);
}
}
@Override
public boolean notifyTransactionIsInBlock(Sha256Hash txHash, StoredBlock block, BlockChain.NewBlockType blockType, int relativityOffset) throws VerificationException {
return false;
}
};
//TODO: finish connecting this. Should we keep a list of transactions sent and received in spv mode?
OnTransactionBroadcastListener transactionBroadcastListener = new OnTransactionBroadcastListener() {
@Override
public void onTransaction(Peer peer, Transaction t) {
syncTransaction(t, null, -1);
}
};
}
|
package org.mskcc.cbio.oncokb.util;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.mskcc.cbio.oncokb.model.*;
import java.text.SimpleDateFormat;
import java.util.*;
public class SummaryUtils {
public static long lastUpdateVariantSummaries = new Date().getTime();
private static String[] SpecialMutations = {"amplification", "deletion", "fusion", "fusions", "activating mutations", "inactivating mutations", "all mutations", "truncating mutations"};
public static String variantTumorTypeSummary(Gene gene, List<Alteration> alterations, String queryAlteration, Set<OncoTreeType> relevantTumorTypes, String queryTumorType) {
if (gene == null) {
return "";
}
String geneId = Integer.toString(gene.getEntrezGeneId());
String key = geneId + "&&" + queryAlteration + "&&" + queryTumorType;
if (CacheUtils.isEnabled() && CacheUtils.containVariantSummary(gene.getEntrezGeneId(), key)) {
return CacheUtils.getVariantSummary(gene.getEntrezGeneId(), key);
}
StringBuilder sb = new StringBuilder();
//Mutation summary (MUTATION_SUMMARY: Deprecated)
// List<Evidence> mutationSummaryEvs = evidenceBo.findEvidencesByAlteration(alterations, Collections.singleton(EvidenceType.MUTATION_SUMMARY));
// if (!mutationSummaryEvs.isEmpty()) {
// Evidence ev = mutationSummaryEvs.get(0);
// String mutationSummary = ev.getShortDescription();
// if (mutationSummary == null) {
// mutationSummary = ev.getDescription();
// if (mutationSummary != null) {
// mutationSummary = StringEscapeUtils.escapeXml(mutationSummary).trim();
// sb.append(mutationSummary)
// .append(" ");
// } else {
String os = oncogenicSummary(gene, alterations, queryAlteration, false);
if (os != null && !os.equals("")) {
sb.append(" " + os);
}
String ts = tumorTypeSummary(gene, queryAlteration, alterations, queryTumorType, relevantTumorTypes);
if (ts != null && !ts.equals("")) {
sb.append(" " + ts);
}
if (CacheUtils.isEnabled()) {
CacheUtils.setVariantSummary(gene.getEntrezGeneId(), key, sb.toString().trim());
}
return sb.toString().trim();
}
public static String variantCustomizedSummary(Set<Gene> genes, List<Alteration> alterations, String queryAlteration, Set<OncoTreeType> relevantTumorTypes, String queryTumorType) {
String geneId = Integer.toString(genes.iterator().next().getEntrezGeneId());
Gene gene = GeneUtils.getGeneByEntrezId(Integer.parseInt(geneId));
StringBuilder sb = new StringBuilder();
sb.append(geneSummary(genes.iterator().next()));
String os = oncogenicSummary(gene, alterations, queryAlteration, false);
if (os != null && !os.equals("")) {
sb.append(" " + os);
}
return sb.toString().trim();
}
public static String tumorTypeSummary(Gene gene, String queryAlteration, List<Alteration> alterations, String queryTumorType, Set<OncoTreeType> relevantTumorTypes) {
//Tumor type summary
Boolean ttSummaryNotGenerated = true;
String tumorTypeSummary = null;
queryTumorType = queryTumorType != null ? StringUtils.isAllUpperCase(queryTumorType) ? queryTumorType : queryTumorType.toLowerCase() : null;
if (queryAlteration != null) {
queryAlteration = queryAlteration.trim();
}
if (queryTumorType != null) {
queryTumorType = queryTumorType.trim();
if (queryTumorType.endsWith(" tumor")) {
queryTumorType = queryTumorType.substring(0, queryTumorType.lastIndexOf(" tumor")) + " tumors";
}
}
if (isSpecialMutation(queryAlteration, true)) {
queryAlteration = queryAlteration.toLowerCase();
}
if (AlterationUtils.isSingularGeneralAlteration(queryAlteration)) {
queryAlteration = queryAlteration + "s";
}
Boolean appendThe = appendThe(queryAlteration);
if (gene == null || alterations == null || relevantTumorTypes == null) {
return "";
}
if (CacheUtils.isEnabled() && CacheUtils.containVariantTumorTypeSummary(gene.getEntrezGeneId(), queryAlteration, queryTumorType)) {
return CacheUtils.getVariantTumorTypeSummary(gene.getEntrezGeneId(), queryAlteration, queryTumorType);
}
if (gene.getHugoSymbol().equals("KIT")) {
tumorTypeSummary = getKITtumorTypeSummaries(queryAlteration, alterations, queryTumorType, relevantTumorTypes);
} else {
// Get all tumor type summary evidences specifically for the alteration
if (tumorTypeSummary == null) {
Alteration alteration = AlterationUtils.findAlteration(gene, queryAlteration);
if (alteration != null) {
tumorTypeSummary = getTumorTypeSummaryFromEvidences(EvidenceUtils.getEvidence(Collections.singletonList(alteration), Collections.singleton(EvidenceType.TUMOR_TYPE_SUMMARY), relevantTumorTypes, null));
// Get Other Tumor Types summary within this alteration
if (tumorTypeSummary == null) {
tumorTypeSummary = getTumorTypeSummaryFromEvidences(EvidenceUtils.getEvidence(Collections.singletonList(alteration), Collections.singleton(EvidenceType.TUMOR_TYPE_SUMMARY), Collections.singleton(TumorTypeUtils.getMappedSpecialTumor(SpecialTumorType.OTHER_TUMOR_TYPES)), null));
}
}
}
// Get all tumor type summary evidences for the alternate alleles
if (tumorTypeSummary == null) {
Alteration alteration = AlterationUtils.findAlteration(gene, queryAlteration);
if (alteration == null) {
alteration = AlterationUtils.getAlteration(gene.getHugoSymbol(), queryAlteration, null, null, null, null);
AlterationUtils.annotateAlteration(alteration, queryAlteration);
}
if (alteration.getConsequence() != null) {
if (alteration.getConsequence().getTerm().equals("missense_variant")) {
List<Alteration> alternateAlleles = AlterationUtils.getAlleleAndRelevantAlterations(alteration);
// Special case for PDGFRA: don't match D842V as alternative allele
if (gene.getHugoSymbol().equals("PDGFRA") && alteration.getProteinStart() == 842) {
Alteration specialAllele = AlterationUtils.findAlteration(gene, "D842V");
alternateAlleles.remove(specialAllele);
}
// Special case for AKT1 E17K alleles
if (gene.getHugoSymbol().equals("AKT1") && alteration.getProteinStart().equals(17)) {
OncoTreeType breastCancer = TumorTypeUtils.getOncoTreeCancerType("Breast Cancer");
OncoTreeType ovarianCancer = TumorTypeUtils.getOncoTreeCancerType("Ovarian Cancer");
if (relevantTumorTypes.contains(breastCancer)) {
tumorTypeSummary = "There is compelling clinical data supporting the use of AKT-targeted inhibitors such as AZD-5363 in patients with AKT1 E17K mutant breast cancer. Therefore, [[gene]] [[mutation]] [[mutant]] breast cancer is considered likely sensitive to the same inhibitors.";
} else if (relevantTumorTypes.contains(ovarianCancer)) {
tumorTypeSummary = "There is compelling clinical data supporting the use of AKT-targeted inhibitors such as AZD-5363 in patients with AKT1 E17K mutant ovarian cancer. Therefore, [[gene]] [[mutation]] [[mutant]] ovarian cancer is considered likely sensitive to the same inhibitors.";
} else {
tumorTypeSummary = getTumorTypeSummaryFromEvidences(EvidenceUtils.getEvidence(Collections.singletonList(AlterationUtils.findAlteration(gene, "E17K")), Collections.singleton(EvidenceType.TUMOR_TYPE_SUMMARY), Collections.singleton(TumorTypeUtils.getMappedSpecialTumor(SpecialTumorType.OTHER_TUMOR_TYPES)), null));
}
} else if (gene.getHugoSymbol().equals("ARAF") && alteration.getProteinStart().equals(214)) {
// Special case for ARAF S214A/F
OncoTreeType histiocytosis = TumorTypeUtils.getOncoTreeCancerType("Histiocytosis");
OncoTreeType NSCLC = TumorTypeUtils.getOncoTreeCancerType("Non-Small Cell Lung Cancer");
if (relevantTumorTypes.contains(histiocytosis)) {
tumorTypeSummary = "There is compelling clinical data supporting the use of sorafenib in patients with ARAF S214A mutant non-Langherhans cell histiocytic disease. Therefore, [[gene]] [[mutation]] [[mutant]] non-Langherhans cell histiocytic disease is considered likely sensitive to this inhibitor.";
} else if (relevantTumorTypes.contains(NSCLC)) {
tumorTypeSummary = "There is compelling clinical data supporting the use of sorafenib in patients with ARAF S214F mutant lung cancer. Therefore, [[gene]] [[mutation]] [[mutant]] lung cancer is considered likely sensitive to this inhibitor.";
} else {
tumorTypeSummary = getTumorTypeSummaryFromEvidences(EvidenceUtils.getEvidence(Collections.singletonList(AlterationUtils.findAlteration(gene, "S214A")), Collections.singleton(EvidenceType.TUMOR_TYPE_SUMMARY), Collections.singleton(TumorTypeUtils.getMappedSpecialTumor(SpecialTumorType.OTHER_TUMOR_TYPES)), null));
}
} else if (gene.getHugoSymbol().equals("MTOR") && alteration.getProteinStart().equals(2014)) {
// Special case for MTOR E2014K
OncoTreeType bladderCancer = TumorTypeUtils.getOncoTreeCancerType("Bladder Cancer");
if (relevantTumorTypes.contains(bladderCancer)) {
tumorTypeSummary = "There is compelling clinical data supporting the use of everolimus in patients with MTOR E2014K mutant bladder cancer. Therefore, [[gene]] [[mutation]] [[mutant]] bladder cancer is considered likely sensitive to the same inhibitor.";
} else {
tumorTypeSummary = getTumorTypeSummaryFromEvidences(EvidenceUtils.getEvidence(Collections.singletonList(AlterationUtils.findAlteration(gene, "E2014K")), Collections.singleton(EvidenceType.TUMOR_TYPE_SUMMARY), Collections.singleton(TumorTypeUtils.getMappedSpecialTumor(SpecialTumorType.OTHER_TUMOR_TYPES)), null));
}
} else {
for (Alteration allele : alternateAlleles) {
tumorTypeSummary = getTumorTypeSummaryFromEvidences(EvidenceUtils.getEvidence(Collections.singletonList(allele), Collections.singleton(EvidenceType.TUMOR_TYPE_SUMMARY), relevantTumorTypes, null));
if (tumorTypeSummary != null) {
break;
}
// Get Other Tumor Types summary
tumorTypeSummary = getTumorTypeSummaryFromEvidences(EvidenceUtils.getEvidence(Collections.singletonList(allele), Collections.singleton(EvidenceType.TUMOR_TYPE_SUMMARY), Collections.singleton(TumorTypeUtils.getMappedSpecialTumor(SpecialTumorType.OTHER_TUMOR_TYPES)), null));
if (tumorTypeSummary != null) {
break;
}
}
}
} else if (alteration.getConsequence().getTerm().equals("synonymous_variant")) {
// No summary for synonymous variant
return "";
}
}
}
// Get all tumor type summary evidence for relevant alterations
if (tumorTypeSummary == null) {
// Base on the priority of relevant alterations
for (Alteration alteration : alterations) {
tumorTypeSummary = getTumorTypeSummaryFromEvidences(EvidenceUtils.getEvidence(Collections.singletonList(alteration), Collections.singleton(EvidenceType.TUMOR_TYPE_SUMMARY), relevantTumorTypes, null));
if (tumorTypeSummary != null) {
break;
}
// Get Other Tumor Types summary
tumorTypeSummary = getTumorTypeSummaryFromEvidences(EvidenceUtils.getEvidence(Collections.singletonList(alteration), Collections.singleton(EvidenceType.TUMOR_TYPE_SUMMARY), Collections.singleton(TumorTypeUtils.getMappedSpecialTumor(SpecialTumorType.OTHER_TUMOR_TYPES)), null));
if (tumorTypeSummary != null) {
break;
}
}
}
}
if (tumorTypeSummary == null) {
tumorTypeSummary = "There are no FDA-approved or NCCN-compendium listed treatments specifically for patients with [[variant]].";
}
tumorTypeSummary = replaceSpecialCharacterInTumorTypeSummary(tumorTypeSummary, gene, queryAlteration, queryTumorType);
if (CacheUtils.isEnabled()) {
CacheUtils.setVariantTumorTypeSummary(gene.getEntrezGeneId(), queryAlteration, queryTumorType, tumorTypeSummary);
}
return tumorTypeSummary;
}
public static String unknownOncogenicSummary(Gene gene) {
String str = gene == null ? "variant" : (gene.getHugoSymbol() + " alteration");
return "The oncogenic activity of this " + str + " is unknown as it has not specifically been investigated by the OncoKB team.";
}
public static String synonymousSummary() {
return "This is a synonymous mutation and is not annotated by OncoKB.";
}
public static String oncogenicSummary(Gene gene, List<Alteration> alterations, String queryAlteration, Boolean addition) {
StringBuilder sb = new StringBuilder();
if (gene == null || alterations == null || alterations.isEmpty() || AlterationUtils.excludeVUS(alterations).size() == 0) {
if (gene != null && queryAlteration != null) {
Alteration alteration = AlterationUtils.getAlteration(gene.getHugoSymbol(), queryAlteration, AlterationType.MUTATION.label(), null, null, null);
if (alteration == null) {
alteration = new Alteration();
alteration.setGene(gene);
alteration.setAlterationType(AlterationType.MUTATION);
alteration.setAlteration(queryAlteration);
alteration.setName(queryAlteration);
AlterationUtils.annotateAlteration(alteration, queryAlteration);
}
if (alteration.getConsequence() != null && alteration.getConsequence().getTerm().equals("synonymous_variant")) {
sb.append(synonymousSummary());
} else if (AlterationUtils.hasAlleleAlterations(alteration)) {
sb.append(alleleSummary(alteration));
} else if (AlterationUtils.excludeVUS(alterations).size() == 0) {
List<Evidence> evidences = EvidenceUtils.getEvidence(alterations, Collections.singleton(EvidenceType.VUS), null);
Date lastEdit = null;
for (Evidence evidence : evidences) {
if (evidence.getLastEdit() == null) {
continue;
}
if (lastEdit == null) {
lastEdit = evidence.getLastEdit();
} else if (lastEdit.compareTo(evidence.getLastEdit()) < 0) {
lastEdit = evidence.getLastEdit();
}
}
if (lastEdit == null) {
sb.append(unknownOncogenicSummary(gene));
} else {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
sb.append("As of " + sdf.format(lastEdit) + ", no functional data about this alteration was available.");
}
} else {
sb.append(unknownOncogenicSummary(gene));
}
} else {
sb.append(unknownOncogenicSummary(gene));
}
} else {
if (isSpecialMutation(queryAlteration, false)) {
if (isSpecialMutation(queryAlteration, true)) {
queryAlteration = queryAlteration.substring(0, 1).toUpperCase() + queryAlteration.substring(1);
}
}
String altName = getGeneMutationNameInVariantSummary(gene, queryAlteration);
if (gene == null || alterations == null) {
return null;
}
String geneId = Integer.toString(gene.getEntrezGeneId());
String key = geneId + "&&" + queryAlteration + "&&" + addition.toString();
if (CacheUtils.isEnabled() && CacheUtils.containVariantSummary(gene.getEntrezGeneId(), key)) {
return CacheUtils.getVariantSummary(gene.getEntrezGeneId(), key);
}
Boolean appendThe = appendThe(queryAlteration);
Boolean isPlural = false;
if (queryAlteration.toLowerCase().contains("fusions")) {
isPlural = true;
}
int oncogenic = -1;
for (Alteration a : alterations) {
List<Evidence> oncogenicEvidences = EvidenceUtils.getEvidence(Collections.singletonList(a), Collections.singleton(EvidenceType.ONCOGENIC), null);
if (oncogenicEvidences != null && oncogenicEvidences.size() > 0) {
Evidence evidence = oncogenicEvidences.iterator().next();
if (evidence != null && evidence.getKnownEffect() != null && Integer.parseInt(evidence.getKnownEffect()) >= 0) {
oncogenic = Integer.parseInt(evidence.getKnownEffect());
break;
}
}
}
if (oncogenic >= 0) {
if (appendThe) {
sb.append("The ");
}
sb.append(altName);
if (isPlural) {
sb.append(" are");
} else {
sb.append(" is");
}
if (oncogenic == 0) {
sb.append(" likely neutral.");
} else {
if (oncogenic == 2) {
sb.append(" likely");
} else if (oncogenic == 1) {
sb.append(" known to be");
}
sb.append(" oncogenic.");
}
} else {
sb.append("It is unknown whether ");
if (appendThe) {
sb.append("the ");
}
sb.append(altName);
if (isPlural) {
sb.append(" are");
} else {
sb.append(" is");
}
sb.append(" oncogenic.");
}
if (addition) {
List<Evidence> oncogenicEvs = EvidenceUtils.getEvidence(alterations, Collections.singleton(EvidenceType.ONCOGENIC), null);
List<String> clinicalSummaries = new ArrayList<>();
for (Evidence evidence : oncogenicEvs) {
if (evidence.getDescription() != null && !evidence.getDescription().isEmpty()) {
clinicalSummaries.add(evidence.getDescription());
}
}
if (clinicalSummaries.size() > 1) {
sb.append("Warning: variant has multiple clinical summaries.");
} else if (clinicalSummaries.size() == 1) {
sb.append(clinicalSummaries.get(0));
}
}
if (CacheUtils.isEnabled()) {
CacheUtils.setVariantSummary(gene.getEntrezGeneId(), key, sb.toString().trim());
}
}
return sb.toString();
}
public static String geneSummary(Gene gene) {
Set<Evidence> geneSummaryEvs = EvidenceUtils.getEvidenceByGeneAndEvidenceTypes(gene, Collections.singleton(EvidenceType.GENE_SUMMARY));
String summary = "";
if (!geneSummaryEvs.isEmpty()) {
Evidence ev = geneSummaryEvs.iterator().next();
if (ev != null) {
summary = ev.getDescription();
if (summary != null) {
summary = StringEscapeUtils.escapeXml(summary).trim();
}
}
}
summary = summary.trim();
summary = summary.endsWith(".") ? summary : summary + ".";
return summary;
}
public static String fullSummary(Gene gene, List<Alteration> alterations, String queryAlteration, Set<OncoTreeType> relevantTumorTypes, String queryTumorType) {
StringBuilder sb = new StringBuilder();
sb.append(geneSummary(gene));
String vts = SummaryUtils.variantTumorTypeSummary(gene, alterations, queryAlteration, relevantTumorTypes, queryTumorType);
if (vts != null && !vts.equals("")) {
sb.append(" " + vts);
}
return sb.toString();
}
public static String alleleSummary(Alteration alteration) {
StringBuilder sb = new StringBuilder();
String altStr = getGeneMutationNameInVariantSummary(alteration.getGene(), alteration.getAlteration());
sb.append("The " + altStr + " has not been functionally or clinically validated.");
Set<Alteration> alleles = new HashSet<>(AlterationUtils.getAlleleAndRelevantAlterations(alteration));
Map<String, Object> map = geAlterationsWithHighestOncogenicity(new HashSet<>(alleles));
Oncogenicity highestOncogenicity = (Oncogenicity) map.get("oncogenicity");
Set<Alteration> highestAlts = (Set<Alteration>) map.get("alterations");
if (highestOncogenicity != null && (highestOncogenicity.getOncogenic().equals("1") || highestOncogenicity.getOncogenic().equals("2"))) {
sb.append(" However, ");
sb.append(alteration.getGene().getHugoSymbol() + " " + allelesToStr(highestAlts));
sb.append((highestAlts.size() > 1 ? " are" : " is"));
if (highestOncogenicity.getOncogenic().equals("1")) {
sb.append(" known to be " + highestOncogenicity.getDescription().toLowerCase());
} else {
sb.append(" " + highestOncogenicity.getDescription().toLowerCase());
}
sb.append(", and therefore " + alteration.getGene().getHugoSymbol() + " " + alteration.getAlteration() + " is considered likely oncogenic.");
}
return sb.toString();
}
private static String alleleNamesStr(Set<Alteration> alterations) {
if (alterations != null && alterations.size() > 0) {
Alteration tmp = alterations.iterator().next();
String residue = tmp.getRefResidues();
String location = Integer.toString(tmp.getProteinStart());
Set<String> variantResidue = new TreeSet<>();
Set<Alteration> withoutVariantResidues = new HashSet<>();
for (Alteration alteration : alterations) {
if (alteration.getVariantResidues() == null) {
withoutVariantResidues.add(alteration);
} else {
variantResidue.add(alteration.getVariantResidues());
}
}
StringBuilder sb = new StringBuilder();
if (variantResidue.size() > 0) {
sb.append(residue + location + StringUtils.join(variantResidue, "/"));
}
if (withoutVariantResidues.size() > 0) {
List<String> alterationNames = new ArrayList<>();
for (Alteration alteration : withoutVariantResidues) {
alterationNames.add(alteration.getName());
}
if (variantResidue.size() > 0) {
sb.append(", ");
}
sb.append(MainUtils.listToString(alterationNames, ", "));
}
return sb.toString();
} else {
return "";
}
}
private static String allelesToStr(Set<Alteration> alterations) {
List<String> alterationNames = new ArrayList<>();
Map<Integer, Set<Alteration>> locationBasedAlts = new HashMap<>();
for (Alteration alteration : alterations) {
if (!locationBasedAlts.containsKey(alteration.getProteinStart()))
locationBasedAlts.put(alteration.getProteinStart(), new HashSet<Alteration>());
locationBasedAlts.get(alteration.getProteinStart()).add(alteration);
}
for (Map.Entry entry : locationBasedAlts.entrySet()) {
alterationNames.add(alleleNamesStr((Set<Alteration>) entry.getValue()));
}
return MainUtils.listToString(alterationNames, " and ");
}
private static Map<String, Object> geAlterationsWithHighestOncogenicity(Set<Alteration> alleles) {
Map<Oncogenicity, Set<Alteration>> oncoCate = new HashMap<>();
// Get oncogenicity info in alleles
for (Alteration alt : alleles) {
Set<EvidenceType> evidenceTypes = new HashSet<>();
evidenceTypes.add(EvidenceType.ONCOGENIC);
List<Evidence> allelesOnco = EvidenceUtils.getEvidence(Collections.singletonList(alt), evidenceTypes, null);
for (Evidence evidence : allelesOnco) {
String oncoStr = evidence.getKnownEffect();
if (oncoStr == null)
continue;
Oncogenicity oncogenicity = Oncogenicity.getByLevel(oncoStr);
if (!oncoCate.containsKey(oncogenicity))
oncoCate.put(oncogenicity, new HashSet<Alteration>());
oncoCate.get(oncogenicity).add(alt);
}
}
Oncogenicity oncogenicity = MainUtils.findHighestOncogenic(oncoCate.keySet());
Map<String, Object> result = new HashMap<>();
result.put("oncogenicity", oncogenicity);
result.put("alterations", oncoCate != null ? oncoCate.get(oncogenicity) : new HashSet<>());
return result;
}
private static Map<LevelOfEvidence, List<Evidence>> groupEvidencesByLevel(List<Evidence> evidences) {
Map<LevelOfEvidence, List<Evidence>> map = new EnumMap<LevelOfEvidence, List<Evidence>>(LevelOfEvidence.class);
for (LevelOfEvidence level : LevelOfEvidence.values()) {
map.put(level, new ArrayList<Evidence>());
}
for (Evidence ev : evidences) {
if (ev.getLevelOfEvidence() == null || ev.getTreatments().isEmpty()) continue;
map.get(ev.getLevelOfEvidence()).add(ev);
}
return map;
}
// According to following rules
// include
// e.g. While the drugs dabrafenib, trametinib and vemurafenib are FDA-approved for patients with BRAF V600E mutant melanoma, bladder or breast cancer, the clinical utility for these agents in patients with BRAF V600E mutant low grade gliomas is unknown.
// IF >2 SAME drug for >2 different cancer types
// include
// While there are FDA-approved drugs for patients with specific cancers harboring the BRAF V600E mutation (please refer to FDA-approved drugs in Other Tumor types section), the clinical utility for these agents in patients with BRAF V600E mutant low grade gliomas is unknown.
// IF <2 DIFFERENT drugs for <2 different tumor types
// While there are FDA-approved drugs for patients with lung and colorectal cancers harboring the EGFR L858R mutation (please refer to FDA-approved drugs in Other Tumor types section), the clinical utility for these agents in patients with EGFR L858R mutant low grade gliomas is unknown.
private static String treatmentsToStringByTumorType(List<Evidence> evidences, String queryAlteration, String queryTumorType, boolean capFirstLetter, boolean fda, boolean nccn, boolean inOtherTumorType) {
// Tumor type -> drug -> LevelOfEvidence and alteration set
Map<String, Map<String, Map<String, Object>>> map = new TreeMap<>();
Set<String> drugs = new HashSet<>();
Map<String, Set<String>> levelZeroDrugs = new HashMap<>();
List<String> list = new ArrayList<String>();
for (Evidence ev : evidences) {
String tt = null;
if (ev.getSubtype() != null) {
tt = ev.getSubtype().toLowerCase();
} else if (ev.getCancerType() != null) {
tt = ev.getCancerType().toLowerCase();
}
if (tt == null) {
continue;
}
Map<String, Map<String, Object>> ttMap = map.get(tt);
if (ttMap == null && !ev.getLevelOfEvidence().equals(LevelOfEvidence.LEVEL_0)) {
ttMap = new TreeMap<String, Map<String, Object>>();
map.put(tt, ttMap);
}
for (Treatment t : ev.getTreatments()) {
for (Drug drug : t.getDrugs()) {
String drugName = drug.getDrugName().toLowerCase();
if (ev.getLevelOfEvidence().equals(LevelOfEvidence.LEVEL_0)) {
if (!levelZeroDrugs.containsKey(drugName)) {
levelZeroDrugs.put(drugName, new HashSet<String>());
}
if (!levelZeroDrugs.get(drugName).contains(tt)) {
levelZeroDrugs.get(drugName).add(tt);
}
} else {
Map<String, Object> drugMap = ttMap.get(drugName);
if (!drugs.contains(drugName)) {
drugs.add(drugName);
}
if (drugMap == null) {
drugMap = new TreeMap<>();
ttMap.put(drugName, drugMap);
// drugMap.put("approvedIndications", t.getApprovedIndications());
drugMap.put("level", ev.getLevelOfEvidence());
drugMap.put("alteration", ev.getAlterations());
}
}
}
}
}
if (map.size() > 2) {
list.add(treatmentsToStringAboveLimit(drugs, capFirstLetter, fda, nccn, null));
} else {
boolean first = true;
for (Map.Entry<String, Map<String, Map<String, Object>>> entry : map.entrySet()) {
String tt = entry.getKey();
list.add(treatmentsToString(entry.getValue(), tt, queryAlteration, first & capFirstLetter, fda, nccn));
first = false;
}
}
// if(levelZeroDrugs.size() > 0) {
// list.add(treatmentsToStringLevelZero(levelZeroDrugs, list.size()==0 & capFirstLetter));
return MainUtils.listToString(list, " and ");
}
private static String treatmentsToStringLevelZero(Map<String, Set<String>> drugs, Boolean capFirstLetter) {
StringBuilder sb = new StringBuilder();
Set<String> tumorTypes = new HashSet<>();
boolean sameDrugs = true;
for (String drugName : drugs.keySet()) {
if (tumorTypes.isEmpty()) {
tumorTypes = drugs.get(drugName);
} else {
if (tumorTypes.size() != drugs.get(drugName).size()) {
sameDrugs = false;
break;
}
for (String tt : drugs.get(drugName)) {
if (!tumorTypes.contains(tt)) {
sameDrugs = false;
break;
}
}
}
}
if (sameDrugs) {
sb.append(drugStr(drugs.keySet(), capFirstLetter, true, false, null));
} else {
sb.append(capFirstLetter ? "T" : "t")
.append("here are multiple FDA-approved agents");
}
sb.append(" for treatment of patients with ");
sb.append(tumorTypes.size() > 2 ? "different tumor types" : MainUtils.listToString(new ArrayList<String>(tumorTypes), " and "))
.append(" irrespective of mutation status");
return sb.toString();
}
private static String treatmentsToStringAboveLimit(Set<String> drugs, boolean capFirstLetter, boolean fda, boolean nccn, String approvedIndication) {
StringBuilder sb = new StringBuilder();
sb.append(drugStr(drugs, capFirstLetter, fda, nccn, null));
sb.append(" for treatment of patients with different tumor types harboring specific mutations");
return sb.toString();
}
private static String treatmentsToString(Map<String, Map<String, Object>> map, String tumorType, String alteration, boolean capFirstLetter, boolean fda, boolean nccn) {
Set<String> drugs = map.keySet();
Map<String, Object> drugAltMap = drugsAreSameByAlteration(map);
StringBuilder sb = new StringBuilder();
Map<String, Object> drugMap = map.get(drugs.iterator().next());
// Set<String> approvedIndications = (Set<String>) drugMap.get("approvedIndications");
String aiStr = null;
// for (String ai : approvedIndications) {
// if (ai != null && !ai.isEmpty()) {
// aiStr = ai;
// break;
sb.append(drugStr(drugs, capFirstLetter, fda, nccn, aiStr))
.append(" for treatment of patients ")
.append(tumorType == null ? "" : ("with " + tumorType + " "))
.append("harboring ");
if (alteration != null) {
sb.append("the ").append(alteration);
} else if ((Boolean) drugAltMap.get("isSame")) {
Set<Alteration> alterations = (Set<Alteration>) drugAltMap.get("alterations");
if (alterations.size() <= 2) {
sb.append("the ").append(alterationsToString(alterations));
} else {
sb.append("specific mutations");
}
} else {
sb.append("specific mutations");
}
return sb.toString();
}
private static String drugStr(Set<String> drugs, boolean capFirstLetter, boolean fda, boolean nccn, String approvedIndication) {
int drugLimit = 3;
StringBuilder sb = new StringBuilder();
if (drugs.size() > drugLimit) {
sb.append(capFirstLetter ? "T" : "t").append("here");
} else {
sb.append(capFirstLetter ? "T" : "t").append("he drug");
if (drugs.size() > 1) {
sb.append("s");
}
sb.append(" ");
sb.append(MainUtils.listToString(new ArrayList<String>(drugs), " and "));
}
if (fda || nccn) {
sb.append(" ");
if (drugs.size() > 1) {
sb.append("are");
} else {
sb.append("is");
}
}
if (fda) {
sb.append(" FDA-approved");
} else if (nccn) {
if (approvedIndication != null) {
sb.append(" FDA-approved for the treatment of ")
.append(approvedIndication)
.append(" and");
}
if (drugs.size() > drugLimit || approvedIndication != null) {
sb.append(" NCCN-compendium listed");
} else if (drugs.size() <= drugLimit) {
sb.append(" listed by NCCN-compendium");
}
}
if (drugs.size() > drugLimit) {
sb.append(" drugs");
}
return sb.toString();
}
private static Map<String, Object> drugsAreSameByAlteration(Map<String, Map<String, Object>> drugs) {
Set<Alteration> alterations = new HashSet<>();
Map<String, Object> map = new HashMap<>();
map.put("isSame", true);
map.put("alterations", alterations);
for (String drugName : drugs.keySet()) {
Map<String, Object> drug = drugs.get(drugName);
Set<Alteration> alts = (Set<Alteration>) drug.get("alteration");
if (alterations.isEmpty()) {
alterations = alts;
} else {
if (alterations.size() != alts.size()) {
map.put("isSame", false);
return map;
}
for (Alteration alt : alts) {
if (!alterations.contains(alt)) {
map.put("isSame", false);
return map;
}
}
}
}
map.put("alterations", alterations);
return map;
}
private static String alterationsToString(Collection<Alteration> alterations) {
Map<Gene, Set<String>> mapGeneVariants = new HashedMap();
for (Alteration alteration : alterations) {
Gene gene = alteration.getGene();
Set<String> variants = mapGeneVariants.get(gene);
if (variants == null) {
variants = new HashSet<>();
mapGeneVariants.put(gene, variants);
}
variants.add(alteration.getName());
}
List<String> list = new ArrayList<>();
for (Map.Entry<Gene, Set<String>> entry : mapGeneVariants.entrySet()) {
for (String variant : entry.getValue()) {
list.add(getGeneMutationNameInVariantSummary(alterations.iterator().next().getGene(), variant));
}
}
String ret = MainUtils.listToString(list, " or ");
return ret;
}
private static Boolean isSpecialMutation(String mutationStr, Boolean exactMatch) {
exactMatch = exactMatch || false;
mutationStr = mutationStr.toString();
if (exactMatch) {
return stringIsFromList(mutationStr, SpecialMutations);
} else if (stringContainsItemFromList(mutationStr, SpecialMutations)
&& itemFromListAtEndString(mutationStr, SpecialMutations)) {
return true;
}
return false;
}
private static Boolean appendThe(String queryAlteration) {
Boolean appendThe = true;
if (queryAlteration.toLowerCase().contains("deletion")
|| queryAlteration.toLowerCase().contains("amplification")
|| queryAlteration.toLowerCase().contains("fusions")) {
appendThe = false;
}
return appendThe;
}
private static String getTumorTypeSummaryFromEvidences(List<Evidence> evidences) {
String summary = null;
if (evidences != null && evidences.size() > 0) {
// Sort all tumor type summaries, the more specific tumor type summary will be picked.
Collections.sort(evidences, new Comparator<Evidence>() {
public int compare(Evidence x, Evidence y) {
if (x.getAlterations() == null) {
return 1;
}
if (y.getAlterations() == null) {
return -1;
}
return x.getAlterations().size() - y.getAlterations().size();
}
});
Evidence ev = evidences.get(0);
String tumorTypeSummary = ev.getDescription();
if (tumorTypeSummary != null) {
summary = StringEscapeUtils.escapeXml(tumorTypeSummary).trim();
}
}
return summary;
}
private static String getGeneMutationNameInVariantSummary(Gene gene, String queryAlteration) {
StringBuilder sb = new StringBuilder();
Alteration alteration = AlterationUtils.findAlteration(gene, queryAlteration);
if (alteration == null) {
alteration = AlterationUtils.getAlteration(gene.getHugoSymbol(), queryAlteration, null, null, null, null);
AlterationUtils.annotateAlteration(alteration, queryAlteration);
}
if (isSpecialMutation(queryAlteration, true)) {
sb.append(gene.getHugoSymbol() + " " + queryAlteration.toLowerCase());
} else if (StringUtils.containsIgnoreCase(queryAlteration, "fusion")) {
queryAlteration = queryAlteration.replace("Fusion", "fusion");
sb.append(queryAlteration);
} else if (isSpecialMutation(queryAlteration, false)
|| (alteration.getConsequence() != null
&& (alteration.getConsequence().getTerm().equals("inframe_deletion")
|| alteration.getConsequence().getTerm().equals("inframe_insertion")))
|| StringUtils.containsIgnoreCase(queryAlteration, "indel")
|| StringUtils.containsIgnoreCase(queryAlteration, "dup")
|| StringUtils.containsIgnoreCase(queryAlteration, "del")
|| StringUtils.containsIgnoreCase(queryAlteration, "ins")
|| StringUtils.containsIgnoreCase(queryAlteration, "splice")) {
sb.append(gene.getHugoSymbol() + " " + queryAlteration + " alteration");
} else {
sb.append(gene.getHugoSymbol() + " " + queryAlteration + " mutation");
}
return sb.toString();
}
private static String getGeneMutationNameInTumorTypeSummary(Gene gene, String queryAlteration) {
StringBuilder sb = new StringBuilder();
Alteration alteration = AlterationUtils.findAlteration(gene, queryAlteration);
if (alteration == null) {
alteration = AlterationUtils.getAlteration(gene.getHugoSymbol(), queryAlteration, null, null, null, null);
AlterationUtils.annotateAlteration(alteration, queryAlteration);
}
if (StringUtils.containsIgnoreCase(queryAlteration, "fusion")) {
if (queryAlteration.toLowerCase().equals("fusions")) {
queryAlteration = gene.getHugoSymbol() + " fusion";
}
queryAlteration = queryAlteration.replace("Fusion", "fusion");
sb.append(queryAlteration + " positive");
} else {
sb.append(gene.getHugoSymbol() + " ");
if (isSpecialMutation(queryAlteration, true)) {
sb.append(queryAlteration.toLowerCase());
} else if (isSpecialMutation(queryAlteration, false)
|| (alteration.getConsequence() != null
&& (alteration.getConsequence().getTerm().equals("inframe_deletion")
|| alteration.getConsequence().getTerm().equals("inframe_insertion")))
|| StringUtils.containsIgnoreCase(queryAlteration, "indel")
|| StringUtils.containsIgnoreCase(queryAlteration, "dup")
|| StringUtils.containsIgnoreCase(queryAlteration, "del")
|| StringUtils.containsIgnoreCase(queryAlteration, "ins")
|| StringUtils.containsIgnoreCase(queryAlteration, "splice")
) {
sb.append(queryAlteration + " altered");
} else {
sb.append(queryAlteration + " mutant");
}
}
return sb.toString();
}
private static String replaceSpecialCharacterInTumorTypeSummary(String summary, Gene gene, String queryAlteration, String queryTumorType) {
String altName = getGeneMutationNameInTumorTypeSummary(gene, queryAlteration);
String alterationName = getGeneMutationNameInVariantSummary(gene, queryAlteration);
summary = summary.replace("[[variant]]", altName + " " + queryTumorType);
summary = summary.replace("[[gene]] [[mutation]] [[[mutation]]]", alterationName);
// In case of miss typed
summary = summary.replace("[[gene]] [[mutation]] [[mutation]]", alterationName);
summary = summary.replace("[[gene]] [[mutation]] [[mutant]]", altName);
summary = summary.replace("[[gene]]", gene.getHugoSymbol());
summary = summary.replace("[[mutation]] [[mutant]]", altName);
summary = summary.replace("[[mutation]] [[[mutation]]]", alterationName);
// In case of miss typed
summary = summary.replace("[[mutation]] [[mutation]]", alterationName);
summary = summary.replace("[[mutation]]", queryAlteration);
summary = summary.replace("[[tumorType]]", queryTumorType);
summary = summary.replace("[[tumor type]]", queryTumorType);
summary = summary.replace("[[fusion name]]", altName);
summary = summary.replace("[[fusion name]]", altName);
return summary;
}
private static String getTumorTypeSummaryFromPickedTreatment(Gene gene, Alteration alteration, Set<OncoTreeType> relevantTumorTypes) {
String tumorTypeSummary = null;
List<Evidence> evidences = EvidenceUtils.getEvidence(Collections.singletonList(alteration), Collections.singleton(EvidenceType.TUMOR_TYPE_SUMMARY), relevantTumorTypes, null);
Evidence pickedTreatment = pickSpecialGeneTreatmentEvidence(gene, EvidenceUtils.getEvidence(Collections.singletonList(alteration), MainUtils.getTreatmentEvidenceTypes(), relevantTumorTypes, null));
for (Evidence evidence : evidences) {
if (evidence.getAlterations().equals(pickedTreatment.getAlterations())) {
tumorTypeSummary = getTumorTypeSummaryFromEvidences(Collections.singletonList(evidence));
if (tumorTypeSummary != null) {
break;
}
}
}
if (tumorTypeSummary == null) {
evidences = EvidenceUtils.getEvidence(Collections.singletonList(alteration), Collections.singleton(EvidenceType.TUMOR_TYPE_SUMMARY), Collections.singleton(TumorTypeUtils.getMappedSpecialTumor(SpecialTumorType.OTHER_TUMOR_TYPES)), null);
for (Evidence evidence : evidences) {
tumorTypeSummary = getTumorTypeSummaryFromEvidences(Collections.singletonList(evidence));
if (tumorTypeSummary != null) {
break;
}
}
}
return tumorTypeSummary;
}
private static String getKITtumorTypeSummaries(String queryAlteration, List<Alteration> alterations, String queryTumorType, Set<OncoTreeType> relevantTumorTypes) {
Gene gene = GeneUtils.getGeneByHugoSymbol("KIT");
String tumorTypeSummary = null;
Evidence pickedTreatment = null;
// Get all tumor type summary evidences specifically for the alteration
if (tumorTypeSummary == null) {
Alteration alteration = AlterationUtils.findAlteration(gene, queryAlteration);
if (alteration != null) {
tumorTypeSummary = getTumorTypeSummaryFromPickedTreatment(gene, alteration, relevantTumorTypes);
}
}
// Get all tumor type summary evidences for the alternate alleles
if (tumorTypeSummary == null) {
Alteration alteration = AlterationUtils.findAlteration(gene, queryAlteration);
if (alteration == null) {
alteration = AlterationUtils.getAlteration(gene.getHugoSymbol(), queryAlteration, null, null, null, null);
AlterationUtils.annotateAlteration(alteration, queryAlteration);
}
if (alteration.getConsequence() != null) {
if (alteration.getConsequence().getTerm().equals("missense_variant")) {
List<Alteration> alternateAlleles = AlterationUtils.getAlleleAndRelevantAlterations(alteration);
// Send all allele tumor types treatment to pick up the unique one.
pickedTreatment = pickSpecialGeneTreatmentEvidence(gene, EvidenceUtils.getEvidence(alternateAlleles, MainUtils.getTreatmentEvidenceTypes(), relevantTumorTypes, null));
if (pickedTreatment != null) {
tumorTypeSummary = getTumorTypeSummaryFromPickedTreatment(gene, (Alteration) CollectionUtils.intersection(alternateAlleles, new ArrayList<>(pickedTreatment.getAlterations())).iterator().next(), relevantTumorTypes);
if (tumorTypeSummary != null) {
// Only keep the first sentence for alternate allele
tumorTypeSummary = tumorTypeSummary.split("\\.")[0] + ".";
}
} else {
// If all alternate alleles don't have any treatment, check whether they have tumor type summaries.
for (Alteration allele : alternateAlleles) {
tumorTypeSummary = getTumorTypeSummaryFromPickedTreatment(gene, allele, relevantTumorTypes);
if (tumorTypeSummary != null) {
// Only keep the first sentence for alternate allele
tumorTypeSummary = tumorTypeSummary.split("\\.")[0] + ".";
break;
}
}
}
} else if (alteration.getConsequence().getTerm().equals("synonymous_variant")) {
// No summary for synonymous variant
return "";
}
}
}
// Get all tumor type summary evidence for relevant alterations
if (tumorTypeSummary == null) {
// Base on the priority of relevant alterations
for (Alteration alteration : alterations) {
tumorTypeSummary = getTumorTypeSummaryFromPickedTreatment(gene, alteration, relevantTumorTypes);
if (tumorTypeSummary != null) {
break;
}
}
}
return tumorTypeSummary;
}
private static Evidence pickSpecialGeneTreatmentEvidence(Gene gene, List<Evidence> treatments) {
Evidence pickedTreatment = null;
if (gene != null && treatments != null) {
List<String> TREATMENTS = null;
String hugoSymbol = gene.getHugoSymbol();
if (hugoSymbol.equals("KIT")) {
TREATMENTS = Arrays.asList("imatinib", "sunitinib", "regorafenib", "sorafenib", "nilotinib", "dasatinib");
}
Integer index = 1000;
for (Evidence treatment : treatments) {
String treatmentName = TreatmentUtils.getTreatmentName(treatment.getTreatments(), false);
if (treatmentName != null) {
Integer _index = TREATMENTS.indexOf(treatmentName.toLowerCase());
if (_index != -1 && _index < index) {
index = _index;
pickedTreatment = treatment;
}
}
}
}
return pickedTreatment;
}
public static boolean stringContainsItemFromList(String inputString, String[] items) {
for (int i = 0; i < items.length; i++) {
if (inputString.contains(items[i])) {
return true;
}
}
return false;
}
public static boolean stringIsFromList(String inputString, String[] items) {
for (int i = 0; i < items.length; i++) {
if (inputString.equalsIgnoreCase(items[i])) {
return true;
}
}
return false;
}
public static boolean itemFromListAtEndString(String inputString, String[] items) {
for (int i = 0; i < items.length; i++) {
if (inputString.endsWith(items[i])) {
return true;
}
}
return false;
}
}
|
package at.zeha.netbeans.cliglue;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import org.netbeans.api.project.Project;
import org.netbeans.api.project.ProjectManager;
import org.netbeans.api.project.ui.OpenProjects;
import org.netbeans.spi.project.ProjectConfiguration;
import org.netbeans.spi.project.ProjectConfigurationProvider;
import org.netbeans.api.sendopts.CommandException;
import org.netbeans.spi.sendopts.Env;
import org.netbeans.spi.sendopts.OptionProcessor;
import org.netbeans.spi.sendopts.Option;
import org.openide.LifecycleManager;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.util.lookup.ServiceProvider;
import org.openide.windows.WindowManager;
@ServiceProvider(service = OptionProcessor.class)
public class AllConfigurationsOpenerCommandLineProcessor extends OptionProcessor {
private static Option action = Option.requiredArgument(Option.NO_SHORT_NAME, "openallconfigs");
private static final Logger logger = Logger.getLogger(AllConfigurationsOpenerCommandLineProcessor.class.getName());
@Override
public Set<org.netbeans.spi.sendopts.Option> getOptions() {
return Collections.singleton(action);
}
@Override
protected void process(Env env, Map<Option, String[]> values) throws CommandException {
final String[] args = values.get(action);
if (args.length > 0) {
WindowManager.getDefault().invokeWhenUIReady(new Runnable() {
@Override
public void run() {
try {
ProjectManager manager = ProjectManager.getDefault();
manager.clearNonProjectCache();
String projectFilePath = args[0];
File projectFile = new File(projectFilePath);
FileObject projectToBeOpened = FileUtil.toFileObject(projectFile);
Project project = ProjectManager.getDefault().findProject(projectToBeOpened);
Project[] array = new Project[1];
array[0] = project;
OpenProjects OpenProjectsInstance = OpenProjects.getDefault();
logger.setLevel(Level.ALL);
logger.log(Level.INFO, "Closing existing projects...");
OpenProjectsInstance.close(OpenProjectsInstance.openProjects().get());
// wait for close to complete
OpenProjectsInstance.openProjects().get();
Thread.sleep(500);
logger.log(Level.INFO, "Opening project...");
OpenProjectsInstance.open(array, false);
// wait for open to complete
OpenProjectsInstance.openProjects().get();
Thread.sleep(500);
project = OpenProjectsInstance.openProjects().get()[0];
ProjectConfigurationProvider configProvider = project.getLookup().lookup(ProjectConfigurationProvider.class);
Collection<ProjectConfiguration> configurations = configProvider.getConfigurations();
for (Object c : configurations.toArray()) {
logger.log(Level.INFO, "Activating configuration \"" + ((ProjectConfiguration) c).getDisplayName() + "\" ...");
configProvider.setActiveConfiguration((ProjectConfiguration) c);
Thread.sleep(500);
}
logger.log(Level.INFO, "Closing opened projects...");
Thread.sleep(500);
OpenProjectsInstance.close(OpenProjectsInstance.openProjects().get());
// wait for close to complete
OpenProjectsInstance.openProjects().get();
} catch (InterruptedException ex) {
ex.printStackTrace();
logger.log(Level.SEVERE, ex.getStackTrace().toString());
} catch (ExecutionException ex) {
ex.printStackTrace();
logger.log(Level.SEVERE, ex.getStackTrace().toString());
} catch (IOException ex) {
ex.printStackTrace();
logger.log(Level.SEVERE, ex.getStackTrace().toString());
} catch (Exception ex) {
// catch all exceptions here so IDE shutdown works anyway.
ex.printStackTrace();
logger.log(Level.SEVERE, ex.getStackTrace().toString());
}
logger.log(Level.INFO, "Shutting down.");
LifecycleManager.getDefault().exit();
}
});
}
}
}
|
package step.core.deployment;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.PostConstruct;
import javax.inject.Singleton;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.bson.types.ObjectId;
import step.commons.datatable.DataTable;
import step.commons.datatable.TableRow;
import step.core.artefacts.AbstractArtefact;
import step.core.artefacts.Artefact;
import step.core.artefacts.ArtefactAccessor;
import step.core.artefacts.ArtefactRegistry;
import step.core.artefacts.reports.ReportNode;
import step.core.artefacts.reports.ReportNodeStatus;
import step.core.execution.ExecutionRunnable;
import step.core.execution.model.Execution;
import step.core.execution.model.ExecutionParameters;
import step.core.execution.model.ExecutionStatus;
import step.core.execution.model.ReportExport;
import step.core.repositories.ArtefactInfo;
import step.core.repositories.RepositoryObjectReference;
import step.core.repositories.TestSetStatusOverview;
import step.core.scheduler.ExecutiontTaskParameters;
@Singleton
@Path("controller")
public class ControllerServices extends AbstractServices {
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Path("/task")
@Secured(right="task-write")
public void execute(ExecutiontTaskParameters schedule) {
getScheduler().addExecutionTask(schedule);
}
@PUT
@Path("/task/{id}")
@Secured(right="task-write")
public void enableExecutionTask(@PathParam("id") String executionTaskID) {
getScheduler().enableExecutionTask(executionTaskID);
}
@DELETE
@Path("/task/{id}")
@Secured(right="task-delete")
public void removeExecutionTask(@PathParam("id") String executionTaskID, @QueryParam("remove") Boolean remove) {
if(remove!=null && remove) {
getScheduler().removeExecutionTask(executionTaskID);
} else {
getScheduler().disableExecutionTask(executionTaskID);
}
}
@GET
@Path("/task/{id}")
@Produces(MediaType.APPLICATION_JSON)
@Secured(right="task-read")
public ExecutiontTaskParameters getExecutionTask(@PathParam("id") String executionTaskID) {
return getScheduler().get(executionTaskID);
}
@GET
@Path("/task")
@Produces(MediaType.APPLICATION_JSON)
@Secured(right="task-read")
public List<ExecutiontTaskParameters> getScheduledExecutions() {
List<ExecutiontTaskParameters> result = new ArrayList<ExecutiontTaskParameters>();
Iterator<ExecutiontTaskParameters> it = getScheduler().getActiveAndInactiveExecutionTasks();
int maxSize = 50;
while(it.hasNext() && result.size()<maxSize) {
result.add(it.next());
}
return result;
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Path("/execution")
@Secured(right="plan-execute")
public String execute(ExecutionParameters executionParams) {
String executionID = getScheduler().execute(executionParams);
return executionID;
}
@GET
@Path("/execution/{id}")
@Produces(MediaType.APPLICATION_JSON)
@Secured(right="report-read")
public Execution getExecution(@PathParam("id") String executionID) {
return getContext().getExecutionAccessor().get(executionID);
}
public class RTMLink {
String link;
public String getLink() {
return link;
}
}
@GET
@Path("/execution/{id}/rtmlink")
@Produces(MediaType.APPLICATION_JSON)
@Secured(right="report-read")
public RTMLink getRtmLink(@PathParam("id") String executionID) {
RTMLink link = new RTMLink();
// link.link = RTMLinkGenerator.getAggregateViewByEid(executionID);
return link;
}
@POST
@Path("/execution/{id}/report")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public ReportExport reportExecution(@PathParam("id") String executionID, RepositoryObjectReference report) {
return getContext().getRepositoryObjectManager().exportTestExecutionReport(report, executionID);
}
@GET
@Path("/execution/{id}/statusdistribution")
@Produces(MediaType.APPLICATION_JSON)
@Secured(right="report-read")
public Map<ReportNodeStatus, Integer> getStatusReport(@PathParam("id") String executionID, @QueryParam("class") String reportNodeClass) {
return getContext().getReportAccessor().getLeafReportNodesStatusDistribution(executionID, reportNodeClass);
}
@GET
@Path("/execution/{id}/throughput")
@Produces({"application/json;response-pass-through=true"})
@Secured(right="report-read")
public DataTable getStatusReport(@PathParam("id") String executionID, @QueryParam("resolution") Integer nInterval) {
Execution e = getContext().getExecutionAccessor().get(executionID);
long t2;
if(e.getStatus()==ExecutionStatus.ENDED) {
t2=e.getEndTime();
} else {
t2=System.currentTimeMillis();
}
long duration = t2 - e.getStartTime();
int resolution = (int) (1.0*duration/nInterval);
DataTable t = getContext().getReportAccessor().getTimeBasedReport(executionID, resolution);
if(t.getRows().size()<resolution) {
long time = t.getRows().size()>0?t.getRows().get(t.getRows().size()-1).getDate().getTime():e.getStartTime();
for(int i=t.getRows().size();i<nInterval;i++) {
time+=resolution;
t.addRow(new TableRow(new Date(time), 0.0));
}
}
return t;
}
@GET
@Path("/execution/{id}/reportnodes")
@Produces(MediaType.APPLICATION_JSON)
@Secured(right="report-read")
public List<ReportNode> getReportNodesByExecutionID(@PathParam("id") String executionID, @QueryParam("class") String reportNodeClass, @QueryParam("limit") int limit) {
List<ReportNode> result = new ArrayList<>();
Iterator<ReportNode> iterator;
if(reportNodeClass!=null) {
iterator = getContext().getReportAccessor().getReportNodesByExecutionIDAndClass(executionID, reportNodeClass);
} else {
iterator = getContext().getReportAccessor().getReportNodesByExecutionID(executionID);
}
int i = 0;
while(iterator.hasNext()&&i<limit) {
i++;
result.add(iterator.next());
}
return result;
}
@GET
@Path("/execution/{id}/stop")
@Secured(right="plan-execute")
public void abort(@PathParam("id") String executionID) {
ExecutionRunnable task = getExecutionRunnable(executionID);
if(task!=null) {
task.getExecutionLifecycleManager().abort();
}
}
@GET
@Path("/reportnode/{id}")
@Produces(MediaType.APPLICATION_JSON)
@Secured(right="report-read")
public ReportNode getReportNode(@PathParam("id") String reportNodeId) {
return getContext().getReportAccessor().get(new ObjectId(reportNodeId));
}
@GET
@Path("/reportnode/{id}/path")
@Secured(right="report-read")
public List<ReportNodeAndArtefact> getReportNodePath(@PathParam("id") String reportNodeId) {
List<ReportNodeAndArtefact> result = new ArrayList<>();
ArtefactAccessor artefactAccessor = getContext().getArtefactAccessor();
List<ReportNode> path = getContext().getReportAccessor().getReportNodePath(new ObjectId(reportNodeId));
path.forEach((node) -> result.add(new ReportNodeAndArtefact(node, node.getArtefactID()!=null?artefactAccessor.get(node.getArtefactID()):null)));
return result;
}
class ReportNodeAndArtefact {
ReportNode reportNode;
AbstractArtefact artefact;
public ReportNodeAndArtefact() {
super();
}
public ReportNodeAndArtefact(ReportNode reportNode, AbstractArtefact artefact) {
this.reportNode = reportNode;
this.artefact = artefact;
}
public ReportNode getReportNode() {
return reportNode;
}
public void setReportNode(ReportNode reportNode) {
this.reportNode = reportNode;
}
public AbstractArtefact getArtefact() {
return artefact;
}
public void setArtefact(AbstractArtefact artefact) {
this.artefact = artefact;
}
}
@GET
@Path("/reportnode/{id}/children")
@Produces(MediaType.APPLICATION_JSON)
@Secured(right="report-read")
public List<ReportNode> getReportNodeChildren(@PathParam("id") String reportNodeId) {
int limit = 1000;
List<ReportNode> result = new ArrayList<>();
Iterator<ReportNode> it = getContext().getReportAccessor().getChildren(new ObjectId(reportNodeId));
while(it.hasNext()) {
result.add(it.next());
if(result.size()>limit) {
break;
}
}
return result;
}
@GET
@Path("/executions")
@Produces(MediaType.APPLICATION_JSON)
@Secured(right="report-read")
public List<Execution> getExecutions(@QueryParam("limit") int limit) {
List<Execution> result = new ArrayList<>();
for(Execution e:getContext().getExecutionAccessor().findLastStarted(limit)) {
result.add(e);
}
return result;
}
@POST
@Path("/repository/artefact/info")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Secured(right="report-read")
public ArtefactInfo getArtefactInfo(RepositoryObjectReference ref) {
try {
return getContext().getRepositoryObjectManager().getArtefactInfo(ref);
} catch (Exception e) {
e.printStackTrace();
throw new WebApplicationException(Response.status(500).entity("Unable to retrieve artefact.").type("text/plain").build());
}
}
@POST
@Path("/repository/report")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Secured(right="report-read")
public TestSetStatusOverview getReport(RepositoryObjectReference report) throws Exception {
return getContext().getRepositoryObjectManager().getReport(report);
}
@GET
@Path("/artefact/{id}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Secured(right="plan-read")
public AbstractArtefact getArtefact(@PathParam("id") String id) {
return getContext().getArtefactAccessor().get(new ObjectId(id));
}
@POST
@Path("/artefact/{id}/attributes")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Secured(right="plan-write")
public AbstractArtefact saveArtefactAttributes(Map<String, String> attributes, @PathParam("id") String id) {
ArtefactAccessor accessor = getContext().getArtefactAccessor();
AbstractArtefact artefact = accessor.get(id);
artefact.setAttributes(attributes);
return accessor.save(artefact);
}
@POST
@Path("/artefact")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Secured(right="plan-write")
public AbstractArtefact saveArtefact(AbstractArtefact artefact) {
return getContext().getArtefactAccessor().save(artefact);
}
@GET
@Path("/artefact/{id}/descendants")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Secured(right="plan-read")
public ArtefactTree getArtefactDescendants(@PathParam("id") String id) {
ArtefactAccessor a = getContext().getArtefactAccessor();
AbstractArtefact root = a.get(id);
ArtefactTree rootNode = new ArtefactTree(root);
getChildrenRecursive(a, rootNode);
return rootNode;
}
@GET
@Path("/artefact/types")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Secured(right="plan-read")
public Set<String> getArtefactTypes() {
return ArtefactRegistry.getInstance().getArtefactNames();
}
@GET
@Path("/artefact/types/{id}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Secured(right="plan-read")
public AbstractArtefact getArtefactType(@PathParam("id") String type) throws Exception {
Class<? extends AbstractArtefact> clazz = ArtefactRegistry.getInstance().getArtefactType(type);
AbstractArtefact sample = clazz.newInstance();
for(Method m:clazz.getMethods()) {
if(m.getAnnotation(PostConstruct.class)!=null) {
m.invoke(sample);
}
}
sample.setAttributes(new HashMap<>());
sample.getAttributes().put("name", getDefaultArtefactName(clazz));
getContext().getArtefactAccessor().save(sample);
return sample;
}
private String getDefaultArtefactName(Class<? extends AbstractArtefact> artefactClass) {
Artefact annotation = artefactClass.getAnnotation(Artefact.class);
return annotation.name().length() > 0 ? annotation.name() : artefactClass.getSimpleName();
}
public class ArtefactTree {
AbstractArtefact artefact;
List<ArtefactTree> children;
public ArtefactTree(AbstractArtefact artefact) {
super();
this.artefact = artefact;
}
public AbstractArtefact getArtefact() {
return artefact;
}
public List<ArtefactTree> getChildren() {
return children;
}
public void setChildren(List<ArtefactTree> children) {
this.children = children;
}
}
private void getChildrenRecursive(ArtefactAccessor a, ArtefactTree current) {
AbstractArtefact parent = current.getArtefact();
if(parent.getChildrenIDs()!=null) {
List<ArtefactTree> childrenNodes = new ArrayList<>();
for(ObjectId childId:parent.getChildrenIDs()) {
AbstractArtefact child = a.get(childId);
ArtefactTree childNode = new ArtefactTree(child);
childrenNodes.add(childNode);
getChildrenRecursive(a, childNode);
}
current.setChildren(childrenNodes);
}
}
@POST
@Path("/artefact/{id}/children")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Secured(right="plan-write")
public AbstractArtefact addChild(@PathParam("id") String id, AbstractArtefact child) {
ArtefactAccessor a = getContext().getArtefactAccessor();
child = a.save(child);
AbstractArtefact artefact = a.get(id);
artefact.addChild(child.getId());
a.save(artefact);
return child;
}
@DELETE
@Path("/artefact/{id}/children/{childid}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Secured(right="plan-write")
public void removeChild(@PathParam("id") String parentid, @PathParam("childid") String childid) {
ArtefactAccessor a = getContext().getArtefactAccessor();
AbstractArtefact artefact = a.get(parentid);
artefact.removeChild(new ObjectId(childid));
a.save(artefact);
}
@POST
@Path("/artefact/{id}/children/{childid}/move")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Secured(right="plan-write")
public void moveChildUp(@PathParam("id") String parentid, @PathParam("childid") String childid, int offset) {
ArtefactAccessor a = getContext().getArtefactAccessor();
AbstractArtefact artefact = a.get(parentid);
ObjectId child = new ObjectId(childid);
int pos = artefact.indexOf(child);
int newPos = pos+offset;
if(newPos>=0&&newPos<artefact.getChildrenIDs().size()) {
artefact.removeChild(child);
artefact.add(newPos, child);
}
a.save(artefact);
}
@POST
@Path("/artefact/{id}/move")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Secured(right="plan-write")
public void moveArtefact(@PathParam("id") String id, @QueryParam("from") String originParentId,
@QueryParam("to") String targetParentId, @QueryParam("pos") int newPosition) {
ArtefactAccessor a = getContext().getArtefactAccessor();
AbstractArtefact origin = a.get(originParentId);
origin.removeChild(new ObjectId(id));
a.save(origin);
AbstractArtefact target = a.get(targetParentId);
target.add(newPosition, new ObjectId(id));
a.save(target);
}
@POST
@Path("/artefact/{id}/copy")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Secured(right="plan-write")
public void copyArtefact(@PathParam("id") String id,
@QueryParam("to") String targetParentId, @QueryParam("pos") int newPosition) {
getContext().getArtefactManager().copyArtefact(id, targetParentId);
}
@POST
@Path("/artefact/{id}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Secured(right="plan-write")
public void updateArtefact(AbstractArtefact artefact) {
getContext().getArtefactAccessor().save(artefact);
}
@DELETE
@Path("/artefact/{id}")
@Consumes(MediaType.APPLICATION_JSON)
@Secured(right="plan-delete")
public void deleteArtefact(@PathParam("id") String id) {
ArtefactAccessor a = getContext().getArtefactAccessor();
removeRecursive(new ObjectId(id), a);
}
private void removeRecursive(ObjectId id, ArtefactAccessor a) {
AbstractArtefact artefact = a.get(id);
if(artefact!=null) {
if(artefact.getChildrenIDs()!=null) {
for(ObjectId childId:artefact.getChildrenIDs()) {
removeRecursive(childId, a);
}
}
a.remove(id);
}
}
}
|
package ca.concordia.cssanalyser.cssmodel.declaration;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.NotImplementedException;
import ca.concordia.cssanalyser.cssmodel.LocationInfo;
import ca.concordia.cssanalyser.cssmodel.declaration.value.DeclarationEquivalentValue;
import ca.concordia.cssanalyser.cssmodel.declaration.value.DeclarationValue;
import ca.concordia.cssanalyser.cssmodel.declaration.value.ValueType;
import ca.concordia.cssanalyser.cssmodel.selectors.Selector;
/**
* Represents multi-valued declarations
* @author Davood Mazinanian
*
*/
public class MultiValuedDeclaration extends Declaration {
protected final boolean isCommaSeparatedListOfValues;
protected final List<DeclarationValue> declarationValues;
/**
* Each property is mapped to a Set or List of DeclarationValues.
* For layered (comma-separated) properties (such as background),
* a layer number is also assigned to each property so we can understand the values
* belong to the property of which layer.
* For non-layered properties, the layer assigned to each property is one.
* We use {@link PropertyAndLayer} class for the keys to store the layer with the property name.
*/
protected final Map<PropertyAndLayer, Collection<DeclarationValue>> stylePropertyToDeclarationValueMap;
protected int numberOfMissingValues;
private static final Set<String> muliValuedProperties = new HashSet<>();
static {
initializeMultiValuedProperties();
}
public MultiValuedDeclaration(String propertyName, List<DeclarationValue> values, Selector belongsTo, boolean important, boolean addMissingValues, LocationInfo location) {
super(propertyName, belongsTo, important, location);
this.declarationValues = values;
this.stylePropertyToDeclarationValueMap = new HashMap<>();
this.isCommaSeparatedListOfValues = isCommaSeparated(property);
if (addMissingValues)
addMissingValues();
}
private static void initializeMultiValuedProperties() {
String[] properties = new String[] {
"background-position",
"background-size",
"border-top-left-radius",
"border-top-right-radius",
"border-bottom-right-radius",
"border-bottom-left-radius",
"transform-origin",
"transition-property",
"transform",
"perspective-origin",
"border-spacing",
"text-shadow",
"box-shadow",
"content",
"font-family",
"quotes"
};
for (String property : properties)
muliValuedProperties.add(property);
}
/**
* Gets a property name (as String) and
* determines whether the property can have a list of
* comma-separated values (like CSS3 background, font, etc.)
* @param property
* @return
*/
public static boolean isCommaSeparated(String property) {
switch (property) {
case "font-family":
case "font":
case "background":
case "background-clip":
case "background-origin":
case "background-position":
case "background-image":
case "background-repeat":
case "background-attachment":
case "box-shadow":
case "text-shadow":
case "transition":
case "transition-delay":
case "transition-duration":
case "transition-property":
case "transition-timing-function":
case "overflow-style":
case "animation":
case "src": // for @font-face
return true;
}
return false;
}
public static boolean isMultiValuedProperty(String propertyName) {
return muliValuedProperties.contains(getNonVendorProperty(getNonHackedProperty(propertyName)));
}
/**
* This method adds missing values to the different properties
* which can have more than one value (like background-position).
*/
protected void addMissingValues() {
// Only multi-valued and non-shorthand declarations are handled here.
// Shorthands are handled in ShorthandDeclaration class
if (declarationValues == null || declarationValues.size() == 0)
return;
switch (getNonVendorProperty(getNonHackedProperty(property))) {
case "background-position": {
//http://www.w3.org/TR/css3-background/#the-background-position
final String BACKGROUND_POSITION_LEFT = "background-position-left";
final String BACKGROUND_POSITION_TOP = "background-position-top";
DeclarationValue firstValue = declarationValues.get(0);
DeclarationValue secondValue = null;
// TODO add four-valued background-position
if (declarationValues.size() == 1) {
if ("inherit".equals(firstValue.getValue())) {
break;
} else {
if (firstValue.isKeyword()) {
secondValue = new DeclarationEquivalentValue("center", "50%", ValueType.LENGTH);
}
else {
secondValue = new DeclarationEquivalentValue("50%", "50%", ValueType.LENGTH);
}
addMissingValue(secondValue, 1);
}
} else {
secondValue = declarationValues.get(1);
}
if ("top".equals(firstValue.getValue()) || "bottom".equals(firstValue.getValue()) ||
"left".equals(secondValue.getValue()) || "right".equals(secondValue.getValue())) {
assignStylePropertyToValue(BACKGROUND_POSITION_TOP, firstValue);
assignStylePropertyToValue(BACKGROUND_POSITION_LEFT, secondValue);
} else {
assignStylePropertyToValue(BACKGROUND_POSITION_LEFT, firstValue);
assignStylePropertyToValue(BACKGROUND_POSITION_TOP, secondValue);
}
break;
}
case "background-size": {
//http://www.w3.org/TR/css3-background/#the-background-size
final String BOTH = "background-size-both";
final String WIDTH = "background-size-width";
final String HEIGHT = "background-size-height";
DeclarationValue firstValue = declarationValues.get(0);
assignStylePropertyToValue(WIDTH, firstValue);
DeclarationValue secondValue = null;
if (declarationValues.size() == 1) {
String val = firstValue.getValue();
if (!("cover".equals(val) || "contain".equals(val) || "inherit".equals(val))) {
secondValue = new DeclarationValue("auto", ValueType.LENGTH);
assignStylePropertyToValue(HEIGHT, secondValue);
addMissingValue(secondValue, 1);
} else {
assignStylePropertyToValue(BOTH, firstValue);
// There if no second value
}
} else {
secondValue = declarationValues.get(1);
assignStylePropertyToValue(HEIGHT, secondValue);
}
break;
}
case "border-top-left-radius":
case "border-top-right-radius":
case "border-bottom-right-radius":
case "border-bottom-left-radius": {
final String HRADIUS = "horizontal-radius";
final String VRADIUS = "vertical-radius";
DeclarationValue firstValue = declarationValues.get(0);
DeclarationValue secondValue = null;
if (declarationValues.size() == 1) {
String val = firstValue.getValue();
secondValue = new DeclarationValue(val, ValueType.LENGTH);
addMissingValue(secondValue, 1);
} else {
secondValue = declarationValues.get(1);
}
assignStylePropertyToValue(HRADIUS, firstValue);
assignStylePropertyToValue(VRADIUS, secondValue);
break;
}
case "transform" : {
String TRANSFORM = "transform";
for (DeclarationValue value : declarationValues) {
if (value.getType() != ValueType.SEPARATOR)
assignStylePropertyToValue(TRANSFORM, value, true);
}
break;
}
case "transform-origin": {
final String XAXIS = "x-axis";
final String YAXIS = "y-axis";
final String ZAXIS = "z-axis";
if (declarationValues.size() == 1) {
addMissingValue(new DeclarationEquivalentValue("center", "50%", ValueType.LENGTH), 1);
addMissingValue(new DeclarationEquivalentValue("0", "0px", ValueType.LENGTH), 2);
} else if (declarationValues.size() == 2) {
addMissingValue(new DeclarationEquivalentValue("0", "0px", ValueType.LENGTH), 2);
}
assignStylePropertyToValue(XAXIS, declarationValues.get(0));
assignStylePropertyToValue(YAXIS, declarationValues.get(1));
assignStylePropertyToValue(ZAXIS, declarationValues.get(2));
break;
}
case "perspective-origin": {
final String XAXIS = "x-axis";
final String YAXIS = "y-axis";
if (declarationValues.size() == 1)
addMissingValue(new DeclarationEquivalentValue("center", "50%", ValueType.LENGTH), 1);
assignStylePropertyToValue(XAXIS, declarationValues.get(0));
assignStylePropertyToValue(YAXIS, declarationValues.get(1));
break;
}
case "border-spacing": {
final String HSPACING = "h-spacing";
final String VSPACING = "v-spacing";
if (declarationValues.size() == 1)
addMissingValue(declarationValues.get(0).clone(), 1);
assignStylePropertyToValue(HSPACING, declarationValues.get(0));
assignStylePropertyToValue(VSPACING, declarationValues.get(1));
break;
}
case "text-shadow":
case "box-shadow": {
List<DeclarationValue> allValues = new ArrayList<>(declarationValues);
DeclarationValue sentinel = new DeclarationValue(",", ValueType.SEPARATOR);
allValues.add(sentinel);
int currentLayerStartIndex = 0;
int totalAddedMissingValues = 0;
int currentLayerIndex = 0;
for (int currentValueIndex = 0; currentValueIndex < allValues.size(); currentValueIndex++) {
DeclarationValue currentValue = allValues.get(currentValueIndex);
// Find the first separator. Sentinel is used here :)
if (currentValue.getType() == ValueType.SEPARATOR && ",".equals(currentValue.getValue())) {
currentLayerIndex++;
DeclarationValue inset = null,
hOffset = null,
vOffset = null,
blurRadius = null,
spreadDistance = null,
color = null;
int numberOfLengths = 0;
// Count from current layer's start index to this separator
for (int currentLayerValueIndex = currentLayerStartIndex; currentLayerValueIndex < currentValueIndex; currentLayerValueIndex++) {
DeclarationValue currentLayerCurrentValue = allValues.get(currentLayerValueIndex);
switch (currentLayerCurrentValue.getType()) {
case COLOR:
color = currentLayerCurrentValue;
break;
case IDENT:
if ("inset".equals(currentLayerCurrentValue.getValue()))
inset = currentLayerCurrentValue;
else if ("none".equals(currentLayerCurrentValue.getValue()))
return;
break;
case LENGTH:
numberOfLengths++;
switch (numberOfLengths) {
case 1:
hOffset = currentLayerCurrentValue;
break;
case 2:
vOffset = currentLayerCurrentValue;
break;
case 3:
blurRadius = currentLayerCurrentValue;
break;
case 4:
spreadDistance = currentLayerCurrentValue;
}
default:
}
}
int missingValueOffset = totalAddedMissingValues;
int vOffsetPosition = 1, blurPosition = 2, distancePosition = 3, colorPosition = 3;
if ("box-shadow".equals(getNonVendorProperty(getNonHackedProperty(property)))) {
colorPosition++;
if (inset != null) {
vOffsetPosition++;
colorPosition++;
blurPosition++;
distancePosition++;
}
}
if (vOffset == null) {
vOffset = new DeclarationEquivalentValue("0", "0px", ValueType.LENGTH);
addMissingValue(vOffset, vOffsetPosition);
totalAddedMissingValues++;
}
if (blurRadius == null) {
blurRadius = new DeclarationEquivalentValue("0", "0px", ValueType.LENGTH);
addMissingValue(blurRadius, blurPosition);
totalAddedMissingValues++;
}
if ("box-shadow".equals(property) && spreadDistance == null) {
spreadDistance = new DeclarationEquivalentValue("0", "0px", ValueType.LENGTH);
addMissingValue(spreadDistance, distancePosition);
totalAddedMissingValues++;
}
if (color == null) {
color = new DeclarationValue("currentColor", ValueType.COLOR);
addMissingValue(color, currentLayerStartIndex + missingValueOffset + colorPosition);
totalAddedMissingValues++;
}
currentLayerStartIndex = currentValueIndex + 1;
final String COLOR = "color";
final String HOFFSET = "hoffset";
final String VOFFSET = "voffset";
final String BLUR = "blur";
final String SPREAD = "spread";
final String INSET = "inset";
assignStylePropertyToValue(COLOR, currentLayerIndex, color, false);
assignStylePropertyToValue(HOFFSET, currentLayerIndex, hOffset, false);
assignStylePropertyToValue(VOFFSET, currentLayerIndex, vOffset, false);
assignStylePropertyToValue(BLUR, currentLayerIndex, blurRadius, false);
if ("box-shadow".equals(property)) {
assignStylePropertyToValue(SPREAD, currentLayerIndex, spreadDistance, false);
if (inset != null)
assignStylePropertyToValue(INSET, currentLayerIndex, inset, false);
}
}
}
break;
}
case "content": {
for (DeclarationValue value : declarationValues) {
if (value.getType() != ValueType.SEPARATOR)
assignStylePropertyToValue("content", 1, value, true);
}
break;
}
case "font-family": {
for (DeclarationValue value : declarationValues) {
if (value.getType() != ValueType.SEPARATOR)
assignStylePropertyToValue("font-family", 1, value, true);
}
break;
}
case "transition-property": {
for (DeclarationValue value : declarationValues) {
if (value.getType() != ValueType.SEPARATOR)
assignStylePropertyToValue("transition-property", 1, value, false);
}
break;
}
case "quotes": {
final String LEFTQ = "leftq";
final String RIGHTQ = "rightq";
if (declarationValues.size() == 1 && "none".equals(declarationValues.get(0).getValue())) {
assignStylePropertyToValue(LEFTQ, 1, declarationValues.get(0), true);
assignStylePropertyToValue(RIGHTQ, 1, declarationValues.get(0), true);
} else if (declarationValues.size() % 2 == 0) {
for (int i = 0; i < declarationValues.size(); i += 2) {
assignStylePropertyToValue(LEFTQ, (i / 2) + 1, declarationValues.get(i), true);
assignStylePropertyToValue(RIGHTQ, (i / 2) + 1, declarationValues.get(i + 1), true);
}
}
else {
throw new RuntimeException("'quotes' property should have even number of variables");
}
break;
}
default:
throw new NotImplementedException("Multivalued property " + property + " not handled.");
}
}
/**
* Maps a styleProperty to a value.
* For instance, in <code>margin: 2px</code>,
* this function is called so margin-left, -right, -bottom and -top all map to the value of 2px.
* If this method is called for the first time, it adds the new value to a Set mapped to the given styleProperty.
* If the styleProperty already exists (i.e., the method has already been called),
* it adds the new value to the existing underlying collection (either a List or Set, based on the previous call to
* this method or its overload).
* @param styleProperty
* @param value
*/
protected void assignStylePropertyToValue(String styleProperty, DeclarationValue value) {
assignStylePropertyToValue(styleProperty, value, false);
}
/**
* Maps a styleProperty to a value.
* For instance, in <code>margin: 2px</code>,
* this function is called so margin-left, -right, -bottom and -top all map to the value of 2px.
* If this method is called for the first time, it adds the new value to a Set or List mapped to the given styleProperty,
* based on the value of orderImportant parameter (List => orderImportant == true, otherwise, Set).
* If this method is called not for the first time, it ignores the value for orderImportant and adds it to the
* existing underlying collection.
* @param styleProperty
* @param value
* @param orderImportant
*/
protected void assignStylePropertyToValue(String styleProperty, DeclarationValue value, boolean orderImportant) {
assignStylePropertyToValue(styleProperty, 1, value, orderImportant);
}
protected void assignStylePropertyToValue(String styleProperty, int layer, DeclarationValue value, boolean orderImportant) {
value.setCorrespondingStyleProperty(styleProperty, layer);
PropertyAndLayer propertyAndLayer = new PropertyAndLayer(styleProperty, layer);
Collection<DeclarationValue> values = stylePropertyToDeclarationValueMap.get(propertyAndLayer);
if (values == null) {
if (orderImportant)
values = new ArrayList<>();
else
values = new HashSet<>();
}
values.add(value);
stylePropertyToDeclarationValueMap.put(propertyAndLayer, values);
}
/**
* Adds a missing value (a value which is missing from the
* real declaration in the file, but is implied in the W3C
* recommendations.) <br />
* Note that it calls {@link DeclarationValue#setIsAMissingValue(true)}
* for given declaration.
* @param {@link DeclarationValue} to be added
* @param position The position in the value list to which
* this value should be added (zero based)
* @param
*/
public void addMissingValue(DeclarationValue value, int position) {
value.setIsAMissingValue(true);
numberOfMissingValues++;
declarationValues.add(position, value);
}
/**
* Returns the number of missing values this declaration have
* @return
*/
public int getNumberOfMissingValues() {
return numberOfMissingValues;
}
/**
* Returns a list of values for current declaration.
* This list also includes the values which are not in the
* real file, but are added later (missing values).
* @return
*/
public List<DeclarationValue> getValues() {
return declarationValues;
}
/**
* Only returns the real values for this declaration
* (not the missing values which were added later).
* @return
*/
public Iterable<DeclarationValue> getRealValues() {
List<DeclarationValue> realValues = new ArrayList<>();
for (DeclarationValue value : getValues()) {
if (!value.isAMissingValue())
realValues.add(value);
}
return realValues;
}
/**
* Only returns the missing values for this declaration
* which are added later
* @return
*/
public Iterable<DeclarationValue> getMissingValues() {
List<DeclarationValue> missingValues = new ArrayList<>();
for (DeclarationValue value : getValues()) {
if (value.isAMissingValue())
missingValues.add(value);
}
return missingValues;
}
/**
* Add a value to this declaration
* @param value
*/
public void addValue(DeclarationValue value) {
if (value.isAMissingValue())
numberOfMissingValues++;
declarationValues.add(value);
}
@Override
public String toString() {
String toReturn = getValuesString();
return String.format("%s: %s", property, toReturn);
}
/**
* Returns the string corresponding to the values
* @return
*/
protected String getValuesString() {
StringBuilder valueString = new StringBuilder("");
for (int i = 0; i < declarationValues.size(); i++) {
DeclarationValue v = declarationValues.get(i);
if (v.isAMissingValue())
continue;
boolean addSpace = true;
if (addSpace) {
// Find the next value which is not missing. If it is a comma, don't add space to get "a, b" style values.
int k = i;
while (++k < declarationValues.size()) {
DeclarationValue tv = declarationValues.get(k);
if (!tv.isAMissingValue()) {
addSpace = tv.getType() != ValueType.SEPARATOR;
break;
}
}
}
valueString.append(v + (addSpace ? " " : ""));
}
return valueString.toString().trim();
}
int hashCode = -1;
@Override
public int hashCode() {
// Only calculate the hashCode once
if (hashCode == -1) {
final int prime = 31;
int result = 1;
result = prime * result + locationInfo.hashCode();
result = prime
* result
+ ((declarationValues == null) ? 0 : declarationValues
.hashCode());
result = prime * result + (isCommaSeparatedListOfValues ? 1231 : 1237);
result = prime * result + (isImportant ? 1231 : 1237);
result = prime * result + numberOfMissingValues;
result = prime * result
+ ((parentSelector == null) ? 0 : parentSelector.hashCode());
result = prime * result
+ ((property == null) ? 0 : property.hashCode());
hashCode = result;
}
return hashCode;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MultiValuedDeclaration other = (MultiValuedDeclaration) obj;
if (isCommaSeparatedListOfValues != other.isCommaSeparatedListOfValues)
return false;
if (isImportant != other.isImportant)
return false;
if (numberOfMissingValues != other.numberOfMissingValues)
return false;
if (property == null) {
if (other.property != null)
return false;
} else if (!property.equals(other.property))
return false;
if (locationInfo == null) {
if (other.locationInfo != null)
return false;
} else if (!locationInfo.equals(other.locationInfo))
return false;
if (parentSelector == null) {
if (other.parentSelector != null)
return false;
} else if (!parentSelector.equals(other.parentSelector))
return false;
if (declarationValues == null) {
if (other.declarationValues != null)
return false;
} else if (!declarationValues.equals(other.declarationValues))
return false;
return true;
}
@Override
public Declaration clone() {
List<DeclarationValue> values = new ArrayList<>();
for (DeclarationValue v : declarationValues) {
values.add(v.clone());
}
//return DeclarationFactory.getDeclaration(property, values, parentSelector, offset, length, isImportant, false);
//return new Declaration(property, values, parentSelector, lineNumber, colNumber, isImportant, false);
return new MultiValuedDeclaration(property, values, parentSelector, isImportant, true, locationInfo);
}
@Override
protected boolean valuesEqual(Declaration otherDeclaration) {
if (!(otherDeclaration instanceof MultiValuedDeclaration))
throw new RuntimeException("This method cannot be called on a declaration rather than MultiValuedDeclaration.");
MultiValuedDeclaration otherMultiValuedDeclaration = (MultiValuedDeclaration)otherDeclaration;
if (((Collection<DeclarationValue>)otherMultiValuedDeclaration.getRealValues()).size() != ((Collection<DeclarationValue>)getRealValues()).size())
return false;
for (PropertyAndLayer propertyAndLayer : getAllSetPropertyAndLayers()) {
Collection<DeclarationValue> valuesForThisStyleProperty = getDeclarationValuesForStyleProperty(propertyAndLayer);
if (valuesForThisStyleProperty != null) {
if (!valuesForThisStyleProperty.equals(otherMultiValuedDeclaration.getDeclarationValuesForStyleProperty(propertyAndLayer)))
return false;
} else {
return false;
}
}
return true;
}
@Override
protected boolean valuesEquivalent(Declaration otherDeclaration) {
if (!(otherDeclaration instanceof MultiValuedDeclaration))
throw new RuntimeException("This method cannot be called on a declaration rather than MultiValuedDeclaration.");
MultiValuedDeclaration otherMultiValuedDeclaration = (MultiValuedDeclaration)otherDeclaration;
if (otherMultiValuedDeclaration.getValues().size() != getValues().size())
return false;
for (PropertyAndLayer propertyAndLayer : getAllSetPropertyAndLayers()) {
Collection<DeclarationValue> valuesForThisStyleProperty = getDeclarationValuesForStyleProperty(propertyAndLayer);
Collection<DeclarationValue> valuesForOtherStyleProperty = otherMultiValuedDeclaration.getDeclarationValuesForStyleProperty(propertyAndLayer);
if (valuesForThisStyleProperty != null && valuesForOtherStyleProperty != null) {
if (valuesForThisStyleProperty.size() != valuesForOtherStyleProperty.size())
return false;
/*
* If the underlying object is a List, we have to take care of the order.
* Otherwise, order is not important.
*/
if (valuesForThisStyleProperty instanceof List && valuesForOtherStyleProperty instanceof List) {
List<DeclarationValue> values1List = (List<DeclarationValue>)valuesForThisStyleProperty;
List<DeclarationValue> values2List = (List<DeclarationValue>)valuesForOtherStyleProperty;
for (int i = 0; i < valuesForOtherStyleProperty.size(); i++) {
if (!values1List.get(i).equivalent(values2List.get(i)))
return false;
}
} else { // Order is not important
List<DeclarationValue> values1List = new ArrayList<>(valuesForThisStyleProperty);
List<DeclarationValue> values2List = new ArrayList<>(valuesForOtherStyleProperty);
Set<Integer> checkedValues = new HashSet<>();
for (int i = 0; i < values1List.size(); i++) {
boolean foundEquivalent = false;
for (int j = 0; j < values2List.size(); j++) {
// Check if we have not already mapped this value to another one
if (checkedValues.contains(j))
continue;
// Are the values are equivalent
if (values1List.get(i).equivalent(values2List.get(j))) {
foundEquivalent = true;
checkedValues.add(j);
break;
}
}
if (!foundEquivalent)
return false;
}
if (checkedValues.size() != values1List.size())
return false;
}
} else {
return false;
}
}
return true;
}
/**
* Returns all the style properties possible for the values of this multi-valued declaration
* @return
*/
@Override
public Collection<String> getStyleProperties() {
Set<String> toReturn = new HashSet<>();
for (PropertyAndLayer propertyAndLayer : getAllSetPropertyAndLayers())
toReturn.add(propertyAndLayer.getPropertyName());
return toReturn;
}
/**
* Returns a Collection of DeclarationValue's for the given property.
* For the multi-valued properties, it returns the values corresponding to the first layer.
* Returns null if such a DeclarationValue is not found.
* @param styleProperty
* @return
*/
public Collection<DeclarationValue> getDeclarationValuesForStyleProperty(String styleProperty) {
return getDeclarationValuesForStyleProperty(styleProperty, 1);
}
/**
* Returns a Collection of DeclarationValue's for the given property, in the given layer.
* Returns null if such a DeclarationValue is not found.
* @param styleProperty
* @return
*/
@Override
public Collection<DeclarationValue> getDeclarationValuesForStyleProperty(String styleProperty, int forLayer) {
return stylePropertyToDeclarationValueMap.get(new PropertyAndLayer(styleProperty, forLayer));
}
@Override
public Map<String, List<Collection<DeclarationValue>>> getPropertyToValuesMap() {
Map<String, List<Collection<DeclarationValue>>> toReturn = new HashMap<>();
for (PropertyAndLayer propertyAndLayer : getAllSetPropertyAndLayers()) {
Collection<DeclarationValue> values = getDeclarationValuesForStyleProperty(propertyAndLayer);
List<Collection<DeclarationValue>> declarationValues = toReturn.get(propertyAndLayer.getPropertyName());
if (declarationValues == null) {
declarationValues = new ArrayList<Collection<DeclarationValue>>();
toReturn.put(propertyAndLayer.getPropertyName(), declarationValues);
}
declarationValues.set(propertyAndLayer.getPropertyLayer() - 1, values);
}
return toReturn;
}
protected Map<Integer, List<PropertyAndLayer>> getLayerToPropertyAndLayerMap() {
Map<Integer, List<PropertyAndLayer>> layerToPropertyMapper = new HashMap<>();
for (PropertyAndLayer propertyAndLayer : getAllSetPropertyAndLayers()) {
List<PropertyAndLayer> currentList = layerToPropertyMapper.get(propertyAndLayer.getPropertyLayer());
if (currentList == null) {
currentList = new ArrayList<>();
layerToPropertyMapper.put(propertyAndLayer.getPropertyLayer(), currentList);
}
currentList.add(propertyAndLayer);
}
return layerToPropertyMapper;
}
@Override
public Iterable<DeclarationValue> getDeclarationValues() {
return declarationValues;
}
@Override
public int getNumberOfValueLayers() {
Set<Integer> layer = new HashSet<>();
for (PropertyAndLayer propertyAndLayer : getAllSetPropertyAndLayers()) {
if (propertyAndLayer.getPropertyLayer() > -1)
layer.add(propertyAndLayer.getPropertyLayer());
}
return layer.size();
}
@Override
public Set<PropertyAndLayer> getAllSetPropertyAndLayers() {
Set<PropertyAndLayer> allSetPropertyAndLayers = new HashSet<>();
for (DeclarationValue value : declarationValues) {
if (value.getCorrespondingStyleProperty() != null)
allSetPropertyAndLayers.add(new PropertyAndLayer(value.getCorrespondingStyleProperty(), value.getCorrespondingStyleLayer()));
}
return allSetPropertyAndLayers;
}
}
|
package ch.unizh.ini.jaer.projects.davis.calibration;
import static org.bytedeco.javacpp.opencv_core.CV_32FC2;
import static org.bytedeco.javacpp.opencv_core.CV_64FC3;
import static org.bytedeco.javacpp.opencv_core.CV_8U;
import static org.bytedeco.javacpp.opencv_core.CV_8UC3;
import static org.bytedeco.javacpp.opencv_core.CV_TERMCRIT_EPS;
import static org.bytedeco.javacpp.opencv_core.CV_TERMCRIT_ITER;
import static org.bytedeco.javacpp.opencv_imgproc.CV_GRAY2RGB;
import static org.bytedeco.javacpp.opencv_imgproc.cvtColor;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.geom.Point2D;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import java.util.logging.Level;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import org.bytedeco.javacpp.FloatPointer;
import org.bytedeco.javacpp.opencv_calib3d;
import org.bytedeco.javacpp.opencv_core;
import org.bytedeco.javacpp.opencv_core.Mat;
import org.bytedeco.javacpp.opencv_core.MatVector;
import org.bytedeco.javacpp.opencv_core.Size;
import org.bytedeco.javacpp.opencv_imgproc;
import org.bytedeco.javacpp.indexer.DoubleBufferIndexer;
import org.bytedeco.javacpp.indexer.DoubleIndexer;
import org.openni.Device;
import org.openni.DeviceInfo;
import org.openni.OpenNI;
import com.jogamp.opengl.GL;
import com.jogamp.opengl.GL2;
import com.jogamp.opengl.GLAutoDrawable;
import ch.unizh.ini.jaer.projects.davis.frames.ApsFrameExtractor;
import ch.unizh.ini.jaer.projects.davis.stereo.SimpleDepthCameraViewerApplication;
import net.sf.jaer.Description;
import net.sf.jaer.DevelopmentStatus;
import net.sf.jaer.chip.AEChip;
import net.sf.jaer.event.ApsDvsEvent;
import net.sf.jaer.event.ApsDvsEventPacket;
import net.sf.jaer.event.BasicEvent;
import net.sf.jaer.event.EventPacket;
import net.sf.jaer.eventprocessing.EventFilter2D;
import net.sf.jaer.eventprocessing.FilterChain;
import net.sf.jaer.graphics.FrameAnnotater;
import net.sf.jaer.graphics.MultilineAnnotationTextRenderer;
import net.sf.jaer.util.TextRendererScale;
/**
* Calibrates a single camera using DAVIS frames and OpenCV calibration methods.
*
* @author Marc Osswald, Tobi Delbruck
*/
@Description("Calibrates a single camera using DAVIS frames and OpenCV calibration methods")
@DevelopmentStatus(DevelopmentStatus.Status.Experimental)
public class SingleCameraCalibration extends EventFilter2D implements FrameAnnotater, Observer /* observes this to get informed about our size */ {
private int sx; // set to chip.getSizeX()
private int sy; // chip.getSizeY()
private int lastTimestamp = 0;
private float[] lastFrame = null, outFrame = null;
/**
* Fires property change with this string when new calibration is available
*/
public static final String EVENT_NEW_CALIBRATION = "EVENT_NEW_CALIBRATION";
private SimpleDepthCameraViewerApplication depthViewerThread;
//encapsulated fields
private boolean realtimePatternDetectionEnabled = getBoolean("realtimePatternDetectionEnabled", true);
private boolean cornerSubPixRefinement = getBoolean("cornerSubPixRefinement", true);
private String dirPath = getString("dirPath", System.getProperty("user.dir"));
private int patternWidth = getInt("patternWidth", 9);
private int patternHeight = getInt("patternHeight", 5);
private int rectangleHeightMm = getInt("rectangleHeightMm", 20); //height in mm
private int rectangleWidthMm = getInt("rectangleWidthMm", 20); //width in mm
private boolean showUndistortedFrames = getBoolean("showUndistortedFrames", false);
private boolean undistortDVSevents = getBoolean("undistortDVSevents", false);
private boolean takeImageOnTimestampReset = getBoolean("takeImageOnTimestampReset", false);
private String fileBaseName = "";
//opencv matrices
private Mat corners;
private MatVector allImagePoints;
private MatVector allObjectPoints;
private Mat cameraMatrix;
private Mat distortionCoefs;
private MatVector rotationVectors;
private MatVector translationVectors;
private Mat imgIn, imgOut;
private short[] undistortedAddressLUT = null; // stores undistortion LUT for event addresses. values are stored by idx = 2 * (y + sy * x);
private boolean isUndistortedAddressLUTgenerated = false;
private float focalLengthPixels = 0;
private float focalLengthMm = 0;
private Point2D.Float principlePoint = null;
private String calibrationString = "Uncalibrated";
private boolean patternFound;
private int imageCounter = 0;
private boolean calibrated = false;
private boolean actionTriggered = false;
private int nAcqFrames = 0;
private int nMaxAcqFrames = 1;
private final ApsFrameExtractor frameExtractor;
private final FilterChain filterChain;
private boolean saved = false;
private boolean textRendererScaleSet = false;
private float textRendererScale = 0.3f;
public SingleCameraCalibration(AEChip chip) {
super(chip);
chip.addObserver(this);
frameExtractor = new ApsFrameExtractor(chip);
filterChain = new FilterChain(chip);
filterChain.add(frameExtractor);
frameExtractor.setExtRender(false);
setEnclosedFilterChain(filterChain);
resetFilter();
setPropertyTooltip("patternHeight", "height of chessboard calibration pattern in internal corner intersections, i.e. one less than number of squares");
setPropertyTooltip("patternWidth", "width of chessboard calibration pattern in internal corner intersections, i.e. one less than number of squares");
setPropertyTooltip("realtimePatternDetectionEnabled", "width of checkerboard calibration pattern in internal corner intersections");
setPropertyTooltip("rectangleWidthMm", "width of square rectangles of calibration pattern in mm");
setPropertyTooltip("rectangleHeightMm", "height of square rectangles of calibration pattern in mm");
setPropertyTooltip("showUndistortedFrames", "shows the undistorted frame in the ApsFrameExtractor display, if calibration has been completed");
setPropertyTooltip("undistortDVSevents", "applies LUT undistortion to DVS event address if calibration has been completed; events outside AEChip address space are filtered out");
setPropertyTooltip("takeImageOnTimestampReset", "??");
setPropertyTooltip("cornerSubPixRefinement", "refine corner locations to subpixel resolution");
setPropertyTooltip("calibrate", "run the camera calibration on collected frame data and print results to console");
setPropertyTooltip("depthViewer", "shows the depth or color image viewer if a Kinect device is connected via NI2 interface");
setPropertyTooltip("setPath", "sets the folder and basename of saved images");
setPropertyTooltip("saveCalibration", "saves calibration files to a selected folder");
setPropertyTooltip("loadCalibration", "loads saved calibration files from selected folder");
setPropertyTooltip("clearCalibration", "clears existing calibration");
setPropertyTooltip("takeImage", "snaps a calibration image that forms part of the calibration dataset");
loadCalibration();
}
/**
* filters in to out. if filtering is enabled, the number of out may be less
* than the number putString in
*
* @param in input events can be null or empty.
* @return the processed events, may be fewer in number. filtering may occur
* in place in the in packet.
*/
@Override
synchronized public EventPacket filterPacket(EventPacket in) {
getEnclosedFilterChain().filterPacket(in);
// for each event only keep it if it is within dt of the last time
// an event happened in the direct neighborhood
Iterator itr = ((ApsDvsEventPacket) in).fullIterator();
while (itr.hasNext()) {
Object o = itr.next();
if (o == null) {
break; // this can occur if we are supplied packet that has data (eIn.g. APS samples) but no events
}
BasicEvent e = (BasicEvent) o;
// if (e.isSpecial()) {
// continue;
//trigger action (on ts reset)
if ((e.timestamp < lastTimestamp) && (e.timestamp < 100000) && takeImageOnTimestampReset) {
log.info("timestamp reset action trigggered");
actionTriggered = true;
nAcqFrames = 0;
}
//acquire new frame
if (frameExtractor.hasNewFrame()) {
lastFrame = frameExtractor.getNewFrame();
//process frame
if (realtimePatternDetectionEnabled) {
patternFound = findCurrentCorners(false);
}
//iterate
if (actionTriggered && (nAcqFrames < nMaxAcqFrames)) {
nAcqFrames++;
generateCalibrationString();
}
//take action
if (actionTriggered && (nAcqFrames == nMaxAcqFrames)) {
patternFound = findCurrentCorners(true);
//reset action
actionTriggered = false;
}
if (calibrated && showUndistortedFrames && frameExtractor.isShowAPSFrameDisplay()) {
float[] outFrame = undistortFrame(lastFrame);
frameExtractor.setDisplayFrameRGB(outFrame);
}
if (calibrated && showUndistortedFrames && frameExtractor.isShowAPSFrameDisplay()) {
frameExtractor.setExtRender(true); // to not alternate
frameExtractor.apsDisplay.setTitleLabel("lens correction enabled");
} else {
frameExtractor.setExtRender(false); // to not alternate
frameExtractor.apsDisplay.setTitleLabel("raw input image");
}
}
//store last timestamp
lastTimestamp = e.timestamp;
if (calibrated && undistortDVSevents && ((ApsDvsEvent) e).isDVSEvent()) {
undistortEvent(e);
}
}
return in;
}
/**
* Undistorts an image frame using the calibration.
*
* @param src the source image, RGB float valued in 0-1 range
* @return float[] destination. IAn internal float[] is created and reused.
* If there is no calibration, the src array is returned.
*/
public float[] undistortFrame(float[] src) {
if (!calibrated) {
return src;
}
FloatPointer ip = new FloatPointer(src);
Mat input = new Mat(ip);
input.convertTo(input, CV_8U, 255, 0);
Mat img = input.reshape(0, sy);
Mat undistortedImg = new Mat();
opencv_imgproc.undistort(img, undistortedImg, cameraMatrix, distortionCoefs);
Mat imgOut8u = new Mat(sy, sx, CV_8UC3);
cvtColor(undistortedImg, imgOut8u, CV_GRAY2RGB);
Mat outImgF = new Mat(sy, sx, opencv_core.CV_32F);
imgOut8u.convertTo(outImgF, opencv_core.CV_32F, 1.0 / 255, 0);
if (outFrame == null) {
outFrame = new float[sy * sx * 3];
}
outImgF.getFloatBuffer().get(outFrame);
return outFrame;
}
public boolean findCurrentCorners(boolean drawAndSave) {
Size patternSize = new Size(patternWidth, patternHeight);
corners = new Mat();
FloatPointer ip = new FloatPointer(lastFrame);
Mat input = new Mat(ip);
input.convertTo(input, CV_8U, 255, 0);
imgIn = input.reshape(0, sy);
imgOut = new Mat(sy, sx, CV_8UC3);
cvtColor(imgIn, imgOut, CV_GRAY2RGB);
//opencv_highgui.imshow("test", imgIn);
//opencv_highgui.waitKey(1);
boolean locPatternFound;
try {
locPatternFound = opencv_calib3d.findChessboardCorners(imgIn, patternSize, corners);
} catch (RuntimeException e) {
log.warning(e.toString());
return false;
}
if (drawAndSave) {
//render frame
if (locPatternFound && cornerSubPixRefinement) {
opencv_core.TermCriteria tc = new opencv_core.TermCriteria(CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 30, 0.1);
opencv_imgproc.cornerSubPix(imgIn, corners, new Size(3, 3), new Size(-1, -1), tc);
}
opencv_calib3d.drawChessboardCorners(imgOut, patternSize, corners, locPatternFound);
Mat outImgF = new Mat(sy, sx, CV_64FC3);
imgOut.convertTo(outImgF, CV_64FC3, 1.0 / 255, 0);
float[] outFrame = new float[sy * sx * 3];
outImgF.getFloatBuffer().get(outFrame);
frameExtractor.setDisplayFrameRGB(outFrame);
//save image
if (locPatternFound) {
Mat imgSave = new Mat(sy, sx, CV_8U);
opencv_core.flip(imgIn, imgSave, 0);
String filename = chip.getName() + "-" + fileBaseName + "-" + String.format("%03d", imageCounter) + ".jpg";
String fullFilePath = dirPath + "\\" + filename;
org.bytedeco.javacpp.opencv_imgcodecs.imwrite(fullFilePath, imgSave);
log.info("wrote " + fullFilePath);
//save depth sensor image if enabled
if (depthViewerThread != null) {
if (depthViewerThread.isFrameCaptureRunning()) {
//save img
String fileSuffix = "-" + String.format("%03d", imageCounter) + ".jpg";
depthViewerThread.saveLastImage(dirPath, fileSuffix);
}
}
//store image points
if (imageCounter == 0) {
allImagePoints = new MatVector(100);
allObjectPoints = new MatVector(100);
}
allImagePoints.put(imageCounter, corners);
//create and store object points, which are just coordinates in mm of corners of pattern as we know they are drawn on the
// calibration target
Mat objectPoints = new Mat(corners.rows(), 1, opencv_core.CV_32FC3);
float x, y;
for (int h = 0; h < patternHeight; h++) {
y = h * rectangleHeightMm;
for (int w = 0; w < patternWidth; w++) {
x = w * rectangleWidthMm;
objectPoints.getFloatBuffer().put(3 * ((patternWidth * h) + w), x);
objectPoints.getFloatBuffer().put((3 * ((patternWidth * h) + w)) + 1, y);
objectPoints.getFloatBuffer().put((3 * ((patternWidth * h) + w)) + 2, 0); // z=0 for object points
}
}
allObjectPoints.put(imageCounter, objectPoints);
//iterate image counter
log.info(String.format("added corner points from image %d", imageCounter));
imageCounter++;
frameExtractor.apsDisplay.setxLabel(filename);
// //debug
// System.out.println(allImagePoints.toString());
// for (int n = 0; n < imageCounter; n++) {
// System.out.println("n=" + n + " " + allImagePoints.get(n).toString());
// for (int i = 0; i < corners.rows(); i++) {
// System.out.println(allImagePoints.get(n).getFloatBuffer().get(2 * i) + " " + allImagePoints.get(n).getFloatBuffer().get(2 * i + 1)+" | "+allObjectPoints.get(n).getFloatBuffer().get(3 * i) + " " + allObjectPoints.get(n).getFloatBuffer().get(3 * i + 1) + " " + allObjectPoints.get(n).getFloatBuffer().get(3 * i + 2));
} else {
log.warning("corners not found for this image");
}
}
return locPatternFound;
}
@Override
public void annotate(GLAutoDrawable drawable) {
GL2 gl = drawable.getGL().getGL2();
if (patternFound && realtimePatternDetectionEnabled) {
int n = corners.rows();
int c = 3;
int w = patternWidth;
int h = patternHeight;
//log.info(corners.toString()+" rows="+n+" cols="+corners.cols());
//draw lines
gl.glLineWidth(2f);
gl.glColor3f(0, 0, 1);
//log.info("width="+w+" height="+h);
gl.glBegin(GL.GL_LINES);
for (int i = 0; i < h; i++) {
float y0 = corners.getFloatBuffer().get(2 * w * i);
float y1 = corners.getFloatBuffer().get((2 * w * (i + 1)) - 2);
float x0 = corners.getFloatBuffer().get((2 * w * i) + 1);
float x1 = corners.getFloatBuffer().get((2 * w * (i + 1)) - 1);
//log.info("i="+i+" x="+x+" y="+y);
gl.glVertex2f(y0, x0);
gl.glVertex2f(y1, x1);
}
for (int i = 0; i < w; i++) {
float y0 = corners.getFloatBuffer().get(2 * i);
float y1 = corners.getFloatBuffer().get(2 * ((w * (h - 1)) + i));
float x0 = corners.getFloatBuffer().get((2 * i) + 1);
float x1 = corners.getFloatBuffer().get((2 * ((w * (h - 1)) + i)) + 1);
//log.info("i="+i+" x="+x+" y="+y);
gl.glVertex2f(y0, x0);
gl.glVertex2f(y1, x1);
}
gl.glEnd();
//draw corners
gl.glLineWidth(2f);
gl.glColor3f(1, 1, 0);
gl.glBegin(GL.GL_LINES);
for (int i = 0; i < n; i++) {
float y = corners.getFloatBuffer().get(2 * i);
float x = corners.getFloatBuffer().get((2 * i) + 1);
//log.info("i="+i+" x="+x+" y="+y);
gl.glVertex2f(y, x - c);
gl.glVertex2f(y, x + c);
gl.glVertex2f(y - c, x);
gl.glVertex2f(y + c, x);
}
gl.glEnd();
}
if (principlePoint != null) {
gl.glLineWidth(3f);
gl.glColor3f(0, 1, 0);
gl.glBegin(GL.GL_LINES);
gl.glVertex2f(principlePoint.x - 4, principlePoint.y);
gl.glVertex2f(principlePoint.x + 4, principlePoint.y);
gl.glVertex2f(principlePoint.x, principlePoint.y - 4);
gl.glVertex2f(principlePoint.x, principlePoint.y + 4);
gl.glEnd();
}
if (calibrationString != null) {
// render once to set the scale using the same TextRenderer
MultilineAnnotationTextRenderer.resetToYPositionPixels(chip.getSizeY() * .15f);
MultilineAnnotationTextRenderer.setColor(Color.green);
MultilineAnnotationTextRenderer.setScale(textRendererScale);
MultilineAnnotationTextRenderer.renderMultilineString(calibrationString);
if (!textRendererScaleSet) {
textRendererScaleSet = true;
String[] lines = calibrationString.split("\n", 0);
int max = 0;
String longestString = null;
for (String s : lines) {
if (s.length() > max) {
max = s.length();
longestString = s;
}
}
textRendererScale = TextRendererScale.draw3dScale(MultilineAnnotationTextRenderer.getRenderer(), longestString, chip.getCanvas().getScale(), chip.getSizeX(), .8f);
}
}
}
@Override
public synchronized final void resetFilter() {
initFilter();
filterChain.reset();
patternFound = false;
imageCounter = 0;
principlePoint = null;
}
@Override
public final void initFilter() {
sx = chip.getSizeX();
sy = chip.getSizeY();
}
/**
* @return the realtimePatternDetectionEnabled
*/
public boolean isRealtimePatternDetectionEnabled() {
return realtimePatternDetectionEnabled;
}
/**
* @param realtimePatternDetectionEnabled the
* realtimePatternDetectionEnabled to set
*/
public void setRealtimePatternDetectionEnabled(boolean realtimePatternDetectionEnabled) {
this.realtimePatternDetectionEnabled = realtimePatternDetectionEnabled;
putBoolean("realtimePatternDetectionEnabled", realtimePatternDetectionEnabled);
}
/**
* @return the cornerSubPixRefinement
*/
public boolean isCornerSubPixRefinement() {
return cornerSubPixRefinement;
}
/**
* @param cornerSubPixRefinement the cornerSubPixRefinement to set
*/
public void setCornerSubPixRefinement(boolean cornerSubPixRefinement) {
this.cornerSubPixRefinement = cornerSubPixRefinement;
}
synchronized public void doSetPath() {
JFileChooser j = new JFileChooser();
j.setCurrentDirectory(new File(dirPath));
j.setApproveButtonText("Select");
j.setDialogTitle("Select a folder and base file name for calibration images");
j.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); // let user specify a base filename
int ret = j.showSaveDialog(null);
if (ret != JFileChooser.APPROVE_OPTION) {
return;
}
//imagesDirPath = j.getSelectedFile().getAbsolutePath();
dirPath = j.getCurrentDirectory().getPath();
fileBaseName = j.getSelectedFile().getName();
if (!fileBaseName.isEmpty()) {
fileBaseName = "-" + fileBaseName;
}
log.log(Level.INFO, "Changed images path to {0}", dirPath);
putString("dirPath", dirPath);
}
synchronized public void doCalibrate() {
//init
Size imgSize = new Size(sx, sy);
cameraMatrix = new Mat();
distortionCoefs = new Mat();
rotationVectors = new MatVector();
translationVectors = new MatVector();
allImagePoints.resize(imageCounter);
allObjectPoints.resize(imageCounter); // resize has side effect that lists cannot hold any more data
log.info(String.format("calibrating based on %d images sized %d x %d", allObjectPoints.size(), imgSize.width(), imgSize.height()));
//calibrate
try {
opencv_calib3d.calibrateCamera(allObjectPoints, allImagePoints, imgSize, cameraMatrix, distortionCoefs, rotationVectors, translationVectors);
generateCalibrationString();
log.info("see http://docs.opencv.org/2.4/modules/calib3d/doc/camera_calibration_and_3d_reconstruction.html \n"
+ "\nCamera matrix: " + cameraMatrix.toString() + "\n" + printMatD(cameraMatrix)
+ "\nDistortion coefficients k_1 k_2 p_1 p_2 k_3 ...: " + distortionCoefs.toString() + "\n" + printMatD(distortionCoefs)
+ calibrationString);
} catch (RuntimeException e) {
log.warning("calibration failed with exception " + e + "See https://adventuresandwhathaveyou.wordpress.com/2014/03/14/opencv-error-messages-suck/");
} finally {
allImagePoints.resize(100);
allObjectPoints.resize(100);
}
calibrated = true;
getSupport().firePropertyChange(EVENT_NEW_CALIBRATION, null, this);
}
/**
* Generate a look-up table that maps the entire chip to undistorted
* addresses.
*
* @param sx chip size x
* @param sy chip size y
*/
public void generateUndistortedAddressLUT() {
if (!calibrated) {
return;
}
if ((sx == 0) || (sy == 0)) {
return; // not set yet
}
FloatPointer fp = new FloatPointer(2 * sx * sy);
int idx = 0;
for (int x = 0; x < sx; x++) {
for (int y = 0; y < sy; y++) {
fp.put(idx++, x);
fp.put(idx++, y);
}
}
Mat dst = new Mat();
Mat pixelArray = new Mat(1, sx * sy, CV_32FC2, fp); // make wide 2 channel matrix of source event x,y
opencv_imgproc.undistortPoints(pixelArray, dst, getCameraMatrix(), getDistortionCoefs());
isUndistortedAddressLUTgenerated = true;
// get the camera matrix elements (focal lengths and principal point)
DoubleIndexer k = getCameraMatrix().createIndexer();
float fx, fy, cx, cy;
fx = (float) k.get(0, 0);
fy = (float) k.get(1, 1);
cx = (float) k.get(0, 2);
cy = (float) k.get(1, 2);
undistortedAddressLUT = new short[2 * sx * sy];
for (int x = 0; x < sx; x++) {
for (int y = 0; y < sy; y++) {
idx = 2 * (y + (sy * x));
undistortedAddressLUT[idx] = (short) Math.round((dst.getFloatBuffer().get(idx) * fx) + cx);
undistortedAddressLUT[idx + 1] = (short) Math.round((dst.getFloatBuffer().get(idx + 1) * fy) + cy);
}
}
}
public boolean isUndistortedAddressLUTgenerated() {
return isUndistortedAddressLUTgenerated;
}
private void generateCalibrationString() {
if ((cameraMatrix == null) || cameraMatrix.isNull() || cameraMatrix.empty()) {
calibrationString = SINGLE_CAMERA_CALIBRATION_UNCALIBRATED;
calibrated = false;
return;
}
DoubleBufferIndexer cameraMatrixIndexer = cameraMatrix.createIndexer();
focalLengthPixels = (float) (cameraMatrixIndexer.get(0, 0) + cameraMatrixIndexer.get(0, 0)) / 2;
focalLengthMm = chip.getPixelWidthUm() * 1e-3f * focalLengthPixels;
principlePoint = new Point2D.Float((float) cameraMatrixIndexer.get(0, 2), (float) cameraMatrixIndexer.get(1, 2));
StringBuilder sb = new StringBuilder();
if (imageCounter > 0) {
sb.append(String.format("Using %d images", imageCounter));
if (!saved) {
sb.append("; not yet saved\n");
} else {
sb.append("; saved\n");
}
} else {
sb.append(String.format("Path:%s\n", shortenDirPath(dirPath)));
}
sb.append(String.format("focal length avg=%.1f pixels=%.2f mm\nPrincipal point (green cross)=%.1f,%.1f, Chip size/2=%d,%d\n",
focalLengthPixels, focalLengthMm,
principlePoint.x, principlePoint.y,
chip.getSizeX() / 2, chip.getSizeY() / 2));
calibrationString = sb.toString();
calibrated = true;
textRendererScaleSet=false;
}
private static final String SINGLE_CAMERA_CALIBRATION_UNCALIBRATED = "SingleCameraCalibration: uncalibrated";
public String shortenDirPath(String dirPath) {
String dirComp = dirPath;
if (dirPath.length() > 30) {
int n = dirPath.length();
dirComp = dirPath.substring(0, 10) + "..." + dirPath.substring(n - 20, n);
}
return dirComp;
}
synchronized public void doSaveCalibration() {
if (!calibrated) {
JOptionPane.showMessageDialog(null, "No calibration yet");
return;
}
JFileChooser j = new JFileChooser();
j.setCurrentDirectory(new File(dirPath));
j.setApproveButtonText("Select folder");
j.setDialogTitle("Select a folder to store calibration XML files");
j.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); // let user specify a base filename
int ret = j.showSaveDialog(null);
if (ret != JFileChooser.APPROVE_OPTION) {
return;
}
dirPath = j.getSelectedFile().getPath();
putString("dirPath", dirPath);
serializeMat(dirPath, "cameraMatrix", cameraMatrix);
serializeMat(dirPath, "distortionCoefs", distortionCoefs);
saved = true;
generateCalibrationString();
}
static void setButtonState(Container c, String buttonString, boolean flag) {
int len = c.getComponentCount();
for (int i = 0; i < len; i++) {
Component comp = c.getComponent(i);
if (comp instanceof JButton) {
JButton b = (JButton) comp;
if (buttonString.equals(b.getText())) {
b.setEnabled(flag);
}
} else if (comp instanceof Container) {
setButtonState((Container) comp, buttonString, flag);
}
}
}
synchronized public void doLoadCalibration() {
final JFileChooser j = new JFileChooser();
j.setCurrentDirectory(new File(dirPath));
j.setApproveButtonText("Select folder");
j.setDialogTitle("Select a folder that has XML files storing calibration");
j.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); // let user specify a base filename
j.setApproveButtonText("Select folder");
j.setApproveButtonToolTipText("Only enabled for a folder that has cameraMatrix.xml and distortionCoefs.xml");
setButtonState(j, j.getApproveButtonText(), calibrationExists(j.getCurrentDirectory().getPath()));
j.addPropertyChangeListener(JFileChooser.DIRECTORY_CHANGED_PROPERTY, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent pce) {
setButtonState(j, j.getApproveButtonText(), calibrationExists(j.getCurrentDirectory().getPath()));
}
});
int ret = j.showOpenDialog(null);
if (ret != JFileChooser.APPROVE_OPTION) {
return;
}
dirPath = j.getSelectedFile().getPath();
putString("dirPath", dirPath);
loadCalibration();
}
private boolean calibrationExists(String dirPath) {
String fn = dirPath + File.separator + "cameraMatrix" + ".xml";
File f = new File(fn);
boolean cameraMatrixExists = f.exists();
fn = dirPath + File.separator + "distortionCoefs" + ".xml";
f = new File(fn);
boolean distortionCoefsExists = f.exists();
if (distortionCoefsExists && cameraMatrixExists) {
return true;
} else {
return false;
}
}
synchronized public void doClearCalibration() {
calibrated = false;
calibrationString = SINGLE_CAMERA_CALIBRATION_UNCALIBRATED;
undistortedAddressLUT = null;
isUndistortedAddressLUTgenerated = false;
}
private void loadCalibration() {
try {
cameraMatrix = deserializeMat(dirPath, "cameraMatrix");
distortionCoefs = deserializeMat(dirPath, "distortionCoefs");
generateCalibrationString();
if (calibrated) {
log.info("Calibrated: loaded cameraMatrix and distortionCoefs from folder " + dirPath);
} else {
log.warning("Uncalibrated: Something was wrong with calibration files so that cameraMatrix or distortionCoefs could not be loaded");
}
getSupport().firePropertyChange(EVENT_NEW_CALIBRATION, null, this);
} catch (Exception i) {
log.warning("Could not load existing calibration from folder " + dirPath + " on construction:" + i.toString());
}
}
/**
* Writes an XML file for the matrix X called path/X.xml
*
* @param dir path to folder
* @param name base name of file
* @param sMat the Mat to write
*/
public void serializeMat(String dir, String name, opencv_core.Mat sMat) {
String fn = dir + File.separator + name + ".xml";
opencv_core.FileStorage storage = new opencv_core.FileStorage(fn, opencv_core.FileStorage.WRITE);
opencv_core.write(storage, name, sMat);
storage.release();
log.info("saved in " + fn);
}
public opencv_core.Mat deserializeMat(String dir, String name) {
String fn = dirPath + File.separator + name + ".xml";
opencv_core.Mat mat = new opencv_core.Mat();
opencv_core.FileStorage storage = new opencv_core.FileStorage(fn, opencv_core.FileStorage.READ);
opencv_core.read(storage.get(name), mat);
storage.release();
if (mat.empty()) {
return null;
}
return mat;
}
synchronized public void doTakeImage() {
actionTriggered = true;
nAcqFrames = 0;
saved = false;
}
private String printMatD(Mat M) {
StringBuilder sb = new StringBuilder();
int c = 0;
for (int i = 0; i < M.rows(); i++) {
for (int j = 0; j < M.cols(); j++) {
sb.append(String.format("%10.5f\t", M.getDoubleBuffer().get(c)));
c++;
}
sb.append("\n");
}
return sb.toString();
}
/**
* @return the patternWidth
*/
public int getPatternWidth() {
return patternWidth;
}
/**
* @param patternWidth the patternWidth to set
*/
public void setPatternWidth(int patternWidth) {
this.patternWidth = patternWidth;
putInt("patternWidth", patternWidth);
}
/**
* @return the patternHeight
*/
public int getPatternHeight() {
return patternHeight;
}
/**
* @param patternHeight the patternHeight to set
*/
public void setPatternHeight(int patternHeight) {
this.patternHeight = patternHeight;
putInt("patternHeight", patternHeight);
}
/**
* @return the rectangleHeightMm
*/
public int getRectangleHeightMm() {
return rectangleHeightMm;
}
/**
* @param rectangleHeightMm the rectangleHeightMm to set
*/
public void setRectangleHeightMm(int rectangleHeightMm) {
this.rectangleHeightMm = rectangleHeightMm;
putInt("rectangleHeightMm", rectangleHeightMm);
}
/**
* @return the rectangleHeightMm
*/
public int getRectangleWidthMm() {
return rectangleWidthMm;
}
/**
* @param rectangleWidthMm the rectangleWidthMm to set
*/
public void setRectangleWidthMm(int rectangleWidthMm) {
this.rectangleWidthMm = rectangleWidthMm;
putInt("rectangleWidthMm", rectangleWidthMm);
}
/**
* @return the showUndistortedFrames
*/
public boolean isShowUndistortedFrames() {
return showUndistortedFrames;
}
/**
* @param showUndistortedFrames the showUndistortedFrames to set
*/
public void setShowUndistortedFrames(boolean showUndistortedFrames) {
this.showUndistortedFrames = showUndistortedFrames;
putBoolean("showUndistortedFrames", showUndistortedFrames);
}
/**
* @return the takeImageOnTimestampReset
*/
public boolean isTakeImageOnTimestampReset() {
return takeImageOnTimestampReset;
}
/**
* @param takeImageOnTimestampReset the takeImageOnTimestampReset to set
*/
public void setTakeImageOnTimestampReset(boolean takeImageOnTimestampReset) {
this.takeImageOnTimestampReset = takeImageOnTimestampReset;
putBoolean("takeImageOnTimestampReset", takeImageOnTimestampReset);
}
public void doDepthViewer() {
try {
System.load(System.getProperty("user.dir") + "\\jars\\openni2\\OpenNI2.dll");
// initialize OpenNI
OpenNI.initialize();
List<DeviceInfo> devicesInfo = OpenNI.enumerateDevices();
if (devicesInfo.isEmpty()) {
JOptionPane.showMessageDialog(null, "No Kinect device is connected via NI2 interface", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
Device device = Device.open(devicesInfo.get(0).getUri());
depthViewerThread = new SimpleDepthCameraViewerApplication(device);
depthViewerThread.start();
} catch (Exception e) {
e.printStackTrace();
}
}
public Mat getCameraMatrix() {
return cameraMatrix;
}
public Mat getDistortionCoefs() {
return distortionCoefs;
}
/**
* Human friendly summary of calibration
*
* @return the calibrationString
*/
public String getCalibrationString() {
return calibrationString;
}
/**
*
* @return true if calibration was completed successfully
*/
public boolean isCalibrated() {
return calibrated;
}
/**
* @return the look-up table of undistorted pixel addresses. The index i is
* obtained by iterating column-wise over the pixel array (y-loop is inner
* loop) until getting to (x,y). Have to multiply by two because both x and
* y addresses are stored consecutively. Thus, i = 2 * (y + sizeY * x)
*/
private short[] getUndistortedAddressLUT() {
return undistortedAddressLUT;
}
/**
* @return the undistorted pixel address. The input index i is obtained by
* iterating column-wise over the pixel array (y-loop is inner loop) until
* getting to (x,y). Have to multiply by two because both x and y addresses
* are stored consecutively. Thus, i = 2 * (y + sizeY * x)
*/
private short getUndistortedAddressFromLUT(int i) {
return undistortedAddressLUT[i];
}
/**
* Transforms an event to undistorted address, using the LUT computed from
* calibration
*
* @param e input event. The address x and y are modified to the unmodified
* address. If the address falls outside the Chip boundaries, the event is
* filtered out.
* @return true if the transformation succeeds within chip boundaries, false
* if the event has been filtered out.
*/
public boolean undistortEvent(BasicEvent e) {
if (undistortedAddressLUT == null) {
generateUndistortedAddressLUT();
}
int uidx = 2 * (e.y + (sy * e.x));
e.x = getUndistortedAddressFromLUT(uidx);
e.y = getUndistortedAddressFromLUT(uidx + 1);
if (xeob(e.x) || yeob(e.y)) {
e.setFilteredOut(true);
return false;
}
return true;
}
private boolean xeob(int x) {
if ((x < 0) || (x > (sx - 1))) {
return true;
}
return false;
}
private boolean yeob(int y) {
if ((y < 0) || (y > (sy - 1))) {
return true;
}
return false;
}
/**
* @return the undistortDVSevents
*/
public boolean isUndistortDVSevents() {
return undistortDVSevents;
}
/**
* @param undistortDVSevents the undistortDVSevents to set
*/
public void setUndistortDVSevents(boolean undistortDVSevents) {
this.undistortDVSevents = undistortDVSevents;
}
@Override
public void update(Observable o, Object o1) {
if (o instanceof AEChip) {
if (chip.getNumPixels() > 0) {
sx = chip.getSizeX();
sy = chip.getSizeY(); // might not yet have been set in constructor
}
}
}
}
|
package net.sourceforge.clonekeenplus;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;
import javax.microedition.khronos.opengles.GL11Ext;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGL11;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLContext;
import javax.microedition.khronos.egl.EGLDisplay;
import javax.microedition.khronos.egl.EGLSurface;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.KeyEvent;
import android.view.InputDevice;
import android.view.Window;
import android.view.WindowManager;
import android.os.Environment;
import java.io.File;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.content.res.Resources;
import android.content.res.AssetManager;
import android.widget.Toast;
import android.util.Log;
import android.widget.TextView;
import java.lang.Thread;
import java.util.concurrent.locks.ReentrantLock;
import android.os.Build;
import java.lang.reflect.Method;
import java.util.LinkedList;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
class Mouse
{
public static final int LEFT_CLICK_NORMAL = 0;
public static final int LEFT_CLICK_NEAR_CURSOR = 1;
public static final int LEFT_CLICK_WITH_MULTITOUCH = 2;
public static final int LEFT_CLICK_WITH_PRESSURE = 3;
public static final int LEFT_CLICK_WITH_KEY = 4;
public static final int LEFT_CLICK_WITH_TIMEOUT = 5;
public static final int LEFT_CLICK_WITH_TAP = 6;
public static final int LEFT_CLICK_WITH_TAP_OR_TIMEOUT = 7;
public static final int RIGHT_CLICK_NONE = 0;
public static final int RIGHT_CLICK_WITH_MULTITOUCH = 1;
public static final int RIGHT_CLICK_WITH_PRESSURE = 2;
public static final int RIGHT_CLICK_WITH_KEY = 3;
public static final int RIGHT_CLICK_WITH_TIMEOUT = 4;
public static final int SDL_FINGER_DOWN = 0;
public static final int SDL_FINGER_UP = 1;
public static final int SDL_FINGER_MOVE = 2;
public static final int SDL_FINGER_HOVER = 3;
public static final int ZOOM_NONE = 0;
public static final int ZOOM_MAGNIFIER = 1;
public static final int ZOOM_SCREEN_TRANSFORM = 2;
public static final int ZOOM_FULLSCREEN_MAGNIFIER = 3;
}
abstract class DifferentTouchInput
{
public abstract void process(final MotionEvent event);
public abstract void processGenericEvent(final MotionEvent event);
public static boolean ExternalMouseDetected = false;
public static DifferentTouchInput getInstance()
{
boolean multiTouchAvailable1 = false;
boolean multiTouchAvailable2 = false;
// Not checking for getX(int), getY(int) etc 'cause I'm lazy
Method methods [] = MotionEvent.class.getDeclaredMethods();
for(Method m: methods)
{
if( m.getName().equals("getPointerCount") )
multiTouchAvailable1 = true;
if( m.getName().equals("getPointerId") )
multiTouchAvailable2 = true;
}
try {
Log.i("SDL", "Device: " + android.os.Build.DEVICE);
Log.i("SDL", "Device name: " + android.os.Build.DISPLAY);
Log.i("SDL", "Device model: " + android.os.Build.MODEL);
Log.i("SDL", "Device board: " + android.os.Build.BOARD);
if( android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH )
{
if ( Globals.GenerateSubframeTouchEvents )
return IcsTouchInputWithHistory.Holder.sInstance;
if( DetectCrappyDragonRiseDatexGamepad() )
return CrappyDragonRiseDatexGamepadInputWhichNeedsItsOwnHandlerBecauseImTooCheapAndStupidToBuyProperGamepad.Holder.sInstance;
if( android.os.Build.BOARD.contains("bird") )
return CrappyMtkTabletWithBrokenTouchDrivers.Holder.sInstance;
return IcsTouchInput.Holder.sInstance;
}
if( android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD )
return GingerbreadTouchInput.Holder.sInstance;
if (multiTouchAvailable1 && multiTouchAvailable2)
return MultiTouchInput.Holder.sInstance;
else
return SingleTouchInput.Holder.sInstance;
} catch( Exception e ) {
try {
if (multiTouchAvailable1 && multiTouchAvailable2)
return MultiTouchInput.Holder.sInstance;
else
return SingleTouchInput.Holder.sInstance;
} catch( Exception ee ) {
return SingleTouchInput.Holder.sInstance;
}
}
}
private static boolean DetectCrappyDragonRiseDatexGamepad()
{
if( CrappyDragonRiseDatexGamepadInputWhichNeedsItsOwnHandlerBecauseImTooCheapAndStupidToBuyProperGamepad.Holder.sInstance == null )
return false;
return CrappyDragonRiseDatexGamepadInputWhichNeedsItsOwnHandlerBecauseImTooCheapAndStupidToBuyProperGamepad.Holder.sInstance.detect();
}
private static class SingleTouchInput extends DifferentTouchInput
{
private static class Holder
{
private static final SingleTouchInput sInstance = new SingleTouchInput();
}
@Override
public void processGenericEvent(final MotionEvent event)
{
process(event);
}
public void process(final MotionEvent event)
{
int action = -1;
if( event.getAction() == MotionEvent.ACTION_DOWN )
action = Mouse.SDL_FINGER_DOWN;
if( event.getAction() == MotionEvent.ACTION_UP )
action = Mouse.SDL_FINGER_UP;
if( event.getAction() == MotionEvent.ACTION_MOVE )
action = Mouse.SDL_FINGER_MOVE;
if ( action >= 0 )
DemoGLSurfaceView.nativeMotionEvent( (int)event.getX(), (int)event.getY(), action, 0,
(int)(event.getPressure() * 1024.0f),
(int)(event.getSize() * 1024.0f) );
}
}
private static class MultiTouchInput extends DifferentTouchInput
{
public static final int TOUCH_EVENTS_MAX = 16; // Max multitouch pointers
private class touchEvent
{
public boolean down = false;
public int x = 0;
public int y = 0;
public int pressure = 0;
public int size = 0;
}
protected touchEvent touchEvents[];
MultiTouchInput()
{
touchEvents = new touchEvent[TOUCH_EVENTS_MAX];
for( int i = 0; i < TOUCH_EVENTS_MAX; i++ )
touchEvents[i] = new touchEvent();
}
private static class Holder
{
private static final MultiTouchInput sInstance = new MultiTouchInput();
}
public void processGenericEvent(final MotionEvent event)
{
process(event);
}
public void process(final MotionEvent event)
{
int action = -1;
//Log.i("SDL", "Got motion event, type " + (int)(event.getAction()) + " X " + (int)event.getX() + " Y " + (int)event.getY());
if( (event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_UP ||
(event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_CANCEL )
{
action = Mouse.SDL_FINGER_UP;
for( int i = 0; i < TOUCH_EVENTS_MAX; i++ )
{
if( touchEvents[i].down )
{
touchEvents[i].down = false;
DemoGLSurfaceView.nativeMotionEvent( touchEvents[i].x, touchEvents[i].y, action, i, touchEvents[i].pressure, touchEvents[i].size );
}
}
}
if( (event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_DOWN )
{
action = Mouse.SDL_FINGER_DOWN;
for( int i = 0; i < event.getPointerCount(); i++ )
{
int id = event.getPointerId(i);
if( id >= TOUCH_EVENTS_MAX )
id = TOUCH_EVENTS_MAX - 1;
touchEvents[id].down = true;
touchEvents[id].x = (int)event.getX(i);
touchEvents[id].y = (int)event.getY(i);
touchEvents[id].pressure = (int)(event.getPressure(i) * 1024.0f);
touchEvents[id].size = (int)(event.getSize(i) * 1024.0f);
DemoGLSurfaceView.nativeMotionEvent( touchEvents[id].x, touchEvents[id].y, action, id, touchEvents[id].pressure, touchEvents[id].size );
}
}
if( (event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_MOVE ||
(event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_POINTER_DOWN ||
(event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_POINTER_UP )
{
/*
String s = "MOVE: ptrs " + event.getPointerCount();
for( int i = 0 ; i < event.getPointerCount(); i++ )
{
s += " p" + event.getPointerId(i) + "=" + (int)event.getX(i) + ":" + (int)event.getY(i);
}
Log.i("SDL", s);
*/
int pointerReleased = -1;
if( (event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_POINTER_UP )
pointerReleased = (event.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
for( int id = 0; id < TOUCH_EVENTS_MAX; id++ )
{
int ii;
for( ii = 0; ii < event.getPointerCount(); ii++ )
{
if( id == event.getPointerId(ii) )
break;
}
if( ii >= event.getPointerCount() )
{
// Up event
if( touchEvents[id].down )
{
action = Mouse.SDL_FINGER_UP;
touchEvents[id].down = false;
DemoGLSurfaceView.nativeMotionEvent( touchEvents[id].x, touchEvents[id].y, action, id, touchEvents[id].pressure, touchEvents[id].size );
}
}
else
{
if( pointerReleased == id && touchEvents[pointerReleased].down )
{
action = Mouse.SDL_FINGER_UP;
touchEvents[id].down = false;
}
else if( touchEvents[id].down )
{
action = Mouse.SDL_FINGER_MOVE;
}
else
{
action = Mouse.SDL_FINGER_DOWN;
touchEvents[id].down = true;
}
touchEvents[id].x = (int)event.getX(ii);
touchEvents[id].y = (int)event.getY(ii);
touchEvents[id].pressure = (int)(event.getPressure(ii) * 1024.0f);
touchEvents[id].size = (int)(event.getSize(ii) * 1024.0f);
DemoGLSurfaceView.nativeMotionEvent( touchEvents[id].x, touchEvents[id].y, action, id, touchEvents[id].pressure, touchEvents[id].size );
}
}
}
if( (event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_HOVER_MOVE ) // Support bluetooth/USB mouse - available since Android 3.1
{
// TODO: it is possible that multiple pointers return that event, but we're handling only pointer
if( touchEvents[0].down )
action = Mouse.SDL_FINGER_UP;
else
action = Mouse.SDL_FINGER_HOVER;
touchEvents[0].down = false;
touchEvents[0].x = (int)event.getX();
touchEvents[0].y = (int)event.getY();
touchEvents[0].pressure = 0;
touchEvents[0].size = 0;
DemoGLSurfaceView.nativeMotionEvent( touchEvents[0].x, touchEvents[0].y, action, 0, touchEvents[0].pressure, touchEvents[0].size );
}
}
}
private static class GingerbreadTouchInput extends MultiTouchInput
{
private static class Holder
{
private static final GingerbreadTouchInput sInstance = new GingerbreadTouchInput();
}
GingerbreadTouchInput()
{
super();
}
public void process(final MotionEvent event)
{
boolean hwMouseEvent = ( (event.getSource() & InputDevice.SOURCE_MOUSE) == InputDevice.SOURCE_MOUSE ||
(event.getSource() & InputDevice.SOURCE_STYLUS) == InputDevice.SOURCE_STYLUS ||
(event.getMetaState() & KeyEvent.FLAG_TRACKING) != 0 ); // Hack to recognize Galaxy Note Gingerbread stylus
if( ExternalMouseDetected != hwMouseEvent )
{
ExternalMouseDetected = hwMouseEvent;
DemoGLSurfaceView.nativeHardwareMouseDetected(hwMouseEvent ? 1 : 0);
}
super.process(event);
}
public void processGenericEvent(final MotionEvent event)
{
process(event);
}
}
private static class IcsTouchInput extends GingerbreadTouchInput
{
private static class Holder
{
private static final IcsTouchInput sInstance = new IcsTouchInput();
}
private int buttonState = 0;
public void process(final MotionEvent event)
{
//Log.i("SDL", "Got motion event, type " + (int)(event.getAction()) + " X " + (int)event.getX() + " Y " + (int)event.getY() + " buttons " + buttonState + " source " + event.getSource());
int buttonStateNew = event.getButtonState();
if( buttonStateNew != buttonState )
{
for( int i = 1; i <= MotionEvent.BUTTON_FORWARD; i *= 2 )
{
if( (buttonStateNew & i) != (buttonState & i) )
DemoGLSurfaceView.nativeMouseButtonsPressed(i, ((buttonStateNew & i) == 0) ? 0 : 1);
}
buttonState = buttonStateNew;
}
super.process(event); // Push mouse coordinate first
}
public void processGenericEvent(final MotionEvent event)
{
// Joysticks are supported since Honeycomb, but I don't care about it, because very little devices have it
if( (event.getSource() & InputDevice.SOURCE_CLASS_JOYSTICK) == InputDevice.SOURCE_CLASS_JOYSTICK )
{
DemoGLSurfaceView.nativeGamepadAnalogJoystickInput(
event.getAxisValue(MotionEvent.AXIS_X), event.getAxisValue(MotionEvent.AXIS_Y),
event.getAxisValue(MotionEvent.AXIS_Z), event.getAxisValue(MotionEvent.AXIS_RZ),
event.getAxisValue(MotionEvent.AXIS_RTRIGGER), event.getAxisValue(MotionEvent.AXIS_LTRIGGER) );
return;
}
// Process mousewheel
if( event.getAction() == MotionEvent.ACTION_SCROLL )
{
int scrollX = Math.round(event.getAxisValue(MotionEvent.AXIS_HSCROLL));
int scrollY = Math.round(event.getAxisValue(MotionEvent.AXIS_VSCROLL));
DemoGLSurfaceView.nativeMouseWheel(scrollX, scrollY);
return;
}
super.processGenericEvent(event);
}
}
private static class IcsTouchInputWithHistory extends IcsTouchInput
{
private static class Holder
{
private static final IcsTouchInputWithHistory sInstance = new IcsTouchInputWithHistory();
}
public void process(final MotionEvent event)
{
int ptr = 0; // Process only one touch event, because that's typically a pen/mouse
for( ptr = 0; ptr < TOUCH_EVENTS_MAX; ptr++ )
{
if( touchEvents[ptr].down )
break;
}
if( ptr >= TOUCH_EVENTS_MAX )
ptr = 0;
//Log.i("SDL", "Got motion event, getHistorySize " + (int)(event.getHistorySize()) + " ptr " + ptr);
for( int i = 0; i < event.getHistorySize(); i++ )
{
DemoGLSurfaceView.nativeMotionEvent( (int)event.getHistoricalX(i), (int)event.getHistoricalY(i),
Mouse.SDL_FINGER_MOVE, ptr, (int)( event.getHistoricalPressure(i) * 1024.0f ), (int)( event.getHistoricalSize(i) * 1024.0f ) );
}
super.process(event); // Push mouse coordinate first
}
}
private static class CrappyDragonRiseDatexGamepadInputWhichNeedsItsOwnHandlerBecauseImTooCheapAndStupidToBuyProperGamepad extends IcsTouchInput
{
private static class Holder
{
private static final CrappyDragonRiseDatexGamepadInputWhichNeedsItsOwnHandlerBecauseImTooCheapAndStupidToBuyProperGamepad sInstance = new CrappyDragonRiseDatexGamepadInputWhichNeedsItsOwnHandlerBecauseImTooCheapAndStupidToBuyProperGamepad();
}
float hatX = 0.0f, hatY = 0.0f;
public void processGenericEvent(final MotionEvent event)
{
// Joysticks are supported since Honeycomb, but I don't care about it, because very little devices have it
if( (event.getSource() & InputDevice.SOURCE_CLASS_JOYSTICK) == InputDevice.SOURCE_CLASS_JOYSTICK )
{
// event.getAxisValue(AXIS_HAT_X) and event.getAxisValue(AXIS_HAT_Y) are joystick arrow keys, they also send keyboard events
DemoGLSurfaceView.nativeGamepadAnalogJoystickInput(
event.getAxisValue(MotionEvent.AXIS_X), event.getAxisValue(MotionEvent.AXIS_Y),
event.getAxisValue(MotionEvent.AXIS_RX), event.getAxisValue(MotionEvent.AXIS_RZ),
0, 0);
if( event.getAxisValue(MotionEvent.AXIS_HAT_X) != hatX )
{
hatX = event.getAxisValue(MotionEvent.AXIS_HAT_X);
if( hatX == 0.0f )
{
DemoGLSurfaceView.nativeKey(KeyEvent.KEYCODE_DPAD_LEFT, 0);
DemoGLSurfaceView.nativeKey(KeyEvent.KEYCODE_DPAD_RIGHT, 0);
}
else
DemoGLSurfaceView.nativeKey(hatX < 0.0f ? KeyEvent.KEYCODE_DPAD_LEFT : KeyEvent.KEYCODE_DPAD_RIGHT, 1);
}
if( event.getAxisValue(MotionEvent.AXIS_HAT_Y) != hatY )
{
hatY = event.getAxisValue(MotionEvent.AXIS_HAT_Y);
if( hatY == 0.0f )
{
DemoGLSurfaceView.nativeKey(KeyEvent.KEYCODE_DPAD_UP, 0);
DemoGLSurfaceView.nativeKey(KeyEvent.KEYCODE_DPAD_DOWN, 0);
}
else
DemoGLSurfaceView.nativeKey(hatY < 0.0f ? KeyEvent.KEYCODE_DPAD_UP : KeyEvent.KEYCODE_DPAD_DOWN, 1);
}
return;
}
super.processGenericEvent(event);
}
public boolean detect()
{
int[] devIds = InputDevice.getDeviceIds();
for( int id : devIds )
{
InputDevice device = InputDevice.getDevice(id);
if( device == null )
continue;
System.out.println("libSDL: input device ID " + id + " type " + device.getSources() + " name " + device.getName() );
if( (device.getSources() & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD &&
(device.getSources() & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK &&
device.getName().indexOf("DragonRise Inc") == 0 )
{
System.out.println("libSDL: Detected crappy DragonRise gamepad, enabling special hack for it. Please press button labeled 'Analog', otherwise it won't work, because it's cheap and crappy");
return true;
}
}
return false;
}
}
private static class CrappyMtkTabletWithBrokenTouchDrivers extends IcsTouchInput
{
private static class Holder
{
private static final CrappyMtkTabletWithBrokenTouchDrivers sInstance = new CrappyMtkTabletWithBrokenTouchDrivers();
}
public void process(final MotionEvent event)
{
if( event.getX() != 0.0f && event.getY() != 0.0f ) // Ignore event when it has zero coordinates
super.process(event);
}
public void processGenericEvent(final MotionEvent event)
{
if( event.getX() != 0.0f && event.getY() != 0.0f ) // Ignore event when it has zero coordinates
super.processGenericEvent(event);
}
}
}
class DemoRenderer extends GLSurfaceView_SDL.Renderer
{
public DemoRenderer(MainActivity _context)
{
context = _context;
}
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
Log.i("SDL", "libSDL: DemoRenderer.onSurfaceCreated(): paused " + mPaused + " mFirstTimeStart " + mFirstTimeStart );
mGlSurfaceCreated = true;
mGl = gl;
if( ! mPaused && ! mFirstTimeStart )
nativeGlContextRecreated();
mFirstTimeStart = false;
}
public void onSurfaceChanged(GL10 gl, int w, int h) {
Log.i("SDL", "libSDL: DemoRenderer.onSurfaceChanged(): paused " + mPaused + " mFirstTimeStart " + mFirstTimeStart + " w " + w + " h " + h);
if( w < h && Globals.HorizontalOrientation )
{
// Sometimes when Android awakes from lockscreen, portrait orientation is kept
int x = w;
w = h;
h = x;
}
mWidth = w;
mHeight = h;
mGl = gl;
nativeResize(w, h, Globals.KeepAspectRatio ? 1 : 0);
}
public void onSurfaceDestroyed() {
Log.i("SDL", "libSDL: DemoRenderer.onSurfaceDestroyed(): paused " + mPaused + " mFirstTimeStart " + mFirstTimeStart );
mGlSurfaceCreated = false;
mGlContextLost = true;
nativeGlContextLost();
};
public void onDrawFrame(GL10 gl) {
mGl = gl;
DrawLogo(mGl);
SwapBuffers();
nativeInitJavaCallbacks();
// Make main thread priority lower so audio thread won't get underrun
// Thread.currentThread().setPriority((Thread.currentThread().getPriority() + Thread.MIN_PRIORITY)/2);
mGlContextLost = false;
if(Globals.CompatibilityHacksStaticInit)
MainActivity.LoadApplicationLibrary(context);
Settings.Apply(context);
Settings.nativeSetEnv( "DISPLAY_RESOLUTION_WIDTH", String.valueOf(Math.max(mWidth, mHeight)) );
Settings.nativeSetEnv( "DISPLAY_RESOLUTION_HEIGHT", String.valueOf(Math.min(mWidth, mHeight)) ); // In Kitkat with immersive mode, getWindowManager().getDefaultDisplay().getMetrics() return inaccurate height
accelerometer = new AccelerometerReader(context);
// Tweak video thread priority, if user selected big audio buffer
if(Globals.AudioBufferConfig >= 2)
Thread.currentThread().setPriority( (Thread.NORM_PRIORITY + Thread.MIN_PRIORITY) / 2 ); // Lower than normal
// Calls main() and never returns, hehe - we'll call eglSwapBuffers() from native code
nativeInit( Globals.DataDir,
Globals.CommandLine,
( (Globals.SwVideoMode && Globals.MultiThreadedVideo) || Globals.CompatibilityHacksVideo ) ? 1 : 0,
android.os.Debug.isDebuggerConnected() ? 1 : 0 );
System.exit(0); // The main() returns here - I don't bother with deinit stuff, just terminate process
}
public int swapBuffers() // Called from native code
{
if( ! super.SwapBuffers() && Globals.NonBlockingSwapBuffers )
{
if(mRatelimitTouchEvents)
{
synchronized(this)
{
this.notify();
}
}
return 0;
}
if(mGlContextLost) {
mGlContextLost = false;
Settings.SetupTouchscreenKeyboardGraphics(context); // Reload on-screen buttons graphics
DrawLogo(mGl);
super.SwapBuffers();
}
// Unblock event processing thread only after we've finished rendering
if(mRatelimitTouchEvents)
{
synchronized(this)
{
this.notify();
}
}
if( context.isScreenKeyboardShown() )
{
try {
Thread.sleep(50); // Give some time to the keyboard input thread
} catch(Exception e) { };
}
return 1;
}
public void showScreenKeyboardWithoutTextInputField() // Called from native code
{
class Callback implements Runnable
{
public MainActivity parent;
public void run()
{
parent.showScreenKeyboardWithoutTextInputField();
}
}
Callback cb = new Callback();
cb.parent = context;
context.runOnUiThread(cb);
}
public void showScreenKeyboard(final String oldText, int sendBackspace) // Called from native code
{
class Callback implements Runnable
{
public MainActivity parent;
public String oldText;
public boolean sendBackspace;
public void run()
{
parent.showScreenKeyboard(oldText, sendBackspace);
}
}
Callback cb = new Callback();
cb.parent = context;
cb.oldText = oldText;
cb.sendBackspace = (sendBackspace != 0);
context.runOnUiThread(cb);
}
public void hideScreenKeyboard() // Called from native code
{
class Callback implements Runnable
{
public MainActivity parent;
public void run()
{
parent.hideScreenKeyboard();
}
}
Callback cb = new Callback();
cb.parent = context;
context.runOnUiThread(cb);
}
public int isScreenKeyboardShown() // Called from native code
{
return context.isScreenKeyboardShown() ? 1 : 0;
}
public void setScreenKeyboardHintMessage(String s)
{
context.setScreenKeyboardHintMessage(s);
}
public void startAccelerometerGyroscope(int started)
{
accelerometer.openedBySDL = (started != 0);
if( accelerometer.openedBySDL && !mPaused )
accelerometer.start();
else
accelerometer.stop();
}
public void exitApp()
{
nativeDone();
}
public void getAdvertisementParams(int params[])
{
context.getAdvertisementParams(params);
}
public void setAdvertisementVisible(int visible)
{
context.setAdvertisementVisible(visible);
}
public void setAdvertisementPosition(int left, int top)
{
context.setAdvertisementPosition(left, top);
}
public void requestNewAdvertisement()
{
context.requestNewAdvertisement();
}
private int PowerOf2(int i)
{
int value = 1;
while (value < i)
value <<= 1;
return value;
}
public void DrawLogo(GL10 gl)
{
/*
// TODO: this not quite works, as it seems
BitmapDrawable bmp = null;
try
{
bmp = new BitmapDrawable(context.getAssets().open("logo.png"));
}
catch(Exception e)
{
bmp = new BitmapDrawable(context.getResources().openRawResource(R.drawable.publisherlogo));
}
int width = bmp.getBitmap().getWidth();
int height = bmp.getBitmap().getHeight();
ByteBuffer byteBuffer = ByteBuffer.allocateDirect(4 * width * height);
//byteBuffer.order(ByteOrder.BIG_ENDIAN);
bmp.getBitmap().copyPixelsToBuffer(byteBuffer);
byteBuffer.position(0);
gl.glViewport(0, 0, mWidth, mHeight);
gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT);
gl.glColor4x(0x10000, 0x10000, 0x10000, 0x10000);
gl.glPixelStorei(gl.GL_UNPACK_ALIGNMENT, 1);
gl.glEnable(GL10.GL_TEXTURE_2D);
int textureName = -1;
int mTextureNameWorkspace[] = new int[1];
int mCropWorkspace[] = new int[4];
gl.glGenTextures(1, mTextureNameWorkspace, 0);
textureName = mTextureNameWorkspace[0];
gl.glBindTexture(GL10.GL_TEXTURE_2D, textureName);
gl.glActiveTexture(textureName);
gl.glClientActiveTexture(textureName);
gl.glTexImage2D(GL10.GL_TEXTURE_2D, 0, GL10.GL_RGBA,
PowerOf2(width), PowerOf2(height), 0,
GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, null);
gl.glTexSubImage2D(GL10.GL_TEXTURE_2D, 0, 0, 0,
width, height,
GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, byteBuffer);
mCropWorkspace[0] = 0; // u
mCropWorkspace[1] = height; // v
mCropWorkspace[2] = width;
mCropWorkspace[3] = -height;
((GL11) gl).glTexParameteriv(GL10.GL_TEXTURE_2D,
GL11Ext.GL_TEXTURE_CROP_RECT_OES, mCropWorkspace, 0);
((GL11Ext) gl).glDrawTexiOES(0, -mHeight, 0, mWidth, mHeight);
gl.glActiveTexture(0);
gl.glClientActiveTexture(0);
gl.glBindTexture(GL10.GL_TEXTURE_2D, 0);
gl.glDeleteTextures(1, mTextureNameWorkspace, 0);
gl.glFlush();
*/
}
private native void nativeInitJavaCallbacks();
private native void nativeInit(String CurrentPath, String CommandLine, int multiThreadedVideo, int isDebuggerConnected);
private native void nativeResize(int w, int h, int keepAspectRatio);
private native void nativeDone();
private native void nativeGlContextLost();
public native void nativeGlContextRecreated();
public native void nativeGlContextLostAsyncEvent();
public static native void nativeTextInput( int ascii, int unicode );
public static native void nativeTextInputFinished();
private MainActivity context = null;
public AccelerometerReader accelerometer = null;
private GL10 mGl = null;
private EGL10 mEgl = null;
private EGLDisplay mEglDisplay = null;
private EGLSurface mEglSurface = null;
private EGLContext mEglContext = null;
private boolean mGlContextLost = false;
public boolean mGlSurfaceCreated = false;
public boolean mPaused = false;
private boolean mFirstTimeStart = true;
public int mWidth = 0;
public int mHeight = 0;
public static final boolean mRatelimitTouchEvents = true; //(Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO);
}
class DemoGLSurfaceView extends GLSurfaceView_SDL {
public DemoGLSurfaceView(MainActivity context) {
super(context);
mParent = context;
touchInput = DifferentTouchInput.getInstance();
setEGLConfigChooser(Globals.VideoDepthBpp, Globals.NeedDepthBuffer, Globals.NeedStencilBuffer, Globals.NeedGles2);
mRenderer = new DemoRenderer(context);
setRenderer(mRenderer);
}
@Override
public boolean onTouchEvent(final MotionEvent event)
{
touchInput.process(event);
if( DemoRenderer.mRatelimitTouchEvents )
{
limitEventRate(event);
}
return true;
};
@Override
public boolean onGenericMotionEvent (final MotionEvent event)
{
touchInput.processGenericEvent(event);
if( DemoRenderer.mRatelimitTouchEvents )
{
limitEventRate(event);
}
return true;
}
public void limitEventRate(final MotionEvent event)
{
// Wait a bit, and try to synchronize to app framerate, or event thread will eat all CPU and we'll lose FPS
// With Froyo the rate of touch events seems to be limited by OS, but they are arriving faster then we're redrawing anyway
if((event.getAction() == MotionEvent.ACTION_MOVE ||
event.getAction() == MotionEvent.ACTION_HOVER_MOVE))
{
synchronized(mRenderer)
{
try
{
mRenderer.wait(300L); // And sometimes the app decides not to render at all, so this timeout should not be big.
} catch (InterruptedException e) { }
}
}
}
public void exitApp() {
mRenderer.exitApp();
};
@Override
public void onPause() {
if(mRenderer.mPaused)
return;
mRenderer.mPaused = true;
mRenderer.nativeGlContextLostAsyncEvent();
if( mRenderer.accelerometer != null ) // For some reason it crashes here often - are we getting this event before initialization?
mRenderer.accelerometer.stop();
super.onPause();
};
public boolean isPaused() {
return mRenderer.mPaused;
}
@Override
public void onResume() {
if(!mRenderer.mPaused)
return;
mRenderer.mPaused = false;
super.onResume();
Log.i("SDL", "libSDL: DemoGLSurfaceView.onResume(): mRenderer.mGlSurfaceCreated " + mRenderer.mGlSurfaceCreated + " mRenderer.mPaused " + mRenderer.mPaused);
if( mRenderer.mGlSurfaceCreated && ! mRenderer.mPaused || Globals.NonBlockingSwapBuffers )
mRenderer.nativeGlContextRecreated();
if( mRenderer.accelerometer != null && mRenderer.accelerometer.openedBySDL ) // For some reason it crashes here often - are we getting this event before initialization?
mRenderer.accelerometer.start();
};
// This seems like redundant code - it handled in MainActivity.java
@Override
public boolean onKeyDown(int keyCode, final KeyEvent event) {
//Log.i("SDL", "Got key down event, id " + keyCode + " meta " + event.getMetaState() + " event " + event.toString());
if( nativeKey( keyCode, 1 ) == 0 )
return super.onKeyDown(keyCode, event);
return true;
}
@Override
public boolean onKeyUp(int keyCode, final KeyEvent event) {
//Log.i("SDL", "Got key up event, id " + keyCode + " meta " + event.getMetaState());
if( nativeKey( keyCode, 0 ) == 0 )
return super.onKeyUp(keyCode, event);
return true;
}
DemoRenderer mRenderer;
MainActivity mParent;
DifferentTouchInput touchInput = null;
public static native void nativeMotionEvent( int x, int y, int action, int pointerId, int pressure, int radius );
public static native int nativeKey( int keyCode, int down );
public static native void initJavaCallbacks();
public static native void nativeHardwareMouseDetected( int detected );
public static native void nativeMouseButtonsPressed( int buttonId, int pressedState );
public static native void nativeMouseWheel( int scrollX, int scrollY );
public static native void nativeGamepadAnalogJoystickInput( float stick1x, float stick1y, float stick2x, float stick2y, float rtrigger, float ltrigger );
}
|
package com.bkahlert.nebula.utils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.jface.viewers.AbstractTreeViewer;
import org.eclipse.jface.viewers.ColumnViewer;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.viewers.TreePath;
import org.eclipse.jface.viewers.TreeViewerColumn;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerColumn;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Item;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.swt.widgets.TreeItem;
import com.bkahlert.nebula.utils.DistributionUtils.AbsoluteWidth;
import com.bkahlert.nebula.utils.DistributionUtils.Width;
/**
* Utility class for manipulation of {@link Viewer Viewers}.
* <p>
* Tries to call alternative methods if a special operation is not supported by
* the viewer. All calls are automatically done in the synchronous SWT thread.
* <p>
* <b>Example 1:</b><br/>
* If you try to update a specific element in a viewer and the viewer does not
* support updating single elements, the whole viewer will be refreshed.
* <p>
* <b>Example 2:</b><br/>
* One element of your model has been removed. For performance reasons you don't
* want to refresh the whole viewer but manually remove the element from the
* viewer in order to reflect the model. If your viewer supports this action the
* element is removed. Otherwise the viewer is advised to reload the model.
*
* @author bkahlert
*/
public class ViewerUtils {
public static class FullWidthResizer {
private final ColumnViewer columnViewer;
private final Map<Integer, Width> numbers = new HashMap<Integer, Width>();
private final Listener resizeListener = new Listener() {
@Override
public void handleEvent(Event event) {
FullWidthResizer.this.resize();
}
};
public FullWidthResizer(ColumnViewer columnViewer) {
this.columnViewer = columnViewer;
this.columnViewer.getControl().addListener(SWT.Resize,
this.resizeListener);
}
public void setWidth(int column, Width width) {
this.numbers.put(column, width);
this.resize();
}
public void resize() {
if (this.columnViewer != null
&& this.columnViewer.getControl() != null
&& !this.columnViewer.getControl().isDisposed()) {
Control control = this.columnViewer.getControl();
if (control instanceof Tree) {
Tree tree = (Tree) control;
Width[] input = new Width[tree.getColumnCount()];
for (int i = 0; i < input.length; i++) {
input[i] = this.numbers.containsKey(i) ? this.numbers
.get(i) : new AbsoluteWidth(
Width.DEFAULT_MIN_WIDTH);
}
double[] distribution = DistributionUtils.distribute(input,
tree.getClientArea().width);
for (int i = 0; i < distribution.length; i++) {
tree.getColumn(i).setWidth(
(int) Math.round(distribution[i]));
}
} else if (control instanceof Table) {
Table table = (Table) control;
Width[] input = new Width[table.getColumnCount()];
for (int i = 0; i < input.length; i++) {
input[i] = this.numbers.containsKey(i) ? this.numbers
.get(i) : new AbsoluteWidth(
Width.DEFAULT_MIN_WIDTH);
}
double[] distribution = DistributionUtils.distribute(input,
table.getClientArea().width);
for (int i = 0; i < distribution.length; i++) {
table.getColumn(i).setWidth(
(int) Math.round(distribution[i]));
}
}
}
}
public void dispose() {
if (this.columnViewer != null
&& this.columnViewer.getControl() != null
&& !this.columnViewer.getControl().isDisposed()) {
this.columnViewer.getControl().removeListener(SWT.Resize,
this.resizeListener);
}
}
}
private ViewerUtils() {
// no instantiation allowed
}
/**
* Sets a viewer's input and makes sure it runs in the SWT thread
*
* @param viewer
* @param input
*
* @see Viewer#setInput(Object)
*/
public static void setInput(final Viewer viewer, final Object input) {
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
if (viewer == null || viewer.getControl().isDisposed()) {
return;
}
viewer.setInput(input);
}
});
}
/**
* Gets a viewer's input
*
* @param viewer
* @return
*
* @see StructuredViewer#setInput(Object)
*/
public static Object getInput(final Viewer viewer) {
if (viewer instanceof StructuredViewer) {
return ((StructuredViewer) viewer).getInput();
}
return null;
}
/**
* Add the a new element to a given element in a viewer and makes sure it
* runs in the SWT thread. Runs a refresh in case the viewer does not
* support additions.
*
* @param viewer
* @param parentElementOrTreePath
* @param childElement
*
* @see StructuredViewer#refresh(boolean)
*/
public static void add(final Viewer viewer,
final Object parentElementOrTreePath, final Object childElement) {
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
if (viewer == null || viewer.getControl().isDisposed()) {
return;
}
if (viewer instanceof AbstractTreeViewer) {
AbstractTreeViewer treeViewer = (AbstractTreeViewer) viewer;
treeViewer.add(parentElementOrTreePath, childElement);
} else {
viewer.refresh();
}
}
});
}
/**
* Add the new elements to a given element in a viewer and makes sure it
* runs in the SWT thread. Runs a refresh in case the viewer does not
* support additions.
*
* @param viewer
* @param parentElementOrTreePath
* @param childElements
*
* @see StructuredViewer#refresh(boolean)
*/
public static void add(final Viewer viewer,
final Object parentElementOrTreePath, final Object[] childElements) {
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
if (viewer == null || viewer.getControl().isDisposed()) {
return;
}
if (viewer instanceof AbstractTreeViewer) {
AbstractTreeViewer treeViewer = (AbstractTreeViewer) viewer;
treeViewer.add(parentElementOrTreePath, childElements);
} else {
viewer.refresh();
}
}
});
}
/**
* Removes an existing element from a viewer and makes sure it runs in the
* SWT thread. Runs a refresh in case the viewer does not support removals.
*
* @param viewer
* @param elementsOrTreePaths
*
* @see StructuredViewer#refresh(boolean)
*/
public static void remove(final Viewer viewer,
final Object elementsOrTreePaths) {
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
if (viewer == null || viewer.getControl().isDisposed()) {
return;
}
if (viewer instanceof AbstractTreeViewer) {
AbstractTreeViewer treeViewer = (AbstractTreeViewer) viewer;
treeViewer.remove(elementsOrTreePaths);
} else {
viewer.refresh();
}
}
});
}
/**
* Removes existing elements from a viewer and makes sure it runs in the SWT
* thread. Runs a refresh in case the viewer does not support removals.
*
* @param viewer
* @param elementsOrTreePaths
*
* @see StructuredViewer#refresh(boolean)
*/
public static void remove(final Viewer viewer,
final Object[] elementsOrTreePaths) {
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
if (viewer == null || viewer.getControl().isDisposed()) {
return;
}
if (viewer instanceof AbstractTreeViewer) {
AbstractTreeViewer treeViewer = (AbstractTreeViewer) viewer;
treeViewer.remove(elementsOrTreePaths);
} else {
viewer.refresh();
}
}
});
}
/**
* Updates a viewer's element and makes sure it runs in the SWT thread. Runs
* a refresh in case the viewer does not support updates.
*
* @param viewer
* @param element
* @param properties
*
* @see StructuredViewer#update(Object, String[])
*/
public static void update(final Viewer viewer, final Object element,
final String[] properties) {
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
if (viewer == null || viewer.getControl().isDisposed()) {
return;
}
if (viewer instanceof StructuredViewer) {
StructuredViewer structuredViewer = (StructuredViewer) viewer;
structuredViewer.update(element, properties);
} else {
viewer.refresh();
}
}
});
}
/**
* Updates a viewer's elements and makes sure it runs in the SWT thread.
* Runs a refresh in case the viewer does not support updates.
*
* @param viewer
* @param elements
* @param properties
*
* @see StructuredViewer#update(Object[], String[])
*/
public static void update(final Viewer viewer, final Object[] elements,
final String[] properties) {
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
if (viewer == null || viewer.getControl().isDisposed()) {
return;
}
if (viewer instanceof StructuredViewer) {
StructuredViewer structuredViewer = (StructuredViewer) viewer;
structuredViewer.update(elements, properties);
} else {
viewer.refresh();
}
}
});
}
/**
* Refreshes a viewer's display and makes sure it runs in the SWT thread.
*
* @param viewer
* @param updateLabels
*
* @see Viewer#refresh()
* @see StructuredViewer#refresh(boolean)
*/
public static void refresh(final Viewer viewer, final boolean updateLabels) {
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
if (viewer == null || viewer.getControl().isDisposed()) {
return;
}
if (viewer instanceof StructuredViewer) {
StructuredViewer structuredViewer = (StructuredViewer) viewer;
structuredViewer.refresh(updateLabels);
} else {
viewer.refresh();
}
}
});
}
/**
* Refreshes a viewer's display and makes sure it runs in the SWT thread.
*
* @param viewer
* @param element
* @param updateLabels
*
* @see Viewer#refresh()
* @see StructuredViewer#refresh(Object, boolean)
*/
public static void refresh(final Viewer viewer, final Object element,
final boolean updateLabels) {
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
if (viewer == null || viewer.getControl().isDisposed()) {
return;
}
if (viewer instanceof StructuredViewer) {
StructuredViewer structuredViewer = (StructuredViewer) viewer;
structuredViewer.refresh(element, updateLabels);
} else {
viewer.refresh();
}
}
});
}
/**
* @see AbstractTreeViewer#expandToLevel(int)
*/
public static void expandToLevel(final Viewer viewer, final int level) {
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
if (viewer == null || viewer.getControl().isDisposed()) {
return;
}
if (viewer instanceof AbstractTreeViewer) {
AbstractTreeViewer treeViewer = (AbstractTreeViewer) viewer;
treeViewer.expandToLevel(level);
}
}
});
}
/**
* @see AbstractTreeViewer#expandToLevel(int)
*/
public static void expandToLevel(final Viewer viewer,
final Object elementOrTreePath, final int level) {
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
if (viewer == null || viewer.getControl().isDisposed()) {
return;
}
if (viewer instanceof AbstractTreeViewer) {
AbstractTreeViewer treeViewer = (AbstractTreeViewer) viewer;
treeViewer.expandToLevel(elementOrTreePath, level);
}
}
});
}
/**
* If supported by the viewer expands all elements and makes sure it runs in
* the SWT thread.
*
* @param viewer
*
* @see AbstractTreeViewer#expandAll()
*/
public static void expandAll(final Viewer viewer) {
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
if (viewer == null || viewer.getControl().isDisposed()) {
return;
}
if (viewer instanceof AbstractTreeViewer) {
AbstractTreeViewer treeViewer = (AbstractTreeViewer) viewer;
treeViewer.expandAll();
}
}
});
}
/**
* @see AbstractTreeViewer#expandToLevel(int)
*/
public static void expandAll(final Viewer viewer,
final Object elementOrTreePath) {
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
if (viewer == null || viewer.getControl().isDisposed()) {
return;
}
if (viewer instanceof AbstractTreeViewer) {
AbstractTreeViewer treeViewer = (AbstractTreeViewer) viewer;
treeViewer.expandToLevel(elementOrTreePath,
Integer.MAX_VALUE);
}
}
});
}
/**
* Returns all {@link Item}s who's {@link Item#getData()} object is of the
* given type.
*
* @param items
* @param clazz
* @return
*/
public static List<Item> getItemWithDataType(Item[] items, Class<?> clazz) {
if (items == null) {
return null;
}
List<Item> itemsWithDataType = new ArrayList<Item>();
for (Item item : ViewerUtils.getAllItems(items)) {
if (clazz.isInstance(item.getData())) {
itemsWithDataType.add(item);
}
}
return itemsWithDataType;
}
/**
* Returns all {@link Item}s who's {@link Item#getData()} object is of the
* given type.
*
* @param items
* @param clazz
* @return
*/
public static List<Item> getItemWithDataType(Control control, Class<?> clazz) {
if (control == null) {
return null;
}
List<Item> itemsWithDataType = new ArrayList<Item>();
for (Item item : ViewerUtils.getAllItems(control)) {
if (clazz.isInstance(item.getData())) {
itemsWithDataType.add(item);
}
}
return itemsWithDataType;
}
/**
* Returns all {@link Item}s who's {@link Item#getData()} object equals the
* given one.
*
* @param items
* @param clazz
* @return
*/
public static List<Item> getItemWithData(Item[] items, Object data) {
if (items == null) {
return null;
}
List<Item> itemsWithData = new ArrayList<Item>();
for (Item item : ViewerUtils.getAllItems(items)) {
if (data.equals(item.getData())) {
itemsWithData.add(item);
}
}
return itemsWithData;
}
/**
* Returns all {@link Item}s who's {@link Item#getData()} object equals the
* given one.
*
* @param items
* @param clazz
* @return
*/
public static List<Item> getItemWithData(Control control, Object data) {
if (control == null) {
return null;
}
List<Item> itemsWithData = new ArrayList<Item>();
for (Item item : ViewerUtils.getAllItems(control)) {
if (data.equals(item.getData())) {
itemsWithData.add(item);
}
}
return itemsWithData;
}
/**
* Returns a list that does not only contain the {@link Item}s themselves
* but also their child, children's children, etc.
*
* @param items
* @return
*/
public static List<Item> getAllItems(Control control) {
Item[] items = (control instanceof Tree) ? ((Tree) control).getItems()
: ((Table) control).getItems();
return ViewerUtils.getAllItems(items);
}
/**
* Returns a list that does not only contain the {@link Item}s themselves
* but also their child, children's children, etc.
*
* @param items
* @return
*/
public static List<Item> getAllItems(Item[] items) {
List<Item> allItems = new ArrayList<Item>();
for (Item item : items) {
allItems.add(item);
if (item instanceof TreeItem) {
TreeItem treeItem = (TreeItem) item;
allItems.addAll(ViewerUtils.listTreeItems(treeItem));
}
}
return allItems;
}
/**
* Returns a list of all elements contained in the {@link TreeItem}.
* <p>
* Example:
*
* <code>a</code> is root and has children <code>b</code> and <code>e</code>. <code>b</code> has the children <code>c</code> and <code>d</code>.
*
* The resulting list contains the elements <code>b</code>, <code>c</code>,
* <code>d</code> and <code>e</code> whereas <code>a</code> was the
* argument.
*
* @param treeItem
* @return
*/
public static List<TreeItem> listTreeItems(TreeItem treeItem) {
List<TreeItem> treeItems = new ArrayList<TreeItem>();
for (TreeItem child : treeItem.getItems()) {
treeItems.add(child);
treeItems.addAll(listTreeItems(child));
}
return treeItems;
}
/**
* Merges an array of {@link TreePath}s to one {@link TreePath}.
*
* Example: {@link TreePath}s
*
* <pre>
* A<br/>
* | -B
* </pre>
*
* and
*
* <pre>
* C<br/>
* | -D
* </pre>
*
* become
*
* <pre>
* A<br/>
* | -B<br/>
* | -C<br/>
* | -D
* </pre>
*
* @param treePaths
* @return
*/
public static TreePath merge(TreePath... treePaths) {
ArrayList<Object> segments = new ArrayList<Object>();
for (TreePath treePath : treePaths) {
for (int i = 0; i < treePath.getSegmentCount(); i++) {
segments.add(treePath.getSegment(i));
}
}
return new TreePath(segments.toArray());
}
public static Rectangle getBounds(ViewerColumn column) {
int index = ViewerUtils.getIndex(column);
Control control = column.getViewer().getControl();
int x = 0;
int w;
if (control instanceof Table) {
for (int i = 0; i < index; i++) {
x += ViewerUtils.getColumn((Table) control, i).getWidth();
}
w = ViewerUtils.getColumn((Table) control, index).getWidth();
} else {
for (int i = 0; i < index; i++) {
x += ViewerUtils.getColumn((Tree) control, i).getWidth();
}
w = ViewerUtils.getColumn((Tree) control, index).getWidth();
;
}
return new Rectangle(x, 0, w, control.getBounds().height);
}
public static int getIndex(ViewerColumn viewerColumn) {
Control control = viewerColumn.getViewer().getControl();
Item column = viewerColumn instanceof TableViewerColumn ? ((TableViewerColumn) viewerColumn)
.getColumn() : ((TreeViewerColumn) viewerColumn).getColumn();
Item[] columns = control instanceof Table ? ((Table) control)
.getColumns() : ((Tree) control).getColumns();
for (int i = 0, m = columns.length; i < m; i++) {
if (columns[i] == column) {
int[] order = control instanceof Table ? ((Table) control)
.getColumnOrder() : ((Tree) control).getColumnOrder();
for (int j = 0, n = order.length; j < n; j++) {
if (order[j] == i) {
return j;
}
}
}
}
return -1;
}
public static Item getColumn(Control control, int index) {
int[] order = control instanceof Table ? ((Table) control)
.getColumnOrder() : ((Tree) control).getColumnOrder();
for (int j = 0, n = order.length; j < n; j++) {
if (order[j] == index) {
Item[] columns = control instanceof Table ? ((Table) control)
.getColumns() : ((Tree) control).getColumns();
return columns[j];
}
}
return null;
}
public static TableColumn getColumn(Table table, int index) {
return (TableColumn) getColumn((Control) table, index);
}
public static TreeColumn getColumn(Tree tree, int index) {
return (TreeColumn) getColumn((Control) tree, index);
}
public static void refresh(final Viewer viewer) {
if (viewer != null) {
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
viewer.refresh();
}
});
}
}
}
|
package Tests;
import java.rmi.UnexpectedException;
import gameWorld.World;
import org.junit.Test;
import dataStorage.Data;
/**
* @author Dylan, Jarred
* Data is very robust and hard to test
*
*/
public class DataTests {
public @Test void testSave1(){
World w = utils.createWorld();
try {
Data.save(null);
} catch (UnexpectedException | IllegalArgumentException e) {
// TODO Auto-generated catch block
assert(e instanceof IllegalArgumentException);
}
}
public @Test void testSave2(){
}
public @Test void testLoadNull(){
try {
Data.load(null);
} catch (UnexpectedException | IllegalArgumentException e) {
// TODO Auto-generated catch block
assert(e instanceof IllegalArgumentException);
}
}
public @Test void testLoad(){
World w = utils.createWorld();
String test = new String("hi");
try {
Data.load(test);
} catch (UnexpectedException e) {
e.printStackTrace();
}
}
public @Test void testSet(){
Data.testSet(null);
}
}
|
package com.dmdirc.ui.swing.dialogs.actioneditor;
import com.dmdirc.actions.ActionCondition;
import com.dmdirc.actions.interfaces.ActionType;
import com.dmdirc.ui.IconManager;
import com.dmdirc.ui.swing.components.ImageButton;
import com.dmdirc.ui.swing.components.ImageToggleButton;
import com.dmdirc.ui.swing.components.TextLabel;
import com.dmdirc.util.ListenerList;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
import net.miginfocom.swing.MigLayout;
/**
* Action condition display panel.
*/
public class ActionConditionDisplayPanel extends JPanel implements ActionListener,
PropertyChangeListener {
/**
* A version number for this class. It should be changed whenever the class
* structure is changed (or anything else that would prevent serialized
* objects being unserialized with the new class).
*/
private static final long serialVersionUID = 1;
/** Info label. */
private TextLabel label;
/** Edit button. */
private JToggleButton editButton;
/** Delete button. */
private ImageButton deleteButton;
/** Edit panel. */
private ActionConditionEditorPanel editPanel;
/** Listeners. */
private ListenerList listeners;
/** Action condition. */
private ActionCondition condition;
/** Action trigger. */
private ActionType trigger;
/**
* Instantiates the panel.
*
* @param condition Action condition
* @param trigger Action trigger
*/
public ActionConditionDisplayPanel(final ActionCondition condition,
final ActionType trigger) {
super();
this.trigger = trigger;
this.condition = new ActionCondition(condition.getArg(),
condition.getComponent(), condition.getComparison(),
condition.getTarget());
initComponents();
addListeners();
layoutComponents();
if (condition.getArg() == -1 && condition.getComponent() == null &&
condition.getComparison() == null && condition.getTarget() ==
null) {
editPanel.setVisible(true);
editButton.setSelected(true);
}
}
/**
* Sets the action trigger.
*
* @param trigger new trigger
*/
void setTrigger(final ActionType trigger) {
this.trigger = trigger;
editPanel.setTrigger(trigger);
editPanel.setVisible(trigger == null);
editButton.setSelected(trigger == null);
label.setText(updateSentence());
}
/** Initialises the components. */
private void initComponents() {
label = new TextLabel("");
editButton = new ImageToggleButton("edit", IconManager.getIconManager().
getIcon("edit-inactive"),
IconManager.getIconManager().getIcon("edit"));
deleteButton = new ImageButton("delete", IconManager.getIconManager().
getIcon("close-inactive"), IconManager.getIconManager().
getIcon("close-inactive"),
IconManager.getIconManager().getIcon("close-active"));
editPanel = new ActionConditionEditorPanel(condition, trigger);
listeners = new ListenerList();
editPanel.setVisible(trigger == null);
editButton.setSelected(trigger == null);
}
/** Adds the listeners. */
private void addListeners() {
editButton.addActionListener(this);
deleteButton.addActionListener(this);
editPanel.addPropertyChangeListener("edit", this);
}
/** Lays out the components. */
private void layoutComponents() {
setLayout(new MigLayout("ins 0, fillx, hidemode 3"));
add(label, "grow, wmax 100%");
add(editButton, "right");
add(deleteButton, "right, wrap");
add(editPanel, "alignx right");
}
/**
* {@inheritDoc}
*
* @param e Action event
*/
@Override
public void actionPerformed(final ActionEvent e) {
if (e.getSource().equals(deleteButton)) {
fireConditionRemoved(this);
} else if (e.getSource().equals(editButton)) {
editPanel.setVisible(editButton.getModel().isSelected());
}
}
/**
* Adds an ActionConditionRemovalListener to the listener list.
*
* @param listener Listener to add
*/
public void addConditionListener(final ActionConditionRemovalListener listener) {
if (listener == null) {
return;
}
listeners.add(ActionConditionRemovalListener.class, listener);
}
/**
* Removes an ActionConditionRemovalListener from the listener list.
*
* @param listener Listener to remove
*/
public void removeConditionListener(final ActionConditionRemovalListener listener) {
listeners.remove(ActionConditionRemovalListener.class, listener);
}
/**
* Fired when the an action condition is removed.
*
* @param condition Removed condition
*/
protected void fireConditionRemoved(final ActionConditionDisplayPanel condition) {
for (ActionConditionRemovalListener listener : listeners.get(ActionConditionRemovalListener.class)) {
listener.conditionRemoved(condition);
}
}
/** {@inheritDoc} */
@Override
public void setEnabled(final boolean enabled) {
editPanel.setEnabled(enabled);
editButton.setEnabled(enabled);
deleteButton.setEnabled(enabled);
}
/**
* Updates the condition sentence.
*
* @return Updated sentence
*/
private String updateSentence() {
if (trigger == null) {
return "";
} else {
final StringBuilder sb = new StringBuilder();
sb.append("The ");
if (condition.getArg() != -1) {
sb.append(trigger.getType().getArgNames()[condition.getArg()]);
} else {
sb.append("something");
}
sb.append("'s ");
if (condition.getComponent() != null) {
sb.append(condition.getComponent().getName());
} else {
sb.append("something");
}
sb.append(" ");
if (condition.getComparison() != null) {
sb.append(condition.getComparison().getName());
} else {
sb.append("something");
}
sb.append(" '");
if (condition.getTarget() != null) {
sb.append(condition.getTarget());
} else {
sb.append("something");
}
sb.append("'");
return sb.toString();
}
}
/**
* Returns the action condition represented by this panel.
*
* @return Action condition
*/
public ActionCondition getCondition() {
return condition;
}
/** {@inheritDoc} */
@Override
public void propertyChange(final PropertyChangeEvent evt) {
label.setText(updateSentence());
}
}
|
package com.example.reader;
import ilearnrw.textadaptation.TextAnnotationModule;
import ilearnrw.textclassification.Word;
import ilearnrw.user.problems.ProblemDefinition;
import ilearnrw.user.problems.ProblemDefinitionIndex;
import ilearnrw.user.problems.ProblemDescription;
import ilearnrw.user.profile.UserProfile;
import java.io.File;
import java.util.ArrayList;
import com.example.reader.interfaces.ColorPickerListener;
import com.example.reader.interfaces.OnHttpListener;
import com.example.reader.interfaces.OnProfileFetched;
import com.example.reader.results.ProfileResult;
import com.example.reader.tasks.ProfileTask;
import com.example.reader.types.ColorPickerDialog;
import com.example.reader.types.BasicListAdapter;
import com.example.reader.utils.FileHelper;
import com.example.reader.utils.HttpHelper;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Spinner;
public class PresentationModule
extends
Activity
implements
OnClickListener,
OnCheckedChangeListener,
OnHttpListener,
OnProfileFetched,
OnItemSelectedListener {
private LinearLayout colorLayout, container;
private Button btnOk, btnCancel;
private CheckBox chkSwitch;
private RadioGroup rulesGroup;
private RadioButton rbtnRule1, rbtnRule2, rbtnRule3, rbtnRule4;
private Spinner spCategories, spProblems;
private ImageView colorBox;
private File fileHtml = null;
private File fileJSON = null;
private String html, json;
private String name = "";
private Boolean showGUI = false;
private ArrayList<Word> trickyWords;
private SharedPreferences sp;
private String TAG;
private ProblemDefinition[] definitions;
private ProblemDescription[][] descriptions;
private ProblemDescription[] problemDescriptions;
private ArrayList<String> categories;
private ArrayList<String> problems;
private final int DEFAULT_COLOR = 0xffff0000;
private final int DEFAULT_RULE = 3;
private int currentColor;
private int currentRule;
private int currentCategoryPos;
private int currentProblemPos;
private UserProfile userProfile;
private TextAnnotationModule txModule;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TAG = getClass().getName();
Bundle bundle = getIntent().getExtras();
boolean loadFiles = true;
if(bundle.containsKey("loadFiles"))
loadFiles = bundle.getBoolean("loadFiles");
name = bundle.getString("title", "");
showGUI = bundle.getBoolean("showGUI", false);
trickyWords = new ArrayList<Word>();
if(loadFiles){
fileHtml = (File)bundle.get("file");
fileJSON = (File)bundle.get("json");
html = FileHelper.readFromFile(fileHtml);
json = FileHelper.readFromFile(fileJSON);
} else {
html = bundle.getString("html");
json = bundle.getString("json");
}
categories = new ArrayList<String>();
problems = new ArrayList<String>();
setContentView(R.layout.activity_presentation_module);
sp = PreferenceManager.getDefaultSharedPreferences(this);
sp.edit().putBoolean("showGUI", showGUI).commit();
int id = sp.getInt("id",-1);
String token = sp.getString("authToken", "");
if(id==-1 || token.isEmpty()) {
finished(); // If you don't have an id something is terribly wrong
throw new IllegalArgumentException("Missing id or token");
}
init();
}
private void init(){
container = (LinearLayout) findViewById(R.id.presentation_module_container);
if(showGUI)
container.setVisibility(View.VISIBLE);
else
container.setVisibility(View.GONE);
spCategories = (Spinner) findViewById(R.id.categories);
spProblems = (Spinner) findViewById(R.id.problems);
btnOk = (Button) findViewById(R.id.pm_btn_ok);
btnCancel = (Button) findViewById(R.id.pm_btn_cancel);
chkSwitch = (CheckBox) findViewById(R.id.pm_switch);
rulesGroup = (RadioGroup) findViewById(R.id.pm_rules);
rbtnRule1 = (RadioButton) findViewById(R.id.pm_rule1);
rbtnRule2 = (RadioButton) findViewById(R.id.pm_rule2);
rbtnRule3 = (RadioButton) findViewById(R.id.pm_rule3);
rbtnRule4 = (RadioButton) findViewById(R.id.pm_rule4);
colorLayout = (LinearLayout) findViewById(R.id.pm_color_layout);
colorBox = (ImageView) findViewById(R.id.pm_color);
btnCancel.setOnClickListener(this);
btnOk.setOnClickListener(this);
colorLayout.setOnClickListener(this);
rulesGroup.setOnCheckedChangeListener(this);
String userId = Integer.toString(sp.getInt("id", 0));
String token = sp.getString("authToken", "");
currentCategoryPos = 0;
currentProblemPos = 0;
updateColor(currentCategoryPos, currentProblemPos);
updateRule(currentCategoryPos, currentProblemPos);
spCategories.setOnItemSelectedListener(this);
spProblems.setOnItemSelectedListener(this);
chkSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
sp.edit().putBoolean("pm_enabled_" + currentCategoryPos + "_" + currentProblemPos, isChecked).commit();
}
});
new ProfileTask(this, showGUI, this, this).run(userId, token);
}
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.pm_btn_ok:
for (int i = 0; i < definitions.length; i++)
{
int problemSize = descriptions[i].length;
for (int j = 0; j < problemSize; j++)
{
int color = sp.getInt("pm_color_"+i+"_"+j, DEFAULT_COLOR);
int rule = sp.getInt("pm_rule_"+i+"_"+j, DEFAULT_RULE);
this.txModule.getPresentationRulesModule().setPresentationRule(i, j, rule);
if (rbtnRule1.isChecked() || rbtnRule2.isChecked())
{
this.txModule.getPresentationRulesModule().setTextColor(i, j, color);
}
else if (rbtnRule3.isChecked() || rbtnRule4.isChecked())
{
this.txModule.getPresentationRulesModule().setHighlightingColor(i, j, color);
}
}
}
finished();
break;
case R.id.pm_btn_cancel:
onBackPressed();
break;
case R.id.pm_color_layout:
int color = sp.getInt("pm_color_" + currentCategoryPos + "_" + currentProblemPos, DEFAULT_COLOR);
ColorPickerDialog dialog = new ColorPickerDialog(this, color, new ColorPickerListener() {
@Override
public void onOk(ColorPickerDialog dialog, int color) {
sp.edit().putInt("pm_color_" + currentCategoryPos + "_" + currentProblemPos, color).commit();
updateColor(currentCategoryPos, currentProblemPos);
}
@Override
public void onCancel(ColorPickerDialog dialog) {}
});
dialog.show();
break;
}
};
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (group.getId()) {
case R.id.pm_rules:
switch(group.getCheckedRadioButtonId()){
case R.id.pm_rule1:
currentRule = 1;
break;
case R.id.pm_rule2:
currentRule = 2;
break;
case R.id.pm_rule3:
currentRule = 3;
break;
case R.id.pm_rule4:
currentRule = 4;
break;
}
default:
break;
}
sp.edit().putInt("pm_rule_"+currentCategoryPos+"_"+currentProblemPos, currentRule).commit();
updateRule(currentCategoryPos, currentProblemPos);
}
@Override
public void onItemSelected(AdapterView<?> parent, View v, int pos, long id) {
switch(parent.getId()){
case R.id.categories:
currentCategoryPos = pos;
updateProblems(currentCategoryPos);
updateColor(currentCategoryPos, 0);
updateRule(currentCategoryPos, 0);
updateEnabled(currentCategoryPos, 0);
break;
case R.id.problems:
currentProblemPos = pos;
updateColor(currentCategoryPos, currentProblemPos);
updateRule(currentCategoryPos, currentProblemPos);
updateEnabled(currentCategoryPos, currentProblemPos);
break;
default:
break;
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {}
@Override
public void onBackPressed() {
Intent i = new Intent(this, LibraryActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(i);
finish();
}
private void finished(){
try
{
String input = "text/annotate?userId=" + 1 + "&lc=EN&token=";
//String result = txModule.sendPostToServer(sp.getString("authToken", ""), input);
//Log.i("Result", result);
}
catch (Exception e)
{
Log.i("Exception", "I am here: " +e.toString());
}
Intent intent = new Intent(PresentationModule.this, ReaderActivity.class);
intent.putExtra("html", html);
intent.putExtra("json", json);
intent.putExtra("title", name);
intent.putExtra("trickyWords", (ArrayList<Word>) trickyWords);
startActivity(intent);
}
private void updateColor(int category, int problem){
currentColor = sp.getInt("pm_color_"+category+"_"+problem, DEFAULT_COLOR);
colorBox.setBackgroundColor(currentColor);
}
private void updateRule(int category, int problem){
currentRule = sp.getInt("pm_rule_"+category+"_"+problem, DEFAULT_RULE);
switch(currentRule){
case 1:
rbtnRule1.setChecked(true);
break;
case 2:
rbtnRule2.setChecked(true);
break;
case 3:
rbtnRule3.setChecked(true);
break;
case 4:
rbtnRule4.setChecked(true);
break;
}
}
private void updateEnabled(int category, int problem){
boolean isChecked = sp.getBoolean("pm_enabled_"+category+"_"+problem, true);
chkSwitch.setChecked(isChecked);
}
private void updateProblems(int index){
problemDescriptions = descriptions[index];
currentProblemPos = 0;
problems.clear();
for(int i=0; i<problemDescriptions.length; i++){
String[] descriptions = problemDescriptions[i].getDescriptions();
String str = "";
for(int j=0; j<descriptions.length; j++){
if(j+1<descriptions.length)
str += descriptions[j] + " | ";
else
str += descriptions[j];
}
problems.add((i+1) + ". " + str);
}
ArrayAdapter<String> problemAdapter = new BasicListAdapter(this, R.layout.textview_item_multiline, problems, true);
problemAdapter.notifyDataSetChanged();
spProblems.setAdapter(problemAdapter);
}
@Override
public void onTokenExpired(final String... params) {
if(HttpHelper.refreshTokens(this)){
final String newToken = sp.getString("authToken", "");
runOnUiThread(new Runnable() {
@Override
public void run() {
new ProfileTask(PresentationModule.this, showGUI, PresentationModule.this, PresentationModule.this).run(params[0], newToken);
Log.d(TAG, getString(R.string.token_error_retry));
Toast.makeText(PresentationModule.this, getString(R.string.token_error_retry), Toast.LENGTH_SHORT).show();
}
});
}
}
@Override
public void onProfileFetched(ProfileResult profile) {
trickyWords = (ArrayList<Word>) profile.userProblems.getTrickyWords();
if(!showGUI){
finished();
return;
}
ProblemDefinitionIndex index = profile.userProblems.getProblems();
definitions = index.getProblemsIndex();
descriptions = index.getProblems();
categories.clear();
for(int i=0; i<definitions.length;i++){
categories.add((i+1) + ". " + definitions[i].getURI());
}
currentCategoryPos = 0;
updateProblems(currentCategoryPos);
ArrayAdapter<String> categoryAdapter = new BasicListAdapter(this, R.layout.textview_item_multiline, categories, true);
spCategories.setAdapter(categoryAdapter);
userProfile = new UserProfile(profile.language, profile.userProblems, profile.preferences);
txModule = new TextAnnotationModule(html, userProfile);
}
}
|
package nallar.tickthreading.util.contextaccess;
import nallar.tickthreading.Log;
import nallar.tickthreading.util.EnvironmentInfo;
class ContextAccessProvider {
private static final Class[] contextAccessClasses = {
ContextAccessReflection.class,
ContextAccessSecurityManager.class,
};
static ContextAccess getContextAccess() {
for (Class<?> clazz : contextAccessClasses) {
try {
ContextAccess contextAccess = (ContextAccess) clazz.newInstance();
Class<?> currentClass = contextAccess.getContext(0);
if (currentClass != ContextAccessProvider.class) {
StringBuilder sb = new StringBuilder();
sb.append("Stack:\n");
for (int i = -2; i < 3; i++) {
try {
sb.append(contextAccess.getContext(i).getName()).append(" at ").append(i).append('\n');
} catch (Throwable ignored) {
}
}
throw new Error("Wrong class returned: " + currentClass + ", expected ContextAccessProvider. " + sb);
}
return contextAccess;
} catch (Throwable t) {
if (Log.debug) {
Log.debug("Unable to set up context access class " + clazz + ". " + t.getMessage() + ", falling back to slower context access. On JRE: " + EnvironmentInfo.getJavaVersion());
}
}
}
throw new Error("Failed to set up any context access");
}
}
|
package com.gh4a.activities.home;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.Loader;
import android.support.v7.app.ActionBar;
import android.util.SparseArray;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.gh4a.BasePagerActivity;
import com.gh4a.Gh4Application;
import com.gh4a.R;
import com.gh4a.activities.BookmarkListActivity;
import com.gh4a.activities.SearchActivity;
import com.gh4a.activities.SettingsActivity;
import com.gh4a.fragment.RepositoryListContainerFragment;
import com.gh4a.loader.LoaderCallbacks;
import com.gh4a.loader.LoaderResult;
import com.gh4a.loader.UserLoader;
import com.gh4a.utils.AvatarHandler;
import com.gh4a.utils.IntentUtils;
import org.eclipse.egit.github.core.User;
public class HomeActivity extends BasePagerActivity implements
View.OnClickListener, RepositoryListContainerFragment.Callback {
private static final int REQUEST_SETTINGS = 10000;
private FragmentFactory mFactory;
private SparseArray<Fragment> mFragments;
private ImageView mAvatarView;
private String mUserLogin;
private int mSelectedFactoryId;
private boolean mStarted;
private static final String STATE_KEY_FACTORY_ITEM = "factoryItem";
private LoaderCallbacks<User> mUserCallback = new LoaderCallbacks<User>(this) {
@Override
protected Loader<LoaderResult<User>> onCreateLoader() {
return new UserLoader(HomeActivity.this, mUserLogin);
}
@Override
protected void onResultReady(User result) {
mAvatarView.setTag(result);
AvatarHandler.assignAvatar(mAvatarView, result);
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
mUserLogin = Gh4Application.get().getAuthLogin();
if (savedInstanceState != null) {
mSelectedFactoryId = savedInstanceState.getInt(STATE_KEY_FACTORY_ITEM);
} else {
mSelectedFactoryId = R.id.news_feed;
}
mFactory = getFactoryForItem(mSelectedFactoryId);
mFragments = new SparseArray<>();
super.onCreate(savedInstanceState);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle(mFactory.getTitleResId());
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_KEY_FACTORY_ITEM, mSelectedFactoryId);
mFactory.onSaveInstanceState(outState);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState != null) {
mFactory.onRestoreInstanceState(savedInstanceState);
}
}
@Override
public void onClick(View view) {
User user = (User) view.getTag();
Intent intent = IntentUtils.getUserActivityIntent(this, user);
if (intent != null) {
closeDrawers();
startActivity(intent);
}
}
@Override
protected int getLeftNavigationDrawerMenuResource() {
return R.menu.home_nav_drawer;
}
@Override
protected int[] getRightNavigationDrawerMenuResources() {
return mFactory.getToolDrawerMenuResIds();
}
@Override
protected void onPrepareRightNavigationDrawerMenu(Menu menu) {
super.onPrepareRightNavigationDrawerMenu(menu);
mFactory.prepareToolDrawerMenu(menu);
}
@Override
protected View getLeftDrawerTitle(ViewGroup container) {
View view = getLayoutInflater().inflate(R.layout.drawer_title_home, container, false);
mAvatarView = (ImageView) view.findViewById(R.id.avatar);
mAvatarView.setOnClickListener(this);
getSupportLoaderManager().initLoader(0, null, mUserCallback);
TextView nameView = (TextView) view.findViewById(R.id.user_name);
nameView.setText(mUserLogin);
return view;
}
@Override
public boolean onNavigationItemSelected(MenuItem item) {
super.onNavigationItemSelected(item);
if (mFactory != null && mFactory.onDrawerItemSelected(item)) {
return true;
}
int id = item.getItemId();
FragmentFactory factory = getFactoryForItem(id);
if (factory != null) {
switchTo(id, factory);
return true;
}
switch (id) {
case R.id.search:
startActivity(new Intent(this, SearchActivity.class));
return true;
case R.id.bookmarks:
startActivity(new Intent(this, BookmarkListActivity.class));
return true;
case R.id.settings:
startActivityForResult(new Intent(this, SettingsActivity.class), REQUEST_SETTINGS);
return true;
}
return false;
}
private FragmentFactory getFactoryForItem(int id) {
switch (id) {
case R.id.news_feed:
return new NewsFeedFactory(this, mUserLogin);
case R.id.my_repos:
return new RepositoryFactory(this, mUserLogin);
case R.id.my_issues:
return new IssueListFactory(this, mUserLogin, false);
case R.id.my_prs:
return new IssueListFactory(this, mUserLogin, true);
case R.id.my_gists:
return new GistFactory(this, mUserLogin);
case R.id.pub_timeline:
return new TimelineFactory(this);
case R.id.blog:
return new BlogFactory(this);
case R.id.trend:
return new TrendingFactory(this);
}
return null;
}
@Override
protected int[] getTabTitleResIds() {
return mFactory.getTabTitleResIds();
}
@Override
protected Fragment getFragment(int position) {
Fragment fragment = mFactory.getFragment(position);
mFragments.put(position, fragment);
return fragment;
}
@Override
protected void onStart() {
super.onStart();
mStarted = true;
mFactory.onStart();
}
@Override
protected void onStop() {
super.onStop();
mStarted = false;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (mFactory.onCreateOptionsMenu(menu)) {
return true;
}
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mFactory.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_SETTINGS) {
if (data.getBooleanExtra(SettingsActivity.RESULT_EXTRA_THEME_CHANGED, false)
|| data.getBooleanExtra(SettingsActivity.RESULT_EXTRA_AUTH_CHANGED, false)) {
goToToplevelActivity();
finish();
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
@Override
protected Intent navigateUp() {
return getToplevelActivityIntent();
}
@Override
protected boolean canSwipeToRefresh() {
return true;
}
@Override
public void onRefresh() {
for (int i = 0; i < mFragments.size(); i++) {
int position = mFragments.keyAt(i);
mFactory.onRefreshFragment(mFragments.get(position));
}
getSupportLoaderManager().restartLoader(0, null, mUserCallback);
refreshDone();
}
@Override
public void supportInvalidateOptionsMenu() {
if (mFactory instanceof RepositoryFactory) {
// happens when load is done; we ignore it as we don't want to close the IME in that case
} else {
super.supportInvalidateOptionsMenu();
}
}
@Override
public void onBackPressed() {
FragmentManager fm = getSupportFragmentManager();
if (fm.getBackStackEntryCount() > 0) {
fm.popBackStack();
} else if (!closeDrawers()) {
super.onBackPressed();
}
}
@Override
public void initiateFilter() {
toggleRightSideDrawer();
}
@Override
protected boolean fragmentNeedsRefresh(Fragment object) {
return true;
}
public void doInvalidateOptionsMenuAndToolDrawer() {
super.supportInvalidateOptionsMenu();
updateRightNavigationDrawer();
}
@Override
public void invalidateFragments() {
mFragments.clear();
super.invalidateFragments();
}
public void toggleToolDrawer() {
toggleRightSideDrawer();
}
public void invalidateTitle() {
getSupportActionBar().setTitle(mFactory.getTitleResId());
}
private void switchTo(int itemId, FragmentFactory factory) {
if (mFactory != null) {
mFactory.onDestroy();
}
mFactory = factory;
mSelectedFactoryId = itemId;
updateRightNavigationDrawer();
super.supportInvalidateOptionsMenu();
getSupportFragmentManager().popBackStackImmediate(null,
FragmentManager.POP_BACK_STACK_INCLUSIVE);
invalidateTitle();
invalidateTabs();
if (mStarted) {
mFactory.onStart();
}
}
}
|
package de.lmu.ifi.dbs.elki.math.statistics.distribution;
import de.lmu.ifi.dbs.elki.math.MathUtil;
import de.lmu.ifi.dbs.elki.utilities.documentation.Reference;
import de.lmu.ifi.dbs.elki.utilities.exceptions.AbortException;
import de.lmu.ifi.dbs.elki.utilities.exceptions.ExceptionMessages;
/**
* INCOMPLETE implementation of the poisson distribution.
*
* TODO: continue implementing, CDF and nextRandom are missing
*
* References:
* <p>
* Catherine Loader<br />
* Fast and Accurate Computation of Binomial Probabilities.
* </p>
*
* @author Erich Schubert
*/
public class PoissonDistribution implements Distribution {
/**
* Number of tries
*/
private int n;
/**
* Success probability
*/
private double p;
/** Stirling error constants: 1./12 */
private final static double S0 = 0.08333333333333333333333d;
/** Stirling error constants: 1./360 */
private final static double S1 = 0.0027777777777777777777777777778d;
/** Stirling error constants: 1./1260 */
private final static double S2 = 0.00079365079365079365079365d;
/** Stirling error constants: 1./1680 */
private final static double S3 = 0.000595238095238095238095238095d;
/** Stirling error constants: 1./1188 */
private final static double S4 = 0.00084175084175084175084175084175d;
/**
* Exact table values for n <= 15 in steps of 0.5
*
* sfe[n] = ln( (n!*e^n)/((n^n)*sqrt(2*pi*n)) )
*/
private final static double STIRLING_EXACT_ERROR[] = {
0.0,
0.1534264097200273452913848,
0.0810614667953272582196702,
0.0548141210519176538961390,
0.0413406959554092940938221,
0.03316287351993628748511048,
0.02767792568499833914878929,
0.02374616365629749597132920,
0.02079067210376509311152277,
0.01848845053267318523077934,
0.01664469118982119216319487,
0.01513497322191737887351255,
0.01387612882307074799874573,
0.01281046524292022692424986,
0.01189670994589177009505572,
0.01110455975820691732662991,
0.010411265261972096497478567,
0.009799416126158803298389475,
0.009255462182712732917728637,
0.008768700134139385462952823,
0.008330563433362871256469318, // 10.0
0.007934114564314020547248100, // 10.5
0.007573675487951840794972024, // 11.0
0.007244554301320383179543912, // 11.5
0.006942840107209529865664152, // 12.0
0.006665247032707682442354394, // 12.5
0.006408994188004207068439631, // 13.0
0.006171712263039457647532867, // 13.5
0.005951370112758847735624416, // 14.0
0.005746216513010115682023589, // 14.5
0.0055547335519628013710386900 // 15.0
};
/**
* Constructor.
*
* Private: API not yet completely implemented!
*
* @param n Number of tries
* @param p Success probability
*/
public PoissonDistribution(int n, double p) {
super();
this.n = n;
this.p = p;
}
@Override
public double nextRandom() {
throw new AbortException(ExceptionMessages.UNSUPPORTED_NOT_YET);
}
/**
* Poisson PMF for integer values.
*
* @param x integer values
* @return Probability
*/
@Reference(title = "Fast and accurate computation of binomial probabilities", authors = "C. Loader", booktitle = "", url = "http://projects.scipy.org/scipy/raw-attachment/ticket/620/loader2000Fast.pdf")
public double pmf(int x) {
// Invalid values
if(x < 0 || x > n) {
return 0.0;
}
// Extreme probabilities
if(p <= 0d) {
return x == 0 ? 1.0 : 0.0;
}
if(p >= 1d) {
return x == n ? 1.0 : 0.0;
}
// Extreme values of x
if(x == 0) {
if(p < 0.1) {
return Math.exp(-devianceTerm(n, n * (1.0 - p)) - n * p);
}
else {
return Math.exp(n * Math.log(1.0 - p));
}
}
if(x == n) {
if(p > 0.9) {
return Math.exp(-devianceTerm(n, n * p) - n * (1 - p));
}
else {
return Math.exp(n * Math.log(p));
}
}
final double lc = stirlingError(n) - stirlingError(x) - stirlingError(n - x) - devianceTerm(x, n * p) - devianceTerm(n - x, n * (1.0 - p));
final double f = (MathUtil.TWOPI * x * (n - x)) / n;
return Math.exp(lc) / Math.sqrt(f);
}
@Override
@Reference(title = "Fast and accurate computation of binomial probabilities", authors = "C. Loader", booktitle = "", url = "http://projects.scipy.org/scipy/raw-attachment/ticket/620/loader2000Fast.pdf")
public double pdf(double x) {
// Invalid values
if(x < 0 || x > n) {
return 0.0;
}
// Extreme probabilities
if(p <= 0d) {
return x == 0 ? 1.0 : 0.0;
}
if(p >= 1d) {
return x == n ? 1.0 : 0.0;
}
final double q = 1 - p;
// FIXME: check for x to be integer, return 0 otherwise?
// Extreme values of x
if(x == 0) {
if(p < 0.1) {
return Math.exp(-devianceTerm(n, n * q) - n * p);
}
else {
return Math.exp(n * Math.log(q));
}
}
if(x == n) {
if(p > 0.9) {
return Math.exp(-devianceTerm(n, n * p) - n * q);
}
else {
return Math.exp(n * Math.log(p));
}
}
final double lc = stirlingError(n) - stirlingError(x) - stirlingError(n - x) - devianceTerm(x, n * p) - devianceTerm(n - x, n * q);
final double f = (MathUtil.TWOPI * x * (n - x)) / n;
return Math.exp(lc) / Math.sqrt(f);
}
@Override
public double cdf(double val) {
throw new AbortException(ExceptionMessages.UNSUPPORTED_NOT_YET);
}
/**
* Compute the poisson distribution PDF with an offset of + 1
*
* pdf(x_plus_1 - 1, lambda)
*
* @param x_plus_1 x+1
* @param lambda Lambda
* @return pdf
*/
public static double poissonPDFm1(double x_plus_1, double lambda) {
if(Double.isInfinite(lambda)) {
return 0.;
}
if(x_plus_1 > 1) {
return rawProbability(x_plus_1 - 1, lambda);
}
if(lambda > Math.abs(x_plus_1 - 1) * MathUtil.LOG2 * Double.MAX_EXPONENT / 1e-14) {
return Math.exp(-lambda - GammaDistribution.logGamma(x_plus_1));
}
else {
return rawProbability(x_plus_1, lambda) * (x_plus_1 / lambda);
}
}
/**
* Compute the poisson distribution PDF with an offset of + 1
*
* log pdf(x_plus_1 - 1, lambda)
*
* @param x_plus_1 x+1
* @param lambda Lambda
* @return pdf
*/
public static double logpoissonPDFm1(double x_plus_1, double lambda) {
if(Double.isInfinite(lambda)) {
return Double.NEGATIVE_INFINITY;
}
if(x_plus_1 > 1) {
return rawLogProbability(x_plus_1 - 1, lambda);
}
if(lambda > Math.abs(x_plus_1 - 1) * MathUtil.LOG2 * Double.MAX_EXPONENT / 1e-14) {
return -lambda - GammaDistribution.logGamma(x_plus_1);
}
else {
return rawLogProbability(x_plus_1, lambda) + Math.log(x_plus_1 / lambda);
}
}
/**
* Calculates the Striling Error
*
* stirlerr(n) = ln(n!) - ln(sqrt(2*pi*n)*(n/e)^n)
*
* @param n Parameter n
* @return Stirling error
*/
@Reference(title = "Fast and accurate computation of binomial probabilities", authors = "C. Loader", booktitle = "", url = "http://projects.scipy.org/scipy/raw-attachment/ticket/620/loader2000Fast.pdf")
private static double stirlingError(int n) {
// Try to use a table value:
if(n < 16) {
return STIRLING_EXACT_ERROR[n * 2];
}
final double nn = n * n;
// Use the appropriate number of terms
if(n > 500) {
return (S0 - S1 / nn) / n;
}
if(n > 80) {
return ((S0 - (S1 - S2 / nn)) / nn) / n;
}
if(n > 35) {
return ((S0 - (S1 - (S2 - S3 / nn) / nn) / nn) / n);
}
return ((S0 - (S1 - (S2 - (S3 - S4 / nn) / nn) / nn) / nn) / n);
}
/**
* Calculates the Striling Error
*
* stirlerr(n) = ln(n!) - ln(sqrt(2*pi*n)*(n/e)^n)
*
* @param n Parameter n
* @return Stirling error
*/
@Reference(title = "Fast and accurate computation of binomial probabilities", authors = "C. Loader", booktitle = "", url = "http://projects.scipy.org/scipy/raw-attachment/ticket/620/loader2000Fast.pdf")
private static double stirlingError(double n) {
if(n < 16.0) {
// Our table has a step size of 0.5
final double n2 = 2.0 * n;
if(Math.floor(n2) == n2) { // Exact match
return STIRLING_EXACT_ERROR[(int) n2];
}
else {
return GammaDistribution.logGamma(n + 1.0) - (n + 0.5) * Math.log(n) + n - MathUtil.LOGSQRTTWOPI;
}
}
final double nn = n * n;
if(n > 500.0) {
return (S0 - S1 / nn) / n;
}
if(n > 80.0) {
return ((S0 - (S1 - S2 / nn)) / nn) / n;
}
if(n > 35.0) {
return ((S0 - (S1 - (S2 - S3 / nn) / nn) / nn) / n);
}
return ((S0 - (S1 - (S2 - (S3 - S4 / nn) / nn) / nn) / nn) / n);
}
/**
* Evaluate the deviance term of the saddle point approximation.
*
* bd0(x,np) = x*ln(x/np)+np-x
*
* @param x probability density function position
* @param np product of trials and success probability: n*p
* @return Deviance term
*/
@Reference(title = "Fast and accurate computation of binomial probabilities", authors = "C. Loader", booktitle = "", url = "http://projects.scipy.org/scipy/raw-attachment/ticket/620/loader2000Fast.pdf")
private static double devianceTerm(double x, double np) {
if(Math.abs(x - np) < 0.1 * (x + np)) {
final double v = (x - np) / (x + np);
double s = (x - np) * v;
double ej = 2.0d * x * v;
for(int j = 1;; j++) {
ej *= v * v;
final double s1 = s + ej / (2 * j + 1);
if(s1 == s) {
return s1;
}
s = s1;
}
}
return x * Math.log(x / np) + np - x;
}
/**
* Poisson distribution probability, but also for non-integer arguments.
*
* lb^x exp(-lb) / x!
*
* @param x X
* @param lambda lambda
* @return Poisson distribution probability
*/
public static double rawProbability(double x, double lambda) {
// Extreme lambda
if(lambda == 0) {
return ((x == 0) ? 1. : 0.);
}
// Extreme values
if(Double.isInfinite(lambda) || x < 0) {
return 0.;
}
if(x <= lambda * Double.MIN_NORMAL) {
return Math.exp(-lambda);
}
if(lambda < x * Double.MIN_NORMAL) {
double r = -lambda + x * Math.log(lambda) - GammaDistribution.logGamma(x + 1);
return Math.exp(r);
}
final double f = MathUtil.TWOPI * x;
final double y = -stirlingError(x) - devianceTerm(x, lambda);
return Math.exp(y) / Math.sqrt(f);
}
/**
* Poisson distribution probability, but also for non-integer arguments.
*
* lb^x exp(-lb) / x!
*
* @param x X
* @param lambda lambda
* @param log_p Flag to return log scale result
* @return Poisson distribution probability
*/
public static double rawLogProbability(double x, double lambda) {
// Extreme lambda
if(lambda == 0) {
return ((x == 0) ? 1. : Double.NEGATIVE_INFINITY);
}
// Extreme values
if(Double.isInfinite(lambda) || x < 0) {
return Double.NEGATIVE_INFINITY;
}
if(x <= lambda * Double.MIN_NORMAL) {
return -lambda;
}
if(lambda < x * Double.MIN_NORMAL) {
return -lambda + x * Math.log(lambda) - GammaDistribution.logGamma(x + 1);
}
final double f = MathUtil.TWOPI * x;
final double y = -stirlingError(x) - devianceTerm(x, lambda);
return -0.5 * Math.log(f) + y;
}
}
|
package de.mpicbg.tds.knime.hcstools.visualization.heatmapviewer;
import de.mpicbg.tds.knime.hcstools.visualization.heatmapviewer.model.Plate;
import de.mpicbg.tds.core.util.PanelImageExporter;
import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.*;
/**
* Creates a window for a detailed plate view.
* Replaces PlatePanel
*
* @author Felix Meyenhofer
* created: 20/12/12
*/
public class PlateViewer extends JFrame implements HeatMapModelChangeListener, HeatMapViewer {
/** The plate grid {@link HeatTrellis} holds the {@link HeatMapModel} instance
* containing the {@link HeatMapModelChangeListener} needed to update the GUIs */
private HeatTrellis updater;
/** The {@link HeatMapModel} object which is patially seperated for this instnance of the PlateViewer. */
private HeatMapModel heatMapModel;
/** GUI components made accessible */
private JPanel heatMapContainer;
private HeatMapColorToolBar colorbar;
private HeatMapInputToolbar toolbar;
/**
* Constructor for the GUI component initialization.
*/
public PlateViewer() {
this.initialize();
}
/**
* Constructor of the PlateViewer allowing to propagate the data from
* {@link ScreenViewer}.
*
* @param parent {@link HeatTrellis} is the plate grid from the {@link ScreenViewer}.
* @param plate {@link Plate} object containing the data for visualization.
*/
public PlateViewer(HeatTrellis parent, Plate plate) {
this();
this.updater = parent;
// Create a new instance of the HeatMapModel and copy some attributes.
HeatMapModel model = new HeatMapModel();
model.setCurrentReadout(parent.heatMapModel.getSelectedReadOut());
model.setOverlay(parent.heatMapModel.getOverlay());
model.setColorScheme(parent.heatMapModel.getColorScheme());
model.setHideMostFreqOverlay(parent.heatMapModel.doHideMostFreqOverlay());
model.setWellSelection(parent.heatMapModel.getWellSelection());
model.setHiLite(parent.heatMapModel.getHiLite());
model.setHiLiteHandler(parent.heatMapModel.getHiLiteHandler());
model.setColorGradient(parent.heatMapModel.getColorGradient());
if ( parent.heatMapModel.isGlobalScaling() ) {
model.setScreen(parent.heatMapModel.getScreen());
model.setReadoutRescaleStrategy(parent.heatMapModel.getReadoutRescaleStrategy());
} else {
model.setScreen(Arrays.asList(plate));
model.setReadoutRescaleStrategy(parent.heatMapModel.getReadoutRescaleStrategyInstance());
}
this.heatMapModel = model;
// Creating the menu
JMenuBar menu = new JMenuBar();
menu.add(new HiLiteMenu(this));
ViewMenu viewMenu = new ViewMenu(this);
menu.add(viewMenu);
if ( parent.heatMapModel.isGlobalScaling() )
viewMenu.getColorMenuItem().setEnabled(!parent.heatMapModel.isGlobalScaling());
setJMenuBar(menu);
// Register the Viewer in the ChangeListeners
parent.heatMapModel.addChangeListener(this);
this.heatMapModel.addChangeListener(this);
// Configure
this.toolbar.configure(this.heatMapModel);
this.colorbar.configure(this.heatMapModel);
// Give a meaningful title.
this.setTitle("Plate Viewer (" + plate.getBarcode() + ")");
// Remove the HeatMapModelChangeListener when closing the window.
this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent windowEvent) {
PlateViewer viewer = (PlateViewer) windowEvent.getSource();
HeatMapModel model = viewer.updater.getHeatMapModel();
model.removeChangeListener(viewer);
viewer.setVisible(false);
}
});
// Configure the toolbars.
toolbar.configure(this.heatMapModel);
colorbar.configure(this.heatMapModel);
// Add the plate heatmap
HeatPlate heatMap = new HeatPlate(this, plate);
heatMapContainer.add(heatMap);
// Add "save image" functionality
new PanelImageExporter(heatMapContainer, true);
// Set the window dimensions given by the plate heatmap size.
Dimension ms = heatMap.getPreferredSize();
heatMapContainer.setPreferredSize(new Dimension(ms.width+10, ms.height+10));
pack();
// Set the location of the new PlateViewer
Random posJitter = new Random();
double left = Toolkit.getDefaultToolkit().getScreenSize().getWidth() - this.getWidth() - 100;
setLocation((int) left + posJitter.nextInt(100), 200 + posJitter.nextInt(100));
}
/**
* GUI component initialization.
*/
private void initialize() {
setMinimumSize(new Dimension(400, 250));
// menu = new PlateMenu(this);
// setJMenuBar(menu);
setLayout(new BorderLayout());
toolbar = new HeatMapInputToolbar(this);
add(toolbar, BorderLayout.NORTH);
heatMapContainer = new JPanel(new FlowLayout(FlowLayout.CENTER, 0,0));
heatMapContainer.setBorder(BorderFactory.createEmptyBorder(0,0,10,10));
add(heatMapContainer, BorderLayout.CENTER);
colorbar = new HeatMapColorToolBar();
add(colorbar, BorderLayout.SOUTH);
}
/**
* Getter for the {@link HeatTrellis} object.
*
* @return {@link HeatTrellis}
*/
public HeatTrellis getUpdater() {
return updater;
}
/**
* The HeatMapModelChangeListener interface.
*/
@Override
public void modelChanged() {
if (isVisible() && getWidth() > 0)
repaint();
}
/** {@inheritDoc} */
@Override
public HeatMapColorToolBar getColorBar() {
return colorbar;
}
/** {@inheritDoc} */
@Override
public HeatMapInputToolbar getToolBar() {
return toolbar;
}
/** {@inheritDoc} */
@Override
public HeatMapModel getHeatMapModel() {
return heatMapModel;
}
/** {@inheritDoc} */
@Override
public Map<UUID, PlateViewer> getChildViews() {
return null;
}
/**
* Quick testing.
*/
public static void main(String[] args) {
PlateViewer plateViewer = new PlateViewer();
plateViewer.heatMapModel = new HeatMapModel();
plateViewer.setSize(new Dimension(400, 250));
plateViewer.setVisible(true);
}
}
|
package com.google.code.quandary;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import com.google.android.youtube.api.YouTube;
import com.google.android.youtube.api.YouTubeBaseActivity;
import com.google.android.youtube.api.YouTubePlayer;
import com.google.android.youtube.api.YouTubePlayer.OnFullscreenListener;
import com.google.android.youtube.api.YouTubePlayerView;
import com.google.code.quandary.quiz.Question;
import com.google.code.quandary.quiz.Quiz;
import java.util.List;
/**
* Sample activity showing how to properly enable custom fullscreen behavior.
* <p/>
* This is the preferred way of handling fullscreen because the default fullscreen implementation
* will cause re-buffering of the video.
*/
public class QuizActivity extends YouTubeBaseActivity implements OnFullscreenListener,
YouTubePlayer.PlaybackEventListener {
private LinearLayout baseLayout;
private YouTubePlayerView player;
private View otherViews;
private int windowFlags;
private Quiz quiz;
private boolean fullscreen;
private Integer currentQuestion = 0;
private Handler mHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mHandler = new Handler(getMainLooper());
windowFlags = Window.FEATURE_NO_TITLE;
if (Build.VERSION.SDK_INT >= 11) {
// If you would like the action bar to be shown together with the player's controls when
// in fullscreen, it has to be an OVERLAY or it will be automatically hidden.
windowFlags |= Window.FEATURE_ACTION_BAR_OVERLAY;
}
requestWindowFeature(windowFlags);
setContentView(R.layout.quiz);
baseLayout = (LinearLayout) findViewById(R.id.layout);
player = (YouTubePlayerView) findViewById(R.id.player);
otherViews = findViewById(R.id.other_views);
if (getActionBar() != null) {
getActionBar().setBackgroundDrawable(new ColorDrawable(Color.BLACK));
}
Intent intent = getIntent();
quiz = (Quiz) intent.getSerializableExtra("myquiz");
YouTube.initialize(this, DeveloperKey.DEVELOPER_KEY);
registerPlayerView(player);
player.setPlaybackEventListener(this);
// Specify that we want handle fullscreen behavior ourselves.
player.enableCustomFullscreen(this);
// You can use your own button to switch to fullscreen too
findViewById(R.id.fullscreen_button).setOnClickListener(
new OnClickListener() {
@Override
public void onClick(View view) {
player.setFullscreen(!fullscreen);
}
}
);
// Go to the QuizScoreActivity when the user presses "Finish".
findViewById(R.id.finish_button).setOnClickListener(
new OnClickListener() {
@Override
public void onClick(View view) {
Intent intent;
intent = new Intent(QuizActivity.this, QuizScoreActivity.class);
intent.putExtra("quiz", quiz);
startActivity(intent);
}
}
);
doLayout();
}
@Override
protected void onResume() {
super.onResume();
player.loadVideo(quiz.getVideoId());
}
public void onPlaying() {
List<Question> questions = quiz.getQuestions();
if (currentQuestion < questions.size()) {
Long timeToPause= currentQuestion == 0 ? questions.get(currentQuestion).getTimeToPause()
: questions.get(currentQuestion).getTimeToPause() - questions.get(currentQuestion - 1).getTimeToPause();
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
player.pause();
currentQuestion++;
}
},timeToPause
);
new QuizCheckerRunnable(player);
}
}
public void onPaused() {}
public void onStopped() {}
public void onBuffering(boolean b) {}
public void onSeekTo(int i) {}
private void doLayout() {
if (fullscreen) {
// When in fullscreen, the visibility of all other views than the player should be set to
// GONE and the player should be laid out across the whole screen.
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) player.getLayoutParams();
params.width = LayoutParams.MATCH_PARENT;
params.height = LayoutParams.MATCH_PARENT;
otherViews.setVisibility(View.GONE);
baseLayout.setPadding(0, 0, 0, 0);
} else {
// This layout is up to you - it's just a very simple demo (vertically stacked boxes in
// portrait, horizontally stacked in landscape).
boolean landscape =
getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE;
setParamsForOrientation(player, landscape);
setParamsForOrientation(otherViews, landscape);
otherViews.setVisibility(View.VISIBLE);
baseLayout.setOrientation(landscape ? LinearLayout.HORIZONTAL : LinearLayout.VERTICAL);
int topPadding = windowFlags != Window.FEATURE_NO_TITLE ? getActionBarHeightPx() : 0;
baseLayout.setPadding(0, topPadding, 0, 0);
}
}
private void setParamsForOrientation(View view, boolean landscape) {
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams();
// We use a LinearLayout with weights and set the size of the dimension we share with the other
// box to 0
params.width = landscape ? 0 : LayoutParams.MATCH_PARENT;
params.height = landscape ? LayoutParams.MATCH_PARENT : 0;
}
@Override
public void onFullscreen(boolean isFullscreen) {
fullscreen = isFullscreen;
doLayout();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
doLayout();
}
private int getActionBarHeightPx() {
int[] attrs = new int[]{android.R.attr.actionBarSize};
return (int) getTheme().obtainStyledAttributes(attrs).getDimension(0, 0f);
}
}
|
package dr.evomodel.epidemiology.casetocase;
import dr.app.tools.NexusExporter;
import dr.evolution.tree.*;
import dr.evolution.util.Date;
import dr.evolution.util.Taxon;
import dr.evolution.util.TaxonList;
import dr.evolution.util.Units;
import dr.evomodel.tree.TreeModel;
import dr.inference.loggers.LogColumn;
import dr.inference.loggers.Loggable;
import dr.inference.model.AbstractModelLikelihood;
import dr.inference.model.Model;
import dr.inference.model.Parameter;
import dr.inference.model.Variable;
import dr.math.LogTricks;
import dr.math.MathUtils;
import dr.util.Author;
import dr.util.Citable;
import dr.util.Citation;
import dr.xml.*;
import java.io.*;
import java.util.*;
/**
* A likelihood function for transmission between identified epidemiological cases
*
* Currently works only for fixed trees and estimates the network and epidemiological parameters. Timescale
* must be in days. Python scripts to write XML for it and analyse the posterior set of networks exist; contact MH.
*
* @author Matthew Hall
* @author Andrew Rambaut
* @version $Id: $
*/
public class CaseToCaseTransmissionLikelihood extends AbstractModelLikelihood implements Loggable, Citable,
TreeTraitProvider {
/* The phylogenetic tree. */
private TreeModel virusTree;
private int noTips;
/* Mapping of cases to branches on the tree; old version is stored before operators are applied */
private AbstractCase[] branchMap;
private AbstractCase[] storedBranchMap;
/* The log likelihood of the subtree from the parent branch of the referred-to node downwards; old version is stored
before TT operators are applied.*/
private double[] nodeLogLikelihoods;
private double[] storedNodeLogLikelihoods;
/* Whether operations have required the recalculation of the log likelihoods of the subtree from the parent branch
of the referred-to node downwards.
*/
private boolean[] nodeRecalculationNeeded;
private boolean[] storedRecalculationArray;
/* Matches cases to external nodes */
private HashMap<AbstractCase, NodeRef> tipMap;
private double estimatedLastSampleTime;
boolean verbose;
protected TreeTraitProvider.Helper treeTraits = new Helper();
/* possible paintings for each node */
private HashMap<Integer, HashSet<AbstractCase>> nodePaintingPossibilities;
private HashMap<Integer, HashSet<AbstractCase>> storedNodePaintingPossibilities;
/**
* The set of cases
*/
private AbstractOutbreak cases;
private boolean likelihoodKnown = false;
private double logLikelihood;
// for extended version (not implemented at present)
private boolean extended;
private boolean[] switchLocks;
private boolean[] creepLocks;
private boolean sampleTTs;
private double[] rootLikelihoods;
private double[] storedRootLikelihoods;
private double[] subLikelihoods;
private double[] storedSubLikelihoods;
private boolean currentReconstructionExists;
// PUBLIC STUFF
// Name
public static final String CASE_TO_CASE_TRANSMISSION_LIKELIHOOD = "caseToCaseTransmissionLikelihood";
public static final String PAINTINGS_KEY = "paintings";
// Basic constructor.
public CaseToCaseTransmissionLikelihood(TreeModel virusTree, AbstractOutbreak caseData,
String startingNetworkFileName, boolean extended, boolean sampleTTs)
throws TaxonList.MissingTaxonException {
this(CASE_TO_CASE_TRANSMISSION_LIKELIHOOD, virusTree, caseData, startingNetworkFileName, extended, sampleTTs);
}
// Legacy constructor
public CaseToCaseTransmissionLikelihood(String name, TreeModel virusTree, AbstractOutbreak caseData, String
startingNetworkFileName){
this(name, virusTree, caseData, startingNetworkFileName, false, false);
}
// Constructor for an instance with a non-default name
public CaseToCaseTransmissionLikelihood(String name, TreeModel virusTree, AbstractOutbreak caseData, String
startingNetworkFileName, boolean extended, boolean sampleTTs) {
super(name);
this.virusTree = virusTree;
noTips = virusTree.getExternalNodeCount();
addModel(virusTree);
Date lastSampleDate = getLatestTaxonDate(virusTree);
/* We assume samples were taken at the end of the date of the last tip */
estimatedLastSampleTime = lastSampleDate.getTimeValue();
cases = caseData;
this.extended = extended;
this.sampleTTs = sampleTTs;
addModel(cases);
verbose = false;
//map cases to tips (needed for both versions)
branchMap = new AbstractCase[virusTree.getNodeCount()];
prepareExternalNodeMap(branchMap);
tipMap = new HashMap<AbstractCase, NodeRef>();
//map the cases to the external nodes
for(int i=0; i<virusTree.getExternalNodeCount(); i++){
TreeModel.Node currentExternalNode = (TreeModel.Node)virusTree.getExternalNode(i);
Taxon currentTaxon = currentExternalNode.taxon;
for(AbstractCase thisCase : cases.getCases()){
for(Taxon caseTaxon: thisCase.getAssociatedTaxa()){
if(caseTaxon.equals(currentTaxon)){
tipMap.put(thisCase, currentExternalNode);
}
}
}
}
if(!sampleTTs){
rootLikelihoods = new double[virusTree.getExternalNodeCount()];
subLikelihoods = new double[virusTree.getInternalNodeCount()
*virusTree.getExternalNodeCount()*virusTree.getExternalNodeCount()];
currentReconstructionExists = false;
} else {
nodeRecalculationNeeded = new boolean[virusTree.getNodeCount()];
Arrays.fill(nodeRecalculationNeeded, true);
nodeLogLikelihoods = new double[virusTree.getNodeCount()];
//paint the starting network onto the tree
if(startingNetworkFileName==null){
branchMap = paintRandomNetwork();
} else {
branchMap = paintSpecificNetwork(startingNetworkFileName);
}
}
nodePaintingPossibilities = possiblePaintingsMap(virusTree.getRoot(),
new HashMap<Integer, HashSet<AbstractCase>>());
treeTraits.addTrait(PAINTINGS_KEY, new TreeTrait.S() {
public String getTraitName() {
return "host_case";
}
public Intent getIntent() {
return Intent.NODE;
}
public String getTrait(Tree tree, NodeRef node) {
return getPaintingForNode(tree, node);
}
});
/* @todo deal with sampleTTs==true and extended==true (probably by prohibiting it)
not considering the extended case just yet
if(extended){
switchLocks = new boolean[virusTree.getInternalNodeCount()];
creepLocks = new boolean[virusTree.getInternalNodeCount()];
for(int i=0; i<virusTree.getInternalNodeCount(); i++){
creepLocks[virusTree.getInternalNode(i).getNumber()] = isCreepLocked(virusTree.getInternalNode(i));
}
}*/
}
/* Get the date of the last tip */
private static Date getLatestTaxonDate(TreeModel tree){
Date latestDate = new Date(new java.util.Date(-1000000), Units.Type.DAYS);
for(int i=0;i<tree.getTaxonCount();i++){
if(tree.getTaxon(i).getDate().after(latestDate)){
latestDate = tree.getTaxon(i).getDate();
}
}
return latestDate;
}
private NodeRef[] getChildren(NodeRef node){
NodeRef[] children = new NodeRef[virusTree.getChildCount(node)];
for(int i=0; i<virusTree.getChildCount(node); i++){
children[i] = virusTree.getChild(node,i);
}
return children;
}
private int[] getChildDays(NodeRef node){
int[] childDays = new int[virusTree.getChildCount(node)];
for(int i=0; i<virusTree.getChildCount(node); i++){
childDays[i] = getNodeDay(virusTree.getChild(node,i));
}
return childDays;
}
// EXTENDED VERSION METHODS - NOT CURRENTLY WORKING
/* check if the given node is tip-linked under the current painting (the tip corresponding to its painting is
a descendant of it
*/
public boolean tipLinked(NodeRef node){
NodeRef tip = tipMap.get(branchMap[node.getNumber()]);
if(tip==node){
return true;
}
NodeRef parent = tip;
while(parent!=virusTree.getRoot()){
parent = virusTree.getParent(parent);
if(parent==node){
return true;
}
}
return false;
}
public boolean[] getSwitchLocks(){
return switchLocks;
}
public boolean[] getCreepLocks(){
return creepLocks;
}
public boolean isSwitchLocked(NodeRef node){
if(virusTree.isExternal(node)){
throw new RuntimeException("Checking the lock on an external node");
}
return !tipLinked(node) || countChildrenWithSamePainting(node) == 2;
}
public boolean isCreepLocked(NodeRef node){
if(virusTree.isExternal(node)){
throw new RuntimeException("Checking the lock on an external node");
}
if(tipLinked(node) && samePaintingUpTree(node, false).contains(virusTree.getRoot().getNumber())){
return true;
} else if(tipLinked(node)){
return doubleChildAncestor(node);
} else {
return doubleChildDescendant(node);
}
}
// An ancestor of this node, or this node has the same painting and two children with that same painting
public boolean doubleChildAncestor(NodeRef node){
AbstractCase nodePainting = branchMap[node.getNumber()];
NodeRef ancestor = node;
while(ancestor!=null && branchMap[ancestor.getNumber()]==nodePainting){
if(countChildrenWithSamePainting(ancestor)==2){
return true;
}
ancestor=virusTree.getParent(ancestor);
}
return false;
}
// A descendant of this node, or this node has the same painting and two children with that same painting
public boolean doubleChildDescendant(NodeRef node){
AbstractCase nodePainting = branchMap[node.getNumber()];
return countChildrenWithSamePainting(node) == 2
|| doubleChildDescendant(virusTree.getChild(node, 0))
|| doubleChildDescendant(virusTree.getChild(node, 1));
}
public boolean isExtended(){
return extended;
}
public void changeSwitchLock(int index, boolean value){
switchLocks[index]=value;
}
public void recalculateLocks(){
for(int i=0; i<virusTree.getInternalNodeCount(); i++){
switchLocks[virusTree.getInternalNode(i).getNumber()]=isSwitchLocked(virusTree.getInternalNode(i));
creepLocks[virusTree.getInternalNode(i).getNumber()]=isCreepLocked(virusTree.getInternalNode(i));
}
}
public void recalculatePaintingSets(){
nodePaintingPossibilities.clear();
nodePaintingPossibilities = possiblePaintingsMap(virusTree.getRoot(),nodePaintingPossibilities);
}
//Counts the children of the current node which have the same painting as itself under the current map.
//This will always be 1 if extended==false.
public int countChildrenWithSamePainting(NodeRef node){
if(virusTree.isExternal(node)){
return -1;
} else {
int count = 0;
AbstractCase parentCase = branchMap[node.getNumber()];
for(int i=0; i<virusTree.getChildCount(node); i++){
if(branchMap[virusTree.getChild(node,i).getNumber()]==parentCase){
count++;
}
}
return count;
}
}
private static NodeRef sibling(TreeModel tree, NodeRef node){
if(tree.isRoot(node)){
return null;
} else {
NodeRef parent = tree.getParent(node);
for(int i=0; i<tree.getChildCount(parent); i++){
if(tree.getChild(parent,i)!=node){
return tree.getChild(parent,i);
}
}
}
return null;
}
// find all valid paintings of the current node
public HashSet<AbstractCase> possiblePaintings(NodeRef node){
HashSet<AbstractCase> out = new HashSet<AbstractCase>();
if(virusTree.isExternal(node)){
out.add(branchMap[node.getNumber()]);
return out;
} else {
for(int i=0; i<virusTree.getChildCount(node); i++){
out.addAll(possiblePaintings(virusTree.getChild(node,i)));
}
return out;
}
}
// find all paintings of the current node and build an array of this information for this node and its children
public HashMap<Integer,HashSet<AbstractCase>> possiblePaintingsMap(NodeRef node,
HashMap<Integer,HashSet<AbstractCase>> map){
HashSet<AbstractCase> out = new HashSet<AbstractCase>();
if(virusTree.isExternal(node)){
out.add(branchMap[node.getNumber()]);
map.put(node.getNumber(),out);
} else {
for(int i=0; i<virusTree.getChildCount(node); i++){
out.addAll(possiblePaintingsMap(virusTree.getChild(node,i),map)
.get(virusTree.getChild(node,i).getNumber()));
}
map.put(node.getNumber(),out);
}
return map;
}
//Return a set of nodes that are not descendants of (or equal to) the current node and have the same painting as it.
//The node recalculation is going to need reworking once the time comes to test the extended version,
public HashSet<Integer> samePaintingUpTree(NodeRef node, boolean flagForRecalc){
if(!nodeRecalculationNeeded[node.getNumber()] && flagForRecalc){
extendedflagForRecalculation(virusTree, virusTree.getChild(node,0), nodeRecalculationNeeded);
extendedflagForRecalculation(virusTree, virusTree.getChild(node,1), nodeRecalculationNeeded);
}
HashSet<Integer> out = new HashSet<Integer>();
AbstractCase painting = branchMap[node.getNumber()];
NodeRef ancestorNode = virusTree.getParent(node);
while(branchMap[ancestorNode.getNumber()]==painting){
out.add(ancestorNode.getNumber());
if(extended){
if(countChildrenWithSamePainting(ancestorNode)==2){
NodeRef otherChild = sibling(virusTree, ancestorNode);
out.add(otherChild.getNumber());
out.addAll(samePaintingDownTree(otherChild, flagForRecalc));
}
}
ancestorNode = virusTree.getParent(ancestorNode);
}
return out;
}
//Return a set of nodes that are descendants (and not equal to) the current node and have the same painting as it.
public HashSet<Integer> samePaintingDownTree(NodeRef node, boolean flagForRecalc){
HashSet<Integer> out = new HashSet<Integer>();
AbstractCase painting = branchMap[node.getNumber()];
boolean creepsFurther = false;
for(int i=0; i<virusTree.getChildCount(node); i++){
if(branchMap[virusTree.getChild(node,i).getNumber()]==painting){
creepsFurther = true;
out.add(virusTree.getChild(node,i).getNumber());
out.addAll(samePaintingDownTree(virusTree.getChild(node,i), flagForRecalc));
}
}
if(flagForRecalc && !creepsFurther){
extendedflagForRecalculation(virusTree, virusTree.getChild(node,0), nodeRecalculationNeeded);
extendedflagForRecalculation(virusTree, virusTree.getChild(node,1), nodeRecalculationNeeded);
}
return out;
}
// Return the node numbers of the entire subtree with the same painting as this node (including itself)
public HashSet<Integer> samePainting(NodeRef node, boolean flagForRecalc){
HashSet<Integer> out = new HashSet<Integer>();
out.add(node.getNumber());
out.addAll(samePaintingDownTree(node, flagForRecalc));
out.addAll(samePaintingUpTree(node, flagForRecalc));
return out;
}
// The flags indicate if a node's painting has changed. Only tree operators can use this shortcut; if parameters of
// the epidemiological model have changed then the whole tree's likelihood needs recalculating. Somewhat out of
// date at this point.
public static void extendedflagForRecalculation(TreeModel tree, NodeRef node, boolean[] flags){
flags[node.getNumber()]=true;
for(int i=0; i<tree.getChildCount(node); i++){
flags[tree.getChild(node,i).getNumber()]=true;
}
NodeRef currentNode=node;
while(!tree.isRoot(currentNode) && !flags[currentNode.getNumber()]){
currentNode = tree.getParent(currentNode);
flags[currentNode.getNumber()]=true;
}
}
public static void flagForRecalculation(NodeRef node, boolean[] flags){
flags[node.getNumber()]=true;
}
public void changeCreepLock(int index, boolean value){
creepLocks[index]=value;
}
// ModelListener IMPLEMENTATION
protected final void handleModelChangedEvent(Model model, Object object, int index) {
if(sampleTTs){
Arrays.fill(nodeRecalculationNeeded, true);
} else {
currentReconstructionExists = false;
}
if(model instanceof Tree){
recalculatePaintingSets();
}
likelihoodKnown = false;
}
// VariableListener IMPLEMENTATION
protected final void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) {
if(sampleTTs){
Arrays.fill(nodeRecalculationNeeded, true);
} else {
currentReconstructionExists = false;
}
likelihoodKnown = false;
}
// Model IMPLEMENTATION
/**
* Stores the precalculated state (in this case the node labels and subtree likelihoods)
*/
protected final void storeState() {
if(sampleTTs){
storedBranchMap = Arrays.copyOf(branchMap, branchMap.length);
storedNodeLogLikelihoods = Arrays.copyOf(nodeLogLikelihoods, nodeLogLikelihoods.length);
storedRecalculationArray = Arrays.copyOf(nodeRecalculationNeeded, nodeRecalculationNeeded.length);
} else {
storedSubLikelihoods = Arrays.copyOf(subLikelihoods, subLikelihoods.length);
storedRootLikelihoods = Arrays.copyOf(rootLikelihoods, rootLikelihoods.length);
}
storedNodePaintingPossibilities = new HashMap<Integer, HashSet<AbstractCase>>(nodePaintingPossibilities);
}
/**
* Restores the precalculated state.
*/
protected final void restoreState() {
if(sampleTTs){
branchMap = storedBranchMap;
nodeLogLikelihoods = storedNodeLogLikelihoods;
nodeRecalculationNeeded = storedRecalculationArray;
} else {
subLikelihoods = storedSubLikelihoods;
rootLikelihoods = storedRootLikelihoods;
}
nodePaintingPossibilities = storedNodePaintingPossibilities;
likelihoodKnown = false;
}
protected final void acceptState() {
} // nothing to do
// Likelihood IMPLEMENTATION
public final Model getModel() {
return this;
}
public final AbstractCase[] getBranchMap(){
return branchMap;
}
public final TreeModel getVirusTree(){
return virusTree;
}
public final void setBranchMap(AbstractCase[] map){
branchMap = map;
}
public final TreeModel getTree(){
return virusTree;
}
public final double getLogLikelihood() {
if (!likelihoodKnown) {
logLikelihood = calculateLogLikelihood();
likelihoodKnown = true;
}
return logLikelihood;
}
public final void makeDirty() {
if(sampleTTs){
Arrays.fill(nodeRecalculationNeeded, true);
} else {
currentReconstructionExists = false;
}
if(extended){
recalculateLocks();
}
likelihoodKnown = false;
recalculatePaintingSets();
}
public void makeDirty(boolean cleanTree){
if(cleanTree){
makeDirty();
} else {
if(extended){
recalculateLocks();
}
likelihoodKnown = false;
}
}
/**
* Calculates the log likelihood of this set of node labels given the tree.
*/
private double calculateLogLikelihood() {
if(!sampleTTs){
Arrays.fill(rootLikelihoods, Double.NEGATIVE_INFINITY);
Arrays.fill(subLikelihoods, Double.NEGATIVE_INFINITY);
return totalTreeLogLikelihood(true);
} else {
if(!checkPaintingIntegrity(branchMap, true)){
throw new RuntimeException("Not a painting");
}
return calculateLogLikelihood(branchMap);
}
}
private double calculateLogLikelihood(AbstractCase[] map){
double paintingLogLikelihood = paintingLogLikelihood(map);
double logNormalisationValue = totalTreeLogLikelihood(false);
if(paintingLogLikelihood>logNormalisationValue){
debugOutputTree();
throw new RuntimeException("Painting likelihood larger than normalisation value. Investigate.");
}
return paintingLogLikelihood - logNormalisationValue;
}
private double totalTreeLogLikelihood(boolean recordForReconstruction){
double[] rootLikelihoods = prune(virusTree.getRoot(), recordForReconstruction);
double normalisationValue = Double.NEGATIVE_INFINITY;
for (double rootLikelihood : rootLikelihoods) {
normalisationValue = LogTricks.logSum(normalisationValue, rootLikelihood);
}
return normalisationValue;
}
private double[] prune(NodeRef node, boolean recordForReconstruction){
if(virusTree.isExternal(node)){
AbstractCase tipPainting = branchMap[node.getNumber()];
NodeRef parent = virusTree.getParent(node);
double[] out = new double[noTips];
Arrays.fill(out, Double.NEGATIVE_INFINITY);
HashSet<AbstractCase> possiblePaintings = nodePaintingPossibilities.get(parent.getNumber());
for(AbstractCase parentPainting: possiblePaintings){
double value = cases.logP(parentPainting, tipPainting, getNodeTime(parent), getNodeTime(node));
out[cases.getCases().indexOf(parentPainting)]=value;
}
return out;
} else {
NodeRef parent = virusTree.getParent(node);
double[][] subtreeLikelihoods = new double[2][noTips];
double[] out = new double[noTips];
Arrays.fill(out, Double.NEGATIVE_INFINITY);
for(int i=0; i<2; i++){
subtreeLikelihoods[i] = Arrays.copyOf(prune(virusTree.getChild(node,i), recordForReconstruction),
noTips);
}
HashSet<AbstractCase> possibleNodePaintings = nodePaintingPossibilities.get(node.getNumber());
if(parent!=null){
// not the root - the likelihood of this subtree given that the parent node has a given painting
HashSet<AbstractCase> possibleParentPaintings = nodePaintingPossibilities.get(parent.getNumber());
for(AbstractCase parentPainting: possibleParentPaintings){
int parentIndex=cases.getCases().indexOf(parentPainting);
double sum = Double.NEGATIVE_INFINITY;
for(AbstractCase nodePainting: possibleNodePaintings){
// is the tip with the parent painting a descendant of this node?
boolean paintingForcedByParent = possibleNodePaintings.contains(parentPainting);
// If paintingForcedByParent is true, then the likelihood is nonzero only if the node
// has the same painting as its parent
boolean treeCompatibilityCheck = !paintingForcedByParent || parentPainting==nodePainting;
if(treeCompatibilityCheck){
double term = 0;
int childIndex = cases.getCases().indexOf(nodePainting);
for(int i=0; i<2; i++){
term = term + subtreeLikelihoods[i][childIndex];
}
term = term + cases.logP(parentPainting,nodePainting,getNodeTime(parent),getNodeTime(node));
if(recordForReconstruction){
subLikelihoods[(node.getNumber()-noTips)*noTips*noTips
+parentIndex*noTips
+childIndex] = term;
}
sum = LogTricks.logSum(sum, term);
}
}
out[parentIndex]=sum;
}
return out;
} else {
// root - these are the likelihoods of the root paintings
for(AbstractCase nodePainting: possibleNodePaintings){
double term = 0;
int index = cases.getCases().indexOf(nodePainting);
for(int i=0; i<2; i++){
term+=subtreeLikelihoods[i][index];
}
term+=cases.logProbInfectiousBy(nodePainting,getNodeTime(node));
if(recordForReconstruction){
rootLikelihoods[index]=term;
}
out[index]=term;
}
return out;
}
}
}
private double paintingLogLikelihood(AbstractCase[] map){
return prune(map, virusTree.getRoot());
}
private double prune(AbstractCase[] map, NodeRef node){
if(virusTree.isExternal(node)){
NodeRef parent = virusTree.getParent(node);
AbstractCase tipPainting = map[node.getNumber()];
AbstractCase parentPainting = map[parent.getNumber()];
double out = cases.logP(parentPainting, tipPainting, getNodeTime(parent), getNodeTime(node));
return out;
} else {
NodeRef parent = virusTree.getParent(node);
double[] subtreeLikelihoods = new double[2];
for(int i=0; i<2; i++){
subtreeLikelihoods[i] = prune(map, virusTree.getChild(node,i));
}
AbstractCase nodePainting = map[node.getNumber()];
if(parent!=null){
// not the root - the likelihood of this subtree given that the parent node has a given painting
AbstractCase parentPainting = map[parent.getNumber()];
// is the tip with the parent painting a descendant of this node?
// If paintingForcedByParent is true, then the likelihood is nonzero only if the node
// has the same painting as its parent
double term = 0;
for(int i=0; i<2; i++){
term+=subtreeLikelihoods[i];
}
term += cases.logP(parentPainting, nodePainting, getNodeTime(parent), getNodeTime(node));
return term;
} else {
// root - these are the likelihoods of the root paintings
double term = 0;
for(int i=0; i<2; i++){
term+=subtreeLikelihoods[i];
}
term+=cases.logProbInfectiousBy(nodePainting, getNodeTime(node));
return term;
}
}
}
/* Return the integer day on which the given node occurred */
public int getNodeDay(NodeRef node){
Double nodeHeight = getHeight(node);
Double estimatedNodeTime = estimatedLastSampleTime-nodeHeight;
Date nodeDate = new Date(estimatedNodeTime, Units.Type.DAYS, false);
/*Since day t begins at time t-1, to find the day of a given decimal time value, take the ceiling.*/
return (int)Math.ceil(nodeDate.getTimeValue());
}
/* Return the double time at which the given node occurred */
public double getNodeTime(NodeRef node){
double nodeHeight = getHeight(node);
return estimatedLastSampleTime-nodeHeight;
}
/**
* Given a node, calculates the log likelihood of its parent branch and then goes down the tree and calculates the
* log likelihoods of lower branches.
*/
public boolean[] getRecalculationArray(){
return nodeRecalculationNeeded;
}
private double getHeight(NodeRef node){
return virusTree.getNodeHeight(node);
}
/* Return the case whose infection resulted from this node (if internal) */
private AbstractCase getInfected(NodeRef node){
if(virusTree.isExternal(node)){
throw new RuntimeException("Node is external");
} else {
for(int i=0;i<2;i++){
NodeRef child = virusTree.getChild(node, i);
if(branchMap[child.getNumber()]!=branchMap[node.getNumber()]){
return branchMap[child.getNumber()];
}
}
}
throw new RuntimeException("Node appears to have two children with its infector");
}
/* Return the case which infected this case */
public AbstractCase getInfector(AbstractCase thisCase){
return getInfector(thisCase, branchMap);
}
/* Return the case which was the infector in the infection event represented by this node */
public AbstractCase getInfector(NodeRef node){
return getInfector(node, branchMap);
}
public AbstractCase getInfector(AbstractCase thisCase, AbstractCase[] branchMap){
NodeRef tip = tipMap.get(thisCase);
return getInfector(tip, branchMap);
}
public AbstractCase getInfector(NodeRef node, AbstractCase[] branchMap){
if(virusTree.isRoot(node) || node.getNumber()==virusTree.getRoot().getNumber()){
return null;
} else {
AbstractCase nodeCase = branchMap[node.getNumber()];
if(branchMap[virusTree.getParent(node).getNumber()]!=nodeCase){
return branchMap[virusTree.getParent(node).getNumber()];
} else {
return getInfector(virusTree.getParent(node), branchMap);
}
}
}
public boolean checkPaintingIntegrity(AbstractCase[] map, boolean verbose){
boolean out=true;
for(int i=0; i<virusTree.getInternalNodeCount(); i++){
NodeRef node = virusTree.getInternalNode(i);
NodeRef firstChild = virusTree.getChild(node,0);
NodeRef secondChild = virusTree.getChild(node,1);
NodeRef parent = virusTree.getParent(node);
if(map[node.getNumber()]!=map[firstChild.getNumber()] &&
map[node.getNumber()]!=map[secondChild.getNumber()] &&
(!extended || map[node.getNumber()]!=map[parent.getNumber()])){
out = false;
if(!verbose){
break;
} else {
System.out.println("Node "+node.getNumber()+" failed painting integrity check:");
System.out.println("Node painting: "+map[node.getNumber()].getName());
System.out.println("Parent painting: "+map[parent.getNumber()].getName());
System.out.println("Child 1 painting: "+map[firstChild.getNumber()].getName());
System.out.println("Child 2 painting: "+map[secondChild.getNumber()].getName());
System.out.println();
}
}
}
return out;
}
/* Return the case (painting) of the parent of this node */
public AbstractCase getParentCase(NodeRef node){
return branchMap[virusTree.getParent(node).getNumber()];
}
/* Populates the branch map for external nodes */
private AbstractCase[] prepareExternalNodeMap(AbstractCase[] map){
for(int i=0; i<virusTree.getExternalNodeCount(); i++){
TreeModel.Node currentExternalNode = (TreeModel.Node)virusTree.getExternalNode(i);
Taxon currentTaxon = currentExternalNode.taxon;
for(AbstractCase thisCase : cases.getCases()){
for(Taxon caseTaxon: thisCase.getAssociatedTaxa()){
if(caseTaxon.equals(currentTaxon)){
map[currentExternalNode.getNumber()]=thisCase;
}
}
}
}
return map;
}
/* The CSV file should have a header line, and then a line for each node with its id in the first column and the id
of its parent in the second. The node with no parent has "Start" in the second column.*/
private AbstractCase[] paintSpecificNetwork(String networkFileName){
System.out.println("Using specified starting network.");
try{
BufferedReader reader = new BufferedReader (new FileReader(networkFileName));
HashMap<AbstractCase, AbstractCase> specificParentMap = new HashMap<AbstractCase, AbstractCase>();
// skip header line
reader.readLine();
String currentLine = reader.readLine();
while(currentLine!=null){
currentLine = currentLine.replace("\"", "");
String[] splitLine = currentLine.split("\\,");
if(!splitLine[1].equals("Start")){
specificParentMap.put(cases.getCase(splitLine[0]), cases.getCase(splitLine[1]));
} else {
specificParentMap.put(cases.getCase(splitLine[0]),null);
}
currentLine = reader.readLine();
}
reader.close();
return paintSpecificNetwork(specificParentMap);
} catch(IOException e){
System.out.println("Cannot read file: " + networkFileName );
return null;
}
}
/* Takes a HashMap referring each case to its parent, and tries to paint the tree with it. This only works on
* the non-extended version right now, watch it. */
private AbstractCase[] paintSpecificNetwork(HashMap<AbstractCase, AbstractCase> map){
Arrays.fill(nodeRecalculationNeeded,true);
AbstractCase[] branchArray = new AbstractCase[virusTree.getNodeCount()];
branchArray = prepareExternalNodeMap(branchArray);
TreeModel.Node root = (TreeModel.Node)virusTree.getRoot();
specificallyPaintNode(root, branchArray, map);
return branchArray;
}
/* Paints a phylogenetic tree node and its children according to a specified map of child to parent cases */
private AbstractCase specificallyPaintNode(TreeModel.Node node, AbstractCase[] map,
HashMap<AbstractCase,AbstractCase> parents){
if(node.isExternal()){
return map[node.getNumber()];
} else {
AbstractCase[] childPaintings = new AbstractCase[2];
for(int i=0; i<node.getChildCount(); i++){
childPaintings[i] = specificallyPaintNode(node.getChild(i), map, parents);
}
if(parents.get(childPaintings[1])==childPaintings[0]){
map[node.getNumber()]=childPaintings[0];
} else if(parents.get(childPaintings[0])==childPaintings[1]){
map[node.getNumber()]=childPaintings[1];
} else {
throw new RuntimeException("This network does not appear to be compatible with the tree");
}
return map[node.getNumber()];
}
}
public void writeNetworkToFile(String fileName){
try{
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
writer.write("Case,Parent");
writer.newLine();
for(int i=0; i<virusTree.getExternalNodeCount(); i++){
TreeModel.Node extNode = (TreeModel.Node)virusTree.getExternalNode(i);
String tipName = extNode.taxon.toString();
String infector;
try{
infector = getInfector(extNode).getName();
} catch(NullPointerException e){
infector = "Start";
}
writer.write(tipName + "," + infector);
writer.newLine();
}
writer.close();
} catch(IOException e) {
System.out.println("Failed to write to file");
}
}
/*Given a new tree with no labels, associates each of the terminal branches with the relevant case and then
* generates a random painting of the rest of the tree to start off with. If checkNonZero is true in
* randomlyPaintNode then the network will be checked to prohibit links with zero (or rounded to zero)
* likelihood first.*/
private AbstractCase[] paintRandomNetwork(){
boolean gotOne = false;
AbstractCase[] map = null;
int tries = 1;
System.out.println("Generating a random starting painting of the tree (checking nonzero likelihood for all " +
"branches and repeating up to 100 times until a start with nonzero likelihood is found)");
System.out.print("Attempt: ");
while(!gotOne){
System.out.print(tries + "...");
map = prepareExternalNodeMap(new AbstractCase[virusTree.getNodeCount()]);
branchMap = Arrays.copyOf(map, map.length);
//Warning - if the BadPaintingException in randomlyPaintNode might be caused by a bug rather than both
//likelihoods rounding to zero, you want to stop catching this to investigate.
paintRandomNetwork(map,true);
if(paintingLogLikelihood(map)!=Double.NEGATIVE_INFINITY){
gotOne = true;
System.out.println("found.");
}
tries++;
if(tries==101){
System.out.println("giving " +
"up.");
throw new RuntimeException("Failed to find a starting transmission network with nonzero likelihood");
}
}
return map;
}
/* Paints a phylogenetic tree with a random compatible painting; if checkNonZero is true, make sure all branch
likelihoods are nonzero in the process (this sometimes still results in a zero likelihood for the whole tree, but
is much less likely to).
*/
private AbstractCase[] paintRandomNetwork(AbstractCase[] map, boolean checkNonZero){
Arrays.fill(nodeRecalculationNeeded,true);
TreeModel.Node root = (TreeModel.Node)virusTree.getRoot();
randomlyPaintNode(root, map, checkNonZero);
return map;
}
private AbstractCase randomlyPaintNode(TreeModel.Node node, AbstractCase[] map, boolean checkNonZero){
if(node.isExternal()){
return map[node.getNumber()];
} else {
AbstractCase[] choices = new AbstractCase[2];
for(int i=0; i<node.getChildCount(); i++){
if((map[node.getChild(i).getNumber()]==null)){
choices[i] = randomlyPaintNode(node.getChild(i),map,checkNonZero);
} else {
choices[i] = map[node.getChild(i).getNumber()];
}
}
int randomSelection = MathUtils.nextInt(2);
AbstractCase decision;
if(checkNonZero){
Double[] branchLogLs = new Double[2];
for(int i=0; i<2; i++){
branchLogLs[i]= cases.logP(choices[i], choices[1-i], getNodeTime(node),
getNodeTime(virusTree.getChild(node,1-i)));
}
if(branchLogLs[0]==Double.NEGATIVE_INFINITY && branchLogLs[1]==Double.NEGATIVE_INFINITY){
for(int i=0; i<2; i++){
branchLogLs[i]= cases.logP(choices[i], choices[1-i], getNodeTime(node),
getNodeTime(virusTree.getChild(node,1-i)));
}
throw new BadPaintingException("Both branch possibilities have zero likelihood: "
+node.toString()+", cases " + choices[0].getName() + " and " + choices[1].getName() + ".");
} else if(branchLogLs[0]==Double.NEGATIVE_INFINITY || branchLogLs[1]==Double.NEGATIVE_INFINITY){
if(branchLogLs[0]==Double.NEGATIVE_INFINITY){
decision = choices[1];
} else {
decision = choices[0];
}
} else {
decision = choices[randomSelection];
}
} else {
decision = choices[randomSelection];
}
map[node.getNumber()]=decision;
return decision;
}
}
/* Sample a random transmission tree from the likelihoods for the paintings of each triplet of nodes */
|
package org.endeavourhealth.ui.endpoints;
import com.codahale.metrics.annotation.Timed;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import io.astefanutti.metrics.aspectj.Metrics;
import org.endeavourhealth.common.cache.ObjectMapperPool;
import org.endeavourhealth.common.config.ConfigManager;
import org.endeavourhealth.common.security.SecurityUtils;
import org.endeavourhealth.common.security.annotations.RequiresAdmin;
import org.endeavourhealth.core.database.dal.DalProvider;
import org.endeavourhealth.core.database.dal.audit.UserAuditDalI;
import org.endeavourhealth.core.database.dal.audit.models.AuditAction;
import org.endeavourhealth.core.database.dal.audit.models.AuditModule;
import org.endeavourhealth.core.queueing.RabbitConfig;
import org.endeavourhealth.coreui.endpoints.AbstractEndpoint;
import org.endeavourhealth.ui.json.*;
import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.*;
import javax.ws.rs.client.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Path("/rabbit")
@Metrics(registry = "EdsRegistry")
public final class RabbitEndpoint extends AbstractEndpoint {
private static final Logger LOG = LoggerFactory.getLogger(RabbitEndpoint.class);
private static final UserAuditDalI userAudit = DalProvider.factoryUserAuditDal(AuditModule.EdsUiModule.Rabbit);
private final HttpAuthenticationFeature rabbitAuth;
{
try {
String user = RabbitConfig.getInstance().getUsername();
String pass = RabbitConfig.getInstance().getPassword();
rabbitAuth = HttpAuthenticationFeature.basic(user, pass);
} catch (Exception e) {
throw new IllegalStateException("Unable to load rabbit config", e);
}
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Timed(absolute = true, name="EDS-UI.RabbitEndpoint.GetRoutings")
@Path("/routings")
public Response getRoutings(@Context SecurityContext sc) throws Exception {
super.setLogbackMarkers(sc);
userAudit.save(SecurityUtils.getCurrentUserId(sc), getOrganisationUuidFromToken(sc), AuditAction.Load, "Routings");
String routings = ConfigManager.getConfiguration("routings");
return Response
.ok()
.entity(routings)
.build();
}
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Timed(absolute = true, name="EDS-UI.RabbitEndpoint.PostRoutings")
@Path("/routings")
public Response saveRoutings(@Context SecurityContext sc, String routings) throws Exception {
super.setLogbackMarkers(sc);
userAudit.save(SecurityUtils.getCurrentUserId(sc), getOrganisationUuidFromToken(sc), AuditAction.Load, "Routings");
ConfigManager.setConfiguration("routings", routings);
return Response
.ok()
.build();
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Timed(absolute = true, name="EDS-UI.RabbitEndpoint.GetRabbitNodes")
@Path("/nodes")
public Response getRabbitNodes(@Context SecurityContext sc) throws Exception {
super.setLogbackMarkers(sc);
userAudit.save(SecurityUtils.getCurrentUserId(sc), getOrganisationUuidFromToken(sc), AuditAction.Load, "Nodes");
String rabbitConfigJson = ConfigManager.getConfiguration("rabbit");
JsonNode rabbitConfig = ObjectMapperPool.getInstance().readTree(rabbitConfigJson);
List<JsonRabbitNode> ret = new ArrayList<>();
String nodes = RabbitConfig.getInstance().getManagementNodes();
for (String node : nodes.split(" *, *")) {
ret.add(new JsonRabbitNode(node, 0));
}
/*String rabbitConfigJson = ConfigManager.getConfiguration("rabbit");
JsonNode rabbitConfig = ObjectMapperPool.getInstance().readTree(rabbitConfigJson);
List<JsonRabbitNode> ret = new ArrayList<>();
for (String node : rabbitConfig.get("nodes").asText().split(",", -1))
ret.add(new JsonRabbitNode(node, 0));*/
clearLogbackMarkers();
return Response
.ok()
.entity(ret)
.build();
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Timed(absolute = true, name="EDS-UI.RabbitEndpoint.PingRabbitNodes")
@Path("/ping")
public Response pingRabbitNode(@Context SecurityContext sc, @QueryParam("address") String address) throws Exception {
super.setLogbackMarkers(sc);
userAudit.save(SecurityUtils.getCurrentUserId(sc), getOrganisationUuidFromToken(sc), AuditAction.Load,
"Ping time",
"Address", address);
Client client = ClientBuilder.newClient();
client.register(rabbitAuth);
WebTarget resource = client.target("http://"+address+"/api/cluster-name");
Invocation.Builder request = resource.request();
int ping = -1;
try {
long startTime = System.currentTimeMillis();
Response response = request.get();
long endTime = System.currentTimeMillis();
if (response.getStatusInfo().getFamily() == Response.Status.Family.SUCCESSFUL) {
ping = Math.toIntExact(endTime - startTime);
}
response.close();
}
catch (Exception e) {
// TODO : Cleanly handle downed rabbit node
e.printStackTrace();
}
client.close();
JsonRabbitNode ret = new JsonRabbitNode(address, ping);
clearLogbackMarkers();
return Response
.ok()
.entity(ret)
.build();
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Timed(absolute = true, name="EDS-UI.RabbitEndpoint.GetRabbitQueues")
@Path("/queues")
public Response getRabbitQueues(@Context SecurityContext sc, @QueryParam("address") String address) throws Exception {
super.setLogbackMarkers(sc);
userAudit.save(SecurityUtils.getCurrentUserId(sc), getOrganisationUuidFromToken(sc), AuditAction.Load,
"Queues",
"Address", address);
Client client = ClientBuilder.newClient();
client.register(rabbitAuth);
WebTarget resource = client.target("http://"+address+"/api/queues");
Invocation.Builder request = resource.request();
Response response = request.get();
String ret = null;
if (response.getStatusInfo().getFamily() == Response.Status.Family.SUCCESSFUL) {
ret = response.readEntity(String.class);
}
response.close();
client.close();
clearLogbackMarkers();
return Response
.ok()
.entity(ret)
.build();
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Timed(absolute = true, name="EDS-UI.RabbitEndpoint.GetRabbitExchanges")
@Path("/exchanges")
public Response getRabbitExchanges(@Context SecurityContext sc, @QueryParam("address") String address) throws Exception {
super.setLogbackMarkers(sc);
userAudit.save(SecurityUtils.getCurrentUserId(sc), getOrganisationUuidFromToken(sc), AuditAction.Load,
"Exchanges",
"Address", address);
Client client = ClientBuilder.newClient();
client.register(rabbitAuth);
WebTarget resource = client.target("http://"+address+"/api/exchanges");
Invocation.Builder request = resource.request();
Response response = request.get();
String ret = null;
if (response.getStatusInfo().getFamily() == Response.Status.Family.SUCCESSFUL) {
ret = response.readEntity(String.class);
}
response.close();
client.close();
clearLogbackMarkers();
return Response
.ok()
.entity(ret)
.build();
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Timed(absolute = true, name="EDS-UI.RabbitEndpoint.GetRabbitBindings")
@Path("/bindings")
public Response getRabbitBindings(@Context SecurityContext sc, @QueryParam("address") String address) throws Exception {
super.setLogbackMarkers(sc);
userAudit.save(SecurityUtils.getCurrentUserId(sc), getOrganisationUuidFromToken(sc), AuditAction.Load,
"Bindings",
"Address", address);
String ret = getRabbitBindingsJson(address);
clearLogbackMarkers();
return Response
.ok()
.entity(ret)
.build();
}
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.TEXT_PLAIN)
@Timed(absolute = true, name="EDS-UI.RabbitEndpoint.SynchronizeRabbit")
@Path("/synchronize")
@RequiresAdmin
public Response synchronizeRabbit(@Context SecurityContext sc, String address) throws Exception {
super.setLogbackMarkers(sc);
userAudit.save(SecurityUtils.getCurrentUserId(sc), getOrganisationUuidFromToken(sc), AuditAction.Save,
"Bindings (Sync)",
"Address", address);
//String[] pipelines = {"EdsInbound", "EdsProtocol", "EdsTransform", "EdsResponse", "EdsSubscriber"};
super.setLogbackMarkers(sc);
// Load current bindings
List<JsonRabbitBinding> currentBindings = getCurrentRabbitBindings(address);
// Load config
List<JsonRouteGroup> allRoutings = getConfiguredBindings();
//hash by exchange name
Map<String, List<JsonRouteGroup>> map = new HashMap<>();
for (JsonRouteGroup r: allRoutings) {
List<JsonRouteGroup> list = map.get(r.getExchangeName());
if (list == null) {
list = new ArrayList<>();
map.put(r.getExchangeName(), list);
}
list.add(r);
}
for (String pipeline: map.keySet()) {
List<JsonRouteGroup> routings = map.get(pipeline);
// Declare exchanges
declareAllExchanges(address, pipeline);
// Declare (config) queues
declareAllQueues(address, pipeline, routings);
// Bind (config) queues to DLE
bindQueuesToExchange(address, pipeline + "-DLE", pipeline, routings);
// Remove all bindings from main exchange (DLE now routes to queues based on new config)
removeBindingsFromMainExchange(address, pipeline, currentBindings);
// Bind (config) to main exchange (main exchange now routes to queues based on new config)
bindQueuesToExchange(address, pipeline, pipeline, routings);
// Remove (config) bindings from DLE
removeBindingsFromDLEExchange(address, pipeline + "-DLE", pipeline, routings);
// Determine queues to remove (unbound)
// Wait for any unbound queues to drain
// Remove (now empty) unbound queues
// (Shutdown readers of unbound queues????)
// (Startup readers of queues without readers????)
}
/*for (String pipeline : pipelines) {
// Declare exchanges
declareAllExchanges(address, pipeline);
// Declare (config) queues
declareAllQueues(address, pipeline, configuredBindings);
// Bind (config) queues to DLE
bindQueuesToExchange(address, pipeline + "-DLE", pipeline, configuredBindings);
// Remove all bindings from main exchange (DLE now routes to queues based on new config)
removeBindingsFromMainExchange(address, pipeline, currentBindings);
// Bind (config) to main exchange (main exchange now routes to queues based on new config)
bindQueuesToExchange(address, pipeline, pipeline, configuredBindings);
// Remove (config) bindings from DLE
removeBindingsFromDLEExchange(address, pipeline + "-DLE", pipeline, configuredBindings);
// Determine queues to remove (unbound)
// Wait for any unbound queues to drain
// Remove (now empty) unbound queues
// (Shutdown readers of unbound queues????)
// (Startup readers of queues without readers????)
}*/
String ret = getRabbitBindingsJson(address);
clearLogbackMarkers();
return Response
.ok(ret)
.build();
}
private String getRabbitBindingsJson(String address) {
String json = null;
Client client = ClientBuilder.newClient();
client.register(rabbitAuth);
WebTarget resource = client.target("http://"+address+"/api/bindings");
Invocation.Builder request = resource.request();
Response response = request.get();
if (response.getStatusInfo().getFamily() == Response.Status.Family.SUCCESSFUL) {
json = response.readEntity(String.class);
}
response.close();
client.close();
return json;
}
private List<JsonRabbitBinding> getCurrentRabbitBindings(String address) throws IOException {
List<JsonRabbitBinding> bindings = new ArrayList<>();
String json = getRabbitBindingsJson(address);
if (json != null) {
bindings = ObjectMapperPool.getInstance().readValue(json, new TypeReference<List<JsonRabbitBinding>>(){});
}
return bindings;
}
private List<JsonRouteGroup> getConfiguredBindings() throws IOException {
List<JsonRouteGroup> bindings = new ArrayList<>();
String routingsJson = ConfigManager.getConfiguration("routings");
if (routingsJson != null) {
bindings = ObjectMapperPool.getInstance().readValue(routingsJson, new TypeReference<List<JsonRouteGroup>>(){});
}
return bindings;
}
private void declareAllExchanges(String address, String pipeline) throws Exception {
Client client = ClientBuilder.newClient();
client.register(rabbitAuth);
// DLE
WebTarget resource = client.target("http://" + address + "/api/exchanges/%2f/"+pipeline+"-DLE");
Invocation.Builder request = resource.request();
JsonRabbitExchangeOptions optionsJson = new JsonRabbitExchangeOptions();
optionsJson.setType("fanout");
optionsJson.setAuto_delete(false);
optionsJson.setDurable(true);
Response response = request.put(Entity.json(optionsJson));
Response.StatusType status = response.getStatusInfo();
if (status.getFamily() != Response.Status.Family.SUCCESSFUL) {
throw new Exception("Unable to declare the dead letter exchange, URI: " + resource.getUri().toString() +
"HTTP code: " + status.getStatusCode() + " " + status.getReasonPhrase());
}
response.close();
// Exchange
resource = client.target("http://" + address + "/api/exchanges/%2f/"+pipeline);
request = resource.request();
optionsJson = new JsonRabbitExchangeOptions();
optionsJson.setType("topic");
optionsJson.setAuto_delete(false);
optionsJson.setDurable(true);
optionsJson.getArguments().put("alternate-exchange", pipeline+"-DLE");
response = request.put(Entity.json(optionsJson));
status = response.getStatusInfo();
if (status.getFamily() != Response.Status.Family.SUCCESSFUL) {
throw new Exception("Unable to declare the " + pipeline + " exchange, URI: " + resource.getUri().toString() +
"HTTP code: " + status.getStatusCode() + " " + status.getReasonPhrase());
}
response.close();
client.close();
}
private void declareAllQueues(String address, String queuePrefix, List<JsonRouteGroup> routeGroups) throws Exception {
Client client = ClientBuilder.newClient();
client.register(rabbitAuth);
//declare a queue for each
for (JsonRouteGroup routeGroup : routeGroups) {
String queueName = queuePrefix + "-" + routeGroup.getRouteKey();
declareQueue(client, address, queueName);
}
client.close();
}
private static void declareQueue(Client client, String address, String queueName) throws Exception {
WebTarget resource = client.target("http://" + address + "/api/queues/%2f/" + queueName);
Invocation.Builder request = resource.request();
JsonRabbitQueueOptions optionsJson = new JsonRabbitQueueOptions();
optionsJson.setAuto_delete(false);
optionsJson.setDurable(true);
Response response = request.put(Entity.json(optionsJson));
Response.StatusType status = response.getStatusInfo();
if (status.getFamily() != Response.Status.Family.SUCCESSFUL) {
throw new Exception("Unable do declare the queue, HTTP code " + status.getStatusCode() + " " + status.getReasonPhrase());
}
response.close();
}
private void bindQueuesToExchange(String address, String exchange, String queuePrefix, List<JsonRouteGroup> routeGroups) throws Exception {
Client client = ClientBuilder.newClient();
client.register(rabbitAuth);
for (JsonRouteGroup routeGroup : routeGroups) {
WebTarget resource = client.target("http://" + address + "/api/bindings/%2f/e/"+exchange+"/q/"+queuePrefix + "-" + routeGroup.getRouteKey());
Invocation.Builder request = resource.request();
JsonRabbitBindingOptions optionsJson = new JsonRabbitBindingOptions();
optionsJson.setRouting_key(routeGroup.getRouteKey());
Response response = request.post(Entity.json(optionsJson));
Response.StatusType status = response.getStatusInfo();
if (status.getFamily() != Response.Status.Family.SUCCESSFUL) {
throw new Exception("Unable do declare the queue, HTTP code " + status.getStatusCode() + " " + status.getReasonPhrase());
}
response.close();
}
client.close();
}
private void removeBindingsFromMainExchange(String address, String exchange, List<JsonRabbitBinding> currentBindings) throws Exception {
for (JsonRabbitBinding rabbitBinding : currentBindings) {
if (exchange.equals(rabbitBinding.getSource())) {
removeBindingFromExchange(address, exchange, rabbitBinding.getDestination(), rabbitBinding.getRouting_key());
}
}
}
private void removeBindingsFromDLEExchange(String address, String exchange, String queuePrefix, List<JsonRouteGroup> routeGroups) throws Exception {
for (JsonRouteGroup routeGroup : routeGroups) {
removeBindingFromExchange(address, exchange, queuePrefix+"-"+routeGroup.getRouteKey(), routeGroup.getRouteKey());
}
}
private void removeBindingFromExchange(String address, String exchange, String queue, String routingKey) throws Exception {
Client client = ClientBuilder.newClient();
client.register(rabbitAuth);
WebTarget resource = client.target("http://" + address + "/api/bindings/%2f/e/" + exchange + "/q/" + queue + "/"+routingKey);
Invocation.Builder request = resource.request();
Response response = request.delete();
Response.StatusType status = response.getStatusInfo();
if (status.getFamily() != Response.Status.Family.SUCCESSFUL) {
throw new Exception("Unable do declare the queue, HTTP code " + status.getStatusCode() + " " + status.getReasonPhrase());
}
response.close();
}
}
|
package com.hp.hpl.jena.db.impl;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringBufferInputStream;
import java.io.UnsupportedEncodingException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Iterator;
import java.util.Properties;
import com.hp.hpl.jena.db.IDBConnection;
import com.hp.hpl.jena.db.RDFRDBException;
/**
* @author hkuno based on code by Dave Reynolds
*
* Extends DriverRDB with Oracle-specific parameters.
* Note: To use this class with Oracle:
* 1. Uncomment out the Oracle-specific
* import statements above this comment block.
* 2. Comment out the interface stubs below.
*/
public class Driver_Oracle extends DriverRDB {
/** The name of the database type this driver supports */
/**
* Constructor
*/
public Driver_Oracle(){
super();
String myPackageName = this.getClass().getPackage().getName();
DATABASE_TYPE = "Oracle";
DRIVER_NAME = "oracle.jdbc.driver.OracleDriver";
EMPTY_LITERAL_MARKER = "EmptyLiteral";
ID_SQL_TYPE = "INTEGER";
INSERT_BY_PROCEDURE = false;
INDEX_KEY_LENGTH = 4000;
LONG_OBJECT_LENGTH = 250;
HAS_XACTS = true;
PRE_ALLOCATE_ID = true;
SKIP_DUPLICATE_CHECK = false;
EMPTY_LITERAL_MARKER = "EmptyLiteral";
SQL_FILE = "etc/oracle.sql";
m_psetClassName = myPackageName + ".PSet_TripleStore_RDB";
m_psetReifierClassName = myPackageName + ".PSet_ReifStore_RDB";
m_lsetClassName = myPackageName + ".SpecializedGraph_TripleStore_RDB";
m_lsetReifierClassName = myPackageName + ".SpecializedGraphReifier_RDB";
QUOTE_CHAR = '\'';
DB_NAMES_TO_UPPER = true;
}
/**
* Set the database connection
*/
public void setConnection( IDBConnection dbcon ) {
m_dbcon = dbcon;
try {
Properties defaultSQL = SQLCache.loadSQLFile(DEFAULT_SQL_FILE, null, ID_SQL_TYPE);
m_sql = new SQLCache(SQL_FILE, defaultSQL, dbcon, ID_SQL_TYPE);
} catch (Exception e) {
e.printStackTrace( System.err );
logger.error("Unable to set connection for Driver:", e);
}
}
/**
* Allocate an identifier for a new graph.
*
*/
public int graphIdAlloc ( String graphName ) {
DBIDInt result = null;
int dbid = 0;
try {
String op = "insertGraph";
dbid = getInsertID(GRAPH_TABLE);
PreparedStatement ps = m_sql.getPreparedSQLStatement(op);
ps.setInt(1,dbid);
ps.setString(2,graphName);
ps.executeUpdate();
m_sql.returnPreparedSQLStatement(ps,op);
} catch (SQLException e) {
throw new RDFRDBException("Failed to get last inserted ID: " + e);
}
return dbid;
}
/**
* Dellocate an identifier for a graph.
*
*/
public void graphIdDealloc ( int graphId ) {
DBIDInt result = null;
try {
String op = "deleteGraph";
PreparedStatement ps = m_sql.getPreparedSQLStatement(op);
ps.setInt(1,graphId);
ps.executeUpdate();
m_sql.returnPreparedSQLStatement(ps,op);
} catch (SQLException e) {
throw new RDFRDBException("Failed to delete graph ID: " + e);
}
return;
}
public int getInsertID ( String tableName ) {
DBIDInt result = null;
try {
String op = "getInsertID";
PreparedStatement ps = m_sql.getPreparedSQLStatement(op,tableName);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
result = wrapDBID(rs.getObject(1));
} else
throw new RDFRDBException("No insert ID");
m_sql.returnPreparedSQLStatement(ps,op);
} catch (SQLException e) {
throw new RDFRDBException("Failed to insert ID: " + e);
}
return result.getIntID();
}
/**
* Return the parameters for table creation.
* 1) column type for subj, prop, obj.
* @param param array to hold table creation parameters.
*/
protected void getTblParams ( String [] param ) {
String objColType;
// length of varchar columns in statement tables
if ( LONG_OBJECT_LENGTH > 4000 )
throw new RDFRDBException("Long object length specified (" + LONG_OBJECT_LENGTH +
") exceeds maximum sane length of 4000.");
if ( INDEX_KEY_LENGTH > 4000 )
throw new RDFRDBException("Index key length specified (" + INDEX_KEY_LENGTH +
") exceeds maximum sane length of 4000.");
objColType = "VARCHAR2(" + LONG_OBJECT_LENGTH + ")";
STRINGS_TRIMMED = false;
param[0] = objColType;
// length of head column in literal tables
String headColType = "VARCHAR2(" + INDEX_KEY_LENGTH + ")";
param[1] = headColType;
}
/**
*
* Return the parameters for table creation.
* Generate the table name by counting the number of existing
* tables for the graph. This is not reliable if another client
* is concurrently trying to create a table so, if failure, we
* make several attempts to create the table.
*/
protected String[] getCreateTableParams( int graphId, boolean isReif ) {
String [] parms = new String[2];
String [] res = new String[2];
getTblParams (parms);
int tblCnt = getTableCount(graphId);
String tblName = TABLE_BASE_NAME +
"g" + Integer.toString(graphId) +
"t" + Integer.toString(tblCnt) +
(isReif ? "_reif" : "_stmt");
tblName = stringToDBname(tblName);
res[0] = tblName;
res[1] = parms[0];
return res;
}
/**
* Return the parameters for database initialization.
*/
protected String[] getDbInitTablesParams() {
String [] res = new String[2];
getTblParams (res);
EOS_LEN = EOS.length();
return res;
}
/**
* Insert a long object into the database.
* This assumes the object is not already in the database.
* @return the db index of the added literal
*/
public DBIDInt addRDBLongObject(RDBLongObject lobj, String table) throws RDFRDBException {
DBIDInt longObjID = null;
try {
int argi = 1;
boolean save = m_dbcon.getConnection().getAutoCommit();
String opname = (lobj.tail.length() > 0) ? "insertLongObjectEmptyTail" : "insertLongObject";
PreparedStatement ps = m_sql.getPreparedSQLStatement(opname, table);
int dbid = 0; // init only needed to satisy java compiler
if ( PRE_ALLOCATE_ID ) {
dbid = getInsertID(table);
ps.setInt(argi++,dbid);
longObjID = wrapDBID(new Integer(dbid));
}
ps.setString(argi++, lobj.head);
if ( lobj.tail.length() > 0 ) {
ps.setLong(argi++, lobj.hash);
} else {
ps.setNull(argi++,java.sql.Types.BIGINT);
}
ps.executeUpdate();
m_sql.returnPreparedSQLStatement(ps, opname);
if ( lobj.tail.length() > 0) {
if (! inTransaction) {
m_dbcon.getConnection().setAutoCommit(false);
}
opname = "getEmptyBLOB";
String cmd = m_sql.getSQLStatement(opname, table, longObjID.getID().toString());
Statement lobStmt = m_sql.getConnection().createStatement();
ResultSet lrs = lobStmt.executeQuery(cmd);
lrs.next();
BLOB blob = ((OracleResultSet) lrs).getBLOB(1);
OutputStream outstream = blob.getBinaryOutputStream();
int size = blob.getBufferSize();
int length = -1;
InputStream instream = new StringBufferInputStream(lobj.tail);
// Buffer to hold chunks of data to being written to the Blob.
byte[] buffer = new byte[size];
while ((length = instream.read(buffer)) != -1)
outstream.write(buffer,0,length);
if (blob.isOpen())
blob.close();
instream.close();
outstream.close();
lobStmt.close();
if (! inTransaction) {
m_dbcon.getConnection().setAutoCommit(save);
}
}
if ( !PRE_ALLOCATE_ID ) {
dbid = getInsertID(table);
longObjID = wrapDBID(new Integer(dbid));
}
} catch (Exception e1) {
/* DEBUG */ System.out.println("Problem on long object (l=" + lobj.head + ") " + e1 );
// System.out.println("ID is: " + id);
throw new RDFRDBException("Failed to add long object ", e1);
}
return longObjID;
}
/**
* Retrieve LongObject from database.
*/
protected RDBLongObject IDtoLongObject ( int dbid, String table ) {
RDBLongObject res = null;
try {
String opName = "getLongObject";
PreparedStatement ps = m_sql.getPreparedSQLStatement(opName, table);
ps.setInt(1,dbid);
OracleResultSet rs = (OracleResultSet) ps.executeQuery();
if (rs.next()) {
res = new RDBLongObject();
res.head = rs.getString(1);
BLOB blob = rs.getBLOB(2);
if (blob != null) {
InputStream blobin = null;
int len = (int)blob.length();
byte[] data = blob.getBytes(1,len);
res.tail = new String(data, "UTF-8");
} else {
res.tail = "";
}
}
rs.close();
m_sql.returnPreparedSQLStatement(ps,opName);
} catch (SQLException e1) {
// /* DEBUG */ System.out.println("Literal truncation (" + l.toString().length() + ") " + l.toString().substring(0, 150));
throw new RDFRDBException("Failed to retrieve long object (SQL Exception): ", e1);
} catch (UnsupportedEncodingException e2) {
throw new RDFRDBException("Failed to retrieve long object (UnsupportedEncoding): ", e2);
}
return res;
}
/**
* Drop all Jena-related sequences from database, if necessary.
* Override in subclass if sequences must be explicitly deleted.
*/
public void clearSequences() {
Iterator seqIt = getSequences().iterator();
while (seqIt.hasNext()) {
removeSequence((String)seqIt.next());
}
}
}
|
package water.util;
import water.Iced;
import java.util.Arrays;
/**
* Serializable 2D Table containing Strings or doubles
* Table can be named
* Columns and Rows can be named
* Fields can be empty
*/
public class TwoDimTable extends Iced {
String description;
String[] colNames;
String[] colFormatStrings; //optional
String[] rowHeaders;
String[][] strings;
public static final double emptyDouble = Double.longBitsToDouble(0x7ff8000000000100L); //also a NaN, but not Double.NaN
double[][] doubles;
/**
* Check whether a double value is considered an "empty field".
* @param d
* @return true iff d represents an empty field
*/
public static boolean isEmpty(double d) { return Double.doubleToRawLongBits(d) == Double.doubleToRawLongBits(emptyDouble); }
/**
* Constructor for TwoDimTable (C columns, R rows)
* @param description
* @param colNames C-dim array with names for each column
* @param colFormatStrings C-dim array with printf format strings for each column
* @param rowHeaders R-dim array with names for each row
* @param strings String[R][C] array with string cell values, can be null (can provide String[R][], for example)
* @param doubles double[R][C] array with double cell values, can be empty (marked with emptyDouble - happens when initialized with double[R][])
*/
public TwoDimTable(String description, String[] colNames, String[] colFormatStrings, String[] rowHeaders, String[][] strings, double[][] doubles) {
assert(Double.isNaN(emptyDouble));
assert(isEmpty(emptyDouble));
assert(!isEmpty(Double.NaN));
if (description == null) throw new IllegalArgumentException("description is missing.");
if (colNames == null) throw new IllegalArgumentException("colNames are missing.");
if (colFormatStrings == null) {
colFormatStrings = new String[colNames.length];
Arrays.fill(colFormatStrings, "%s");
}
if (rowHeaders == null) throw new IllegalArgumentException("rowHeaders are missing.");
if (strings == null) throw new IllegalArgumentException("string values are missing.");
if (strings.length != rowHeaders.length)
throw new IllegalArgumentException("string values must have the same length as rowHeaders: " + rowHeaders.length);
if (doubles == null) throw new IllegalArgumentException("double values are missing.");
if (doubles.length != rowHeaders.length)
throw new IllegalArgumentException("double values must have the same length as rowHeaders: " + rowHeaders.length);
for (String[] v : strings) {
if (v != null)
if (v.length != colNames.length)
throw new IllegalArgumentException("Each entry in string values must have the same length as colNames: " + colNames.length);
}
for (double[] v : doubles) {
if (v != null)
if (v.length != colNames.length)
throw new IllegalArgumentException("Each entry in string values must have the same length as colNames: " + colNames.length);
}
if (colFormatStrings.length != colNames.length)
throw new IllegalArgumentException("colFormatStrings must have the same length as colNames: " + colNames.length);
this.description = description;
this.colNames = colNames;
this.colFormatStrings = colFormatStrings;
this.rowHeaders = rowHeaders;
this.strings = strings;
this.doubles = doubles;
checkConsistency();
}
/**
* Internal helper
*/
private void checkConsistency() {
for (int r=0; r<rowHeaders.length; ++r) {
for (int c=0; c<colNames.length; ++c) {
if (doubles[r]==null) {
doubles[r] = new double[colNames.length];
Arrays.fill(doubles[r], emptyDouble);
}
if (strings[r]==null) {
strings[r] = new String[colNames.length];
}
if (strings[r] != null && strings[r][c] != null && doubles[r] != null && !isEmpty(doubles[r][c]))
throw new IllegalArgumentException("Cannot provide both a String and a Double at row idx " + r + " and column idx " + c + ".");
}
}
}
/**
* Accessor for table cells
* @param row
* @param col
* @return Object (either String or Double)
*/
public Object get(int row, int col) {
return strings[row][col] != null ? strings[row][col]
: !isEmpty(doubles[row][col]) ? doubles[row][col] : null;
}
/**
* Setter for table cells
* @param row
* @param col
* @param s String value
*/
public void set(int row, int col, String s) {
strings[row][col] = s;
checkConsistency();
}
/**
* Setter for table cells
* @param row
* @param col
* @param d double value
*/
public void set(int row, int col, double d) {
doubles[row][col] = d;
checkConsistency();
}
/**
* Setter for table cells
* @param row
* @param col
* @param f float value
*/
public void set(int row, int col, float f) {
doubles[row][col] = (double)f;
checkConsistency();
}
/**
* Setter for table cells
* @param row
* @param col
* @param i integer value
*/
public void set(int row, int col, int i) {
doubles[row][col] = (double)i;
checkConsistency();
}
/**
* Setter for table cells
* @param row
* @param col
* @param l long value
*/
public void set(int row, int col, long l) {
if (l != (double)l) throw new IllegalArgumentException("Can't fit long value of " + l + " into double without loss.");
doubles[row][col] = (double)l;
checkConsistency();
}
/**
* Print table to String, using 2 spaces for padding between columns
* @return String containing the ASCII version of the table
*/
public String toString() {
return toString(2);
}
/**
* Print table to String, using user-given padding
* @param pad number of spaces for padding between columns
* @return String containing the ASCII version of the table
*/
public String toString(int pad) {
StringBuilder sb = new StringBuilder();
// First pass to figure out cell sizes
int maxRowNameLen = rowHeaders[0] == null ? 0 : rowHeaders[0].length();
for (int r=1; r<rowHeaders.length; ++r) {
if (rowHeaders[r] != null) maxRowNameLen = Math.max(maxRowNameLen, rowHeaders[r].length());
}
if (maxRowNameLen != 0) maxRowNameLen += pad;
int[] colLen = new int[colNames.length];
for (int c=0; c<colNames.length; ++c) {
colLen[c] = colNames[c].length();
for (int r=0; r<rowHeaders.length; ++r) {
if (strings[r] != null && strings[r][c] != null)
colLen[c] = Math.max(colLen[c], String.format(colFormatStrings[c], strings[r][c]).length());
else if (doubles[r] != null && !isEmpty(doubles[r][c])) {
if (colFormatStrings[c].equals("%d")) {
colLen[c] = Math.max(colLen[c], String.format("%" + colLen[c] + "s", String.format(colFormatStrings[c], (int)(double) doubles[r][c])).length());
} else {
colLen[c] = Math.max(colLen[c], String.format("%" + colLen[c] + "s", String.format(colFormatStrings[c], doubles[r][c])).length());
}
}
}
colLen[c] += pad;
}
// Print column header
sb.append(description).append(":\n");
for (int i=0; i<maxRowNameLen; ++i) sb.append(" ");
for (int c=0; c<colNames.length; ++c)
sb.append(String.format("%" + colLen[c] + "s", colNames[c]));
sb.append("\n");
// Print table entries row by row
for (int r=0; r<rowHeaders.length; ++r) {
if (rowHeaders[r] != null) sb.append(String.format("%" + maxRowNameLen + "s", rowHeaders[r]));
for (int c=0; c<colNames.length; ++c) {
if (strings[r] != null && strings[r][c] != null)
sb.append(String.format("%" + colLen[c] + "s", String.format(colFormatStrings[c], strings[r][c])));
else if (doubles[r] != null && !isEmpty(doubles[r][c])) {
if (colFormatStrings[c].equals("%d")) {
sb.append(String.format("%" + colLen[c] + "s", String.format(colFormatStrings[c], (int) (double) doubles[r][c])));
} else {
sb.append(String.format("%" + colLen[c] + "s", String.format(colFormatStrings[c], doubles[r][c])));
}
} else {
sb.append(String.format("%" + colLen[c] + "s", "")); //empty field
}
}
sb.append("\n");
}
return sb.toString();
}
}
|
package com.jetbrains.unchain.ui;
import com.intellij.icons.AllIcons;
import com.intellij.ide.actions.CloseTabToolbarAction;
import com.intellij.ide.util.TreeClassChooser;
import com.intellij.ide.util.TreeClassChooserFactory;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.fileEditor.OpenFileDescriptor;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.ComponentWithBrowseButton;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.pom.Navigatable;
import com.intellij.psi.*;
import com.intellij.psi.search.LocalSearchScope;
import com.intellij.psi.search.ProjectScope;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.ui.*;
import com.intellij.ui.components.JBList;
import com.jetbrains.unchain.BadDependencyItem;
import com.jetbrains.unchain.PsiQNames;
import com.jetbrains.unchain.UnchainMover;
import com.jetbrains.unchain.Unchainer;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @author yole
*/
public class UnchainPanel extends JPanel {
private final Project myProject;
private JPanel myMainPanel;
private JPanel myClassNamePlaceholder;
private JComboBox myTargetModuleComboBox;
private JButton myGoButton;
private JPanel myCardsPanel;
private JBList myBadDepsList;
private JBList myCallChainList;
private JList myGoodDepsList;
private JButton myMoveClassesButton;
private final EditorTextField myClassNameField;
private boolean myBadDepsVisible;
private boolean myGoodDepsVisible;
private final List<String> myUnwantedDeps = new ArrayList<String>();
public UnchainPanel(final Project project) {
myProject = project;
setLayout(new BorderLayout());
add(myMainPanel, BorderLayout.CENTER);
myBadDepsList.getEmptyText().setText("Select class to analyze and press Go");
createToolbar();
myClassNameField = new EditorTextField("", project, StdFileTypes.JAVA);
final JavaCodeFragmentFactory factory = JavaCodeFragmentFactory.getInstance(myProject);
PsiPackage defaultPackage = JavaPsiFacade.getInstance(myProject).findPackage("");
final PsiCodeFragment fragment = factory.createReferenceCodeFragment("", defaultPackage, true, true);
myClassNameField.setDocument(PsiDocumentManager.getInstance(myProject).getDocument(fragment));
ComponentWithBrowseButton<EditorTextField> classNameWithBrowseButton = new ComponentWithBrowseButton<EditorTextField>(myClassNameField, new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
PsiClass initialClass = getSelectedClass();
TreeClassChooser chooser = TreeClassChooserFactory.getInstance(project).createProjectScopeChooser("Choose Class to Move", initialClass);
chooser.showDialog();
PsiClass selected = chooser.getSelected();
if (selected != null) {
myClassNameField.setText(selected.getQualifiedName());
}
}
});
myClassNamePlaceholder.add(classNameWithBrowseButton, BorderLayout.CENTER);
Module[] modules = ModuleManager.getInstance(project).getModules();
myTargetModuleComboBox.setModel(new CollectionComboBoxModel(Arrays.asList(modules)));
myTargetModuleComboBox.setRenderer(new ColoredListCellRenderer() {
@Override
protected void customizeCellRenderer(JList list, Object value, int index, boolean selected, boolean hasFocus) {
if (value != null) {
append(((Module) value).getName());
}
}
});
new ComboboxSpeedSearch(myTargetModuleComboBox) {
@Override
protected String getElementText(Object element) {
return element instanceof Module ? ((Module) element).getName() : "";
}
};
myGoButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
runUnchainer();
}
});
setupBadDependenciesListeners();
setupCallChainListeners();
setupGoodDependenciesListeners();
myMoveClassesButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
moveClasses();
}
});
}
private void createToolbar() {
DefaultActionGroup group = new DefaultActionGroup();
group.add(new CloseTabToolbarAction() {
@Override
public void actionPerformed(AnActionEvent e) {
ToolWindowManager.getInstance(myProject).unregisterToolWindow(UnchainAction.UNCHAIN_TOOLWINDOW_ID);
}
});
group.add(new MergeAction());
group.add(new MarkUnwantedAction());
ActionToolbar toolbar = ActionManager.getInstance().createActionToolbar(ActionPlaces.UNKNOWN, group, true);
add(toolbar.getComponent(), BorderLayout.NORTH);
}
private void setupBadDependenciesListeners() {
myBadDepsList.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent mouseEvent) {
if (mouseEvent.getClickCount() == 2 && !mouseEvent.isPopupTrigger()) {
BadDependencyItem selectedValue = (BadDependencyItem) myBadDepsList.getSelectedValue();
if (selectedValue != null) {
Navigatable navigatable = selectedValue.getNavigatable();
if (navigatable != null) {
navigatable.navigate(true);
}
}
}
}
});
myBadDepsList.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent listSelectionEvent) {
BadDependencyItem selectedValue = (BadDependencyItem) myBadDepsList.getSelectedValue();
if (selectedValue != null) {
myCallChainList.setModel(new CollectionListModel<String>(selectedValue.getCallChain()));
}
}
});
}
private void setupCallChainListeners() {
new DoubleClickListener() {
@Override
protected boolean onDoubleClick(MouseEvent event) {
String qName = (String) myCallChainList.getSelectedValue();
PsiElement target = PsiQNames.findElementByQName(myProject, qName);
navigateToReference(target);
return true;
}
}.installOn(myCallChainList);
}
private void setupGoodDependenciesListeners() {
new DoubleClickListener() {
@Override
protected boolean onDoubleClick(MouseEvent event) {
String qName = (String) myGoodDepsList.getSelectedValue();
PsiElement target = PsiQNames.findElementByQName(myProject, qName);
if (target instanceof Navigatable) {
((Navigatable) target).navigate(true);
}
return true;
}
}.installOn(myGoodDepsList);
}
private void navigateToReference(PsiElement target) {
if (target != null && myCallChainList.getSelectedIndex() == myCallChainList.getModel().getSize() - 1) {
BadDependencyItem badDependency = (BadDependencyItem) myBadDepsList.getSelectedValue();
PsiReference reference = ReferencesSearch.search(badDependency.getPsiElement(), new LocalSearchScope(target)).findFirst();
if (reference != null) {
new OpenFileDescriptor(myProject, reference.getElement().getContainingFile().getVirtualFile(),
reference.getRangeInElement().getStartOffset() + reference.getElement().getTextRange().getStartOffset()).navigate(true);
return;
}
}
if (target instanceof Navigatable) {
((Navigatable) target).navigate(true);
}
}
private void runUnchainer() {
PsiClass psiClass = getSelectedClass();
Module module = (Module) myTargetModuleComboBox.getSelectedItem();
if (psiClass != null && module != null) {
runUnchainer(psiClass, module);
}
}
private void runUnchainer(PsiClass psiClass, Module module) {
final Unchainer unchainer = new Unchainer(psiClass, module);
unchainer.setUnwantedDependencies(myUnwantedDeps);
unchainer.setBadDependencyFoundCallback(new Runnable() {
@Override
public void run() {
ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
indicator.setText2("Found " + unchainer.getBadDependencyCount() + " bad dependencies");
}
});
ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() {
@Override
public void run() {
ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
indicator.setIndeterminate(true);
indicator.setText2("Found no bad dependencies");
unchainer.run();
}
}, "Analyzing Dependencies", true, myProject);
boolean haveBadDeps = unchainer.getBadDependencies().size() > 0;
showDepsCard(haveBadDeps);
if (haveBadDeps) {
fillBadDependenciesList(unchainer);
}
else {
fillGoodDependenciesList(unchainer);
}
}
private void showDepsCard(boolean bad) {
myGoodDepsVisible = false;
myBadDepsVisible = false;
CardLayout cardLayout = (CardLayout) myCardsPanel.getLayout();
if (bad) {
cardLayout.show(myCardsPanel, "BadDeps");
myBadDepsVisible = true;
}
else {
cardLayout.show(myCardsPanel, "GoodDeps");
myGoodDepsVisible = true;
}
}
private void fillGoodDependenciesList(Unchainer unchainer) {
myGoodDepsList.setModel(new CollectionListModel<String>(unchainer.getGoodDependencies()));
}
private void fillBadDependenciesList(Unchainer unchainer) {
myBadDepsList.setModel(new CollectionListModel<BadDependencyItem>(unchainer.getBadDependencies()));
}
private PsiClass getSelectedClass() {
return JavaPsiFacade.getInstance(myProject).findClass(myClassNameField.getText(), ProjectScope.getProjectScope(myProject));
}
private List<String> mergeMembers(List<String> qNames, String selectedMemberQName) {
List<String> result = new ArrayList<String>();
String classToMergeQName = PsiQNames.extractClassName(selectedMemberQName);
for (String qName : qNames) {
if (qName.startsWith(classToMergeQName)) {
if (!result.contains(classToMergeQName)) {
result.add(classToMergeQName);
}
}
else {
result.add(qName);
}
}
return result;
}
private void moveClasses() {
Module selectedItem = (Module) myTargetModuleComboBox.getSelectedItem();
CollectionListModel<String> model = (CollectionListModel<String>) myGoodDepsList.getModel();
final UnchainMover mover = new UnchainMover(selectedItem, model.getItems());
final Ref<Boolean> failed = Ref.create(false);
new WriteCommandAction.Simple(myProject, "Moving classes to target module") {
@Override
protected void run() throws Throwable {
try {
mover.run();
}
catch (UnsupportedOperationException e) {
Messages.showErrorDialog(myProject, e.getMessage(), "Move Failed");
failed.set(true);
}
}
}.execute();
if (!failed.get()) {
myClassNameField.setText("");
((CollectionListModel) myBadDepsList.getModel()).removeAll();
((CollectionListModel) myCallChainList.getModel()).removeAll();
showDepsCard(true);
}
}
private class MergeAction extends AnAction {
public MergeAction() {
super("Merge", "Move all methods of selected class to target module", AllIcons.Modules.Merge);
}
@Override
public void actionPerformed(AnActionEvent e) {
CollectionListModel<String> model = (CollectionListModel<String>) myGoodDepsList.getModel();
model.replaceAll(mergeMembers(model.getItems(), (String) myGoodDepsList.getSelectedValue()));
}
@Override
public void update(AnActionEvent e) {
e.getPresentation().setEnabled(myGoodDepsVisible && myGoodDepsList.getSelectedValue() != null);
}
}
private class MarkUnwantedAction extends AnAction {
private MarkUnwantedAction() {
super("Mark Unwanted", "Mark selected class as an unwanted dependency", AllIcons.Actions.Menu_cut);
}
@Override
public void actionPerformed(AnActionEvent e) {
myUnwantedDeps.add(PsiQNames.extractClassName((String) myCallChainList.getSelectedValue()));
int selIndex = myBadDepsList.getSelectedIndex();
runUnchainer();
int size = myBadDepsList.getModel().getSize();
if (size > 0 && myBadDepsVisible) {
myBadDepsList.setSelectedIndex(selIndex >= size ? size - 1 : selIndex);
}
}
@Override
public void update(AnActionEvent e) {
e.getPresentation().setEnabled(myBadDepsVisible && myCallChainList.getSelectedValue() != null);
}
}
}
|
package com.stickycoding.rokon;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;
import javax.microedition.khronos.opengles.GL11Ext;
import com.stickycoding.rokon.VBO.ArrayVBO;
import com.stickycoding.rokon.VBO.VBO;
/**
* DrawableObject.java
* An extension of DynamicObject, for objects which are to be drawn
* Confusion with Androids own Drawable class may be a potential issue, though this being an interface they cannot easily be used accidentally
*
* @author Richard
*/
public class DrawableObject extends PhysicalObject {
protected boolean isTouchable = false;
protected BlendFunction blendFunction;
protected int forceDrawType = DrawPriority.DEFAULT;
protected Layer parentLayer;
protected boolean isOnScene = false;
protected boolean killNextUpdate = false;
protected float red, green, blue, alpha;
protected BufferObject buffer;
protected Texture texture;
protected ArrayVBO arrayVBO;
public DrawableObject(float x, float y, float width, float height) {
super(x, y, width, height);
onCreate();
}
public DrawableObject(float x, float y, float width, float height, Texture texture) {
super(x, y, width, height);
onCreate();
setTexture(texture);
}
/**
* Sets the DrawableObject to a touchable, it will be checked when Scene handles input events
*/
public void setTouchable() {
isTouchable = true;
}
/**
* Sets the DrawableObject as un-touchable
*/
public void removeTouchable() {
isTouchable = false;
}
/**
* @return TRUE if the object is touchable, FALSE otherwise
*/
public boolean isTouchable() {
return isTouchable;
}
/**
* Uses a Texture rather than a blank square
*
* @param texture valid Texture object
*/
public void setTexture(Texture texture) {
this.texture = texture;
}
/**
* Sets a specific BlendFunction to be applied to this DrawableObject
* If no BlendFunction is passed, the default will be used
*
* @param blendFunction a valid BlendFunction
*/
public void setBlendFunction(BlendFunction blendFunction) {
this.blendFunction = blendFunction;
}
/**
* Returns the specific BlendFunction associated with this DrawableObject
*
* @return NULL if no specific BlendFunction has been given
*/
public BlendFunction getBlendFunction() {
return blendFunction;
}
protected void onCreate() {
red = 1f;
green = 1f;
blue = 1f;
alpha = 1f;
isOnScene = false;
killNextUpdate = false;
if(forceDrawType == DrawPriority.VBO || DrawPriority.drawPriority == DrawPriority.PRIORITY_VBO_DRAWTEX_NORMAL || DrawPriority.drawPriority == DrawPriority.PRIORITY_VBO_NORMAL) {
prepareVBO();
}
}
private void prepareVBO() {
arrayVBO = new ArrayVBO(VBO.STATIC);
arrayVBO.update(x, y, width, height);
}
public void forceDrawType(int drawType) {
forceDrawType = drawType;
onDrawType();
}
protected void onDrawType() {
if(forceDrawType == DrawPriority.VBO || DrawPriority.drawPriority == DrawPriority.PRIORITY_VBO_DRAWTEX_NORMAL || DrawPriority.drawPriority == DrawPriority.PRIORITY_VBO_NORMAL) {
prepareVBO();
} else {
if(arrayVBO != null) {
Debug.print("Destroying VBO, onDrawType change");
arrayVBO.destroy();
arrayVBO = null;
}
}
}
protected void onAdd(Layer layer) {
killNextUpdate = false;
isOnScene = true;
parentScene = layer.parentScene;
if(texture != null && texture.textureIndex == -1) {
if(layer.parentScene != null) {
if(Rokon.verbose) Debug.verbose("DrawableObject.onAdd", "Scene does not already contain the this objects Texture, adding automatically.");
layer.parentScene.useTexture(texture);
}
}
}
protected void onRemove() {
isOnScene = false;
}
/**
* Sets the red value
*
* @param red fixed point integer, 0 to ONE
*/
public void setRed(int red) {
this.red = red;
}
/**
* @return current red value
*/
public float getRed() {
return red;
}
/**
* Sets the green value
*
* @param green float, 0 to 1
*/
public void setGreen(float green) {
this.green = green;
}
/**
* @return current green value
*/
public float getGreen() {
return green;
}
/**
* Sets the blue value
*
* @param blue float, 0 to 1
*/
public void setBlue(float blue) {
this.blue = blue;
}
/**
* @return blue value
*/
public float getBlue() {
return blue;
}
/**
* Sets the alpha value
*
* @param alpha float, 0 to 1
*/
public void setAlpha(float alpha) {
this.alpha = alpha;
}
/**
* @return alpha value
*/
public float getAlpha() {
return alpha;
}
/**
* Sets the red, green and blue values
*
* @param red float, 0 to 1
* @param green float, 0 to 1
* @param blue float, 0 to 1
*/
public void setRGB(float red, float green, float blue) {
this.red = red;
this.green = green;
this.blue = blue;
}
/**
* Sets the red, green, blue and alpha values
*
* @param red fixed point integer, 0 to ONE
* @param green fixed point integer, 0 to ONE
* @param blue fixed point integer, 0 to ONE
* @param alpha fixed point integer, 0 to ONE
*/
public void setRGBA(int red, int green, int blue, int alpha) {
this.red = red;
this.green = green;
this.blue = blue;
this.alpha = alpha;
}
/**
* Removes this DrawableObject from the Scene
*/
public void remove() {
killNextUpdate = true;
}
/**
* @return TRUE if the DrawableObject has been added to the current Scene
*/
public boolean isAdded() {
return isOnScene;
}
protected void onDraw(GL10 gl) {
switch(forceDrawType) {
case DrawPriority.DEFAULT:
switch(DrawPriority.drawPriority) {
case DrawPriority.PRIORITY_VBO_DRAWTEX_NORMAL:
if(Device.supportsVBO) {
onDrawVBO(gl);
return;
}
if(Device.supportsDrawTex && rotation == 0) {
onDrawTex(gl);
return;
}
onDrawNormal(gl);
return;
case DrawPriority.PRIORITY_VBO_NORMAL:
if(Device.supportsVBO) {
onDrawVBO(gl);
return;
}
onDrawNormal(gl);
return;
case DrawPriority.PRIORITY_DRAWTEX_VBO_NORMAL:
if(Device.supportsDrawTex) {
onDrawTex(gl);
return;
}
if(Device.supportsVBO) {
onDrawVBO(gl);
return;
}
onDrawNormal(gl);
return;
case DrawPriority.PRIORITY_DRAWTEX_NORMAL:
if(Device.supportsDrawTex) {
onDrawTex(gl);
return;
}
onDrawNormal(gl);
return;
case DrawPriority.PRIORITY_NORMAL:
onDrawNormal(gl);
return;
default:
Debug.warning("DrawableObject.onDraw", "Invalid draw priority on DrawableObject");
return;
}
case DrawPriority.NORMAL:
onDrawNormal(gl);
return;
case DrawPriority.VBO:
onDrawVBO(gl);
return;
case DrawPriority.DRAWTEX:
onDrawTex(gl);
return;
default:
Debug.warning("DrawableObject.onDraw", "Invalid forced draw priority");
return;
}
}
protected void onDrawNormal(GL10 gl) {
GLHelper.color4f(red, green, blue, alpha);
if(blendFunction != null) {
GLHelper.blendMode(blendFunction);
} else {
GLHelper.blendMode(Rokon.blendFunction);
}
gl.glPushMatrix();
GLHelper.enableVertexArray();
GLHelper.vertexPointer(Rokon.defaultVertexBuffer, GL10.GL_FLOAT);
gl.glTranslatef(x, y, 0);
if(rotation != 0) {
if(!rotateAboutPoint) {
gl.glTranslatef(width / 2, height / 2, 0);
gl.glRotatef(rotation, 0, 0, 1);
gl.glTranslatef(-width / 2, -height / 2, 0);
} else {
gl.glTranslatef(rotationPivotX, rotationPivotY, 0);
gl.glRotatef(rotation, 0, 0, 1);
gl.glTranslatef(-rotationPivotX, -rotationPivotY, 0);
}
}
gl.glScalef(width, height, 0);
if(texture != null) {
GLHelper.enableTextures();
GLHelper.enableTexCoordArray();
GLHelper.bindTexture(texture.textureIndex);
GLHelper.texCoordPointer(texture.buffer, GL10.GL_FLOAT);
} else {
GLHelper.disableTexCoordArray();
GLHelper.disableTextures();
}
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4);
gl.glPopMatrix();
}
protected void onDrawTex(GL10 gl) {
if(texture == null) {
return;
}
GLHelper.color4f(red, green, blue, alpha);
GLHelper.bindTexture(texture.textureIndex);
GLHelper.drawTexCrop(new float[] { 0, 0, texture.width, texture.height} );
((GL11Ext)gl).glDrawTexfOES(x, Device.heightPixels - y - height, 0, 100, 100);
}
protected void onDrawVBO(GL10 gl) {
if(!arrayVBO.isLoaded()) {
Debug.print("VBO isn't loaded");
arrayVBO.load(gl);
}
GLHelper.color4f(red, green, blue, alpha);
if(blendFunction != null) {
GLHelper.blendMode(blendFunction);
} else {
GLHelper.blendMode(Rokon.blendFunction);
}
gl.glPushMatrix();
GLHelper.enableVertexArray();
GLHelper.vertexPointer(GL10.GL_FLOAT);
gl.glTranslatef(x, y, 0);
if(rotation != 0) {
if(!rotateAboutPoint) {
gl.glTranslatef(width / 2, height / 2, 0);
gl.glRotatef(rotation, 0, 0, 1);
gl.glTranslatef(-width / 2, -height / 2, 0);
} else {
gl.glTranslatef(rotationPivotX, rotationPivotY, 0);
gl.glRotatef(rotation, 0, 0, 1);
gl.glTranslatef(-rotationPivotX, -rotationPivotY, 0);
}
}
gl.glScalef(width, height, 0);
if(texture != null) {
GLHelper.enableTextures();
GLHelper.enableTexCoordArray();
GLHelper.bindTexture(texture.textureIndex);
GLHelper.texCoordPointer(texture.buffer, GL10.GL_FLOAT);
} else {
GLHelper.disableTexCoordArray();
GLHelper.disableTextures();
}
GLHelper.bindElementBuffer(Rokon.defaultElementVBO().getBufferIndex());
((GL11)gl).glDrawElements(GL11.GL_TRIANGLE_STRIP, 4, GL11.GL_FLOAT, 0);
gl.glPopMatrix();
}
/**
* Determines whether this object is actually visible on screen
*
* @return TRUE if on screen, FALSE otherwise
*/
public boolean isOnScreen() {
//TODO Take into account Windows
//TODO Make this better, in regards of rotation
//Currently assumes extra width/height due to possible rotation
float maxSize = width;
if(height > width) maxSize = height;
if(parentScene.window == null) {
if (x - (maxSize / 2) < RokonActivity.gameWidth && x + maxSize + (maxSize / 2) > 0 && y - (maxSize / 2) < RokonActivity.gameHeight && y + maxSize + (maxSize / 2) > 0) {
return true;
}
} else {
if (x - (maxSize / 2) < parentScene.window.x + parentScene.window.width && x + maxSize + (maxSize / 2) > parentScene.window.x && y - (maxSize / 2) < parentScene.window.height + parentScene.window.y && y + maxSize + (maxSize / 2) > parentScene.window.y) {
return true;
}
}
return false;
}
}
|
package com.szlosek.whenmoving;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context) {
super(context, "locations.db", null, 4);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table locations (day integer, hour integer, milliseconds integer, latitude real, longitude real, altitude real, gpsStart integer, accuracy real, bearing real, speed real, provider text, best integer);");
db.execSQL("create index day_hour on locations (day, hour);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion < 4 && newVersion == 4) {
db.execSQL("drop index day_hour;");
db.execSQL("create table newLocations (day integer, hour integer, milliseconds integer, latitude real, longitude real, altitude real, gpsStart integer, accuracy real, bearing real, speed real, provider text, best integer);");
db.execSQL("insert into newLocations (day, hour, milliseconds, latitude, longitude, altitude, gpsStart, accuracy, bearing, speed, provider, best) select strftime('%Y%m%d', date(milliseconds/1000, 'unixepoch')) as day, strftime('%H', datetime(milliseconds/1000, 'unixepoch')) as hour, milliseconds, latitude, longitude, altitude, gpsStart, accuracy, bearing, speed, provider, best from locations;");
db.execSQL("alter table locations rename to oldLocations;");
db.execSQL("alter table newLocations rename to locations;");
db.execSQL("create index day_hour on locations (day, hour);");
db.execSQL("drop table oldLocations;");
}
}
}
|
package com.tactfactory.harmony.test;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
/**
* All Harmony tests.
*/
@RunWith(Suite.class)
@SuiteClasses({
com.tactfactory.harmony.test.CoreTest.class,
com.tactfactory.harmony.test.project.AllTests.class,
com.tactfactory.harmony.test.orm.AllTests.class,
com.tactfactory.harmony.test.common.AllTests.class,
com.tactfactory.harmony.test.fixture.AllTests.class})
public class AllTests {
}
|
package com.twolattes.json;
import static com.twolattes.json.FieldDescriptor.GetSetFieldDescriptor.Type.GETTER;
import static com.twolattes.json.FieldDescriptor.GetSetFieldDescriptor.Type.SETTER;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.commons.EmptyVisitor;
import com.twolattes.json.DescriptorFactory.EntityDescriptorStore;
import com.twolattes.json.FieldDescriptor.GetSetFieldDescriptor;
class EntityClassVisitor extends EmptyVisitor {
private static final Pattern GETTER_PATTERN = Pattern.compile("^(get|is)[A-Z0-9_].*$");
private static final Pattern GETTER_SIGNATURE = Pattern.compile("^\\(\\).*$");
private static final Pattern SETTER_PATTERN = Pattern.compile("^set[A-Z0-9_].*$");
private static final Pattern SETTER_SIGNATURE = Pattern.compile("^\\([^\\)]+\\)V$");
private Map<String, FieldDescriptor> fieldDescriptors = new HashMap<String, FieldDescriptor>();
private final Class<?> entityClass;
private final EntityDescriptorStore store;
private final boolean shouldInline;
private final Map<String, Set<Method>> methods = new HashMap<String, Set<Method>>();
public EntityClassVisitor(Class<?> entityClass, EntityDescriptorStore store, boolean shouldInline) {
this.entityClass = entityClass;
this.store = store;
this.shouldInline = shouldInline;
methods2map(entityClass.getDeclaredMethods());
}
private void methods2map(Method[] declaredMethods) {
for (Method m : declaredMethods) {
String name = m.getName();
Set<Method> set = methods.get(name);
if (set == null) {
set = new HashSet<Method>();
methods.put(name, set);
}
set.add(m);
}
}
@Override
public FieldVisitor visitField(int access, String name, String desc,
String signature, Object value) {
try {
if (signature != null) {
return new EntityFieldVisitor(this, entityClass.getDeclaredField(name), signature, store);
} else {
return new EntityFieldVisitor(this, entityClass.getDeclaredField(name), desc, store);
}
} catch (NoSuchFieldException e) {
throw new IllegalStateException();
}
}
@SuppressWarnings("unchecked")
@Override
public MethodVisitor visitMethod(int access, String name, String desc,
String signature, String[] exceptions) {
signature = (signature != null) ? signature : desc;
if (isGetterName(name) &&
isGetterSignature(signature) &&
methods.get(name).size() == 1) {
Method getter = methods.get(name).iterator().next();
Value annotation = getter.getAnnotation(Value.class);
if (annotation != null) {
// creating, checking against discovered descriptors
GetSetFieldDescriptor descriptor = new GetSetFieldDescriptor(GETTER, getter);
FieldDescriptor potentialDescriptor = fieldDescriptors.get(descriptor.getFieldName());
if (potentialDescriptor != null) {
if (potentialDescriptor instanceof GetSetFieldDescriptor) {
descriptor = (GetSetFieldDescriptor) potentialDescriptor;
descriptor.setGetter(getter);
} else {
throw new IllegalArgumentException("Value with name "
+ descriptor.getFieldName() + " is described multiple times.");
}
} else {
fieldDescriptors.put(descriptor.getFieldName(), descriptor);
}
// type
if (!annotation.type().equals(com.twolattes.json.types.JsonType.class)) {
try {
descriptor.setDescriptor(
new UserTypeDescriptor(annotation.type().newInstance()));
} catch (InstantiationException e) {
throw new IllegalStateException("could not instanciate " + annotation.type());
} catch (IllegalAccessException e) {
throw new IllegalStateException("could not access " + annotation.type());
}
} else if (descriptor.getDescriptor() == null) {
descriptor.setDescriptor(
new DescriptorFactory().create(signature.substring(2), store, descriptor));
}
// using annotation to populate the descriptor
descriptor.setJsonName(annotation.name());
descriptor.setOptional(annotation.optional());
descriptor.setShouldInline(annotation.inline());
for (String view : annotation.views()) {
descriptor.addView(view);
}
}
} else if (isSetterName(name) &&
isSetterSignature(signature) &&
methods.get(name).size() == 1) {
Method setter = methods.get(name).iterator().next();
Value annotation = setter.getAnnotation(Value.class);
if (annotation != null) {
// creating, checking against discovered descriptors
GetSetFieldDescriptor descriptor = new GetSetFieldDescriptor(SETTER, setter);
FieldDescriptor potentialDescriptor = fieldDescriptors.get(descriptor.getFieldName());
if (potentialDescriptor != null) {
if (potentialDescriptor instanceof GetSetFieldDescriptor) {
descriptor = (GetSetFieldDescriptor) potentialDescriptor;
descriptor.setSetter(setter);
} else {
throw new IllegalArgumentException("Value with name "
+ descriptor.getFieldName() + " is described multiple times.");
}
} else {
fieldDescriptors.put(descriptor.getFieldName(), descriptor);
}
// type
if (!annotation.type().equals(com.twolattes.json.types.JsonType.class)) {
try {
descriptor.setDescriptor(
new UserTypeDescriptor(annotation.type().newInstance()));
} catch (InstantiationException e) {
throw new IllegalStateException("could not instanciate " + annotation.type());
} catch (IllegalAccessException e) {
throw new IllegalStateException("could not access " + annotation.type());
}
} else if (descriptor.getDescriptor() == null) {
descriptor.setDescriptor(
new DescriptorFactory().create(
signature.substring(1, signature.length() - 2), store, descriptor));
}
// using annotation to populate the descriptor
descriptor.setJsonName(annotation.name());
descriptor.setOptional(annotation.optional());
descriptor.setShouldInline(annotation.inline());
for (String view : annotation.views()) {
descriptor.addView(view);
}
}
}
return null;
}
protected void add(FieldDescriptor fieldDescriptor) {
fieldDescriptors.put(fieldDescriptor.getFieldName(), fieldDescriptor);
}
@SuppressWarnings("unchecked")
EntityDescriptor<?> getDescriptor(ConcreteEntityDescriptor<?> parent) {
return new ConcreteEntityDescriptor(entityClass,
new HashSet<FieldDescriptor>(fieldDescriptors.values()),
shouldInline, parent);
}
boolean isGetterName(String name) {
return GETTER_PATTERN.matcher(name).matches();
}
boolean isGetterSignature(String desc) {
return GETTER_SIGNATURE.matcher(desc).matches();
}
boolean isSetterName(String name) {
return SETTER_PATTERN.matcher(name).matches();
}
boolean isSetterSignature(String desc) {
return SETTER_SIGNATURE.matcher(desc).matches();
}
}
|
package com.uwflow.flow_android;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.crashlytics.android.Crashlytics;
import com.facebook.Session;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
import com.google.analytics.tracking.android.EasyTracker;
import com.j256.ormlite.android.apptools.OrmLiteBaseActivity;
import com.uwflow.flow_android.dao.FlowDatabaseHelper;
import com.uwflow.flow_android.network.*;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
public class LoginActivity extends OrmLiteBaseActivity<FlowDatabaseHelper> {
private static final String TAG = "LoginActivity";
protected FlowDatabaseLoader databaseLoader;
private LoginButton mLoginButton;
private ProgressBar mLoginProgressBar;
private Button mSkipLoginButton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_layout);
databaseLoader = new FlowDatabaseLoader(this.getApplicationContext(), getHelper());
mLoginProgressBar = (ProgressBar) findViewById(R.id.login_progress_bar);
mLoginButton = (LoginButton) findViewById(R.id.login_button);
mSkipLoginButton = (Button) findViewById(R.id.skip_login_button);
// The only way to get to the login screen is if you're logged out.
((FlowApplication) getApplication()).setUserLoggedIn(false);
mLoginButton.setUserInfoChangedCallback(new LoginButton.UserInfoChangedCallback() {
@Override
public void onUserInfoFetched(GraphUser user) {
if (user != null) {
if (FlowAsyncClient.getSessionCookie() == null ||
StringUtils.isEmpty(FlowAsyncClient.getCsrfToken())) {
// Clear existing cookies to force a login, in case we're missing a CSRF token
FlowAsyncClient.clearCookie();
FlowApiRequests.login(user.getId(), Session.getActiveSession().getAccessToken(),
new FlowApiRequestCallbackAdapter() {
@Override
public void onSuccess(JSONObject response) {
loadDataAndLogin(response);
}
@Override
public void onFailure(String error) {
// Clear Facebook session
if (Session.getActiveSession() != null) {
Session.getActiveSession().closeAndClearTokenInformation();
}
Session.setActiveSession(null);
// Remove any cookies
FlowAsyncClient.clearCookie();
FlowApplication app = (FlowApplication) getApplication();
// TODO(david): The server should return an app error code to be less brittle
if (error.toLowerCase().contains("create an account")) {
app.track("Login with new account");
// Prompt the user to create an account on uwflow.com or skip login
promptCreateAccount();
} else {
JSONObject properties = new JSONObject();
try {
properties.put("error", error);
} catch (JSONException e) {
e.printStackTrace();
}
app.track("Login error", properties);
// Toast with error text
Toast.makeText(
getApplicationContext(),
"Oops! Couldn't log into Flow. " + error,
Toast.LENGTH_LONG)
.show();
Log.e(TAG, "Error logging in: " + error);
Crashlytics.log(Log.ERROR, TAG, "Error logging in: " + error);
}
}
});
}
}
}
});
Button skipLoginButton = (Button) findViewById(R.id.skip_login_button);
skipLoginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
skipLogin();
}
});
// TODO(david): Also ensure session cookie hasn't expired
if (FlowAsyncClient.getSessionCookie() != null) {
loadDataAndLogin(null);
}
}
@Override
protected void onStart() {
super.onStart();
// Google Analytics tracking
EasyTracker.getInstance(this).activityStart(this);
// Mixpanel tracking
((FlowApplication) getApplication()).track("Impression: LoginActivity");
}
@Override
protected void onStop() {
super.onStop();
// Google Analytics tracking
EasyTracker.getInstance(this).activityStop(this);
}
private void skipLogin() {
FlowApplication app = (FlowApplication) getApplication();
app.setUserLoggedIn(false);
app.track("Login skipped", new JSONObject());
Intent myIntent = new Intent(LoginActivity.this, MainFlowActivity.class);
LoginActivity.this.startActivity(myIntent);
}
private void promptCreateAccount() {
new AlertDialog.Builder(LoginActivity.this)
.setMessage("Oops, looks like you'll have to create an account on uwflow.com first.")
.setPositiveButton("Go to uwflow.com", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("https://uwflow.com")));
}
})
.setNegativeButton("Skip login", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
skipLogin();
}
})
.create()
.show();
}
protected void loadDataAndLogin(JSONObject response) {
// Save the CSRF token that we get back from the login response. This is needed for all non-GET requests.
if (response != null) {
try {
String csrfToken = response.getString("csrf_token");
FlowAsyncClient.setCsrfToken(csrfToken);
} catch (JSONException e) {
Log.e(TAG, "Could not extract CSRF token from JSON response " + response.toString());
Crashlytics.logException(e);
}
}
// Indicate loading state and hide other actions
mLoginProgressBar.setVisibility(View.VISIBLE);
mLoginButton.setVisibility(View.GONE);
mSkipLoginButton.setVisibility(View.GONE);
((FlowApplication) getApplication()).track("Login started");
databaseLoader.loadOrReloadProfileData(new ResultCollectorCallback() {
@Override
public void loadOrReloadCompleted() {
FlowApplication app = (FlowApplication) getApplication();
app.setUserLoggedIn(true);
app.track("Login completed");
Intent myIntent = new Intent(LoginActivity.this, MainFlowActivity.class);
LoginActivity.this.startActivity(myIntent);
finish();
}
});
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}
}
|
package com.valkryst.VTerminal;
import com.valkryst.VRadio.Radio;
import com.valkryst.VTerminal.misc.ColorFunctions;
import com.valkryst.VTerminal.misc.ColoredImageCache;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
import lombok.ToString;
import javax.swing.Timer;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.util.Objects;
@ToString
public class AsciiCharacter {
/** The hash value, of the character, used by the image cache. */
@Getter protected int cacheHash;
/** The character. */
@Getter private char character;
/** Whether or not the foreground should be drawn using the background color. */
@Getter @Setter private boolean isHidden = false;
/** The background color. Defaults to black. */
@Getter private Color backgroundColor = Color.BLACK;
/** The foreground color. Defaults to white. */
@Getter private Color foregroundColor = Color.WHITE;
/** The bounding box of the character's area. */
@Getter private final Rectangle boundingBox;
/** Whether or not to draw the character as underlined. */
@Getter @Setter private boolean isUnderlined = false;
/** The thickness of the underline to draw beneath the character. */
@Getter private int underlineThickness = 2;
/** Whether or not the character should be flipped horizontally when drawn. */
@Getter private boolean isFlippedHorizontally = false;
/** Whether or not the character should be flipped vertically when drawn. */
@Getter private boolean isFlippedVertically = false;
private Timer blinkTimer;
/** The amount of time, in milliseconds, before the blink effect can occur. */
@Getter private short millsBetweenBlinks = 1000;
/**
* Constructs a new AsciiCharacter.
*
* @param character
* The character.
*/
public AsciiCharacter(final char character) {
this.character = character;
boundingBox = new Rectangle();
updateCacheHash();
}
/**
* Constructs a new AsciiCharacter by copying the data
* of an AsciiCharacter.
*
* Does not copy the blinkTimer.
*
* @param character
* The AsciiCharacter.
*
* @throws NullPointerException
* If the character is null.
*/
public AsciiCharacter(final @NonNull AsciiCharacter character) {
boundingBox = new Rectangle();
copy(character);
updateCacheHash();
}
/**
* Copies the settings of an AsciiCharacter to this
* AsciiCharacter.
*
* Does not copy the blinkTimer.
*
* @param character
* The other AsciiCharacter.
*/
public void copy(final @NonNull AsciiCharacter character) {
this.character = character.getCharacter();
isHidden = character.isHidden();
backgroundColor = character.getBackgroundColor();
foregroundColor = character.getForegroundColor();
boundingBox.setSize(character.getBoundingBox().getSize());
boundingBox.setLocation(character.getBoundingBox().getLocation());
isUnderlined = character.isUnderlined();
underlineThickness = character.getUnderlineThickness();
isFlippedHorizontally = character.isFlippedHorizontally();
isFlippedVertically = character.isFlippedVertically();
}
/** Updates the cache hash value. */
protected void updateCacheHash() {
cacheHash = Objects.hash(character, backgroundColor, foregroundColor, isFlippedHorizontally, isFlippedVertically);
}
/**
* Draws the character onto the specified context.
*
* @param gc
* The graphics context to draw with.
*
* @param imageCache
* The image cache to retrieve character images from.
*
* @param columnIndex
* The x-axis (column) coordinate where the character is to be drawn.
*
* @param rowIndex
* The y-axis (row) coordinate where the character is to be drawn.
*
* @throws NullPointerException
* If the gc or image cache are null.
*/
public void draw(final @NonNull Graphics2D gc, final @NonNull ColoredImageCache imageCache, int columnIndex, int rowIndex) {
final int fontWidth = imageCache.getFont().getWidth();
final int fontHeight = imageCache.getFont().getHeight();
columnIndex *= fontWidth;
rowIndex *= fontHeight;
boundingBox.setLocation(columnIndex, rowIndex);
boundingBox.setSize(fontWidth, fontHeight);
// Handle hidden state:
if (isHidden) {
gc.setColor(backgroundColor);
gc.fillRect(columnIndex, rowIndex, fontWidth, fontHeight);
} else {
final BufferedImage image = imageCache.retrieveFromCache(this);
gc.drawImage(image, columnIndex, rowIndex, null);
}
// Draw underline:
if (isUnderlined) {
gc.setColor(foregroundColor);
final int y = rowIndex + fontHeight - underlineThickness;
gc.fillRect(columnIndex, y, fontWidth, underlineThickness);
}
}
/**
* Enables the blink effect.
*
* @param millsBetweenBlinks
* The amount of time, in milliseconds, before the blink effect can occur.
*
* @param radio
* The Radio to transmit a DRAW event to whenever a blink occurs.
*/
public void enableBlinkEffect(final short millsBetweenBlinks, final Radio<String> radio) {
if (radio == null) {
throw new NullPointerException("You must specify a Radio when enabling a blink effect.");
}
if (millsBetweenBlinks <= 0) {
this.millsBetweenBlinks = 1000;
} else {
this.millsBetweenBlinks = millsBetweenBlinks;
}
blinkTimer = new Timer(this.millsBetweenBlinks, e -> {
isHidden = !isHidden;
radio.transmit("DRAW");
});
blinkTimer.setInitialDelay(this.millsBetweenBlinks);
blinkTimer.setRepeats(true);
blinkTimer.start();
}
/** Resumes the blink effect. */
public void resumeBlinkEffect() {
if (blinkTimer != null && blinkTimer.isRunning() == false) {
blinkTimer.start();
}
}
/** Pauses the blink effect. */
public void pauseBlinkEffect() {
if (blinkTimer != null && blinkTimer.isRunning()) {
isHidden = false;
blinkTimer.stop();
}
}
/** Disables the blink effect. */
public void disableBlinkEffect() {
if (blinkTimer != null) {
blinkTimer.stop();
blinkTimer = null;
}
}
/** Swaps the background and foreground colors. */
public void invertColors() {
final Color temp = backgroundColor;
setBackgroundColor(foregroundColor);
setForegroundColor(temp);
}
/**
* Shades the background color by some factor, where a higher factor results
* in a darker shade.
*
* @param tintFactor
* The factor.
*
* Values should range from 0.0 to 1.0.
*/
public void tintBackgroundColor(final double tintFactor) {
backgroundColor = ColorFunctions.tint(backgroundColor, tintFactor);
updateCacheHash();
}
/**
* Shades the foreground color by some factor, where a higher factor results
* in a darker shade.
*
* @param tintFactor
* The factor.
*
* Values should range from 0.0 to 1.0.
*/
public void tintForegroundColor(final double tintFactor) {
foregroundColor = ColorFunctions.tint(foregroundColor, tintFactor);
updateCacheHash();
}
/**
* Shades the background and foreground color by some factor, where a higher
* factor results in a darker shade.
*
* @param tintFactor
* The factor.
*
* Values should range from 0.0 to 1.0.
*/
public void tintBackgroundAndForegroundColor(final double tintFactor) {
backgroundColor = ColorFunctions.tint(backgroundColor, tintFactor);
foregroundColor = ColorFunctions.tint(foregroundColor, tintFactor);
updateCacheHash();
}
/**
* Tints the background color by some factor, where a higher factor results
* in a lighter tint.
*
* @param shadeFactor
* The factor.
*
* Values should range from 0.0 to 1.0.
*/
public void shadeBackgroundColor(final double shadeFactor) {
backgroundColor = ColorFunctions.shade(backgroundColor, shadeFactor);
updateCacheHash();
}
/**
* Tints the foreground color by some factor, where a higher factor results
* in a lighter tint.
*
* @param shadeFactor
* The factor.
*
* Values should range from 0.0 to 1.0.
*/
public void shadeForegroundColor(final double shadeFactor) {
foregroundColor = ColorFunctions.shade(foregroundColor, shadeFactor);
updateCacheHash();
}
/**
* Tints the background and foreground color by some factor, where a higher
* factor results in a lighter tint.
*
* @param shadeFactor
* The factor.
*
* Values should range from 0.0 to 1.0.
*/
public void shadeBackgroundAndForegroundColor(final double shadeFactor) {
backgroundColor = ColorFunctions.shade(backgroundColor, shadeFactor);
foregroundColor = ColorFunctions.shade(foregroundColor, shadeFactor);
updateCacheHash();
}
/**
* Sets the new character.
*
* @param character
* The new character.
*/
public void setCharacter(final char character) {
if (this.character != character) {
this.character = character;
updateCacheHash();
}
}
/**
* Sets the new background color.
*
* @param color
* The new background color.
*
* @throws NullPointerException
* If the color is null.
*/
public void setBackgroundColor(final @NonNull Color color) {
if (backgroundColor.equals(color) == false) {
backgroundColor = color;
updateCacheHash();
}
}
/**
* Sets the new foreground color.
*
* @param color
* The new foreground color.
*
* @throws NullPointerException
* If the color is null.
*/
public void setForegroundColor(final @NonNull Color color) {
if (foregroundColor.equals(color) == false) {
foregroundColor = color;
updateCacheHash();
}
}
/**
* Sets whether or not the character is flipped horizontally.
*
* @param isFlippedHorizontally
* Whether or not the character is flipped horizontally.
*/
public void setFlippedHorizontally(final boolean isFlippedHorizontally) {
if (this.isFlippedHorizontally != isFlippedHorizontally) {
this.isFlippedHorizontally = isFlippedHorizontally;
updateCacheHash();
}
}
/**
* Sets whether or not the character is flipped vertically.
*
* @param isFlippedVertically
* Whether or not the character is flipped vertically.
*/
public void setFlippedVertically(final boolean isFlippedVertically) {
if (this.isFlippedVertically != isFlippedVertically) {
this.isFlippedVertically = isFlippedVertically;
updateCacheHash();
}
}
/**
* Sets the new underline thickness.
*
* If the specified thickness is negative, then the thickness is set to 1.
* If the specified thickness is greater than the font height, then the thickness is set to the font height.
* If the font height is greater than Byte.MAX_VALUE, then the thickness is set to Byte.MAX_VALUE.
*
* @param underlineThickness
* The new underline thickness.
*/
public void setUnderlineThickness(final int underlineThickness) {
if (underlineThickness > boundingBox.getHeight()) {
this.underlineThickness = (int) boundingBox.getHeight();
} else if (underlineThickness <= 0) {
this.underlineThickness = 1;
} else {
this.underlineThickness = underlineThickness;
}
}
}
|
package com.xtouchme.gamebase.entities;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.Area;
import java.util.HashMap;
import com.xtouchme.gamebase.Animation;
import com.xtouchme.gamebase.AnimationFrame;
import com.xtouchme.gamebase.Vector;
import com.xtouchme.gamebase.managers.ResourceManager;
import com.xtouchme.gamebase.managers.SettingsManager;
public class Entity {
protected Vector position = new Vector(0, 0);
protected Vector lastPosition = new Vector(0, 0);
protected Vector speed = new Vector(0, 0);
private int width = 0;
private int height = 0;
private boolean centered = false;
private boolean collidable = false;
private float angle = 0;
private Shape hitbox = null;
protected Entity following = null;
private HashMap<String, Image> imageMap = new HashMap<>();
protected Image sprite = null;
protected Animation animation = null;
public Entity(float x, float y) {
setPosition(x, y);
}
/** Blank Override-able method **/
public void updateHitbox() {}
/** Blank Override-able method **/
public void collisionResponse(Entity other) {}
/** Blank Override-able method **/
public void onPreAdd() {}
/** Blank Override-able method **/
public void onPostAdd() {}
/** Blank Override-able method **/
public void onPreRemove() {}
/** Blank Override-able method **/
public void onPostRemove() {}
public void render(Graphics2D g) {
AffineTransform defTrans = g.getTransform();
if(angle != 0) g.rotate(Math.toRadians(angle), position.x(), position.y());
if(animation != null) {
if(width == 0) width = animation.getImage().getWidth(null);
if(height == 0) height = animation.getImage().getHeight(null);
if(centered)
g.drawImage(animation.getImage(), (int)(position.x() - (width/2)), (int)(position.y() - (height/2)), null);
else
g.drawImage(animation.getImage(), (int)position.x(), (int)position.y(), null);
} else if(sprite != null) {
if(width == 0) width = sprite.getWidth(null);
if(height == 0) height = sprite.getHeight(null);
if(centered)
g.drawImage(sprite, (int)(position.x() - (width/2)), (int)(position.y() - (height/2)), null);
else
g.drawImage(sprite, (int)position.x(), (int)position.y(), null);
}
if(angle != 0) g.setTransform(defTrans);
/* "Hitbox" */
Color def = g.getColor();
g.setColor(Color.MAGENTA);
if(hitbox != null) {
g.draw(hitbox);
}
g.setColor(def);
/* Speed Lines? */
g.setColor(Color.blue);
g.drawLine((int)position.x(), (int)position.y(), (int)(position.x() + speed.x()), (int)(position.y() + speed.y()));
g.setColor(def);
}
public void update(int delta) {
if(animation != null) animation.update(delta);
lastPosition.setX(position.x()).setY(position.y());
if(following != null) position.setX(following.x()).setY(following.y());
else position.add(speed);
updateHitbox();
}
public Entity setAnimation(boolean looping, AnimationFrame... frames) {
Animation a = new Animation().loop(looping);
for(AnimationFrame f : frames) {
a.addFrame(f);
}
return setAnimation(a);
}
public Entity setAnimation(Animation animation) {
this.animation = animation;
return this;
}
public Entity setSprite(String sprite) {
ResourceManager rm = ResourceManager.getInstance(null);
return setSprite(rm.getImage(sprite));
}
public Entity setSprite(Image sprite) {
this.sprite = sprite;
width = sprite.getWidth(null);
height = sprite.getHeight(null);
return this;
}
public float x() {
return position.x();
}
public float y() {
return position.y();
}
public int width() {
return width;
}
public int height() {
return height;
}
public Entity setPosition(float x, float y) {
lastPosition.setX(position.x()).setY(position.y());
position.setX(x).setY(y);
return this;
}
public Entity setSpeed(Vector speed) {
this.speed = speed;
return this;
}
public Entity setSpeed(float x, float y) {
return setSpeed(new Vector(x, y));
}
public Entity setCentered(boolean centered) {
this.centered = centered;
return this;
}
public Entity setCollidable(boolean collidable) {
this.collidable = collidable;
return this;
}
public boolean isCollidable() {
return collidable;
}
public boolean isVisible() {
SettingsManager sm = SettingsManager.getInstance();
if(centered) return position.x() + (width/2) >= 0 && position.x() - (width/2) <= sm.gameWidth() && position.y() + (height/2) >= 0 && position.y() - (height/2) <= sm.gameHeight();
else return position.x() + width >= 0 && position.x() <= sm.gameWidth() && position.y() + height >= 0 && position.y() <= sm.gameHeight();
}
public Entity setAngle(float angle) {
if(angle < 0) angle += 360 * ((int)Math.abs(angle/360)+1);
angle %= 360;
this.angle = angle;
return this;
}
public float angle() {
return angle;
}
public float distanceFrom(Entity other) {
return position.distanceFrom(other.position);
}
public Entity follow(Entity following) {
this.following = following;
return this;
}
public Entity setHitbox(Shape hitbox) {
this.hitbox = hitbox;
return this;
}
public boolean collides(Entity other) {
if(hitbox == null) return false;
Area a = new Area(hitbox);
Area b = new Area(other.hitbox);
a.intersect(b);
return !a.isEmpty();
}
public void addSprite(String tag, String imagePath) {
ResourceManager rm = ResourceManager.getInstance(null);
addSprite(tag, rm.getImage(imagePath));
}
public void addSprite(String tag, Image img) {
imageMap.put(tag, img);
}
public void switchSprite(String tag) {
if(!imageMap.containsKey(tag)) return;
setSprite(imageMap.get(tag));
}
public Entity setInitialAnimationFrame(int frame) {
this.animation.setInitialFrame(frame);
return this;
}
public Entity setWidth(int width) {
this.width = width;
return this;
}
public Entity setHeight(int height) {
this.height = height;
return this;
}
}
|
package gov.nih.nci.ncicb.cadsr.loader.validator;
import java.util.*;
import gov.nih.nci.ncicb.cadsr.domain.*;
import gov.nih.nci.ncicb.cadsr.loader.ElementsLists;
import gov.nih.nci.ncicb.cadsr.loader.UserSelections;
import gov.nih.nci.ncicb.cadsr.loader.event.ProgressListener;
import gov.nih.nci.ncicb.cadsr.loader.event.ProgressEvent;
import gov.nih.nci.ncicb.cadsr.loader.util.*;
import org.apache.log4j.Logger;
/**
* Validates presence of repTerm ID / Version in the VD.
* At this point, this is a requirement in UML Loader only, which is why this is removed from the main VD validator.
*/
public class ValueDomainRepTermValidator implements Validator {
private ElementsLists elements = ElementsLists.getInstance();
private ValidationItems items = ValidationItems.getInstance();
private ProgressListener progressListener;
private Logger logger = Logger.getLogger(ValueDomainRepTermValidator.class.getName());
public ValueDomainRepTermValidator() {
}
public void addProgressListener(ProgressListener l) {
progressListener = l;
}
private void fireProgressEvent(ProgressEvent evt) {
if(progressListener != null)
progressListener.newProgressEvent(evt);
}
public ValidationItems validate() {
Boolean ignoreVD = (Boolean)UserSelections.getInstance().getProperty("ignore-vd");
if(ignoreVD == null)
ignoreVD = false;
List<ValueDomain> vds = elements.getElements(DomainObjectFactory.newValueDomain());
if(vds != null) {
ProgressEvent evt = new ProgressEvent();
evt.setMessage("Validating Value Domains ...");
evt.setGoal(vds.size());
evt.setStatus(0);
fireProgressEvent(evt);
int count = 1;
for(ValueDomain vd : vds) {
evt = new ProgressEvent();
evt.setMessage(" Validating " + vd.getLongName());
evt.setStatus(count++);
fireProgressEvent(evt);
if(vd.getRepresentation() != null) {
if(StringUtil.isEmpty(vd.getRepresentation().getPublicId())) {
items.addItem
(new ValidationError
(PropertyAccessor.getProperty
("vd.missing.repTermId", vd.getLongName()), vd));
}
if(vd.getRepresentation().getVersion() == null) {
items.addItem
(new ValidationError
(PropertyAccessor.getProperty
("vd.missing.repTermVersion", vd.getLongName()), vd));
}
}
}
}
return items;
}
}
|
package com.mixpanel.android.mpmetrics;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.test.AndroidTestCase;
import android.test.mock.MockContext;
import android.test.mock.MockPackageManager;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
public class MixpanelBasicTest extends AndroidTestCase {
@Override
protected void setUp() throws Exception {
super.setUp();
AnalyticsMessages messages = AnalyticsMessages.getInstance(getContext());
messages.hardKill();
Thread.sleep(500);
} // end of setUp() method definition
public void testTrivialRunning() {
assertTrue(getContext() != null);
}
public void testCustomConfig() {
Bundle bundle = new Bundle();
bundle.putInt("com.mixpanel.android.MPConfig.BulkUploadLimit", 101);
bundle.putInt("com.mixpanel.android.MPConfig.FlushInterval", 102);
bundle.putInt("com.mixpanel.android.MPConfig.DataExpiration", 103);
bundle.putString("com.mixpanel.android.MPConfig.EventsEndpoint", "EventsEndpoint");
bundle.putString("com.mixpanel.android.MPConfig.EventsFallbackEndpoint", "EventsFallback");
bundle.putString("com.mixpanel.android.MPConfig.PeopleEndpoint", "PeopleEndpoint");
bundle.putString("com.mixpanel.android.MPConfig.PeopleFallbackEndpoint", "PeopleFallback");
bundle.putString("com.mixpanel.android.MPConfig.DecideEndpoint", "DecideEndpoint");
bundle.putString("com.mixpanel.android.MPConfig.DecideFallbackEndpoint", "DecideFallback");
MPConfig config = new MPConfig(bundle);
assertEquals(config.getBulkUploadLimit(), 101);
assertEquals(config.getFlushInterval(), 102);
assertEquals(config.getDataExpiration(), 103);
assertEquals(config.getEventsEndpoint(), "EventsEndpoint");
assertEquals(config.getEventsFallbackEndpoint(), "EventsFallback");
assertEquals(config.getPeopleEndpoint(), "PeopleEndpoint");
assertEquals(config.getPeopleFallbackEndpoint(), "PeopleFallback");
assertEquals(config.getDecideEndpoint(), "DecideEndpoint");
assertEquals(config.getDecideFallbackEndpoint(), "DecideFallback");
}
public void testGeneratedDistinctId() {
String fakeToken = UUID.randomUUID().toString();
MixpanelAPI mixpanel = MixpanelAPI.getInstance(getContext(), fakeToken);
String generatedId1 = mixpanel.getDistinctId();
assertTrue(generatedId1 != null);
mixpanel.clearPreferences();
String generatedId2 = mixpanel.getDistinctId();
assertTrue(generatedId2 != null);
assertTrue(generatedId1 != generatedId2);
}
public void testDeleteDB() {
Map<String, String> beforeMap = new HashMap<String, String>();
beforeMap.put("added", "before");
JSONObject before = new JSONObject(beforeMap);
Map<String, String> afterMap = new HashMap<String,String>();
afterMap.put("added", "after");
JSONObject after = new JSONObject(afterMap);
MPDbAdapter adapter = new MPDbAdapter(getContext(), "DeleteTestDB");
adapter.addJSON(before, MPDbAdapter.Table.EVENTS);
adapter.addJSON(before, MPDbAdapter.Table.PEOPLE);
adapter.deleteDB();
String[] emptyEventsData = adapter.generateDataString(MPDbAdapter.Table.EVENTS);
assertEquals(emptyEventsData, null);
String[] emptyPeopleData = adapter.generateDataString(MPDbAdapter.Table.PEOPLE);
assertEquals(emptyPeopleData, null);
adapter.addJSON(after, MPDbAdapter.Table.EVENTS);
adapter.addJSON(after, MPDbAdapter.Table.PEOPLE);
try {
String[] someEventsData = adapter.generateDataString(MPDbAdapter.Table.EVENTS);
JSONArray someEvents = new JSONArray(someEventsData[1]);
assertEquals(someEvents.length(), 1);
assertEquals(someEvents.getJSONObject(0).get("added"), "after");
String[] somePeopleData = adapter.generateDataString(MPDbAdapter.Table.PEOPLE);
JSONArray somePeople = new JSONArray(somePeopleData[1]);
assertEquals(somePeople.length(), 1);
assertEquals(somePeople.getJSONObject(0).get("added"), "after");
} catch (JSONException e) {
fail("Unexpected JSON or lack thereof in MPDbAdapter test");
}
}
public void testReadOlderWaitingPeopleRecord() {
// $append is a late addition to the waiting record protocol, we need to handle old records as well.
try {
WaitingPeopleRecord r = new WaitingPeopleRecord();
r.readFromJSONString("{ \"$set\":{\"a\":1}, \"$add\":{\"b\":2} }");
JSONObject setMessage = r.setMessage();
Map<String, Double> incrementMessage = r.incrementMessage();
List<JSONObject> appendMessages = r.appendMessages();
assertEquals(setMessage.getLong("a"), 1L);
assertEquals(incrementMessage.get("b").longValue(), 2L);
assertEquals(appendMessages.size(), 0);
} catch(JSONException e) {
fail("Can't read old-style waiting people record");
}
}
public void testLooperDestruction() {
final BlockingQueue<JSONObject> messages = new LinkedBlockingQueue<JSONObject>();
// If something terrible happens in the worker thread, we
// should make sure
final MPDbAdapter explodingDb = new MPDbAdapter(getContext()) {
@Override
public int addJSON(JSONObject message, MPDbAdapter.Table table) {
messages.add(message);
throw new RuntimeException("BANG!");
}
};
final AnalyticsMessages explodingMessages = new AnalyticsMessages(getContext()) {
// This will throw inside of our worker thread.
@Override
public MPDbAdapter makeDbAdapter(Context context) {
return explodingDb;
}
};
MixpanelAPI mixpanel = new MixpanelAPI(getContext(), "TEST TOKEN testLooperDisaster") {
@Override
protected AnalyticsMessages getAnalyticsMessages() {
return explodingMessages;
}
};
try {
mixpanel.clearPreferences();
assertFalse(explodingMessages.isDead());
mixpanel.track("event1", null);
JSONObject found = messages.poll(1, TimeUnit.SECONDS);
assertNotNull(found);
Thread.sleep(1000);
assertTrue(explodingMessages.isDead());
mixpanel.track("event2", null);
JSONObject shouldntFind = messages.poll(1, TimeUnit.SECONDS);
assertNull(shouldntFind);
assertTrue(explodingMessages.isDead());
} catch (InterruptedException e) {
fail("Unexpected interruption");
}
}
public void testIdentifyAfterSet() {
final List<JSONObject> messages = new ArrayList<JSONObject>();
final AnalyticsMessages listener = new AnalyticsMessages(getContext()) {
@Override
public void peopleMessage(JSONObject heard) {
messages.add(heard);
}
};
MixpanelAPI mixpanel = new MixpanelAPI(getContext(), "TEST TOKEN testIdentifyAfterSet") {
@Override
protected AnalyticsMessages getAnalyticsMessages() {
return listener;
}
};
mixpanel.clearPreferences();
MixpanelAPI.People people = mixpanel.getPeople();
people.increment("the prop", 100L);
people.append("the prop", 66);
people.set("the prop", 1); // should wipe out what comes before
people.increment("the prop", 2L);
people.increment("the prop", 3);
people.append("the prop", 88);
people.append("the prop", 99);
people.identify("Personal Identity");
assertEquals(messages.size(), 4);
JSONObject setMessage = messages.get(0);
try {
JSONObject setValues = setMessage.getJSONObject("$set");
Long setForProp = setValues.getLong("the prop");
assertEquals(setForProp.longValue(), 1);
} catch (JSONException e) {
fail("Unexpected JSON for set message " + setMessage.toString());
}
// We can guarantee that appendOne happens before appendTwo,
// but not that it happens before or after increment
JSONObject addMessage = null;
JSONObject appendOne = null;
JSONObject appendTwo = null;
for (int i = 1; i < 4; i ++) {
JSONObject nextMessage = messages.get(i);
if (nextMessage.has("$append") && appendOne == null) {
appendOne = nextMessage;
}
else if(nextMessage.has("$append") && appendTwo == null) {
appendTwo = nextMessage;
}
else if(nextMessage.has("$add") && addMessage == null) {
addMessage = nextMessage;
}
else {
fail("Unexpected JSON message sent: " + nextMessage.toString());
}
}
assertTrue(addMessage != null);
assertTrue(appendOne != null);
assertTrue(appendTwo != null);
try {
JSONObject addValues = addMessage.getJSONObject("$add");
Long addForProp = addValues.getLong("the prop");
assertEquals(addForProp.longValue(), 5);
} catch (JSONException e) {
fail("Unexpected JSON for add message " + addMessage.toString());
}
try {
JSONObject appendValuesOne = appendOne.getJSONObject("$append");
Long appendForProp = appendValuesOne.getLong("the prop");
assertEquals(appendForProp.longValue(), 88);
} catch (JSONException e) {
fail("Unexpected JSON for append message " + appendOne.toString());
}
messages.clear();
Map<String, Long> lastIncrement = new HashMap<String, Long>();
lastIncrement.put("the prop", 9000L);
people.increment(lastIncrement);
people.set("the prop", "identified");
assertEquals(messages.size(), 2);
JSONObject nextIncrement = messages.get(0);
try {
JSONObject addValues = nextIncrement.getJSONObject("$add");
Long addForProp = addValues.getLong("the prop");
assertEquals(addForProp.longValue(), 9000);
} catch (JSONException e) {
fail("Unexpected JSON for add message " + nextIncrement.toString());
}
JSONObject nextSet = messages.get(1);
try {
JSONObject setValues = nextSet.getJSONObject("$set");
String setForProp = setValues.getString("the prop");
assertEquals(setForProp, "identified");
} catch (JSONException e) {
fail("Unexpected JSON for set message " + nextSet.toString());
}
}
public void testIdentifyAndGetDistinctId() {
MixpanelAPI metrics = new MixpanelAPI(getContext(), "Identify Test Token");
metrics.clearPreferences();
String generatedId = metrics.getDistinctId();
assertNotNull(generatedId);
String emptyId = metrics.getPeople().getDistinctId();
assertNull(emptyId);
metrics.identify("Events Id");
String setId = metrics.getDistinctId();
assertEquals("Events Id", setId);
String stillEmpty = metrics.getPeople().getDistinctId();
assertNull(stillEmpty);
metrics.getPeople().identify("People Id");
String unchangedId = metrics.getDistinctId();
assertEquals("Events Id", unchangedId);
String setPeopleId = metrics.getPeople().getDistinctId();
assertEquals("People Id", setPeopleId);
}
public void testSurveys() {
final List<String> responses = Collections.synchronizedList(new ArrayList<String>());
final BlockingQueue<String> foundQueue = new LinkedBlockingQueue<String>();
MixpanelAPI mixpanel = apiForSurvey(responses);
responses.add("{\"surveys\":[]}");
mixpanel.getPeople().checkForSurvey(new SurveyCallbacks() {
@Override
public void foundSurvey(final Survey s) {
fail("Shouldn't check for surveys if the user is not identified.");
}
});
mixpanel = apiForSurvey(responses);
mixpanel.getPeople().identify("SURVEY TEST USER");
mixpanel.getPeople().checkForSurvey(new SurveyCallbacks(){
@Override
public void foundSurvey(Survey s) {
assertNull(s);
try {
foundQueue.put("OK 0");
} catch (InterruptedException e) {
throw new RuntimeException("Test Interrupted");
}
}
});
try {
final String ok = foundQueue.poll(1, TimeUnit.SECONDS);
assertEquals("OK 0", ok);
} catch(InterruptedException e) {
fail("checkForSurvey never returned");
}
responses.add(
"{\"surveys\":[ {" +
" \"id\":291," +
" \"questions\":[" +
" {\"id\":275,\"type\":\"multiple_choice\",\"extra_data\":{\"$choices\":[\"Option 1\",\"Option 2\"]},\"prompt\":\"Multiple Choice Prompt\"}," +
" {\"id\":277,\"type\":\"text\",\"extra_data\":{},\"prompt\":\"Text Field Prompt\"}]," +
" \"collections\":[{\"selector\":\"\\\"@mixpanel\\\" in properties[\\\"$email\\\"]\",\"id\":141}]}" +
"]}"
);
mixpanel = apiForSurvey(responses);
mixpanel.getPeople().identify("SURVEY TEST USER");
mixpanel.getPeople().checkForSurvey(new SurveyCallbacks(){
@Override public void foundSurvey(Survey s) {
if (Build.VERSION.SDK_INT < 10) {
assertNull(s);
} else {
assertEquals(s.getId(), 291);
assertEquals(s.getCollectionId(), 141);
List<Survey.Question> questions = s.getQuestions();
assertEquals(questions.size(), 2);
Survey.Question mcQuestion = questions.get(0);
assertEquals(mcQuestion.getId(), 275);
assertEquals(mcQuestion.getPrompt(), "Multiple Choice Prompt");
assertEquals(mcQuestion.getType(), Survey.QuestionType.MULTIPLE_CHOICE);
List<String> mcChoices = mcQuestion.getChoices();
assertEquals(mcChoices.size(), 2);
assertEquals(mcChoices.get(0), "Option 1");
assertEquals(mcChoices.get(1), "Option 2");
Survey.Question textQuestion = questions.get(1);
assertEquals(textQuestion.getId(), 277);
assertEquals(textQuestion.getPrompt(), "Text Field Prompt");
assertEquals(textQuestion.getType(), Survey.QuestionType.TEXT);
List<String> textChoices = textQuestion.getChoices();
assertEquals(textChoices.size(), 0);
}
try {
foundQueue.put("OK 1");
} catch (InterruptedException e) {
throw new RuntimeException("Test was interrupted");
}
}
});
try {
final String ok = foundQueue.poll(1, TimeUnit.SECONDS);
assertEquals("OK 1", ok);
} catch(InterruptedException e) {
fail("checkForSurvey never returned");
}
responses.add(
"{\"surveys\":[{\"collections\":[{\"id\":151,\"selector\":\"\\\"@mixpanel\\\" in properties[\\\"$email\\\"]\"}],\"id\":299,\"questions\":[{\"prompt\":\"PROMPT1\",\"extra_data\":{\"$choices\":[\"Answer1,1\",\"Answer1,2\",\"Answer1,3\"]},\"type\":\"multiple_choice\",\"id\":287},{\"prompt\":\"How has the demo affected you?\",\"extra_data\":{\"$choices\":[\"I laughed, I cried, it was better than \\\"Cats\\\"\",\"I want to see it again, and again, and again.\"]},\"type\":\"multiple_choice\",\"id\":289}]}]}"
);
mixpanel = apiForSurvey(responses);
mixpanel.getPeople().identify("SURVEY TEST USER");
mixpanel.getPeople().checkForSurvey(new SurveyCallbacks(){
@Override public void foundSurvey(Survey s) {
if (Build.VERSION.SDK_INT < 10) {
assertNull(s);
} else {
assertEquals(s.getId(), 299);
assertEquals(s.getCollectionId(), 151);
List<Survey.Question> questions = s.getQuestions();
assertEquals(questions.size(), 2);
Survey.Question mcQuestion = questions.get(0);
assertEquals(mcQuestion.getId(), 287);
assertEquals(mcQuestion.getPrompt(), "PROMPT1");
assertEquals(mcQuestion.getType(), Survey.QuestionType.MULTIPLE_CHOICE);
List<String> mcChoices = mcQuestion.getChoices();
assertEquals(mcChoices.size(), 3);
assertEquals(mcChoices.get(0), "Answer1,1");
assertEquals(mcChoices.get(1), "Answer1,2");
assertEquals(mcChoices.get(2), "Answer1,3");
}
try {
foundQueue.put("OK 2");
} catch (InterruptedException e) {
throw new RuntimeException("Test was interrupted");
}
}
});
try {
final String ok = foundQueue.poll(1, TimeUnit.SECONDS);
assertEquals("OK 2", ok);
} catch(InterruptedException e) {
fail("checkForSurvey never returned");
}
// Corrupted or crazy responses.
responses.add("{ WONT PARSE");
mixpanel = apiForSurvey(responses);
mixpanel.getPeople().identify("SURVEY TEST USER");
getNoSurvey(mixpanel, foundQueue);
// Valid JSON but bad (no name)
responses.add("{\"surveys\":{\"id\":3,\"collections\":[{\"id\": 9}],\"questions\":[{\"id\":12,\"type\":\"text\",\"prompt\":\"P\",\"extra_data\":{}}]}");
mixpanel = apiForSurvey(responses);
mixpanel.getPeople().identify("SURVEY TEST USER");
getNoSurvey(mixpanel, foundQueue);
// Just pure craziness
responses.add("null");
mixpanel = apiForSurvey(responses);
mixpanel.getPeople().identify("SURVEY TEST USER");
getNoSurvey(mixpanel, foundQueue);
// Valid JSON that isn't relevant
responses.add("{\"Ziggy Startdust and the Spiders from Mars\":\"The Best Ever Number One\"}");
mixpanel = apiForSurvey(responses);
mixpanel.getPeople().identify("SURVEY TEST USER");
getNoSurvey(mixpanel, foundQueue);
// Valid survey with no questions
responses.add(
"{\"surveys\":[{\"collections\":[{\"id\":151,\"selector\":\"\\\"@mixpanel\\\" in properties[\\\"$email\\\"]\"}],\"id\":299,\"questions\":[]}]}"
);
mixpanel = apiForSurvey(responses);
mixpanel.getPeople().identify("SURVEY TEST USER");
getNoSurvey(mixpanel, foundQueue);
// Valid survey with a question with no choices
responses.add(
"{\"surveys\":[ {" +
" \"id\":291," +
" \"questions\":[" +
" {\"id\":275,\"type\":\"multiple_choice\",\"extra_data\":{\"$choices\":[]},\"prompt\":\"Multiple Choice Prompt\"}," +
" \"collections\":[{\"selector\":\"\\\"@mixpanel\\\" in properties[\\\"$email\\\"]\",\"id\":141}]}" +
"]}"
);
mixpanel = apiForSurvey(responses);
mixpanel.getPeople().identify("SURVEY TEST USER");
getNoSurvey(mixpanel, foundQueue);
}
public void testMessageQueuing() {
final BlockingQueue<String> messages = new LinkedBlockingQueue<String>();
final MPDbAdapter mockAdapter = new MPDbAdapter(getContext()) {
@Override
public int addJSON(JSONObject message, MPDbAdapter.Table table) {
try {
messages.put("TABLE " + table.getName());
messages.put(message.toString());
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return super.addJSON(message, table);
}
};
mockAdapter.cleanupEvents(Long.MAX_VALUE, MPDbAdapter.Table.EVENTS);
mockAdapter.cleanupEvents(Long.MAX_VALUE, MPDbAdapter.Table.PEOPLE);
final ServerMessage mockPoster = new ServerMessage() {
@Override
public Result postData(String rawMessage, String endpointUrl, String fallbackUrl) {
try {
messages.put("SENT FLUSH " + endpointUrl);
messages.put(rawMessage);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return new Result(Status.SUCCEEDED, "1\n");
}
};
final MPConfig mockConfig = new MPConfig(new Bundle()) {
@Override
public int getFlushInterval() {
return -1;
}
@Override
public int getBulkUploadLimit() {
return 40;
}
@Override
public String getEventsEndpoint() {
return "EVENTS_ENDPOINT";
}
@Override
public String getPeopleEndpoint() {
return "PEOPLE_ENDPOINT";
}
};
final AnalyticsMessages listener = new AnalyticsMessages(getContext()) {
@Override
protected MPDbAdapter makeDbAdapter(Context context) {
return mockAdapter;
}
@Override
protected MPConfig getConfig(Context context) {
return mockConfig;
}
@Override
protected ServerMessage getPoster() {
return mockPoster;
}
};
MixpanelAPI metrics = new MixpanelAPI(getContext(), "Test Message Queuing") {
@Override
protected AnalyticsMessages getAnalyticsMessages() {
return listener;
}
};
// metrics.logPosts();
// Test filling up the message queue
for (int i=0; i < mockConfig.getBulkUploadLimit() - 1; i++) {
metrics.track("frequent event", null);
}
metrics.track("final event", null);
String expectedJSONMessage = "<No message actually recieved>";
try {
for (int i=0; i < mockConfig.getBulkUploadLimit() - 1; i++) {
String messageTable = messages.poll(1, TimeUnit.SECONDS);
assertEquals("TABLE " + MPDbAdapter.Table.EVENTS.getName(), messageTable);
expectedJSONMessage = messages.poll(1, TimeUnit.SECONDS);
JSONObject message = new JSONObject(expectedJSONMessage);
assertEquals("frequent event", message.getString("event"));
}
String messageTable = messages.poll(1, TimeUnit.SECONDS);
assertEquals("TABLE " + MPDbAdapter.Table.EVENTS.getName(), messageTable);
expectedJSONMessage = messages.poll(1, TimeUnit.SECONDS);
JSONObject message = new JSONObject(expectedJSONMessage);
assertEquals("final event", message.getString("event"));
String messageFlush = messages.poll(1, TimeUnit.SECONDS);
assertEquals("SENT FLUSH EVENTS_ENDPOINT", messageFlush);
expectedJSONMessage = messages.poll(1, TimeUnit.SECONDS);
JSONArray bigFlush = new JSONArray(expectedJSONMessage);
assertEquals(mockConfig.getBulkUploadLimit(), bigFlush.length());
metrics.track("next wave", null);
metrics.flush();
String nextWaveTable = messages.poll(1, TimeUnit.SECONDS);
assertEquals("TABLE " + MPDbAdapter.Table.EVENTS.getName(), nextWaveTable);
expectedJSONMessage = messages.poll(1, TimeUnit.SECONDS);
JSONObject nextWaveMessage = new JSONObject(expectedJSONMessage);
assertEquals("next wave", nextWaveMessage.getString("event"));
String manualFlush = messages.poll(1, TimeUnit.SECONDS);
assertEquals("SENT FLUSH EVENTS_ENDPOINT", manualFlush);
expectedJSONMessage = messages.poll(1, TimeUnit.SECONDS);
JSONArray nextWave = new JSONArray(expectedJSONMessage);
assertEquals(1, nextWave.length());
JSONObject nextWaveEvent = nextWave.getJSONObject(0);
assertEquals("next wave", nextWaveEvent.getString("event"));
metrics.getPeople().identify("new person");
metrics.getPeople().set("prop", "yup");
metrics.flush();
String peopleTable = messages.poll(1, TimeUnit.SECONDS);
assertEquals("TABLE " + MPDbAdapter.Table.PEOPLE.getName(), peopleTable);
expectedJSONMessage = messages.poll(1, TimeUnit.SECONDS);
JSONObject peopleMessage = new JSONObject(expectedJSONMessage);
assertEquals("new person", peopleMessage.getString("$distinct_id"));
assertEquals("yup", peopleMessage.getJSONObject("$set").getString("prop"));
String peopleFlush = messages.poll(1, TimeUnit.SECONDS);
assertEquals("SENT FLUSH PEOPLE_ENDPOINT", peopleFlush);
expectedJSONMessage = messages.poll(1, TimeUnit.SECONDS);
JSONArray peopleSent = new JSONArray(expectedJSONMessage);
assertEquals(1, peopleSent.length());
} catch (InterruptedException e) {
fail("Expected a log message about mixpanel communication but did not recieve it.");
} catch (JSONException e) {
fail("Expected a JSON object message and got something silly instead: " + expectedJSONMessage);
}
}
public void testHTTPFailures() {
final List<ServerMessage.Result> results = new ArrayList<ServerMessage.Result>();
results.add(new ServerMessage.Result(ServerMessage.Status.SUCCEEDED, "1\n"));
results.add(new ServerMessage.Result(ServerMessage.Status.FAILED_RECOVERABLE, null));
results.add(new ServerMessage.Result(ServerMessage.Status.FAILED_UNRECOVERABLE, "0\n"));
results.add(new ServerMessage.Result(ServerMessage.Status.FAILED_RECOVERABLE, null));
results.add(new ServerMessage.Result(ServerMessage.Status.SUCCEEDED, "1\n"));
final BlockingQueue<String> attempts = new LinkedBlockingQueue<String>();
final ServerMessage mockPoster = new ServerMessage() {
@Override
public ServerMessage.Result postData(String rawMessage, String endpointUrl, String fallbackUrl) {
try {
JSONArray msg = new JSONArray(rawMessage);
JSONObject event = msg.getJSONObject(0);
attempts.put(event.getString("event"));
} catch (JSONException e) {
throw new RuntimeException("Malformed data passed to test mock");
} catch (InterruptedException e) {
throw new RuntimeException("Could not write message to reporting queue for tests.");
}
return results.remove(0);
}
};
final AnalyticsMessages listener = new AnalyticsMessages(getContext()) {
@Override
protected ServerMessage getPoster() {
return mockPoster;
}
};
MixpanelAPI metrics = new MixpanelAPI(getContext(), "Test Message Queuing") {
@Override
protected AnalyticsMessages getAnalyticsMessages() {
return listener;
}
};
try {
metrics.track("Should Succeed", null);
metrics.flush(); // Should result in SUCCEEDED
Thread.sleep(200);
metrics.track("Should Retry, then Fail", null);
metrics.flush();
Thread.sleep(200);
metrics.flush();
metrics.track("Should Retry, then Succeed", null);
metrics.flush();
Thread.sleep(200);
metrics.flush();
String success1 = attempts.poll(1, TimeUnit.SECONDS);
assertEquals(success1, "Should Succeed");
String recoverable2 = attempts.poll(1, TimeUnit.SECONDS);
assertEquals(recoverable2, "Should Retry, then Fail");
String hard_fail3 = attempts.poll(1, TimeUnit.SECONDS);
assertEquals(hard_fail3, "Should Retry, then Fail");
String recoverable4 = attempts.poll(1, TimeUnit.SECONDS);
assertEquals(recoverable4, "Should Retry, then Succeed");
String success5 = attempts.poll(1, TimeUnit.SECONDS);
assertEquals(success5, "Should Retry, then Succeed");
} catch (InterruptedException e) {
throw new RuntimeException("Test was interrupted.");
}
}
public void testTrackCharge() {
final List<JSONObject> messages = new ArrayList<JSONObject>();
final AnalyticsMessages listener = new AnalyticsMessages(getContext()) {
@Override
public void eventsMessage(EventDTO heard) {
throw new RuntimeException("Should not be called during this test");
}
@Override
public void peopleMessage(JSONObject heard) {
messages.add(heard);
}
};
class ListeningAPI extends MixpanelAPI {
public ListeningAPI(Context c, String token) {
super(c, token);
}
@Override
protected AnalyticsMessages getAnalyticsMessages() {
return listener;
}
}
MixpanelAPI api = new ListeningAPI(getContext(), "TRACKCHARGE TEST TOKEN");
api.getPeople().identify("TRACKCHARGE PERSON");
JSONObject props;
try {
props = new JSONObject("{'$time':'Should override', 'Orange':'Banana'}");
} catch (JSONException e) {
throw new RuntimeException("Can't construct fixture for trackCharge test");
}
api.getPeople().trackCharge(2.13, props);
assertEquals(messages.size(), 1);
JSONObject message = messages.get(0);
try {
JSONObject append = message.getJSONObject("$append");
JSONObject newTransaction = append.getJSONObject("$transactions");
assertEquals(newTransaction.optString("Orange"), "Banana");
assertEquals(newTransaction.optString("$time"), "Should override");
assertEquals(newTransaction.optDouble("$amount"), 2.13);
} catch (JSONException e) {
fail("Transaction message had unexpected layout:\n" + message.toString());
}
}
public void testPersistence() {
MixpanelAPI metricsOne = new MixpanelAPI(getContext(), "SAME TOKEN");
metricsOne.clearPreferences();
JSONObject props;
try {
props = new JSONObject("{ 'a' : 'value of a', 'b' : 'value of b' }");
} catch (JSONException e) {
throw new RuntimeException("Can't construct fixture for super properties test.");
}
metricsOne.clearSuperProperties();
metricsOne.registerSuperProperties(props);
metricsOne.identify("Expected Events Identity");
metricsOne.getPeople().identify("Expected People Identity");
// We exploit the fact that any metrics object with the same token
// will get their values from the same persistent store.
final List<Object> messages = new ArrayList<Object>();
final AnalyticsMessages listener = new AnalyticsMessages(getContext()) {
@Override
public void eventsMessage(EventDTO heard) {
messages.add(heard);
}
@Override
public void peopleMessage(JSONObject heard) {
messages.add(heard);
}
};
class ListeningAPI extends MixpanelAPI {
public ListeningAPI(Context c, String token) {
super(c, token);
}
@Override
protected AnalyticsMessages getAnalyticsMessages() {
return listener;
}
}
MixpanelAPI differentToken = new ListeningAPI(getContext(), "DIFFERENT TOKEN");
differentToken.track("other event", null);
differentToken.getPeople().set("other people prop", "Word"); // should be queued up.
assertEquals(1, messages.size());
AnalyticsMessages.EventDTO eventMessage = (AnalyticsMessages.EventDTO) messages.get(0);
try {
JSONObject eventProps = eventMessage.getProperties();
String sentId = eventProps.getString("distinct_id");
String sentA = eventProps.optString("a");
String sentB = eventProps.optString("b");
assertFalse("Expected Events Identity".equals(sentId));
assertEquals("", sentA);
assertEquals("", sentB);
} catch (JSONException e) {
fail("Event message has an unexpected shape " + e);
}
messages.clear();
MixpanelAPI metricsTwo = new ListeningAPI(getContext(), "SAME TOKEN");
metricsTwo.track("eventname", null);
metricsTwo.getPeople().set("people prop name", "Indeed");
assertEquals(2, messages.size());
eventMessage = (AnalyticsMessages.EventDTO) messages.get(0);
JSONObject peopleMessage = (JSONObject) messages.get(1);
try {
JSONObject eventProps = eventMessage.getProperties();
String sentId = eventProps.getString("distinct_id");
String sentA = eventProps.getString("a");
String sentB = eventProps.getString("b");
assertEquals("Expected Events Identity", sentId);
assertEquals("value of a", sentA);
assertEquals("value of b", sentB);
} catch (JSONException e) {
fail("Event message has an unexpected shape " + e);
}
try {
String sentId = peopleMessage.getString("$distinct_id");
assertEquals("Expected People Identity", sentId);
} catch (JSONException e) {
fail("Event message has an unexpected shape: " + peopleMessage.toString());
}
}
public void testTrackInThread() throws InterruptedException, JSONException {
class TestThread extends Thread {
BlockingQueue<JSONObject> mMessages;
public TestThread(BlockingQueue<JSONObject> messages) {
this.mMessages = messages;
}
@Override
public void run() {
final MPDbAdapter dbMock = new MPDbAdapter(getContext()) {
@Override
public int addJSON(JSONObject message, MPDbAdapter.Table table) {
mMessages.add(message);
return 1;
}
};
final AnalyticsMessages analyticsMessages = new AnalyticsMessages(getContext()) {
@Override
public MPDbAdapter makeDbAdapter(Context context) {
return dbMock;
}
};
MixpanelAPI mixpanel = new MixpanelAPI(getContext(), "TEST TOKEN") {
@Override
protected AnalyticsMessages getAnalyticsMessages() {
return analyticsMessages;
}
};
mixpanel.track("test in thread", new JSONObject());
}
}
final BlockingQueue<JSONObject> messages = new LinkedBlockingQueue<JSONObject>();
TestThread testThread = new TestThread(messages);
testThread.start();
JSONObject found = messages.poll(1, TimeUnit.SECONDS);
assertNotNull(found);
assertEquals(found.getString("event"), "test in thread");
assertTrue(found.getJSONObject("properties").has("$bluetooth_version"));
}
public void testConfiguration() {
final ApplicationInfo appInfo = new ApplicationInfo();
appInfo.metaData = new Bundle();
appInfo.metaData.putInt("com.mixpanel.android.MPConfig.BulkUploadLimit", 1);
appInfo.metaData.putInt("com.mixpanel.android.MPConfig.FlushInterval", 2);
appInfo.metaData.putInt("com.mixpanel.android.MPConfig.DataExpiration", 3);
appInfo.metaData.putBoolean("com.mixpanel.android.MPConfig.DisableFallback", true);
appInfo.metaData.putBoolean("com.mixpanel.android.MPConfig.AutoCheckForSurveys", false);
appInfo.metaData.putString("com.mixpanel.android.MPConfig.EventsEndpoint", "EVENTS ENDPOINT");
appInfo.metaData.putString("com.mixpanel.android.MPConfig.EventsFallbackEndpoint", "EVENTS FALLBACK ENDPOINT");
appInfo.metaData.putString("com.mixpanel.android.MPConfig.PeopleEndpoint", "PEOPLE ENDPOINT");
appInfo.metaData.putString("com.mixpanel.android.MPConfig.PeopleFallbackEndpoint", "PEOPLE FALLBACK ENDPOINT");
appInfo.metaData.putString("com.mixpanel.android.MPConfig.DecideEndpoint", "DECIDE ENDPOINT");
appInfo.metaData.putString("com.mixpanel.android.MPConfig.DecideFallbackEndpoint", "DECIDE FALLBACK ENDPOINT");
final PackageManager packageManager = new MockPackageManager() {
@Override
public ApplicationInfo getApplicationInfo(String packageName, int flags) {
assertEquals(packageName, "TEST PACKAGE NAME");
assertTrue((flags & PackageManager.GET_META_DATA) == PackageManager.GET_META_DATA);
return appInfo;
}
};
final Context context = new MockContext() {
@Override
public String getPackageName() {
return "TEST PACKAGE NAME";
}
@Override
public PackageManager getPackageManager() {
return packageManager;
}
};
final MPConfig testConfig = MPConfig.readConfig(context);
assertEquals(1, testConfig.getBulkUploadLimit());
assertEquals(2, testConfig.getFlushInterval());
assertEquals(3, testConfig.getDataExpiration());
assertEquals(true, testConfig.getDisableFallback());
assertEquals(false, testConfig.getAutoCheckForSurveys());
assertEquals("EVENTS ENDPOINT", testConfig.getEventsEndpoint());
assertEquals("EVENTS FALLBACK ENDPOINT", testConfig.getEventsFallbackEndpoint());
assertEquals("PEOPLE ENDPOINT", testConfig.getPeopleEndpoint());
assertEquals("PEOPLE FALLBACK ENDPOINT", testConfig.getPeopleFallbackEndpoint());
assertEquals("DECIDE ENDPOINT", testConfig.getDecideEndpoint());
assertEquals("DECIDE FALLBACK ENDPOINT", testConfig.getDecideFallbackEndpoint());
}
private void getNoSurvey(final MixpanelAPI mixpanel, final BlockingQueue<String> foundQueue) {
mixpanel.getPeople().checkForSurvey(new SurveyCallbacks() {
@Override
public void foundSurvey(final Survey s) {
assertNull(s);
try {
foundQueue.put("OK NO SURVEY");
} catch (InterruptedException e) {
throw new RuntimeException("Test was interrupted");
}
}
});
try {
final String ok = foundQueue.poll(1, TimeUnit.SECONDS);
assertEquals("OK NO SURVEY", ok);
} catch (InterruptedException e) {
throw new RuntimeException("Test was interrupted");
}
}
private MixpanelAPI apiForSurvey(final List<String> responses) {
final ServerMessage mockMessage = new ServerMessage() {
@Override
public Result get(String endpointUrl, String fallbackUrl) {
return new Result(Status.SUCCEEDED, responses.remove(0));
}
};
final AnalyticsMessages mockMessages = new AnalyticsMessages(getContext()) {
@Override
protected ServerMessage getPoster() {
return mockMessage;
}
};
final MixpanelAPI mixpanel = new MixpanelAPI(getContext(), "TEST TOKEN test checkForSurveys") {
@Override
protected AnalyticsMessages getAnalyticsMessages() {
return mockMessages;
}
};
mixpanel.clearPreferences();
return mixpanel;
}
}
|
package es.logongas.fpempresa.presentacion.flyway;
import com.googlecode.flyway.core.Flyway;
import javax.naming.InitialContext;
import javax.servlet.*;
import javax.sql.DataSource;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class FlyWayContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
String dataSourceName=getDataSourceNameFromHibernate();
DataSource dataSource=getDataSource(dataSourceName);
Flyway flyway = new Flyway();
flyway.setDataSource(dataSource);
flyway.setLocations(sce.getServletContext().getInitParameter("flyway.migration.location"));
flyway.setEncoding("utf-8");
flyway.migrate();
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
}
/**
* Obtiene un dataource a partir de su nombre
* @param dataSourceName
* @return
*/
public DataSource getDataSource(String dataSourceName) {
try {
InitialContext initialContext = new InitialContext();;
DataSource dataSource = (DataSource) initialContext.lookup(dataSourceName);
initialContext.close();
return dataSource;
} catch (RuntimeException rex) {
throw rex;
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
/**
* Obtiene el nombre del datasource que usa hibernate
* @return
*/
private String getDataSourceNameFromHibernate() {
try {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setValidating(false);
documentBuilderFactory.setNamespaceAware(true);
documentBuilderFactory.setFeature("http://xml.org/sax/features/namespaces", false);
documentBuilderFactory.setFeature("http://xml.org/sax/features/validation", false);
documentBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
documentBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(FlyWayContextListener.class.getResourceAsStream("/hibernate.cfg.xml"));
document.getDocumentElement().normalize();
NodeList nodeList = document.getElementsByTagName("property");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
if ("connection.datasource".equalsIgnoreCase(element.getAttribute("name"))) {
return element.getTextContent();
}
}
}
return null;
} catch (RuntimeException rex) {
throw rex;
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
}
|
package View;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import javax.swing.JOptionPane;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter.DEFAULT;
import GUIFunctions.GUIFunction;
import turtle.Position;
import turtle.Turtle;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyEvent;
public class SingleGrid extends Grid {
private final static Dimension DEFAULT_GRID_SIZE = new Dimension(800, 500);
private String backgroundColor = "FFFFFF";
private int myHeight;
private int myWidth;
private ImageView myImageView;
private HashSet<Turtle> allTurtles=new HashSet<Turtle>();
private HashSet<Turtle> activeTurtles=new HashSet<Turtle>();
private HashMap<String, GUIFunction> myGridFunctions=new HashMap<String, GUIFunction>();
public SingleGrid(){
}
public SingleGrid(KeyFrame frame, HashMap myMap, int ID){
this.setStyle("-fx-border-color: BLACK; -fx-border-width: 10");
myID=ID;
myHeight=DEFAULT_GRID_SIZE.height;
myWidth=DEFAULT_GRID_SIZE.width;
this.setPrefSize(myWidth, myHeight);
Timeline time=new Timeline();
time.setCycleCount(Timeline.INDEFINITE);
time.getKeyFrames().add(frame);
setBackgroundColor(backgroundColor);
myGridFunctions=myMap;
}
public int getMyHeight(){
return myHeight;
}
public int getMyWidth(){
return myWidth;
}
public Collection<Turtle> getAllTurtles(){
return allTurtles;
}
public Turtle addTurtle(){
Image image = new Image("bowser.png");
Turtle myTurtle = new Turtle(new Position(0, 0), image);
myTurtle.setID(getAllTurtles().size());
myTurtle.setFitWidth(60);
myTurtle.setPreserveRatio(true);
myTurtle.setSmooth(true);
return addTurtle(myTurtle);
}
public void setBackgroundColor(String color){
backgroundColor = color;
this.getChildren().remove(myImageView);
setStyle("-fx-background-color: #"+backgroundColor);
}
public void moveTurtle(Turtle t){
t.relocate(t.getXPos(), t.getYPos());
t.setRotate(t.getOrientation());
}
/**
* Takes in the coordinates (x,y) from the controller and pops the last coordinate from the stack to call move(int x, int y)
* @param x x location on the Grid
* @param y y location on the Grid
*/
public void update(Collection<Turtle> activatedTurtles){
activeTurtles.clear();
for (Turtle active: activatedTurtles){
keepTurtleInBounds(active);
moveTurtle(active);
getChildren().add(active.getPen().drawLine(active.getXPos(), active.getYPos()));
activeTurtles.add(active);
}
}
public void keepTurtleInBounds(Turtle t){
t.getPen().setPenDown(false);
if(t.getXPos() > myWidth){
t.setXPos(t.getXPos()%myWidth);
// t.move((t.getXPos()-myWidth), t.getYPos());
System.out.println("OUT OF BOUNDS!!!! xpos = " + t.getXPos());
System.out.println("width = " + myWidth);
}
if(t.getXPos() < 0) t.move(t.getXPos()+myWidth, t.getYPos());
if(t.getYPos() > this.myHeight) t.move(t.getXPos(), t.getYPos()%myHeight);
if(t.getYPos() < 0) t.move(t.getXPos(), t.getYPos() + myHeight);
moveTurtle(t);
t.getPen().setPenDown(true);
}
public void keyUpdate(){
for (Turtle active: getActiveTurtles()){
keepTurtleInBounds(active);
// moveTurtle(active);
// System.out.println(this.getChildren());
getChildren().add(active.getPen().drawLine(active.getXPos(), active.getYPos()));
}
}
public Collection<Turtle> getActiveTurtles(){
activeTurtles.clear();
for (Turtle a: allTurtles){
if (a.isActive()){
activeTurtles.add(a);
}
}
return activeTurtles;
}
public Collection<Pen> getAllPens(){
return getPens(activeTurtles);
}
public Collection<Pen> getActivePens(){
return getPens(getActiveTurtles());
}
private Collection<Pen> getPens(Collection<Turtle> myTurtles){
Collection<Pen> pens=new ArrayList<Pen>();
for (Turtle t: myTurtles){
pens.add(t.getPen());
}
return pens;
}
public void updateGUI(String myFunction){
myGridFunctions.get(myFunction).doAction();
}
public void updateGUI(String myFunction, List<? extends Number> myNumber){
myGridFunctions.get(myFunction).doAction(myNumber);
}
public void sendErrorMessage(String s){
JOptionPane.showMessageDialog(null, s);
}
public Turtle addTurtle(Turtle myTurtle){
allTurtles.add(myTurtle);
activeTurtles.add(myTurtle);
getChildren().add(myTurtle);
myTurtle.move(myWidth/2,myHeight/2);
myTurtle.getPen().setInitialPosition(myTurtle.getXPos(), myTurtle.getYPos());
moveTurtle(myTurtle);
return myTurtle;
}
@Override
public void setPalette(Double myRed, Double myGreen, Double myBlue) {
// TODO Auto-generated method stub
}
}
|
package bisq.core.filter;
import bisq.network.p2p.storage.payload.ExpirablePayload;
import bisq.network.p2p.storage.payload.ProtectedStoragePayload;
import bisq.common.crypto.Sig;
import bisq.common.proto.ProtoUtil;
import bisq.common.util.CollectionUtils;
import bisq.common.util.ExtraDataMapValidator;
import bisq.common.util.Utilities;
import com.google.protobuf.ByteString;
import com.google.common.annotations.VisibleForTesting;
import java.security.PublicKey;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import javax.annotation.Nullable;
@Slf4j
@Getter
@EqualsAndHashCode
public final class Filter implements ProtectedStoragePayload, ExpirablePayload {
public static final long TTL = TimeUnit.DAYS.toMillis(180);
private final List<String> bannedOfferIds;
private final List<String> nodeAddressesBannedFromTrading;
private final List<String> bannedAutoConfExplorers;
private final List<PaymentAccountFilter> bannedPaymentAccounts;
private final List<String> bannedCurrencies;
private final List<String> bannedPaymentMethods;
private final List<String> arbitrators;
private final List<String> seedNodes;
private final List<String> priceRelayNodes;
private final boolean preventPublicBtcNetwork;
private final List<String> btcNodes;
// SignatureAsBase64 is not set initially as we use the serialized data for signing. We set it after signature is
@Nullable
private final String signatureAsBase64;
// The pub EC key from the dev who has signed and published the filter (different to ownerPubKeyBytes)
private final String signerPubKeyAsHex;
// The pub key used for the data protection in the p2p storage
private final byte[] ownerPubKeyBytes;
private final boolean disableDao;
private final String disableDaoBelowVersion;
private final String disableTradeBelowVersion;
private final List<String> mediators;
private final List<String> refundAgents;
private final List<String> bannedAccountWitnessSignerPubKeys;
private final List<String> btcFeeReceiverAddresses;
private final long creationDate;
private final List<String> bannedPrivilegedDevPubKeys;
// Should be only used in emergency case if we need to add data but do not want to break backward compatibility
// at the P2P network storage checks. The hash of the object will be used to verify if the data is valid. Any new
// field in a class would break that hash and therefore break the storage mechanism.
@Nullable
private Map<String, String> extraDataMap;
private transient PublicKey ownerPubKey;
// added at v1.3.8
private final boolean disableAutoConf;
// added at v1.5.5
private final Set<String> nodeAddressesBannedFromNetwork;
private final boolean disableApi;
// added at v1.6.0
private final boolean disableMempoolValidation;
// After we have created the signature from the filter data we clone it and apply the signature
static Filter cloneWithSig(Filter filter, String signatureAsBase64) {
return new Filter(filter.getBannedOfferIds(),
filter.getNodeAddressesBannedFromTrading(),
filter.getBannedPaymentAccounts(),
filter.getBannedCurrencies(),
filter.getBannedPaymentMethods(),
filter.getArbitrators(),
filter.getSeedNodes(),
filter.getPriceRelayNodes(),
filter.isPreventPublicBtcNetwork(),
filter.getBtcNodes(),
filter.isDisableDao(),
filter.getDisableDaoBelowVersion(),
filter.getDisableTradeBelowVersion(),
filter.getMediators(),
filter.getRefundAgents(),
filter.getBannedAccountWitnessSignerPubKeys(),
filter.getBtcFeeReceiverAddresses(),
filter.getOwnerPubKeyBytes(),
filter.getCreationDate(),
filter.getExtraDataMap(),
signatureAsBase64,
filter.getSignerPubKeyAsHex(),
filter.getBannedPrivilegedDevPubKeys(),
filter.isDisableAutoConf(),
filter.getBannedAutoConfExplorers(),
filter.getNodeAddressesBannedFromNetwork(),
filter.isDisableMempoolValidation(),
filter.isDisableApi());
}
// Used for signature verification as we created the sig without the signatureAsBase64 field we set it to null again
static Filter cloneWithoutSig(Filter filter) {
return new Filter(filter.getBannedOfferIds(),
filter.getNodeAddressesBannedFromTrading(),
filter.getBannedPaymentAccounts(),
filter.getBannedCurrencies(),
filter.getBannedPaymentMethods(),
filter.getArbitrators(),
filter.getSeedNodes(),
filter.getPriceRelayNodes(),
filter.isPreventPublicBtcNetwork(),
filter.getBtcNodes(),
filter.isDisableDao(),
filter.getDisableDaoBelowVersion(),
filter.getDisableTradeBelowVersion(),
filter.getMediators(),
filter.getRefundAgents(),
filter.getBannedAccountWitnessSignerPubKeys(),
filter.getBtcFeeReceiverAddresses(),
filter.getOwnerPubKeyBytes(),
filter.getCreationDate(),
filter.getExtraDataMap(),
null,
filter.getSignerPubKeyAsHex(),
filter.getBannedPrivilegedDevPubKeys(),
filter.isDisableAutoConf(),
filter.getBannedAutoConfExplorers(),
filter.getNodeAddressesBannedFromNetwork(),
filter.isDisableMempoolValidation(),
filter.isDisableApi());
}
public Filter(List<String> bannedOfferIds,
List<String> nodeAddressesBannedFromTrading,
List<PaymentAccountFilter> bannedPaymentAccounts,
List<String> bannedCurrencies,
List<String> bannedPaymentMethods,
List<String> arbitrators,
List<String> seedNodes,
List<String> priceRelayNodes,
boolean preventPublicBtcNetwork,
List<String> btcNodes,
boolean disableDao,
String disableDaoBelowVersion,
String disableTradeBelowVersion,
List<String> mediators,
List<String> refundAgents,
List<String> bannedAccountWitnessSignerPubKeys,
List<String> btcFeeReceiverAddresses,
PublicKey ownerPubKey,
String signerPubKeyAsHex,
List<String> bannedPrivilegedDevPubKeys,
boolean disableAutoConf,
List<String> bannedAutoConfExplorers,
Set<String> nodeAddressesBannedFromNetwork,
boolean disableMempoolValidation,
boolean disableApi) {
this(bannedOfferIds,
nodeAddressesBannedFromTrading,
bannedPaymentAccounts,
bannedCurrencies,
bannedPaymentMethods,
arbitrators,
seedNodes,
priceRelayNodes,
preventPublicBtcNetwork,
btcNodes,
disableDao,
disableDaoBelowVersion,
disableTradeBelowVersion,
mediators,
refundAgents,
bannedAccountWitnessSignerPubKeys,
btcFeeReceiverAddresses,
Sig.getPublicKeyBytes(ownerPubKey),
System.currentTimeMillis(),
null,
null,
signerPubKeyAsHex,
bannedPrivilegedDevPubKeys,
disableAutoConf,
bannedAutoConfExplorers,
nodeAddressesBannedFromNetwork,
disableMempoolValidation,
disableApi);
}
// PROTO BUFFER
@VisibleForTesting
public Filter(List<String> bannedOfferIds,
List<String> nodeAddressesBannedFromTrading,
List<PaymentAccountFilter> bannedPaymentAccounts,
List<String> bannedCurrencies,
List<String> bannedPaymentMethods,
List<String> arbitrators,
List<String> seedNodes,
List<String> priceRelayNodes,
boolean preventPublicBtcNetwork,
List<String> btcNodes,
boolean disableDao,
String disableDaoBelowVersion,
String disableTradeBelowVersion,
List<String> mediators,
List<String> refundAgents,
List<String> bannedAccountWitnessSignerPubKeys,
List<String> btcFeeReceiverAddresses,
byte[] ownerPubKeyBytes,
long creationDate,
@Nullable Map<String, String> extraDataMap,
@Nullable String signatureAsBase64,
String signerPubKeyAsHex,
List<String> bannedPrivilegedDevPubKeys,
boolean disableAutoConf,
List<String> bannedAutoConfExplorers,
Set<String> nodeAddressesBannedFromNetwork,
boolean disableMempoolValidation,
boolean disableApi) {
this.bannedOfferIds = bannedOfferIds;
this.nodeAddressesBannedFromTrading = nodeAddressesBannedFromTrading;
this.bannedPaymentAccounts = bannedPaymentAccounts;
this.bannedCurrencies = bannedCurrencies;
this.bannedPaymentMethods = bannedPaymentMethods;
this.arbitrators = arbitrators;
this.seedNodes = seedNodes;
this.priceRelayNodes = priceRelayNodes;
this.preventPublicBtcNetwork = preventPublicBtcNetwork;
this.btcNodes = btcNodes;
this.disableDao = disableDao;
this.disableDaoBelowVersion = disableDaoBelowVersion;
this.disableTradeBelowVersion = disableTradeBelowVersion;
this.mediators = mediators;
this.refundAgents = refundAgents;
this.bannedAccountWitnessSignerPubKeys = bannedAccountWitnessSignerPubKeys;
this.btcFeeReceiverAddresses = btcFeeReceiverAddresses;
this.ownerPubKeyBytes = ownerPubKeyBytes;
this.creationDate = creationDate;
this.extraDataMap = ExtraDataMapValidator.getValidatedExtraDataMap(extraDataMap);
this.signatureAsBase64 = signatureAsBase64;
this.signerPubKeyAsHex = signerPubKeyAsHex;
this.bannedPrivilegedDevPubKeys = bannedPrivilegedDevPubKeys;
this.disableAutoConf = disableAutoConf;
this.bannedAutoConfExplorers = bannedAutoConfExplorers;
this.nodeAddressesBannedFromNetwork = nodeAddressesBannedFromNetwork;
this.disableMempoolValidation = disableMempoolValidation;
this.disableApi = disableApi;
// ownerPubKeyBytes can be null when called from tests
if (ownerPubKeyBytes != null) {
ownerPubKey = Sig.getPublicKeyFromBytes(ownerPubKeyBytes);
} else {
ownerPubKey = null;
}
}
@Override
public protobuf.StoragePayload toProtoMessage() {
List<protobuf.PaymentAccountFilter> paymentAccountFilterList = bannedPaymentAccounts.stream()
.map(PaymentAccountFilter::toProtoMessage)
.collect(Collectors.toList());
protobuf.Filter.Builder builder = protobuf.Filter.newBuilder().addAllBannedOfferIds(bannedOfferIds)
.addAllNodeAddressesBannedFromTrading(nodeAddressesBannedFromTrading)
.addAllBannedPaymentAccounts(paymentAccountFilterList)
.addAllBannedCurrencies(bannedCurrencies)
.addAllBannedPaymentMethods(bannedPaymentMethods)
.addAllArbitrators(arbitrators)
.addAllSeedNodes(seedNodes)
.addAllPriceRelayNodes(priceRelayNodes)
.setPreventPublicBtcNetwork(preventPublicBtcNetwork)
.addAllBtcNodes(btcNodes)
.setDisableDao(disableDao)
.setDisableDaoBelowVersion(disableDaoBelowVersion)
.setDisableTradeBelowVersion(disableTradeBelowVersion)
.addAllMediators(mediators)
.addAllRefundAgents(refundAgents)
.addAllBannedSignerPubKeys(bannedAccountWitnessSignerPubKeys)
.addAllBtcFeeReceiverAddresses(btcFeeReceiverAddresses)
.setOwnerPubKeyBytes(ByteString.copyFrom(ownerPubKeyBytes))
.setSignerPubKeyAsHex(signerPubKeyAsHex)
.setCreationDate(creationDate)
.addAllBannedPrivilegedDevPubKeys(bannedPrivilegedDevPubKeys)
.setDisableAutoConf(disableAutoConf)
.addAllBannedAutoConfExplorers(bannedAutoConfExplorers)
.addAllNodeAddressesBannedFromNetwork(nodeAddressesBannedFromNetwork)
.setDisableMempoolValidation(disableMempoolValidation)
.setDisableApi(disableApi);
Optional.ofNullable(signatureAsBase64).ifPresent(builder::setSignatureAsBase64);
Optional.ofNullable(extraDataMap).ifPresent(builder::putAllExtraData);
return protobuf.StoragePayload.newBuilder().setFilter(builder).build();
}
public static Filter fromProto(protobuf.Filter proto) {
List<PaymentAccountFilter> bannedPaymentAccountsList = proto.getBannedPaymentAccountsList().stream()
.map(PaymentAccountFilter::fromProto)
.collect(Collectors.toList());
return new Filter(ProtoUtil.protocolStringListToList(proto.getBannedOfferIdsList()),
ProtoUtil.protocolStringListToList(proto.getNodeAddressesBannedFromTradingList()),
bannedPaymentAccountsList,
ProtoUtil.protocolStringListToList(proto.getBannedCurrenciesList()),
ProtoUtil.protocolStringListToList(proto.getBannedPaymentMethodsList()),
ProtoUtil.protocolStringListToList(proto.getArbitratorsList()),
ProtoUtil.protocolStringListToList(proto.getSeedNodesList()),
ProtoUtil.protocolStringListToList(proto.getPriceRelayNodesList()),
proto.getPreventPublicBtcNetwork(),
ProtoUtil.protocolStringListToList(proto.getBtcNodesList()),
proto.getDisableDao(),
proto.getDisableDaoBelowVersion(),
proto.getDisableTradeBelowVersion(),
ProtoUtil.protocolStringListToList(proto.getMediatorsList()),
ProtoUtil.protocolStringListToList(proto.getRefundAgentsList()),
ProtoUtil.protocolStringListToList(proto.getBannedSignerPubKeysList()),
ProtoUtil.protocolStringListToList(proto.getBtcFeeReceiverAddressesList()),
proto.getOwnerPubKeyBytes().toByteArray(),
proto.getCreationDate(),
CollectionUtils.isEmpty(proto.getExtraDataMap()) ? null : proto.getExtraDataMap(),
proto.getSignatureAsBase64(),
proto.getSignerPubKeyAsHex(),
ProtoUtil.protocolStringListToList(proto.getBannedPrivilegedDevPubKeysList()),
proto.getDisableAutoConf(),
ProtoUtil.protocolStringListToList(proto.getBannedAutoConfExplorersList()),
ProtoUtil.protocolStringListToSet(proto.getNodeAddressesBannedFromNetworkList()),
proto.getDisableMempoolValidation(),
proto.getDisableApi()
);
}
// API
@Override
public long getTTL() {
return TTL;
}
@Override
public String toString() {
return "Filter{" +
"\n bannedOfferIds=" + bannedOfferIds +
",\n nodeAddressesBannedFromTrading=" + nodeAddressesBannedFromTrading +
",\n bannedAutoConfExplorers=" + bannedAutoConfExplorers +
",\n bannedPaymentAccounts=" + bannedPaymentAccounts +
",\n bannedCurrencies=" + bannedCurrencies +
",\n bannedPaymentMethods=" + bannedPaymentMethods +
",\n arbitrators=" + arbitrators +
",\n seedNodes=" + seedNodes +
",\n priceRelayNodes=" + priceRelayNodes +
",\n preventPublicBtcNetwork=" + preventPublicBtcNetwork +
",\n btcNodes=" + btcNodes +
",\n signatureAsBase64='" + signatureAsBase64 + '\'' +
",\n signerPubKeyAsHex='" + signerPubKeyAsHex + '\'' +
",\n ownerPubKeyBytes=" + Utilities.bytesAsHexString(ownerPubKeyBytes) +
",\n disableDao=" + disableDao +
",\n disableDaoBelowVersion='" + disableDaoBelowVersion + '\'' +
",\n disableTradeBelowVersion='" + disableTradeBelowVersion + '\'' +
",\n mediators=" + mediators +
",\n refundAgents=" + refundAgents +
",\n bannedAccountWitnessSignerPubKeys=" + bannedAccountWitnessSignerPubKeys +
",\n btcFeeReceiverAddresses=" + btcFeeReceiverAddresses +
",\n creationDate=" + creationDate +
",\n bannedPrivilegedDevPubKeys=" + bannedPrivilegedDevPubKeys +
",\n extraDataMap=" + extraDataMap +
",\n ownerPubKey=" + ownerPubKey +
",\n disableAutoConf=" + disableAutoConf +
",\n nodeAddressesBannedFromNetwork=" + nodeAddressesBannedFromNetwork +
",\n disableMempoolValidation=" + disableMempoolValidation +
",\n disableApi=" + disableApi +
"\n}";
}
}
|
package hudson.model;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.ExtensionList;
import hudson.Util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.NotThreadSafe;
import jenkins.model.ModelObjectWithContextMenu;
import jenkins.model.TransientActionFactory;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
/**
* {@link ModelObject} that can have additional {@link Action}s.
*
* @author Kohsuke Kawaguchi
*/
@ExportedBean
public abstract class Actionable extends AbstractModelObject implements ModelObjectWithContextMenu {
/**
* Actions contributed to this model object.
*
* Typed more strongly than it should to improve the serialization signature.
*/
private volatile CopyOnWriteArrayList<Action> actions;
/**
* Gets actions contributed to this object.
*
* <p>
* A new {@link Action} can be added by {@link #addAction}.
*
* <p>If you are <em>reading</em> the list, rather than <em>modifying</em> it,
* use {@link #getAllActions} instead.
* This method by default returns only <em>persistent</em> actions
* (though some subclasses override it to return an extended unmodifiable list).
*
* @return
* may be empty but never null.
* @deprecated Normally outside code should not call this method any more.
* Use {@link #getAllActions}, or {@link #addAction}, or {@link #replaceAction}.
* May still be called for compatibility reasons from subclasses predating {@link TransientActionFactory}.
*/
@Deprecated
public List<Action> getActions() {
return getOrCreateActions();
}
/**
* We need to handle the initialization of the actions list in Actionable so that child classes that override
* getActions() for historical reasons do not have to override the manipulation methods: {@link #addAction(Action)},
* {@link #replaceAction(Action)}, {@link #removeAction(Action)}, etc.
* @return the CopyOnWriteArrayList of persisted actions.
*/
private CopyOnWriteArrayList<Action> getOrCreateActions() {
if(actions == null) {
synchronized (this) {
if(actions == null) {
actions = new CopyOnWriteArrayList<Action>();
}
}
}
return actions;
}
/**
* Gets all actions, transient or persistent.
* {@link #getActions} is supplemented with anything contributed by {@link TransientActionFactory}.
* @return an unmodifiable, possible empty list
* @since 1.548
*/
@Exported(name="actions")
public final List<? extends Action> getAllActions() {
List<Action> _actions = new ArrayList<Action>(getActions());
for (TransientActionFactory<?> taf : ExtensionList.lookup(TransientActionFactory.class)) {
if (taf.type().isInstance(this)) {
try {
_actions.addAll(createFor(taf));
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Could not load actions from " + taf + " for " + this, e);
}
}
}
return Collections.unmodifiableList(_actions);
}
private <T> Collection<? extends Action> createFor(TransientActionFactory<T> taf) {
return taf.createFor(taf.type().cast(this));
}
/**
* Gets all actions of a specified type that contributed to this object.
*
* @param type The type of action to return.
* @return
* may be empty but never null.
* @see #getAction(Class)
*/
public <T extends Action> List<T> getActions(Class<T> type) {
return Util.filter(getAllActions(), type);
}
/**
* Adds a new action.
* Note: calls to {@link #getAllActions()} that happen before calls to this method may not see the update.
* <strong>Note: this method will always modify the actions</strong>
*
* The default implementation is mostly equivalent to the call chain {@code getActions().add(a)}.
*/
@SuppressWarnings({"ConstantConditions","deprecation"})
@SuppressFBWarnings("RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE")
public void addAction(@Nonnull Action a) {
if(a==null) {
throw new IllegalArgumentException("Action must be non-null");
}
getOrCreateActions().add(a);
}
/**
* Add an action, replacing any existing actions of the (exact) same class.
* Note: calls to {@link #getAllActions()} that happen before calls to this method may not see the update.
* Note: this method does not affect transient actions contributed by a {@link TransientActionFactory}.
* Note: this method cannot provide concurrency control due to the backing storage being a
* {@link CopyOnWriteArrayList} so concurrent calls to any of the mutation methods may produce surprising results
* though technically consistent from the concurrency contract of {@link CopyOnWriteArrayList} (we would need
* some form of transactions or a different backing type).
*
* @param a an action to add/replace
* @since 1.548
* @see #addOrReplaceAction(Action) if you want to know whether the backing {@link #actions} was modified, for
* example in cases where the caller would need to persist the {@link Actionable} in order to persist the change
* and there is a desire to elide unneccessary persistence of unmodified objects.
*/
@SuppressWarnings({"ConstantConditions", "deprecation"})
@SuppressFBWarnings("RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE")
public void replaceAction(@Nonnull Action a) {
addOrReplaceAction(a);
}
/**
* Add an action, replacing any existing actions of the (exact) same class.
* Note: calls to {@link #getAllActions()} that happen before calls to this method may not see the update.
* Note: this method does not affect transient actions contributed by a {@link TransientActionFactory}
* Note: this method cannot provide concurrency control due to the backing storage being a
* {@link CopyOnWriteArrayList} so concurrent calls to any of the mutation methods may produce surprising results
* though technically consistent from the concurrency contract of {@link CopyOnWriteArrayList} (we would need
* some form of transactions or a different backing type).
*
* @param a an action to add/replace
* @return {@code true} if this actions changed as a result of the call
* @since FIXME
*/
@SuppressWarnings({"ConstantConditions", "deprecation"})
@SuppressFBWarnings("RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE")
public boolean addOrReplaceAction(@Nonnull Action a) {
if (a == null) {
throw new IllegalArgumentException("Action must be non-null");
}
// CopyOnWriteArrayList does not support Iterator.remove, so need to do it this way:
List<Action> old = new ArrayList<Action>(1);
List<Action> current = getOrCreateActions();
boolean found = false;
for (Action a2 : current) {
if (!found && a.equals(a2)) {
found = true;
} else if (a2.getClass() == a.getClass()) {
old.add(a2);
}
}
current.removeAll(old);
if (!found) {
addAction(a);
}
return !found || !old.isEmpty();
}
/**
* Remove an action.
* Note: calls to {@link #getAllActions()} that happen before calls to this method may not see the update.
* Note: this method does not affect transient actions contributed by a {@link TransientActionFactory}
* Note: this method cannot provide concurrency control due to the backing storage being a
* {@link CopyOnWriteArrayList} so concurrent calls to any of the mutation methods may produce surprising results
* though technically consistent from the concurrency contract of {@link CopyOnWriteArrayList} (we would need
* some form of transactions or a different backing type).
*
* @param a an action to remove (if {@code null} then this will be a no-op)
* @return {@code true} if this actions changed as a result of the call
* @since FIXME
*/
@SuppressWarnings("deprecation")
public boolean removeAction(@Nullable Action a) {
if (a == null) {
return false;
}
// CopyOnWriteArrayList does not support Iterator.remove, so need to do it this way:
return getOrCreateActions().removeAll(Collections.singleton(a));
}
/**
* Removes any actions of the specified type.
* Note: calls to {@link #getAllActions()} that happen before calls to this method may not see the update.
* Note: this method does not affect transient actions contributed by a {@link TransientActionFactory}
* Note: this method cannot provide concurrency control due to the backing storage being a
* {@link CopyOnWriteArrayList} so concurrent calls to any of the mutation methods may produce surprising results
* though technically consistent from the concurrency contract of {@link CopyOnWriteArrayList} (we would need
* some form of transactions or a different backing type).
*
* @param clazz the type of actions to remove
* @return {@code true} if this actions changed as a result of the call
* @since FIXME
*/
@SuppressWarnings({"ConstantConditions","deprecation"})
@SuppressFBWarnings("RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE")
public boolean removeActions(@Nonnull Class<? extends Action> clazz) {
if (clazz == null) {
throw new IllegalArgumentException("Action type must be non-null");
}
// CopyOnWriteArrayList does not support Iterator.remove, so need to do it this way:
List<Action> old = new ArrayList<Action>();
List<Action> current = getOrCreateActions();
for (Action a : current) {
if (clazz.isInstance(a)) {
old.add(a);
}
}
return current.removeAll(old);
}
/**
* Replaces any actions of the specified type by the supplied action.
* Note: calls to {@link #getAllActions()} that happen before calls to this method may not see the update.
* Note: this method does not affect transient actions contributed by a {@link TransientActionFactory}
* Note: this method cannot provide concurrency control due to the backing storage being a
* {@link CopyOnWriteArrayList} so concurrent calls to any of the mutation methods may produce surprising results
* though technically consistent from the concurrency contract of {@link CopyOnWriteArrayList} (we would need
* some form of transactions or a different backing type).
*
* @param clazz the type of actions to replace (note that the action you are replacing this with need not extend
* this class)
* @param a the action to replace with
* @return {@code true} if this actions changed as a result of the call
* @since FIXME
*/
@SuppressWarnings({"ConstantConditions", "deprecation"})
@SuppressFBWarnings("RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE")
public boolean replaceActions(@Nonnull Class<? extends Action> clazz, @Nonnull Action a) {
if (clazz == null) {
throw new IllegalArgumentException("Action type must be non-null");
}
if (a == null) {
throw new IllegalArgumentException("Action must be non-null");
}
// CopyOnWriteArrayList does not support Iterator.remove, so need to do it this way:
List<Action> old = new ArrayList<Action>();
List<Action> current = getOrCreateActions();
boolean found = false;
for (Action a1 : current) {
if (!found) {
if (a.equals(a1)) {
found = true;
} else if (clazz.isInstance(a1)) {
old.add(a1);
}
} else if (clazz.isInstance(a1) && !a.equals(a1)) {
old.add(a1);
}
}
current.removeAll(old);
if (!found) {
addAction(a);
}
return !(old.isEmpty() && found);
}
/** @deprecated No clear purpose, since subclasses may have overridden {@link #getActions}, and does not consider {@link TransientActionFactory}. */
@Deprecated
public Action getAction(int index) {
if(actions==null) return null;
return actions.get(index);
}
/**
* Gets the action (first instance to be found) of a specified type that contributed to this build.
*
* @param type
* @return The action or <code>null</code> if no such actions exist.
* @see #getActions(Class)
*/
public <T extends Action> T getAction(Class<T> type) {
for (Action a : getAllActions())
if (type.isInstance(a))
return type.cast(a);
return null;
}
public Object getDynamic(String token, StaplerRequest req, StaplerResponse rsp) {
for (Action a : getAllActions()) {
if(a==null)
continue; // be defensive
String urlName = a.getUrlName();
if(urlName==null)
continue;
if(urlName.equals(token))
return a;
}
return null;
}
@Override public ContextMenu doContextMenu(StaplerRequest request, StaplerResponse response) throws Exception {
return new ContextMenu().from(this,request,response);
}
private static final Logger LOGGER = Logger.getLogger(Actionable.class.getName());
}
|
import java.lang.reflect.*;
import java.io.*;
import java.net.*;
import java.util.*;
import org.xbill.DNS.*;
import org.xbill.DNS.utils.*;
/** @author Brian Wellington <bwelling@xbill.org> */
public class jnamed {
static final int FLAG_DNSSECOK = 1;
static final int FLAG_SIGONLY = 2;
Map caches;
Map znames;
Map TSIGs;
public
jnamed(String conffile) throws IOException {
FileInputStream fs;
List ports = new ArrayList();
List addresses = new ArrayList();
try {
fs = new FileInputStream(conffile);
}
catch (Exception e) {
System.out.println("Cannot open " + conffile);
return;
}
caches = new HashMap();
znames = new HashMap();
TSIGs = new HashMap();
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
String line = null;
while ((line = br.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line);
if (!st.hasMoreTokens())
continue;
String keyword = st.nextToken();
if (!st.hasMoreTokens()) {
System.out.println("Invalid line: " + line);
continue;
}
if (keyword.charAt(0) == '
continue;
if (keyword.equals("primary"))
addPrimaryZone(st.nextToken(), st.nextToken());
else if (keyword.equals("secondary"))
addSecondaryZone(st.nextToken(), st.nextToken());
else if (keyword.equals("cache")) {
Cache cache = new Cache(st.nextToken());
caches.put(new Short(DClass.IN), cache);
}
else if (keyword.equals("key"))
addTSIG(st.nextToken(), st.nextToken());
else if (keyword.equals("port"))
ports.add(Short.valueOf(st.nextToken()));
else if (keyword.equals("address")) {
String addr = st.nextToken();
addresses.add(InetAddress.getByName(addr));
} else {
System.out.println("ignoring invalid keyword: " +
keyword);
}
}
if (ports.size() == 0)
ports.add(new Short((short)53));
if (addresses.size() == 0)
addresses.add(null);
Iterator iaddr = addresses.iterator();
while (iaddr.hasNext()) {
InetAddress addr = (InetAddress) iaddr.next();
Iterator iport = ports.iterator();
while (iport.hasNext()) {
short port = ((Short)iport.next()).shortValue();
String addrString;
addUDP(addr, port);
addTCP(addr, port);
if (addr == null)
addrString = "0.0.0.0";
else
addrString = addr.getHostAddress();
System.out.println("jnamed: listening on " +
addrString + "#" + port);
}
}
System.out.println("jnamed: running");
}
public void
addPrimaryZone(String zname, String zonefile) throws IOException {
Name origin = null;
Cache cache = getCache(DClass.IN);
if (zname != null)
origin = Name.fromString(zname, Name.root);
Zone newzone = new Zone(zonefile, cache, origin);
znames.put(newzone.getOrigin(), newzone);
}
public void
addSecondaryZone(String zone, String remote) throws IOException {
Cache cache = getCache(DClass.IN);
Name zname = Name.fromString(zone, Name.root);
Zone newzone = new Zone(zname, DClass.IN, remote, cache);
znames.put(zname, newzone);
}
public void
addTSIG(String namestr, String key) throws IOException {
Name name = Name.fromString(namestr, Name.root);
TSIGs.put(name, base64.fromString(key));
}
public Cache
getCache(short dclass) {
Cache c = (Cache) caches.get(new Short(dclass));
if (c == null) {
c = new Cache(dclass);
caches.put(new Short(dclass), c);
}
return c;
}
public Zone
findBestZone(Name name) {
Zone foundzone = null;
foundzone = (Zone) znames.get(name);
if (foundzone != null)
return foundzone;
int labels = name.labels();
for (int i = 1; i < labels; i++) {
Name tname = new Name(name, i);
foundzone = (Zone) znames.get(tname);
if (foundzone != null)
return foundzone;
}
return null;
}
public RRset
findExactMatch(Name name, short type, short dclass, boolean glue) {
Zone zone = findBestZone(name);
if (zone != null)
return zone.findExactMatch(name, type);
else {
RRset [] rrsets;
Cache cache = getCache(dclass);
if (glue)
rrsets = cache.findAnyRecords(name, type);
else
rrsets = cache.findRecords(name, type);
if (rrsets == null)
return null;
else
return rrsets[0]; /* not quite right */
}
}
void
addRRset(Name name, Message response, RRset rrset, byte section, int flags) {
for (byte s = 1; s <= section; s++)
if (response.findRRset(name, rrset.getType(), s))
return;
if ((flags & FLAG_SIGONLY) == 0) {
Iterator it = rrset.rrs();
while (it.hasNext()) {
Record r = (Record) it.next();
if (r.getName().isWild() && !name.isWild())
r = r.withName(name);
response.addRecord(r, section);
}
}
if ((flags & (FLAG_SIGONLY | FLAG_DNSSECOK)) != 0) {
Iterator it = rrset.sigs();
while (it.hasNext()) {
Record r = (Record) it.next();
if (r.getName().isWild() && !name.isWild())
r = r.withName(name);
response.addRecord(r, section);
}
}
}
private final void
addSOA(Message response, Zone zone) {
response.addRecord(zone.getSOA(), Section.AUTHORITY);
}
private final void
addNS(Message response, Zone zone, int flags) {
RRset nsRecords = zone.getNS();
addRRset(nsRecords.getName(), response, nsRecords,
Section.AUTHORITY, flags);
}
private final void
addCacheNS(Message response, Cache cache, Name name) {
SetResponse sr = cache.lookupRecords(name, Type.NS, Credibility.HINT);
if (!sr.isDelegation())
return;
RRset nsRecords = sr.getNS();
Iterator it = nsRecords.rrs();
while (it.hasNext()) {
Record r = (Record) it.next();
response.addRecord(r, Section.AUTHORITY);
}
}
private void
addGlue(Message response, Name name, int flags) {
RRset a = findExactMatch(name, Type.A, DClass.IN, true);
if (a == null)
return;
addRRset(name, response, a, Section.ADDITIONAL, flags);
}
private void
addAdditional2(Message response, int section, int flags) {
Record [] records = response.getSectionArray(section);
for (int i = 0; i < records.length; i++) {
Record r = records[i];
Name glueName = null;
switch (r.getType()) {
case Type.MX:
glueName = ((MXRecord)r).getTarget();
break;
case Type.NS:
glueName = ((NSRecord)r).getTarget();
break;
case Type.KX:
glueName = ((KXRecord)r).getTarget();
break;
case Type.NAPTR:
glueName = ((NAPTRRecord)r).getReplacement();
break;
case Type.SRV:
glueName = ((SRVRecord)r).getTarget();
break;
default:
break;
}
if (glueName != null)
addGlue(response, glueName, flags);
}
}
private final void
addAdditional(Message response, int flags) {
addAdditional2(response, Section.ANSWER, flags);
addAdditional2(response, Section.AUTHORITY, flags);
}
byte
addAnswer(Message response, Name name, short type, short dclass,
int iterations, int flags)
{
SetResponse sr;
byte rcode = Rcode.NOERROR;
if (iterations > 6)
return Rcode.NOERROR;
if (type == Type.SIG) {
type = Type.ANY;
flags |= FLAG_SIGONLY;
}
Zone zone = findBestZone(name);
if (zone != null)
sr = zone.findRecords(name, type);
else {
Cache cache = getCache(dclass);
sr = cache.lookupRecords(name, type,
Credibility.NONAUTH_ANSWER);
}
if (sr.isUnknown()) {
addCacheNS(response, getCache(dclass), name);
}
if (sr.isNXDOMAIN()) {
response.getHeader().setRcode(Rcode.NXDOMAIN);
if (zone != null) {
addSOA(response, zone);
if (iterations == 0)
response.getHeader().setFlag(Flags.AA);
}
rcode = Rcode.NXDOMAIN;
}
else if (sr.isNXRRSET()) {
if (zone != null) {
addSOA(response, zone);
if (iterations == 0)
response.getHeader().setFlag(Flags.AA);
}
}
else if (sr.isDelegation()) {
RRset nsRecords = sr.getNS();
addRRset(nsRecords.getName(), response, nsRecords,
Section.AUTHORITY, flags);
}
else if (sr.isCNAME()) {
RRset rrset = new RRset();
CNAMERecord cname = sr.getCNAME();
rrset.addRR(cname);
addRRset(name, response, rrset, Section.ANSWER, flags);
if (zone != null && iterations == 0)
response.getHeader().setFlag(Flags.AA);
rcode = addAnswer(response, cname.getTarget(),
type, dclass, iterations + 1, flags);
}
else if (sr.isDNAME()) {
RRset rrset = new RRset();
DNAMERecord dname = sr.getDNAME();
rrset.addRR(dname);
addRRset(name, response, rrset, Section.ANSWER, flags);
Name newname = name.fromDNAME(dname);
if (newname == null)
return Rcode.SERVFAIL;
try {
rrset = new RRset();
rrset.addRR(new CNAMERecord(name, dclass, 0, newname));
addRRset(name, response, rrset, Section.ANSWER, flags);
}
catch (IOException e) {}
if (zone != null && iterations == 0)
response.getHeader().setFlag(Flags.AA);
rcode = addAnswer(response, newname, type, dclass,
iterations + 1, flags);
}
else if (sr.isSuccessful()) {
RRset [] rrsets = sr.answers();
for (int i = 0; i < rrsets.length; i++)
addRRset(name, response, rrsets[i],
Section.ANSWER, flags);
if (zone != null) {
addNS(response, zone, flags);
if (iterations == 0)
response.getHeader().setFlag(Flags.AA);
}
else
addCacheNS(response, getCache(dclass), name);
}
return rcode;
}
TSIG
findTSIG(Name name) {
byte [] key = (byte []) TSIGs.get(name);
if (key != null)
return new TSIG(name, key);
else
return null;
}
Message
doAXFR(Name name, Message query, TSIG tsig, TSIGRecord qtsig, Socket s) {
Zone zone = (Zone) znames.get(name);
boolean first = true;
if (zone == null)
return errorMessage(query, Rcode.REFUSED);
Enumeration e = zone.AXFR();
try {
DataOutputStream dataOut;
dataOut = new DataOutputStream(s.getOutputStream());
int id = query.getHeader().getID();
while (e.hasMoreElements()) {
RRset rrset = (RRset) e.nextElement();
Message response = new Message(id);
Header header = response.getHeader();
header.setFlag(Flags.QR);
header.setFlag(Flags.AA);
addRRset(rrset.getName(), response, rrset,
Section.ANSWER, FLAG_DNSSECOK);
tsig.applyAXFR(response, qtsig, first);
qtsig = response.getTSIG();
first = false;
byte [] out = response.toWire();
dataOut.writeShort(out.length);
dataOut.write(out);
}
}
catch (IOException ex) {
System.out.println("AXFR failed");
}
try {
s.close();
}
catch (IOException ex) {
}
return null;
}
/*
* Note: a null return value means that the caller doesn't need to do
* anything. Currently this only happens if this is an AXFR request over
* TCP.
*/
Message
generateReply(Message query, byte [] in, Socket s) {
Header header;
boolean badversion;
int maxLength;
boolean sigonly;
SetResponse sr;
int flags = 0;
header = query.getHeader();
if (header.getFlag(Flags.QR))
return null;
if (header.getRcode() != Rcode.NOERROR)
return errorMessage(query, Rcode.FORMERR);
if (header.getOpcode() != Opcode.QUERY)
return errorMessage(query, Rcode.NOTIMPL);
Record queryRecord = query.getQuestion();
TSIGRecord queryTSIG = query.getTSIG();
TSIG tsig = null;
if (queryTSIG != null) {
tsig = findTSIG(queryTSIG.getName());
if (tsig == null ||
tsig.verify(query, in, null) != Rcode.NOERROR)
return formerrMessage(in);
}
OPTRecord queryOPT = query.getOPT();
if (queryOPT != null && queryOPT.getVersion() > 0)
badversion = true;
if (s != null)
maxLength = 65535;
else if (queryOPT != null)
maxLength = queryOPT.getPayloadSize();
else
maxLength = 512;
if (queryOPT != null && (queryOPT.getFlags() & Flags.DO) != 0)
flags = FLAG_DNSSECOK;
Message response = new Message(query.getHeader().getID());
response.getHeader().setFlag(Flags.QR);
if (query.getHeader().getFlag(Flags.RD));
response.getHeader().setFlag(Flags.RD);
response.addRecord(queryRecord, Section.QUESTION);
Name name = queryRecord.getName();
short type = queryRecord.getType();
short dclass = queryRecord.getDClass();
if (type == Type.AXFR && s != null)
return doAXFR(name, query, tsig, queryTSIG, s);
if (!Type.isRR(type) && type != Type.ANY)
return errorMessage(query, Rcode.NOTIMPL);
byte rcode = addAnswer(response, name, type, dclass, 0, flags);
if (rcode != Rcode.NOERROR && rcode != Rcode.NXDOMAIN)
return errorMessage(query, rcode);
addAdditional(response, flags);
if (queryTSIG != null) {
try {
if (tsig != null)
tsig.apply(response, queryTSIG);
}
catch (IOException e) {
}
}
try {
response.freeze();
byte [] out = response.toWire();
if (out.length > maxLength) {
response.thaw();
truncate(response, out.length, maxLength);
if (tsig != null)
tsig.apply(response, queryTSIG);
}
}
catch (IOException e) {
}
return response;
}
public int
truncateSection(Message in, int maxLength, int length, int section) {
int removed = 0;
Record [] records = in.getSectionArray(section);
for (int i = records.length - 1; i >= 0; i
Record r = records[i];
removed += r.getWireLength();
length -= r.getWireLength();
in.removeRecord(r, section);
if (length > maxLength)
continue;
else {
for (int j = i - 1; j >= 0; j
Record r2 = records[j];
if (!r.getName().equals(r2.getName()) ||
r.getType() != r2.getType() ||
r.getDClass() != r2.getDClass())
break;
removed += r2.getWireLength();
length -= r2.getWireLength();
in.removeRecord(r2, section);
}
return removed;
}
}
return removed;
}
public void
truncate(Message in, int length, int maxLength) {
TSIGRecord tsig = in.getTSIG();
if (tsig != null)
maxLength -= tsig.getWireLength();
length -= truncateSection(in, maxLength, length, Section.ADDITIONAL);
if (length < maxLength)
return;
in.getHeader().setFlag(Flags.TC);
if (tsig != null) {
in.removeAllRecords(Section.ANSWER);
in.removeAllRecords(Section.AUTHORITY);
return;
}
length -= truncateSection(in, maxLength, length, Section.AUTHORITY);
if (length < maxLength)
return;
length -= truncateSection(in, maxLength, length, Section.ANSWER);
}
public Message
formerrMessage(byte [] in) {
Header header;
try {
header = new Header(new DataByteInputStream(in));
}
catch (IOException e) {
header = new Header(0);
}
Message response = new Message();
response.setHeader(header);
for (int i = 0; i < 4; i++)
response.removeAllRecords(i);
header.setRcode(Rcode.FORMERR);
return response;
}
public Message
errorMessage(Message query, short rcode) {
Header header = query.getHeader();
Message response = new Message();
response.setHeader(header);
for (int i = 0; i < 4; i++)
response.removeAllRecords(i);
if (rcode == Rcode.SERVFAIL)
response.addRecord(query.getQuestion(), Section.QUESTION);
header.setRcode(rcode);
return response;
}
public void
serveTCP(InetAddress addr, short port) {
try {
ServerSocket sock = new ServerSocket(port, 128, addr);
while (true) {
Socket s = sock.accept();
int inLength;
DataInputStream dataIn;
DataOutputStream dataOut;
byte [] in;
try {
InputStream is = s.getInputStream();
dataIn = new DataInputStream(is);
inLength = dataIn.readUnsignedShort();
in = new byte[inLength];
dataIn.readFully(in);
}
catch (InterruptedIOException e) {
s.close();
continue;
}
Message query, response;
try {
query = new Message(in);
response = generateReply(query, in, s);
if (response == null)
continue;
}
catch (IOException e) {
response = formerrMessage(in);
}
byte [] out = response.toWire();
dataOut = new DataOutputStream(s.getOutputStream());
dataOut.writeShort(out.length);
dataOut.write(out);
s.close();
}
}
catch (IOException e) {
String addrString;
if (addr == null)
addrString = "0.0.0.0";
else
addrString = addr.getHostAddress();
System.out.println("serveTCP(" + addrString + "#" + port +
"): " + e);
}
}
public void
serveUDP(InetAddress addr, short port) {
try {
DatagramSocket sock = new DatagramSocket(port, addr);
final short udpLength = 512;
byte [] in = new byte[udpLength];
DatagramPacket indp = new DatagramPacket(in, in.length);
DatagramPacket outdp = null;
while (true) {
indp.setLength(in.length);
try {
sock.receive(indp);
}
catch (InterruptedIOException e) {
continue;
}
Message query, response;
try {
query = new Message(in);
response = generateReply(query, in, null);
if (response == null)
continue;
}
catch (IOException e) {
response = formerrMessage(in);
}
byte [] out = response.toWire();
if (outdp == null)
outdp = new DatagramPacket(out, out.length,
indp.getAddress(),
indp.getPort());
else {
outdp.setData(out);
outdp.setLength(out.length);
outdp.setAddress(indp.getAddress());
outdp.setPort(indp.getPort());
}
sock.send(outdp);
}
}
catch (IOException e) {
String addrString;
if (addr == null)
addrString = "0.0.0.0";
else
addrString = addr.getHostAddress();
System.out.println("serveUDP(" + addrString + "#" + port +
"): " + e);
}
}
public void
addTCP(final InetAddress addr, final short port) {
Thread t;
t = new Thread(new Runnable() {
public void run() {serveTCP(addr, port);}});
t.start();
}
public void
addUDP(final InetAddress addr, final short port) {
Thread t;
t = new Thread(new Runnable() {
public void run() {serveUDP(addr, port);}});
t.start();
}
public static void main(String [] args) {
if (args.length > 1) {
System.out.println("usage: jnamed [conf]");
System.exit(0);
}
jnamed s;
try {
String conf;
if (args.length == 1)
conf = args[0];
else
conf = "jnamed.conf";
s = new jnamed(conf);
}
catch (IOException e) {
System.out.println(e);
}
}
}
|
package me.benjozork.onyx.object;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import me.benjozork.onyx.internal.GameManager;
import me.benjozork.onyx.utils.Utils;
public abstract class Drawable {
protected Vector2 position;
protected Vector2 velocity = new Vector2(0, 0);
protected Vector2 acceleration = new Vector2(0, 0);
protected float maxVelocity = 100f;
protected float angle;
protected Rectangle bounds;
private float speed;
private boolean boundsDebug = false;
public Drawable(int x, int y) {
this.position = new Vector2(x, y);
}
public Drawable(Vector2 position) {
this.position = position;
}
/**
* Internally update the Drawable
*
* @param dt The delta time
*/
public void update(float dt) {
if (boundsDebug) {
GameManager.getShapeRenderer().begin(ShapeRenderer.ShapeType.Filled);
GameManager.getShapeRenderer().rect(bounds.x, bounds.y, bounds.width, bounds.height);
GameManager.getShapeRenderer().end();
}
bounds.setPosition(position);
velocity.setAngle(angle);
//velocity.add(acceleration);
position.add(velocity.nor().scl(speed).scl(Utils.delta()));
}
public abstract void init();
/**
* Update the Drawable
*/
public abstract void update();
public abstract void draw();
/**
* Check if the Drawable collides with a rectangle
*
* @param otherBounds The rectangle used to check
* @return If the Drawable collides with otherBounds
*/
public boolean collidesWith(Rectangle otherBounds) {
return bounds.overlaps(otherBounds);
}
/**
* The Drawable's position
*
* @return The Drawable's position
*/
public Vector2 getPosition() {
return position;
}
public void setPosition(Vector2 position) {
this.position = position;
this.bounds.setPosition(position);
}
/**
* The X coordinate value
*
* @return The X coordinate value
*/
public float getX() {
return position.x;
}
public void setX(float v) {
position.x = v;
bounds.x = v;
}
/**
* The Y coordinate value
*
* @return The Y coordinate value
*/
public float getY() {
return position.y;
}
public void setY(float v) {
position.y = v;
bounds.y = v;
}
public void move(float dx, float dy) {
// here, we move the position and the bounding box
position.x += dx * Utils.delta();
bounds.x += dx * Utils.delta();
position.y += dy * Utils.delta();
bounds.y += dy * Utils.delta();
}
/**
* The velocity
*
* @return The velocity
*/
public Vector2 getVelocity() {
return velocity;
}
public void setVelocity(Vector2 velocity) {
this.velocity = velocity;
}
/**
* The acceleration
*
* @return The acceleration
*/
public Vector2 getAcceleration() {
return acceleration;
}
public void setAcceleration(Vector2 acceleration) {
this.acceleration = acceleration;
}
/**
* Change the speed
*
* @param v The speed offset
*/
public void accelerate(float v) {
speed += v;
if (velocity.x == 0 && velocity.y == 0 && speed > 0f) velocity.set(1, 1); // Prevent this from having no effect
}
/**
* The max velocity
*
* @return The max velocity
*/
public float getMaxVelocity() {
return maxVelocity;
}
public void setMaxVelocity(float maxVelocity) {
this.maxVelocity = maxVelocity;
}
public void rotate(float v) {
angle += v * Utils.delta();
}
/**
* The speed
*
* @return The speed
*/
public float getSpeed() {
return speed;
}
public void setSpeed(float speed) {
this.speed = speed;
}
/**
* Check if the mouse hovers above the hitbox
*
* @return result
*/
public boolean hovering() {
Vector2 mouse = Utils.unprojectWorld(Gdx.input.getX(), Gdx.input.getY());
if (mouse.x > getBounds().getX()
&& mouse.x < (getBounds().getX() + getBounds().getWidth())
&& mouse.y > getBounds().getY()
&& mouse.y < (getBounds().getY() + getBounds().getHeight())) {
return true;
} else return false;
}
/**
* The bounding box
*
* @return The bounding box
*/
public Rectangle getBounds() {
return bounds;
}
public void setBounds(Rectangle bounds) {
this.bounds = bounds;
}
/**
* Toggle the hitbox debug rendering
*/
public void toggleBoundsDebug() {
boundsDebug = ! boundsDebug;
}
public abstract void dispose();
}
|
package net.plastboks.gameworld;
import net.plastboks.gameobjects.Autonomous;
import net.plastboks.gameobjects.Bird;
import net.plastboks.gameobjects.Mouse;
import net.plastboks.gameobjects.Snake;
import java.util.LinkedList;
public class GameWorld {
private Snake snake;
private LinkedList<Autonomous> food;
private int score = 0;
private int midPointY;
public enum GameState { READY, RUNNING, GAMEOVER, HIGHSCORE }
private GameState currentState;
public GameWorld(int midPointY) {
this.midPointY = midPointY;
currentState = GameState.READY;
snake = new Snake(33, midPointY - 5, 15, 15, midPointY * 2);
food = new LinkedList<Autonomous>();
initFood();
}
private void initFood() {
food.add(new Bird(15, 15));
food.add(new Mouse(15, 15));
}
public void update(float delta) {
switch (currentState) {
case READY:
updateReady(delta);
break;
case RUNNING:
updateRunning(delta);
break;
default:
break;
}
}
public void updateReady(float delta) { }
public void updateRunning(float delta) {
if (delta > .15f) { delta = .15f; }
snake.update(delta);
for(Autonomous a : food) {
a.update(delta);
if (snake.collides(a)) { a.respawn(); }
}
//if (snake.isAlive()) {
// snake.die();
// AssetLoader.dead.play();
}
public void restart() {
currentState = GameState.READY;
score = 0;
snake.onRestart(midPointY - 5);
currentState = GameState.READY;
}
public void addScore(int inc) { score += inc; }
public void start() { currentState = GameState.RUNNING; }
public Snake getSnake() { return snake; }
public LinkedList<Autonomous> getFood() { return food; }
public int getScore() { return score; }
public boolean isReady() { return currentState == GameState.READY; }
public boolean isGameOver() { return currentState == GameState.GAMEOVER; }
public boolean isHighScore() { return currentState == GameState.HIGHSCORE; }
}
|
package interviewquestions;
/**
* Given a string 'S' and a character 't'. Print out the position of the rightmost
* occurrence of 't' (case matters) in 'S' or -1 if there is none.
*/
public class RightMostCharacter extends TestCase {
public static int rightmost(String string, Character ch) {
for (int idx = string.length() - 1; idx >= 0; --idx) {
if (string.charAt(idx) == ch) return idx;
}
return -1;
}
public static void main(String[] args) {
assertEquals(8, rightmost("Hello World", 'r'));
assertEquals(10, rightmost("Hello World", 'd'));
assertEquals(4, rightmost("Hello WOrld", 'o'));
assertEquals(7, rightmost("Hello WOrld", 'O'));
assertEquals(10, rightmost("aaaaaaaaaaa", 'a'));
assertEquals(-1, rightmost("", 'a'));
assertEquals(16, rightmost("How to learn to Cook", 'C'));
assertEquals(15, rightmost("What is your name", 'm'));
assertEquals(-1, rightmost("lKHFLOpCmu0bxE0AooKQ8gYcrvf7Go22pMVKjFCc7DU9qIpcd55 Px00SdUCV4fzSq", 'W'));
}
}
|
package jkind.api.xml;
import java.io.InputStream;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import jkind.JKindException;
import jkind.api.Backend;
import jkind.api.results.JKindResult;
import jkind.api.results.PropertyResult;
import jkind.interval.IntEndpoint;
import jkind.interval.Interval;
import jkind.interval.NumericEndpoint;
import jkind.interval.NumericInterval;
import jkind.interval.RealEndpoint;
import jkind.lustre.values.IntegerValue;
import jkind.lustre.values.RealValue;
import jkind.lustre.values.Value;
import jkind.results.Counterexample;
import jkind.results.InvalidProperty;
import jkind.results.Property;
import jkind.results.Signal;
import jkind.results.UnknownProperty;
import jkind.results.ValidProperty;
import jkind.util.Util;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
public class XmlParseThread extends Thread {
private final InputStream xmlStream;
private final JKindResult result;
private final Backend backend;
private final DocumentBuilderFactory factory;
private volatile Throwable throwable;
private Map<String, List<PropertyResult>> analysisToProps = new HashMap<>();
public XmlParseThread(InputStream xmlStream, JKindResult result, Backend backend) {
super("Xml Parse");
this.xmlStream = xmlStream;
this.result = result;
this.backend = backend;
this.factory = DocumentBuilderFactory.newInstance();
}
@Override
public void run() {
/*
* XML parsers buffer their input which conflicts with the way we are
* streaming data from the XML file as it is written. This results in
* data in the XML not being acted upon until more content is written to
* the XML file which causes the buffer to fill. Instead, we read the
* XML file ourselves and give relevant pieces of it to the parser as
* they are ready.
*
* The downside is we assume the <Property ...> and </Property> tags are
* on their own lines.
*/
try (LineInputStream lines = new LineInputStream(xmlStream)) {
StringBuilder buffer = null;
String line;
String analysis = null;
while ((line = lines.readLine()) != null) {
boolean beginProperty = line.contains("<Property ");
boolean endProperty = line.contains("</Property>");
boolean beginProgress = line.contains("<Progress ");
boolean endProgress = line.contains("</Progress>");
boolean beginAnalysis = line.contains("<AnalysisStart");
boolean endAnalysis = line.contains("<AnalysisStop");
if (beginProgress && endProgress) {
// Kind 2 progress format uses a single line
parseKind2ProgressXml(line, analysis);
} else if (beginProgress || beginProperty) {
buffer = new StringBuilder();
buffer.append(line);
} else if (endProperty) {
buffer.append(line);
parsePropetyXml(buffer.toString(), analysis);
buffer = null;
} else if (endProgress) {
buffer.append(line);
parseJKindProgressXml(buffer.toString());
buffer = null;
} else if (beginAnalysis) {
analysis = parseKind2AnalysisXml(line);
} else if (endAnalysis) {
analysis = null;
} else if (buffer != null) {
buffer.append(line);
}
}
} catch (Throwable t) {
throwable = t;
}
}
private String parseKind2AnalysisXml(String line) {
Element progressElement = parseXml(line);
String analysis = progressElement.getAttribute("top");
analysisToProps.putIfAbsent(analysis, new ArrayList<>());
return analysis;
}
private Element parseXml(String xml) {
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(xml)));
return doc.getDocumentElement();
} catch (Exception e) {
throw new JKindException("Error parsing: " + xml, e);
}
}
private void parseKind2ProgressXml(String progressXml, String analysis) {
Element progressElement = parseXml(progressXml);
String source = progressElement.getAttribute("source");
if ("bmc".equals(source)) {
int k = Integer.parseInt(progressElement.getTextContent());
for (PropertyResult pr : analysisToProps.get(analysis)) {
pr.setBaseProgress(k);
}
}
}
private void parseJKindProgressXml(String progressXml) {
Element progressElement = parseXml(progressXml);
String source = progressElement.getAttribute("source");
if ("bmc".equals(source)) {
int trueFor = Integer.parseInt(progressElement.getAttribute("trueFor"));
for (Element propertyElement : getElements(progressElement, "PropertyProgress")) {
String prop = propertyElement.getAttribute("name");
PropertyResult pr = result.getPropertyResult(prop);
if (pr != null) {
pr.setBaseProgress(trueFor);
}
}
}
}
public void parsePropetyXml(String propertyXml, String analysis) {
Property prop = getProperty(parseXml(propertyXml));
String propName = prop.getName();
PropertyResult pr = getOrAddProperty(analysis, propName);
if (pr != null) {
pr.setProperty(prop);
if (analysis != null) {
analysisToProps.get(analysis).add(pr);
}
}
}
private PropertyResult getOrAddProperty(String analysis, String propName) {
PropertyResult pr = result.getPropertyResult(propName);
if (pr == null && analysis != null) {
propName = analysis + propName;
pr = result.getPropertyResult(propName);
}
if (pr == null) {
pr = result.addProperty(propName);
}
return pr;
}
private Property getProperty(Element propertyElement) {
String name = propertyElement.getAttribute("name");
double runtime = getRuntime(getElement(propertyElement, "Runtime"));
int trueFor = getTrueFor(getElement(propertyElement, "TrueFor"));
int k = getK(getElement(propertyElement, "K"));
String answer = getAnswer(getElement(propertyElement, "Answer"));
String source = getSource(getElement(propertyElement, "Answer"));
List<String> invariants = getInvariants(getElements(propertyElement, "Invariant"));
List<String> conflicts = getConflicts(getElement(propertyElement, "Conflicts"));
Counterexample cex = getCounterexample(getElement(propertyElement, "Counterexample"), k);
switch (answer) {
case "valid":
return new ValidProperty(name, source, k, runtime, invariants);
case "falsifiable":
return new InvalidProperty(name, source, cex, conflicts, runtime);
case "unknown":
return new UnknownProperty(name, trueFor, cex, runtime);
default:
throw new JKindException("Unknown property answer in XML file: " + answer);
}
}
private double getRuntime(Node runtimeNode) {
if (runtimeNode == null) {
return 0;
}
return Double.parseDouble(runtimeNode.getTextContent());
}
private int getTrueFor(Node trueForNode) {
if (trueForNode == null) {
return 0;
}
return Integer.parseInt(trueForNode.getTextContent());
}
private int getK(Node kNode) {
if (kNode == null) {
return 0;
}
return Integer.parseInt(kNode.getTextContent());
}
private String getAnswer(Node answerNode) {
return answerNode.getTextContent();
}
private String getSource(Element answerNode) {
return answerNode.getAttribute("source");
}
private List<String> getInvariants(List<Element> invariantElements) {
List<String> invariants = new ArrayList<>();
for (Element invariantElement : invariantElements) {
invariants.add(invariantElement.getTextContent());
}
return invariants;
}
private List<String> getConflicts(Element conflictsElement) {
if (conflictsElement == null) {
return Collections.emptyList();
}
List<String> conflicts = new ArrayList<>();
for (Element conflictElement : getElements(conflictsElement, "Conflict")) {
conflicts.add(conflictElement.getTextContent());
}
return conflicts;
}
private Counterexample getCounterexample(Element cexElement, int k) {
if (cexElement == null) {
return null;
}
Counterexample cex = new Counterexample(k);
for (Element signalElement : getElements(cexElement, getSignalTag())) {
cex.addSignal(getSignal(signalElement));
}
return cex;
}
protected String getSignalTag() {
switch (backend) {
case JKIND:
return "Signal";
case KIND2:
return "Stream";
default:
throw new IllegalArgumentException();
}
}
private Signal<Value> getSignal(Element signalElement) {
String name = signalElement.getAttribute("name");
String type = signalElement.getAttribute("type");
if (type.contains("subrange ")) {
type = "int";
}
Signal<Value> signal = new Signal<>(name);
for (Element valueElement : getElements(signalElement, "Value")) {
int time = Integer.parseInt(valueElement.getAttribute(getTimeAttribute()));
signal.putValue(time, getValue(valueElement, type));
}
return signal;
}
protected String getTimeAttribute() {
switch (backend) {
case JKIND:
return "time";
case KIND2:
return "instant";
default:
throw new IllegalArgumentException();
}
}
private Value getValue(Element valueElement, String type) {
Element intervalElement = getElement(valueElement, "Interval");
if (intervalElement != null) {
return getIntervalValue(intervalElement, type);
}
return Util.parseValue(type, valueElement.getTextContent());
}
private Interval getIntervalValue(Element intervalElement, String type) {
String low = intervalElement.getAttribute("low");
String high = intervalElement.getAttribute("high");
NumericEndpoint lowEnd;
NumericEndpoint highEnd;
switch (type) {
case "int":
lowEnd = readIntEndpoint(low);
highEnd = readIntEndpoint(high);
break;
case "real":
lowEnd = readRealEndpoint(low);
highEnd = readRealEndpoint(high);
break;
default:
throw new JKindException("Unknown interval type in XML file: " + type);
}
return new NumericInterval(lowEnd, highEnd);
}
private IntEndpoint readIntEndpoint(String text) {
switch (text) {
case "inf":
return IntEndpoint.POSITIVE_INFINITY;
case "-inf":
return IntEndpoint.NEGATIVE_INFINITY;
default:
IntegerValue iv = (IntegerValue) Util.parseValue("int", text);
return new IntEndpoint(iv.value);
}
}
private RealEndpoint readRealEndpoint(String text) {
switch (text) {
case "inf":
return RealEndpoint.POSITIVE_INFINITY;
case "-inf":
return RealEndpoint.NEGATIVE_INFINITY;
default:
RealValue rv = (RealValue) Util.parseValue("real", text);
return new RealEndpoint(rv.value);
}
}
private Element getElement(Element element, String name) {
return (Element) element.getElementsByTagName(name).item(0);
}
private List<Element> getElements(Element element, String name) {
List<Element> elements = new ArrayList<>();
NodeList nodeList = element.getElementsByTagName(name);
for (int i = 0; i < nodeList.getLength(); i++) {
elements.add((Element) nodeList.item(i));
}
return elements;
}
public Throwable getThrowable() {
return throwable;
}
}
|
package au.com.agic.apptesting.utils.impl;
import au.com.agic.apptesting.constants.Constants;
import au.com.agic.apptesting.profiles.FileProfileAccess;
import au.com.agic.apptesting.profiles.configuration.*;
import au.com.agic.apptesting.profiles.dataset.DataSet;
import au.com.agic.apptesting.profiles.dataset.DatasetsRootElement;
import au.com.agic.apptesting.profiles.dataset.Setting;
import au.com.agic.apptesting.utils.ApplicationUrlLoader;
import au.com.agic.apptesting.utils.SystemPropertyUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.validation.constraints.NotNull;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.*;
import java.util.regex.Matcher;
import java.util.stream.Collectors;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
/**
* Loads the application urls from configuration
*/
public class ApplicationUrlLoaderImpl implements ApplicationUrlLoader {
private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationUrlLoaderImpl.class);
private static final SystemPropertyUtils SYSTEM_PROPERTY_UTILS = new SystemPropertyUtilsImpl();
private FileProfileAccess<Configuration> profileAccess = new FileProfileAccess<>(
SYSTEM_PROPERTY_UTILS.getProperty(Constants.CONFIGURATION),
Configuration.class);
private FileProfileAccess<DatasetsRootElement> datasetAccess = new FileProfileAccess<>(
SYSTEM_PROPERTY_UTILS.getProperty(Constants.DATA_SETS_PROFILE_SYSTEM_PROPERTY),
DatasetsRootElement.class);
public void initialise() {
profileAccess = new FileProfileAccess<>(
SYSTEM_PROPERTY_UTILS.getProperty(Constants.CONFIGURATION),
Configuration.class);
datasetAccess = new FileProfileAccess<>(
SYSTEM_PROPERTY_UTILS.getProperty(Constants.DATA_SETS_PROFILE_SYSTEM_PROPERTY),
DatasetsRootElement.class);
}
private String getAppUrl() {
final String appUrl = SYSTEM_PROPERTY_UTILS.getProperty(Constants.APP_URL_OVERRIDE_SYSTEM_PROPERTY);
if (StringUtils.isNotBlank(appUrl)) {
return appUrl;
}
return null;
}
@Override
public List<UrlMapping> getAppUrls(final String featureGroup) {
checkState(profileAccess != null, "initialise() must be called");
checkState(datasetAccess != null, "initialise() must be called");
/*
Deal with the override. This system property takes precedence over
all other options.
*/
final String appUrlOverride = getAppUrl();
if (StringUtils.isNotBlank(appUrlOverride)) {
LOGGER.info("Getting URL from global system property");
return Arrays.asList(new UrlMapping(appUrlOverride));
}
/*
We can also define a collection of URLs as system properties.
*/
final List<String> normalisedKeys = SYSTEM_PROPERTY_UTILS.getNormalisedProperties();
final List<Url> systemPropValues = normalisedKeys.stream()
.map(Constants.APP_URL_OVERRIDE_SYSTEM_PROPERTY_REGEX::matcher)
.filter(Matcher::matches)
.map(x -> new Url(SYSTEM_PROPERTY_UTILS.getProperty(x.group(0)), x.group(1)))
.collect(Collectors.toList());
if (!systemPropValues.isEmpty()) {
LOGGER.info("Getting URL from specific system property");
return Arrays.asList(new UrlMapping(systemPropValues));
}
/*
The final option is to get the mappins from the xml file
*/
final Optional<Configuration> configuration = profileAccess.getProfile();
if (configuration.isPresent()) {
LOGGER.info("Getting URL config file");
final List<UrlMapping> retValue = getUrlMappings(configuration.get(), featureGroup);
return getLimitedAppUrls(retValue);
}
/*
There are no mappings to return
*/
return new ArrayList<>();
}
private List<UrlMapping> getLimitedAppUrls(@NotNull final List<UrlMapping> completeList) {
checkNotNull(completeList);
final String limitedUrls = SYSTEM_PROPERTY_UTILS.getProperty(Constants.NUMBER_URLS_SYSTEM_PROPERTY);
if (StringUtils.isNoneBlank(limitedUrls)) {
try {
Collections.shuffle(completeList, SecureRandom.getInstance("SHA1PRNG"));
final Integer limit = Integer.parseInt(limitedUrls);
final List<UrlMapping> subList = new ArrayList<>();
for (int i = 0; i < Math.min(limit, completeList.size()); ++i) {
subList.add(completeList.get(i));
}
return subList;
} catch (final NumberFormatException | NoSuchAlgorithmException ignored) {
/*
Invalid input that we ignore
*/
}
}
return completeList;
}
@Override
public Map<Integer, Map<String, String>> getDatasets() {
checkState(profileAccess != null, "initialise() must be called");
checkState(datasetAccess != null, "initialise() must be called");
final Optional<DatasetsRootElement> dataset = datasetAccess.getProfile();
/*
It is possible that a profile does not exist with data sets for this featureGroup
*/
if (!dataset.isPresent()) {
return new HashMap<>();
}
return getDatasets(dataset.get());
}
private Map<Integer, Map<String, String>> getDatasets(@NotNull final DatasetsRootElement profile) {
checkNotNull(profile);
final Map<String, String> commonDataSet = getCommonDataset(profile);
final Map<Integer, Map<String, String>> dataSets = new HashMap<>();
int index = 0;
for (final DataSet dataSet : profile.getDataSets().getDataSets()) {
if (!dataSets.containsKey(index)) {
final Map<String, String> newMap = new HashMap<>(commonDataSet);
dataSets.put(index, newMap);
}
for (final Setting setting : dataSet.getSettings()) {
dataSets.get(index).put(setting.getName(), setting.getValue());
}
++index;
}
return dataSets;
}
private List<UrlMapping> getUrlMappings(@NotNull final Configuration configuration, final String app) {
checkNotNull(configuration);
return Optional.ofNullable(configuration)
.map(Configuration::getUrlMappings)
.map(URLMappings::getFeatureGroups)
.map(featureGroups ->
featureGroups.stream().filter(e -> StringUtils.endsWithIgnoreCase(app, e.getName()))
.findFirst()
.map(FeatureGroup::getUrlMappings)
.orElse(new ArrayList<>())
)
.get();
}
/**
* @param profile The combined profile
* @return The common data set values to be applied to all other datasets
*/
private Map<String, String> getCommonDataset(@NotNull final DatasetsRootElement profile) {
checkNotNull(profile);
final Map<String, String> commonDataSet = new HashMap<>();
profile.getDataSets().getCommonDataSet().getSettings().stream()
/*
Ensure we add the data set to a sequential index
*/
.forEach(e -> commonDataSet.put(e.getName(), e.getValue()));
return commonDataSet;
}
}
|
package bio.terra.workspace.service.workspace;
import bio.terra.workspace.service.iam.model.IamRole;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import java.util.List;
public class CloudSyncRoleMapping {
public static final ImmutableMap<IamRole, List<String>> cloudSyncRoleMap =
ImmutableMap.of(
IamRole.OWNER,
ImmutableList.of(
"roles/viewer",
"roles/bigquery.dataEditor",
// resources for service accounts.
"roles/iam.serviceAccountUser",
"roles/lifesciences.editor",
// resources for notebooks.
"roles/notebooks.admin",
// resources for buckets.
"roles/storage.admin"),
IamRole.WRITER,
ImmutableList.of(
"roles/viewer",
"roles/bigquery.dataEditor",
// resources for service accounts.
"roles/iam.serviceAccountUser",
"roles/lifesciences.editor",
// resources for notebooks.
"roles/notebooks.admin",
// resources for buckets.
"roles/storage.admin"),
IamRole.READER, ImmutableList.of("roles/viewer"));
}
|
// Implementation of a simple graph client for the ArangoDB.
package com.arangodb.tinkerpop.gremlin.client;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.arangodb.tinkerpop.gremlin.utils.ArangoDBUtil;
public class ArangoDBQueryBuilder {
/** The Logger. */
private static final Logger logger = LoggerFactory.getLogger(ArangoDBQueryBuilder.class);
/**
* The Enum QueryType.
*/
public enum QueryType {
/** The graph vertices. */
GRAPH_VERTICES,
/** The graph edges. */
GRAPH_EDGES,
/** The graph neighbors. */
GRAPH_NEIGHBORS
}
/** The query builder. */
private StringBuilder queryBuilder;
/** The iterate counter. */
private int iterateCnt = 1;
/** The filtered flag. */
private boolean filtered = false;
/** Whether the builder should prefix collection names with grpah name. */
private Boolean shouldPrefixWithGraphName;
/**
* Direction to navigate for vertex paths.
*/
public enum Direction {
/** direction into a element. */
IN("INBOUND"),
/** direction out of a element. */
OUT("OUTBOUND"),
/** direction out and in of a element. */
ALL("ANY");
/** The aql name. */
private final String aqlName;
/**
* Instantiates a new direction.
*
* @param aqlName the aql name
*/
Direction(String aqlName) {
this.aqlName = aqlName;
}
/**
* Gets the aql name.
*
* @return the aql name
*/
String getAqlName() {
return aqlName;
}
};
/**
* Options for vertices in Graph Traversals.
*
* @author Horacio Hoyos Rodriguez (@horaciohoyosr)
*/
enum UniqueVertices {
/** It is guaranteed that there is no path returned with a duplicate vertex. */
PATH("path"),
/** it is guaranteed that each vertex is visited at most once during the traversal, no
* matter how many paths lead from the start vertex to this one. */
GLOBAL("global"),
/** No uniqueness check is applied on vertices - (default). */
NONE("none");
/** The aql name. */
private final String aqlName;
/**
* Instantiates a new unique vertices.
*
* @param aqlName the aql name
*/
UniqueVertices(String aqlName) {
this.aqlName = aqlName;
}
/**
* Gets the aql name.
*
* @return the aql name
*/
String getAqlName() {
return aqlName;
}
}
/**
* Options for edges in Graph Traversals.
*
* @author Horacio Hoyos Rodriguez (@horaciohoyosr)
*/
enum UniqueEdges {
/** It is guaranteed that there is no path returned with a duplicate edge - (default). */
PATH("path"),
/** No uniqueness check is applied on edges. <b>Note</b>: Using this configuration the
* traversal will follow cycles in edges. */
NONE("none");
/** The aql name. */
private final String aqlName;
/**
* Instantiates a new unique edges.
*
* @param aqlName the aql name
*/
UniqueEdges(String aqlName) {
this.aqlName = aqlName;
}
/**
* Gets the aql name.
*
* @return the aql name
*/
String getAqlName() {
return aqlName;
}
}
/**
* Create a new QueryBuilder with config of whether Collection Names should be prefixed with Graph name or not.
*/
public ArangoDBQueryBuilder( boolean shouldPrefixCollectionWithGraphName) {
this.shouldPrefixWithGraphName = shouldPrefixCollectionWithGraphName;
this.queryBuilder = new StringBuilder();
}
/**
* Append a WITH statement to the query builder for the given collections. The required bindVars are
* added to the bindVars map.
* @param graphName the graph name
* @param collections the list of Collections to use in the statement
* @param bindVars the map of bind parameters
*
* @return a reference to this object.
*/
public ArangoDBQueryBuilder with(
String graphName,
List<String> collections, Map<String, Object> bindVars) {
queryBuilder.append("WITH ");
String separator = "";
int colId = 1;
for (String c : collections) {
queryBuilder.append(separator);
separator = ",";
String varName = String.format("@with%s", colId);
queryBuilder.append("@").append(varName);
bindVars.put(varName, ArangoDBUtil.getCollectioName(graphName, c, this.shouldPrefixWithGraphName));
}
queryBuilder.append("\n");
logger.debug("with", queryBuilder.toString());
return this;
}
/**
* Append a Document and FILTER statements to the query builder. Use this to find a single or
* group of elements in the graph. This segment should be used in conjunction with the
* {@link #with(String, List, Map)} segment.
*
* @param ids the id(s) to look for
* @param loopVariable the loop variable name
* @param bindVars the map of bind parameters
* @return a reference to this object.
*/
public ArangoDBQueryBuilder documentsById(
List<String> ids,
String loopVariable,
Map<String, Object> bindVars) {
queryBuilder.append("LET docs = FLATTEN(RETURN Document(@ids))\n");
queryBuilder.append(String.format("FOR %s IN docs\n", loopVariable));
queryBuilder.append(String.format(" FILTER NOT IS_NULL(%s)\n", loopVariable)); // Not needed?
bindVars.put("ids", ids);
logger.debug("documentsById", queryBuilder.toString());
return this;
}
/**
* Append a Document statement to find a single element in the graph. This segment should be
* used in conjunction with the {@link #with(String, List, Map)} segment.
*
* @param id the id to look for
* @param loopVariable the loop variable name
* @param bindVars the the map of bind parameters
* @return a reference to this object.
*/
public ArangoDBQueryBuilder documentById(
String id,
String loopVariable,
Map<String, Object> bindVars) {
queryBuilder.append(String.format("LET %s = Document(@id)\n", loopVariable));
bindVars.put("id", id);
logger.debug("documentById", queryBuilder.toString());
return this;
}
/**
* Append an union segment.
* @param graphName the graph name
* @param collections the collections that participate in the union
* @param loopVariable the loop variable
* @param bindVars the map of bind parameters
*
* @return a reference to this object.
*/
public ArangoDBQueryBuilder union(
String graphName,
List<String> collections,
String loopVariable,
Map<String, Object> bindVars) {
int count = 1;
String separator = "";
queryBuilder.append(String.format("FOR %s in UNION( \n", loopVariable));
queryBuilder.append(" (");
for (String c : collections) {
queryBuilder.append(separator);
separator = "),\n (";
queryBuilder.append(String.format("FOR x%1$s IN @@col%1$s RETURN x%1$s", count));
bindVars.put(String.format("@col%s", count++), ArangoDBUtil.getCollectioName(graphName, c, shouldPrefixWithGraphName));
}
queryBuilder.append(" )\n");
queryBuilder.append(")\n");
logger.debug("union", queryBuilder.toString());
return this;
}
/**
* Add a FOR x IN y iteration to the query. A global collection counter is used so this operation
* can be used to created nested loops.
* @param graphName the graph name
* @param loopVariable the loop variable
* @param collectionName the collection name
* @param bindVars the map of bind parameters
*
* @return a reference to this object.
*/
public ArangoDBQueryBuilder iterateCollection(
String graphName,
String loopVariable,
String collectionName, Map<String, Object> bindVars) {
queryBuilder.append(String.format("FOR %1$s IN @@col%2$s", loopVariable, iterateCnt)).append("\n");
bindVars.put(String.format("@col%s", iterateCnt++), ArangoDBUtil.getCollectioName(graphName, collectionName, shouldPrefixWithGraphName));
logger.debug("iterateCollection", queryBuilder.toString());
return this;
}
/**
* Add a graph iteration segment.
* @param graphName the graph name
* @param vertexVariable the vertex variable
* @param edgeVariable the edge variable
* @param pathVariable the path variable
* @param min edges and vertices returned by this query will start at the traversal depth of min
* @param max up to max length paths are traversed
* @param direction follow edges pointing in the direction
* @param startVertex the start vertex id
* @param bindVars the map of bind parameters
*
* @return a reference to this object.
*/
public ArangoDBQueryBuilder iterateGraph(
String graphName,
String vertexVariable,
Optional<String> edgeVariable,
Optional<String> pathVariable,
Optional<Integer> min,
Optional<Integer> max,
Direction direction,
String startVertex,
Map<String, Object> bindVars) {
queryBuilder.append(String.format("FOR %s", vertexVariable));
if (edgeVariable.isPresent()) {
queryBuilder.append(String.format(", %s", edgeVariable.get()));
}
if (pathVariable.isPresent()) {
queryBuilder.append(String.format(", %s", pathVariable.get()));
}
queryBuilder.append("\n IN ");
if (min.isPresent()) {
queryBuilder.append(min.get());
if (max.isPresent()) {
queryBuilder.append(String.format("..%s", max.get()));
}
queryBuilder.append(" ");
}
queryBuilder.append(direction.getAqlName()).append(" @startVertex\n")
.append(" GRAPH '").append(graphName).append("'\n"); // FIXME Graph could be a parameter
bindVars.put("startVertex", startVertex);
logger.debug("iterateGraph", queryBuilder.toString());
return this;
}
/**
* Iterate over a collection of edges.
* @param graphName the graph name
* @param vertexVariable the vertex variable
* @param edgeVariable the edge variable
* @param pathVariable the path variable
* @param min edges and vertices returned by this query will start at the traversal depth of min
* @param max up to max length paths are traversed
* @param direction follow edges pointing in the direction
* @param edgeCollections the edge collections
* @param startVertex the start vertex id
* @param bindVars the map of bind parameters
*
* @return a reference to this object.
*/
public ArangoDBQueryBuilder iterateEdges(
String graphName,
String vertexVariable,
Optional<String> edgeVariable,
Optional<String> pathVariable,
Optional<Integer> min,
Optional<Integer> max,
Direction direction,
List<String> edgeCollections,
String startVertex, Map<String, Object> bindVars) {
queryBuilder.append(String.format("FOR %s", vertexVariable));
if (edgeVariable.isPresent()) {
queryBuilder.append(String.format(", %s", edgeVariable.get()));
}
if (pathVariable.isPresent()) {
queryBuilder.append(String.format(", %s", pathVariable.get()));
}
queryBuilder.append("\n IN ");
if (min.isPresent()) {
queryBuilder.append(min.get());
}
if (max.isPresent()) {
queryBuilder.append(String.format("..%s", max.get()));
}
queryBuilder.append(direction.getAqlName()).append(" @startVertex\n");
String separator = "";
for (String c : edgeCollections) {
queryBuilder.append(separator);
separator = ", ";
queryBuilder.append(String.format("@@col%s", iterateCnt));
bindVars.put(String.format("@col%s", iterateCnt++), ArangoDBUtil.getCollectioName(graphName, c, shouldPrefixWithGraphName));
}
bindVars.put("@startVertex", startVertex);
logger.debug("iterateGraph", queryBuilder.toString());
return this;
}
/**
* Add a Graph options segment.
*
* @see UniqueVertices
* @see UniqueEdges
* @param onVertices the vertices options
* @param onEdges the edges options
* @param bfs if true, the traversal will be executed breadth-first, else it will
* be executed depth-first.
* @return a reference to this object.
*/
public ArangoDBQueryBuilder graphOptions(
Optional<UniqueVertices> onVertices,
Optional<UniqueEdges> onEdges,
boolean bfs) {
if (onVertices.isPresent() || onEdges.isPresent() || bfs) {
queryBuilder.append(" OPTIONS {");
if (onVertices.isPresent()) {
queryBuilder.append(String.format("uniqueVertices: '%s', ", onVertices.get().getAqlName()));
}
if (onEdges.isPresent()) {
queryBuilder.append(String.format("uniqueEdges: '%s', ", onEdges.get().getAqlName()));
}
if (bfs) {
queryBuilder.append("bfs: true");
}
queryBuilder.append("}\n");
}
logger.debug("graphOptions", queryBuilder.toString());
return this;
}
/**
* Add a filter same collections segment, i.e. element represented by variable must be in any
* of the provided collections.
* @param graphName the graph name
* @param filterVariable the filter variable
* @param collections the collections to filter by
* @param bindVars the map of bind parameters
*
* @return a reference to this object.
*/
public ArangoDBQueryBuilder filterSameCollections(
String graphName,
String filterVariable,
List<String> collections, Map<String, Object> bindVars) {
if (!collections.isEmpty()) {
queryBuilder.append(" FILTER (IS_SAME_COLLECTION(");
String separator = "";
for (String c : collections) {
queryBuilder.append(separator);
separator = String.format(", %s) OR IS_SAME_COLLECTION(", filterVariable);
queryBuilder.append(String.format("@@col%s", iterateCnt));
bindVars.put(String.format("@col%s", iterateCnt++), ArangoDBUtil.getCollectioName(graphName, c, shouldPrefixWithGraphName));
}
queryBuilder.append(String.format(", %s))\n", filterVariable));
}
filtered = true;
logger.debug("filterSameCollections", queryBuilder.toString());
return this;
}
/**
* Add a filter on element properties segment. The filter operations are defined using a
* #link {@link ArangoDBPropertyFilter}.
*
* @param propertyFilter the property filter
* @param filterVariable the filter variable
* @param bindVars the map of bind parameters
* @return a reference to this object.
*/
public ArangoDBQueryBuilder filterProperties(
ArangoDBPropertyFilter propertyFilter,
String filterVariable,
Map<String, Object> bindVars) {
List<String> filterSegments = new ArrayList<String>();
propertyFilter.addAqlSegments(String.format("%s.", filterVariable), filterSegments, bindVars);
if (CollectionUtils.isNotEmpty(filterSegments)) {
if (filtered) {
queryBuilder.append(" AND ");
} else {
queryBuilder.append(" FILTER ");
}
queryBuilder.append(StringUtils.join(filterSegments, " AND ")).append("\n");
}
logger.debug("filterProperties", queryBuilder.toString());
return this;
}
/**
* Add a limit segment to limit the number of elements returned.
*
* @param limit the limit number
* @return a reference to this object.
*/
public ArangoDBQueryBuilder limit(Long limit) {
queryBuilder.append(" LIMIT " + limit.toString());
logger.debug("limit", queryBuilder.toString());
return this;
}
/**
* Add a RETURN Segment.
* TODO provide finer grained return statements
*
* @param returnStatement the return statement
* @return a reference to this object.
*/
public ArangoDBQueryBuilder ret(String returnStatement) {
queryBuilder.append("RETURN ").append(returnStatement).append("\n");
logger.debug("ret", queryBuilder.toString());
return this;
}
/**
* Appends the specified string to this character sequence.
* <p>
* The characters of the String argument are appended, in order, increasing the length of this
* sequence by the length of the argument. If str is null, then the four characters "null" are
* appended.
* <p>
* Let n be the length of this character sequence just prior to execution of the append method.
* Then the character at index k in the new character sequence is equal to the character at
* index k in the old character sequence, if k is less than n; otherwise, it is equal to the
* character at index k-n in the argument str.
* @param segment a str
* @return a reference to this object.
*/
public ArangoDBQueryBuilder append(String segment) {
queryBuilder.append(segment);
return this;
}
@Override
public String toString() {
return queryBuilder.toString();
}
}
|
package com.epam.reportportal.auth.integration;
import com.epam.reportportal.auth.store.entity.AbstractAuthConfig;
import com.epam.reportportal.auth.store.entity.AuthConfigEntity;
import java.util.Arrays;
import java.util.Optional;
import static java.util.Optional.ofNullable;
/**
* @author Andrei Varabyeu
*/
public enum AuthIntegrationType {
ACTIVE_DIRECTORY("ad", "activeDirectory") {
@Override
public Optional<AbstractAuthConfig> get(AuthConfigEntity entity) {
return ofNullable(entity).map(AuthConfigEntity::getActiveDirectory);
}
},
LDAP("ldap", "ldap") {
@Override
public Optional<AbstractAuthConfig> get(AuthConfigEntity entity) {
return ofNullable(entity).map(AuthConfigEntity::getLdap);
}
};
private String id;
private String dbField;
AuthIntegrationType(String id, String dbField) {
this.id = id;
this.dbField = dbField;
}
public abstract Optional<AbstractAuthConfig> get(AuthConfigEntity entity);
public String getId() {
return id;
}
public String getDbField() {
return dbField;
}
public static Optional<AuthIntegrationType> fromId(String id) {
return Arrays.stream(values()).filter(it -> it.id.equalsIgnoreCase(id)).findAny();
}
@Override
public String toString() {
return this.id;
}
}
|
package com.example.integration;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.example.scheduling.quartz.PollingEndpointQuartzBridgeJob;
import org.quartz.JobBuilder;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.ScheduleBuilder;
import org.quartz.Scheduler;
import org.quartz.TriggerBuilder;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.util.Assert;
public class PollingEndpointQuartzBridgeTrigger implements BeanNameAware, InitializingBean, Trigger {
private static final Pattern TRIGGER_BEAN_NAME_PATTERN = Pattern.compile("(\\S+)Trigger");
private Scheduler scheduler;
private ScheduleBuilder scheduleBuilder;
private String pollingEndpointBeanName;
private String triggerBeanName;
private boolean done;
public PollingEndpointQuartzBridgeTrigger(Scheduler scheduler, ScheduleBuilder scheduleBuilder) {
Assert.notNull(scheduler, "scheduler is required");
Assert.notNull(scheduleBuilder, "scheduleBuilder is required");
this.scheduler = scheduler;
this.scheduleBuilder = scheduleBuilder;
}
@Override
public void setBeanName(String name) {
Matcher triggerBeanNameMatcher = TRIGGER_BEAN_NAME_PATTERN.matcher(name);
if (!triggerBeanNameMatcher.matches()) {
throw new IllegalArgumentException(getClass().getName() + " instance name must match " + TRIGGER_BEAN_NAME_PATTERN.pattern());
}
this.pollingEndpointBeanName = triggerBeanNameMatcher.group(1);
this.triggerBeanName = name;
}
@Override
public void afterPropertiesSet() throws Exception {
JobKey jobKey = new JobKey(pollingEndpointBeanName);
if (!scheduler.checkExists(jobKey)) {
JobDetail jobDetail = JobBuilder.newJob(PollingEndpointQuartzBridgeJob.class)
.withIdentity(jobKey)
.storeDurably()
.build();
JobDataMap jobDataMap = new JobDataMap();
jobDataMap.put(PollingEndpointQuartzBridgeJob.POLLING_ENDPOINT_BEAN_NAME_KEY, pollingEndpointBeanName);
jobDataMap.put(PollingEndpointQuartzBridgeJob.TRIGGER_BEAN_NAME_KEY, triggerBeanName);
org.quartz.Trigger trigger = TriggerBuilder.newTrigger()
.withIdentity(pollingEndpointBeanName)
.withSchedule(scheduleBuilder)
.forJob(jobDetail)
.usingJobData(jobDataMap)
.build();
scheduler.scheduleJob(jobDetail, trigger);
}
}
@Override
public Date nextExecutionTime(TriggerContext triggerContext) {
if (done) {
return null;
}
done = true;
return new Date();
}
public void reset() {
done = false;
}
}
|
package com.fillumina.performance.sequence;
import com.fillumina.performance.PerformanceProducer;
import com.fillumina.performance.PerformanceConsumer;
import com.fillumina.performance.timer.PerformanceTimer;
import java.util.concurrent.TimeUnit;
/**
*
* @author fra
*/
public class AutoProgressionSequence implements PerformanceProducer {
public static final int MINIMUM_ITERATIONS = 100;
public static final int MAXIMUM_MAGNITUDE = 10;
public static final int SAMPLE_PER_MAGNITUDE = 10;
private final ProgressionSequence progressionSerie;
private double maxStandardDeviation = 1.5D;
public AutoProgressionSequence(final PerformanceTimer pt) {
this.progressionSerie = new ProgressionSequence(pt) {
@Override
protected boolean stopIterating(SequencePerformances serie) {
return AutoProgressionSequence.this.stopIterating(serie);
}
};
}
public AutoProgressionSequence setPerformanceConsumerOnIteration(
final PerformanceConsumer consumer) {
progressionSerie.setOnIterationPerformanceConsumer(consumer);
return this;
}
/**
* The assigned consumer receives the average of the
* values of the last sequence of tests.
*/
@Override
public AutoProgressionSequence setPerformanceConsumer(
final PerformanceConsumer consumer) {
progressionSerie.setPerformanceConsumer(consumer);
return this;
}
public AutoProgressionSequence setTimeout(final int time, final TimeUnit unit) {
progressionSerie.setTimeout(time, unit);
return this;
}
public AutoProgressionSequence getSeriePerformance() {
progressionSerie.getSeriePerformance();
return this;
}
@Override
public <T extends PerformanceConsumer> T use(final T consumer) {
progressionSerie.use(consumer);
return consumer;
}
public AutoProgressionSequence setMaxStandardDeviation(
final double maxStandardDeviation) {
this.maxStandardDeviation = maxStandardDeviation;
return this;
}
public void autoSerie() {
progressionSerie
.serie(MINIMUM_ITERATIONS, MAXIMUM_MAGNITUDE, SAMPLE_PER_MAGNITUDE);
}
private boolean stopIterating(final SequencePerformances serie) {
return serie.getMaximumStandardDeviation() < maxStandardDeviation;
}
}
|
package com.forgeessentials.core.commands.selections;
//Depreciated
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayer;
import com.forgeessentials.api.permissions.RegGroup;
import com.forgeessentials.core.PlayerInfo;
import com.forgeessentials.core.commands.ForgeEssentialsCommandBase;
import com.forgeessentials.util.ChatUtils;
import com.forgeessentials.util.OutputHandler;
import com.forgeessentials.util.AreaSelector.Point;
public class CommandExpand extends ForgeEssentialsCommandBase
{
public CommandExpand()
{
return;
}
@Override
public String getCommandName()
{
return "/expand";
}
@Override
public void processCommandPlayer(EntityPlayer player, String[] args)
{
if (args.length == 1)
{
int x = Math.round((float) player.getLookVec().xCoord);
int y = Math.round((float) player.getLookVec().yCoord);
int z = Math.round((float) player.getLookVec().zCoord);
PlayerInfo info = PlayerInfo.getPlayerInfo(player.username);
int expandby = Integer.decode(args[0]);
// Check to see if selection is valid for expand.
if (info.getPoint1() == null || info.getPoint2() == null)
{
player.sendChatToPlayer("Invalid previous selection.");
return;
}
if (x == -1)
{
if (info.getPoint1().x < info.getPoint2().x)
{
info.setPoint1(new Point(info.getPoint1().x - expandby, info.getPoint1().y, info.getPoint1().z));
}
else
{
info.setPoint2(new Point(info.getPoint2().x - expandby, info.getPoint2().y, info.getPoint2().z));
}
}
else if (z == 1)
{
if (info.getPoint1().z < info.getPoint2().z)
{
info.setPoint1(new Point(info.getPoint1().x, info.getPoint1().y, info.getPoint1().z + expandby));
}
else
{
info.setPoint2(new Point(info.getPoint2().x, info.getPoint2().y, info.getPoint2().z + expandby));
}
}
else if (x == 1)
{
if (info.getPoint1().x < info.getPoint2().x)
{
info.setPoint1(new Point(info.getPoint1().x + expandby, info.getPoint1().y, info.getPoint1().z));
}
else
{
info.setPoint2(new Point(info.getPoint2().x + expandby, info.getPoint2().y, info.getPoint2().z));
}
}
else if (z == -1)
{
if (info.getPoint1().z < info.getPoint2().z)
{
info.setPoint1(new Point(info.getPoint1().x, info.getPoint1().y, info.getPoint1().z - expandby));
}
else
{
info.setPoint2(new Point(info.getPoint2().x, info.getPoint2().y, info.getPoint2().z - expandby));
}
}
else if (y == 1)
{
if (info.getPoint1().y > info.getPoint2().y)
{
info.setPoint1(new Point(info.getPoint1().x, info.getPoint1().y + expandby, info.getPoint1().z));
}
else
{
info.setPoint2(new Point(info.getPoint2().x, info.getPoint2().y + expandby, info.getPoint2().z));
}
}
else if (y == -1)
{
if (info.getPoint1().y < info.getPoint2().y)
{
info.setPoint1(new Point(info.getPoint1().x, info.getPoint1().y - expandby, info.getPoint1().z));
}
else
{
info.setPoint2(new Point(info.getPoint2().x, info.getPoint2().y - expandby, info.getPoint2().z));
}
}
ChatUtils.sendMessage(player, "Region expanded by: " + expandby);
return;
}
else if (args.length == 2)
{
PlayerInfo info = PlayerInfo.getPlayerInfo(player.username);
int expandby = 0;
try
{
expandby = Integer.decode(args[0]);
}
catch (Exception e)
{
try
{
expandby = Integer.decode(args[1]);
}
catch (Exception ex)
{
OutputHandler.chatError(player, "Neither " + args[0] + " or " + args[1] + " is a number.");
return;
}
}
if (args[0].equalsIgnoreCase("north") || args[1].equalsIgnoreCase("north"))
{
if (info.getPoint1().z < info.getPoint2().z)
{
info.setPoint1(new Point(info.getPoint1().x, info.getPoint1().y, info.getPoint1().z - expandby));
}
else
{
info.setPoint2(new Point(info.getPoint2().x, info.getPoint2().y, info.getPoint2().z - expandby));
}
}
else if (args[0].equalsIgnoreCase("east") || args[1].equalsIgnoreCase("east"))
{
if (info.getPoint1().x > info.getPoint2().x)
{
info.setPoint1(new Point(info.getPoint1().x + expandby, info.getPoint1().y, info.getPoint1().z));
}
else
{
info.setPoint2(new Point(info.getPoint2().x + expandby, info.getPoint2().y, info.getPoint2().z));
}
}
else if (args[0].equalsIgnoreCase("south") || args[1].equalsIgnoreCase("south"))
{
if (info.getPoint1().z > info.getPoint2().z)
{
info.setPoint1(new Point(info.getPoint1().x, info.getPoint1().y, info.getPoint1().z + expandby));
}
else
{
info.setPoint2(new Point(info.getPoint2().x, info.getPoint2().y, info.getPoint2().z + expandby));
}
}
else if (args[0].equalsIgnoreCase("west") || args[1].equalsIgnoreCase("west"))
{
if (info.getPoint1().x < info.getPoint2().x)
{
info.setPoint1(new Point(info.getPoint1().x - expandby, info.getPoint1().y, info.getPoint1().z));
}
else
{
info.setPoint2(new Point(info.getPoint2().x - expandby, info.getPoint2().y, info.getPoint2().z));
}
}
else if (args[0].equalsIgnoreCase("up") || args[1].equalsIgnoreCase("up"))
{
if (info.getPoint1().z > info.getPoint2().z)
{
info.setPoint1(new Point(info.getPoint1().x, info.getPoint1().y + expandby, info.getPoint1().z));
}
else
{
info.setPoint2(new Point(info.getPoint2().x, info.getPoint2().y + expandby, info.getPoint2().z));
}
}
else if (args[0].equalsIgnoreCase("down") || args[1].equalsIgnoreCase("down"))
{
if (info.getPoint1().y < info.getPoint2().y)
{
info.setPoint1(new Point(info.getPoint1().x, info.getPoint1().y - expandby, info.getPoint1().z));
}
else
{
info.setPoint2(new Point(info.getPoint2().x, info.getPoint2().y - expandby, info.getPoint2().z));
}
}
else
{
OutputHandler.chatError(player, "Invalid Direction");
}
ChatUtils.sendMessage(player, "Region expanded by: " + expandby);
return;
}
else
{
error(player);
}
}
@Override
public String getCommandPerm()
{
return "fe.core.pos.expand";
}
@Override
public boolean canConsoleUseCommand()
{
return false;
}
@Override
public int compareTo(Object o) {
// TODO Auto-generated method stub
return 0;
}
@Override
public String getCommandUsage(ICommandSender sender) {
// TODO Auto-generated method stub
return "//expand [direction] <number of blocks to expand> Expands the currently selected area.";
}
@Override
public RegGroup getReggroup() {
// TODO Auto-generated method stub
return RegGroup.MEMBERS;
}
}
|
package com.github.niwaniwa.we.core.command;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.bukkit.Sound;
import org.bukkit.command.Command;
import com.github.niwaniwa.we.core.api.WhiteEggAPI;
import com.github.niwaniwa.we.core.command.abs.ConsoleCancellable;
import com.github.niwaniwa.we.core.command.abs.core.WhiteEggCoreLowCommandExecutor;
import com.github.niwaniwa.we.core.player.WhitePlayer;
import com.github.niwaniwa.we.core.player.commad.WhiteCommandSender;
import com.github.niwaniwa.we.core.util.Util;
/**
* Whisper
* @author nwianiwa
*
*/
public class WhiteEggWhisperCommand extends WhiteEggCoreLowCommandExecutor implements ConsoleCancellable{
private static final Map<WhitePlayer, WhitePlayer> replay = new HashMap<>();
private final String key = commandMessageKey + ".whisper";
private final String permission = commandPermission + ".whisper";
@Override
public boolean onCommand(WhiteCommandSender sender, Command cmd, String label, String[] args) {
if(!sender.hasPermission(permission)){
sender.sendMessage(msg.getMessage(sender, error_Permission, "", true));
return true;
}
if(args.length <= 1){
sendUsing((WhitePlayer) sender);
return true;
}
WhitePlayer player = (WhitePlayer) sender;
WhitePlayer target = WhiteEggAPI.getPlayer(args[0]);
if(target == null){
sender.sendMessage(msg.getMessage(player, error_Player, msgPrefix, true));
return true;
}
if(player.getUniqueId().equals(target.getUniqueId())){
return true;
}
String message = Util.build(args, 1);
target.sendMessage(replace(msg.getMessage(target, key + ".format", "", true), player, target, message));
player.sendMessage(replace(msg.getMessage(player, key + ".format", "", true), player, target, message));
target.getPlayer().playSound(target.getPlayer().getLocation(), Sound.CHICKEN_EGG_POP, 1, 1);
replay.put(target, player);
return true;
}
private String replace(String s, WhitePlayer from, WhitePlayer to, String message){
return s.replace("%from%", from.getName()).replace("%to%", to.getName()).replace("%message%", message);
}
@Override
public void sendUsing(WhitePlayer sender) {
sender.sendMessage("&6! ω !");
}
@Override
public String getPermission() {
return permission;
}
public static Map<WhitePlayer, WhitePlayer> getPlayer(){
return replay;
}
@Override
public String getCommandName() {
return "whisper";
}
@Override
public List<String> getUsing() {
return Arrays.asList("");
}
}
|
package com.github.timm.cucumber.generate.name;
import com.github.timm.cucumber.ModuloCounter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Generate a Class Name based on a pattern.
*
* <p>
* No validation is performed to ensure that the generated class name is valid.
* </p>
*
* <p>
* The following placeholders are supported:
* </p>
* <ul>
* <li>'{f}' - The feature file, converted using supplied naming scheem.</li>
* <li>'{c}' - A one-up number, formatted to have minimum 2 character width
* , but optionally prefix-able by width required. Example {3c} resulting 001,002....</li>
* <li>'{c:n}' - A one-up number modulo n, with no minimum character width
* , but optionally prefix-able by width required. Example {2c:16} resulting 00,01,02,....,15</li>
* </ul>
*/
public class PatternNamingScheme implements ClassNamingScheme {
private static final Pattern COUNTER_PATTERN = Pattern.compile("\\{(\\d*)c}");
private static final Pattern MODULO_COUNTER_PATTERN = Pattern.compile("\\{(\\d*)c:(\\d+)}");
private final String pattern;
private final Counter counter;
private final Counter moduloCounter;
private final ClassNamingScheme featureFileNamingScheme;
/**
* Constructor.
* @param pattern The pattern to use.
* @param counter Counter to generate one up numbers
* @param featureFileNamingScheme Naming scheme to use for '{f}' placeholder
*/
public PatternNamingScheme(final String pattern, final Counter counter,
final ClassNamingScheme featureFileNamingScheme) {
this.pattern = pattern;
this.counter = counter;
this.moduloCounter = new ModuloCounter(pattern);
this.featureFileNamingScheme = featureFileNamingScheme;
}
/**
* Generate a class name using the required pattern and feature file.
* @param featureFileName The feature file to generate a class name for
* @return A class name based on the required pattern.
*/
public String generate(final String featureFileName) {
String className =
pattern.replace("{f}", featureFileNamingScheme.generate(featureFileName));
className = replaceAll( COUNTER_PATTERN, className, counter.next(), 2);
className = replaceAll( MODULO_COUNTER_PATTERN, className, moduloCounter.next(), 1);
return className;
}
private String replaceAll(Pattern compiledPattern,String pattern, int number, int defaultLen) {
Matcher matcher = compiledPattern.matcher(pattern);
boolean result = matcher.find();
if (result) {
StringBuffer sb = new StringBuffer();
do {
int len = matcher.start(1) == matcher.end(1) ? defaultLen : Integer.decode(matcher.group(1));
matcher.appendReplacement(sb, String.format("%0" + len + "d", number));
result = matcher.find();
}
while (result);
matcher.appendTail(sb);
return sb.toString();
}
return pattern;
}
}
|
package com.helion3.prism.events.listeners;
import com.helion3.prism.api.records.PrismRecord;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.Order;
import org.spongepowered.api.event.filter.cause.Root;
import org.spongepowered.api.event.item.inventory.ChangeInventoryEvent;
public class ChangeInventoryListener {
/**
* Saves event records when a player picks up an item.
*
* @param event Pickup event.
*/
@Listener(order = Order.POST)
public void onItemPickup(final ChangeInventoryEvent.Pickup event, @Root Player player) {
PrismRecord.create().player(player).pickedUp(event.getTargetEntity()).save();
}
}
|
package com.persado.oss.quality.stevia.selenium.core;
import com.persado.oss.quality.stevia.annotations.AnnotationsHelper;
import com.persado.oss.quality.stevia.selenium.core.controllers.WebDriverWebController;
import com.persado.oss.quality.stevia.testng.Verify;
import org.openqa.selenium.WebDriverException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
/**
* The Class SteviaContext.
*/
public class SteviaContext {
/**
* The Constant STEVIA_CONTEXT_LOG.
*/
private static final Logger LOG = LoggerFactory.getLogger(SteviaContext.class);
private static final AtomicInteger threadSeq = new AtomicInteger((int) (System.currentTimeMillis() % 0xcafe));
/**
* The inner Class Context.
*/
static class Context {
/**
* The controller.
*/
private WebController controller;
/**
* The verify.
*/
private Verify verify;
/**
* The is web driver.
*/
private boolean isWebDriver;
/**
* The params registry.
*/
private Map<String, String> paramsRegistry;
private int waitForPageToLoad = 120;
private int waitForAjaxComplete = 120000;
private int waitForElement = 10;
private int waitForWindow = 10;
private int waitForElementInvisibility = 1;
private ApplicationContext context;
private TestState state;
/**
* Clear context.
*/
public void clear() {
if (controller != null) {
try {
controller.quit();
} catch (WebDriverException wde) {
LOG.warn("Exception caught calling controller.quit(): \"" + wde.getMessage() + "\" additional info: " + wde.getAdditionalInformation());
}
}
controller = null;
verify = null;
isWebDriver = false;
if (paramsRegistry != null) {
paramsRegistry.clear();
}
context = null;
state = null;
Thread.currentThread().setName("Stevia - Inactive");
LOG.info("Context closed, controller shutdown");
AnnotationsHelper.disposeControllers();
System.runFinalization();
}
public int getWaitForPageToLoad() {
return waitForPageToLoad;
}
public void setWaitForPageToLoad(int waitForPageToLoad) {
this.waitForPageToLoad = waitForPageToLoad;
}
public int getWaitForElement() {
return waitForElement;
}
public void setWaitForElement(int waitForElement) {
this.waitForElement = waitForElement;
}
public int getWaitForAjaxComplete() {
return waitForAjaxComplete;
}
public void setWaitForAjaxComplete(int waitForAjaxComplete) {
this.waitForAjaxComplete = waitForAjaxComplete;
}
public int getWaitForElementInvisibility() {
return waitForElementInvisibility;
}
public void setWaitForElementInvisibility(int waitForElementInvisibility) {
this.waitForElementInvisibility = waitForElementInvisibility;
}
public int getWaitForWindow() {
return waitForWindow;
}
public void setWaitForWindow(int waitForWindow) {
this.waitForWindow = waitForWindow;
}
public ApplicationContext getContext() {
return context;
}
public void setContext(ApplicationContext context) {
this.context = context;
}
}
/**
* The inner context as a thread local variable.
*/
private static ThreadLocal<Context> innerContext = new ThreadLocal<SteviaContext.Context>() {
@Override
protected Context initialValue() {
return new Context(); //initial is empty;
}
};
/**
* Gets the web controller.
*
* @return the web controller
*/
public static WebController getWebController() {
return innerContext.get().controller;
}
/**
* Determines the instance of the Web Controller
*
* @return true, if it is instance of WebDriverWebController false if it is instance of SeleniumWebController
*/
public static boolean isWebDriver() {
return innerContext.get().isWebDriver;
}
/**
* Adds parameters to registry; if a parameter exists already it will be overwritten.
*
* @param params a type of SteviaContextParameters
*/
public static void registerParameters(SteviaContextParameters params) {
Map<String, String> paramsRegistry = innerContext.get().paramsRegistry;
if (paramsRegistry == null) {
innerContext.get().paramsRegistry = new HashMap<String, String>();
}
innerContext.get().paramsRegistry.putAll(params.getAllParameters());
LOG.warn("Thread {} just registered {}", new Object[]{Thread.currentThread().getName(), params.getAllParameters()});
}
/**
* get a parameter from the registry.
*
* @param paramName the param name
* @return the parameter value
*/
public static String getParam(String paramName) {
return innerContext.get().paramsRegistry.get(paramName);
}
/**
* Gets the params.
*
* @return a Map of the registered parameters
*/
public static Map<String, String> getParams() {
return innerContext.get().paramsRegistry;
}
/**
* get the test state that is relevant to the running thread for this test script
*
* @return <T extends TestState> T an object that implements TestState
*/
@SuppressWarnings("unchecked")
public static <T extends TestState> T getTestState() {
return (T) innerContext.get().state;
}
/**
* set the test state at any given time for the running thread.
*
* @param state an object implementing the marker interface
*/
public static <T extends TestState> void setTestState(T state) {
innerContext.get().state = state;
}
/**
* Register the controller in the context of current thread's copy for this thread-local variable.
*
* @param instance the new web controller
*/
public static void setWebController(WebController instance) {
Context context = innerContext.get();
context.controller = instance;
if (instance instanceof WebDriverWebController) {
context.isWebDriver = true;
LOG.warn("Handle is : " + ((WebDriverWebController) instance).getDriver().getWindowHandle());
} else {
context.isWebDriver = false;
}
Thread.currentThread().setName(
"Stevia [" + (context.isWebDriver ? "WD" : "RC") + " "
+ instance.getClass().getSimpleName() + "@"
+ Integer.toHexString(threadSeq.incrementAndGet()) + "]");
LOG.info("Context ready, controller is now set, type is {}", context.isWebDriver ? "WebDriver" : "SeleniumRC");
}
/**
* return a verify helper initialized with the right controller.
*
* @return the verify
*/
public static Verify verify() {
Context context = innerContext.get();
if (context.verify == null) {
context.verify = new Verify();
}
return context.verify;
}
/**
* Clean the local thread context
*/
public static void clean() {
innerContext.get().clear();
innerContext.remove();
try {
Thread.sleep(5000);
}catch (InterruptedException e){}
}
public static int getWaitForPageToLoad() {
return innerContext.get().getWaitForPageToLoad();
}
public static void setWaitForPageToLoad(int waitForPageToLoad) {
innerContext.get().setWaitForPageToLoad(waitForPageToLoad);
}
public static int getWaitForElement() {
return innerContext.get().getWaitForElement();
}
public static int getWaitForAjaxComplete() {
return innerContext.get().getWaitForAjaxComplete();
}
public static void setWaitForAjaxComplete(int waitForAjaxComplete) {
innerContext.get().setWaitForAjaxComplete(waitForAjaxComplete);
}
public static void setWaitForElement(int waitForElement) {
innerContext.get().setWaitForElement(waitForElement);
}
public static int getWaitForElementInvisibility() {
return innerContext.get().getWaitForElementInvisibility();
}
public static void setWaitForElementInvisibility(int waitForElementInvisibility) {
innerContext.get().setWaitForElementInvisibility(waitForElementInvisibility);
}
public static void setWaitForNewWindow(int waitForNewWindow) {
innerContext.get().setWaitForWindow(waitForNewWindow);
}
public static int getWaitForNewWindow() {
return innerContext.get().getWaitForWindow();
}
public static void attachSpringContext(ApplicationContext applicationContext) {
innerContext.get().setContext(applicationContext);
}
public static ApplicationContext getSpringContext() {
return innerContext.get().getContext();
}
}
|
// checkstyle: Checks Java source code for adherence to a set of rules.
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.puppycrawl.tools.checkstyle.checks.javadoc;
import java.util.List;
/**
* Value object for combining the list of valid validTags with information
* about invalid validTags encountered in a certain Javadoc comment.
*/
public final class JavadocTags {
/** Valid validTags. */
private final List<JavadocTag> validTags;
/** Invalid validTags. */
private final List<InvalidJavadocTag> invalidTags;
/**
* Creates an instance.
*
* @param tags valid tags
* @param invalidTags invalid tags
*/
public JavadocTags(List<JavadocTag> tags, List<InvalidJavadocTag> invalidTags) {
validTags = List.copyOf(tags);
this.invalidTags = List.copyOf(invalidTags);
}
/**
* Getter for validTags field.
*
* @return validTags field
*/
public List<JavadocTag> getValidTags() {
return validTags;
}
/**
* Getter for invalidTags field.
*
* @return invalidTags field
*/
public List<InvalidJavadocTag> getInvalidTags() {
return invalidTags;
}
}
|
package com.sugarcrm.candybean.automation.webdriver;
import com.sugarcrm.candybean.automation.Candybean;
import com.sugarcrm.candybean.automation.element.Hook;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.*;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
import com.sugarcrm.candybean.exceptions.CandybeanException;
import java.text.DecimalFormat;
import java.util.logging.Logger;
import static java.lang.System.currentTimeMillis;
/**
* Utility class that provides several methods for an element to pause until a
* condition is satisfied
*
* @author Eric Tam
* @author Jason Mittertreiner
*/
public class WebDriverPause {
private WebDriver wd;
private long defaultTimeoutMs;
private long defaultPollingIntervalS;
public Logger logger;
public WebDriverPause(WebDriver wd, long defaultTimeoutMs, long defaultPollingIntervalS) {
this.wd = wd;
this.defaultTimeoutMs = defaultTimeoutMs;
this.defaultPollingIntervalS = defaultPollingIntervalS;
this.logger = Logger.getLogger(Candybean.class.getSimpleName());
}
/**
* Accepts any ExpectedCondition and poll under this condition is satisfied within timeout
* @param timeoutMs Timeout in Milliseconds
* @param condition The condition to poll
* @return Returning the object that is returned from ExpectedCondition when the condition is met
* @throws CandybeanException
*/
public Object waitUntil(ExpectedCondition condition, long timeoutMs) throws CandybeanException {
// This is done by double-polling. WebDriverWait waits for wdPollingInterval amount of time.
// This is done repetitively until the time reaches timeoutMs.
final long pollingIntervalS = Math.min(defaultPollingIntervalS, Math.max(timeoutMs/1000, 1));
final long seleniumPollingIntervalMs = 250;
final long startTime = currentTimeMillis();
String toThrow = null;
Object toReturn = null;
logger.info("Waiting until " + condition.toString() + " is satisfied.");
while(currentTimeMillis() - startTime <= timeoutMs) {
try {
toReturn = (new WebDriverWait(this.wd, pollingIntervalS, seleniumPollingIntervalMs)).until(condition);
toThrow = null;
break;
} catch (WebDriverException wdException) {
logger.info(currentTimeMillis() - startTime+ "ms have passed. Waiting until " + condition.toString() + " is satisfied.");
toThrow = wdException.toString();
}
}
if(toThrow != null) {
logger.severe("The timeout of " + timeoutMs + "ms was reached. Throwing Exception.");
throw new CandybeanException("Timed out after "+ timeoutMs + " seconds");
}
return toReturn;
}
public Object waitUntil(ExpectedCondition<?> condition) throws CandybeanException {
return this.waitUntil(condition, defaultTimeoutMs);
}
/**
* Wait until an element is present on the DOM for up to timeoutMs seconds
*
* @param hook Hook to find the element
* @param timeoutMs Max wait time
* @return The located element
* @throws CandybeanException
*/
public WebDriverElement waitForElement(Hook hook, long timeoutMs) throws CandybeanException {
return (WebDriverElement) this.waitUntil(WaitConditions.present(hook), timeoutMs);
}
/**
* Wait until an element is present on the DOM for up to 15 seconds
*
* @param hook Hook to find the element
* @return The located element
* @throws CandybeanException
*/
public WebDriverElement waitForElement(Hook hook) throws CandybeanException {
return (WebDriverElement) this.waitUntil(WaitConditions.present(hook), defaultTimeoutMs);
}
/**
* wait until an element is no present on the dom for up to timeoutMs seconds
*
* @param hook hook to find the element
* @param timeoutMs max wait time
* @throws CandybeanException
*/
public void waitForElementRemoved(Hook hook, long timeoutMs) throws CandybeanException {
waitUntil(WaitConditions.not(WaitConditions.present(hook)), timeoutMs);
}
/**
* wait until an element is no present on the dom for up to 15 seconds
*
* @param hook hook to find the element
* @throws CandybeanException
*/
public void waitForElementRemoved(Hook hook) throws CandybeanException {
waitUntil(WaitConditions.not(WaitConditions.present(hook)), defaultTimeoutMs);
}
/**
* Provides a simple method to wait for visible as it is often used
* @param hook
* @param timeoutMs
* @throws CandybeanException
*/
public WebDriverElement waitForVisible(Hook hook, long timeoutMs) throws CandybeanException {
return (WebDriverElement) this.waitUntil(WaitConditions.visible(hook), timeoutMs);
}
/**
* Provides a simple method to wait for visible as it is often used
* @param hook
* @return
* @throws CandybeanException
*/
public WebDriverElement waitForVisible(Hook hook) throws CandybeanException {
return this.waitForVisible(hook, defaultTimeoutMs);
}
/**
* Provides a simple method to wait for visible as it is often used
* @param wde
* @param timeoutMs
* @throws CandybeanException
*/
public WebDriverElement waitForVisible(WebDriverElement wde, long timeoutMs) throws CandybeanException {
return (WebDriverElement) this.waitUntil(WaitConditions.visible(wde), timeoutMs);
}
/**
* Provides a simple method to wait for visible as it is often used
* @param wde
* @return
* @throws CandybeanException
*/
public WebDriverElement waitForVisible(WebDriverElement wde) throws CandybeanException {
return this.waitForVisible(wde, defaultTimeoutMs);
}
/**
* Provides a simple method to wait for invisible
*
* @param hook The hook used to find the element
* @param timeoutMs The max wait time
* @throws CandybeanException If the element is visible after timeout
*/
public void waitForInvisible(Hook hook, long timeoutMs) throws CandybeanException {
waitUntil(WaitConditions.invisible(hook), timeoutMs);
}
/**
* Provides a simple method to wait for invisible
*
* @param hook The hook used to find the element
* @throws CandybeanException If the element is visible after timeout
*/
public void waitForInvisible(Hook hook) throws CandybeanException {
waitForInvisible(hook, defaultTimeoutMs);
}
/**
* Provides a simple method to wait for invisible
*
* @param wde The WebDriverElement to wait for
* @param timeoutMs The max wait time
* @throws CandybeanException
* If the element visible after timeout
*/
public void waitForInvisible(WebDriverElement wde, long timeoutMs) throws CandybeanException {
waitUntil(WaitConditions.invisible(wde), timeoutMs);
}
/**
* Provides a simple method to wait for invisible
*
* @param wde The WebDriverElement to wait for
* @throws CandybeanException If the element visible after timeout
*/
public void waitForInvisible(WebDriverElement wde) throws CandybeanException {
waitForInvisible(wde, defaultTimeoutMs);
}
/**
* Wait for an element to have the specified attribute with the specified value if expectValue is true, and the
* reverse if false, waiting for up to timeoutMS milliseconds.
*
* @param hook Hook used to search for the element
* @param attribute Attributed used to check for value
* @param value Specified value of the attribute
* @param expectValue If the value is expected or not
* @param timeoutMS Max wait time before timeout
* @return The found matching element
* @throws CandybeanException If element not found or attribute has the wrong value
*/
public WebDriverElement waitForAttribute(Hook hook, String attribute, String value, boolean expectValue, long timeoutMS)
throws CandybeanException {
return (WebDriverElement) waitUntil(WaitConditions.hasAttribute(hook, attribute, value, expectValue), timeoutMS);
}
/**
* Wait for an element to have the specified attribute with the specified value if expectValue is true, and the
* reverse if false, waiting for up to 15s
*
* @param hook Hook used to search for the element
* @param attribute Attributed used to check for value
* @param value Specified value of the attribute
* @param expectValue If the value is expected or not
* @return The found matching element
* @throws CandybeanException If element not found or attribute has the wrong value
*/
public WebDriverElement waitForAttribute(Hook hook, String attribute, String value, boolean expectValue)
throws CandybeanException {
return (WebDriverElement) waitUntil(WaitConditions.hasAttribute(hook, attribute, value, expectValue), defaultTimeoutMs);
}
/**
* Wait for an element to have the specified attribute with the specified value if expectValue is true, and the
* reverse if false, waiting for up to timeoutMS milliseconds.
*
* @param hook Hook used to search for the element
* @param attribute Attributed used to check for value
* @param regex Speecified regex pattern of the attribute
* @param expectValue If the value is expected or not
* @param timeoutMS Max wait time before timeout
* @return The found matching element
* @throws CandybeanException If element not found or attribute has the wrong value
*/
public WebDriverElement waitForRegexAttribute(Hook hook, String attribute, String regex, boolean expectValue, long timeoutMS)
throws CandybeanException {
return (WebDriverElement) waitUntil(WaitConditions.hasRegexAttribute(hook, attribute, regex, expectValue), timeoutMS);
}
/**
* Wait for an element to have the specified attribute with the specified value if expectValue is true, and the
* reverse if false, waiting for up to 15s
*
* @param hook Hook used to search for the element
* @param attribute Attributed used to check for value
* @param regex Specified regex pattern of the attribute
* @param expectValue If the value is expected or not
* @return The found matching element
* @throws CandybeanException If element not found or attribute has the wrong value
*/
public WebDriverElement waitForRegexAttribute(Hook hook, String attribute, String regex, boolean expectValue)
throws CandybeanException {
return (WebDriverElement) waitUntil(WaitConditions.hasRegexAttribute(hook, attribute, regex, expectValue), defaultTimeoutMs);
}
/**
* Waits until a specified element is on(off) screen for up to 15 seconds
*
* @param hook Hook used to search for the element
* @param isOnScreen Whether to check is the element is on or off screen
* @return The element
* @throws CandybeanException
*/
public WebDriverElement waitForOnScreen(Hook hook, boolean isOnScreen) throws CandybeanException {
return this.waitForOnScreen(hook, defaultTimeoutMs, isOnScreen);
}
/**
* Waits until a specified element is on(off) screen for up to timeoutMS seconds
*
* @param hook Hook used to search for the element
* @param timeoutMs Maximum time to wait for the element
* @param isOnScreen Whether to check is the element is on or off screen
* @return The element
* @throws CandybeanException
*/
public WebDriverElement waitForOnScreen(Hook hook, long timeoutMs, boolean isOnScreen) throws CandybeanException {
return (WebDriverElement) this.waitUntil(WaitConditions.onScreen(hook, isOnScreen), timeoutMs);
}
}
|
package com.wandrell.tabletop.punkapocalyptic.service;
import java.util.Collection;
import com.wandrell.tabletop.procedure.Constraint;
import com.wandrell.tabletop.punkapocalyptic.model.faction.Faction;
import com.wandrell.tabletop.punkapocalyptic.model.unit.Gang;
import com.wandrell.tabletop.punkapocalyptic.model.unit.Unit;
import com.wandrell.tabletop.punkapocalyptic.model.unit.UnitTemplate;
public interface ModelService {
public Constraint getConstraint(final Gang gang, final String name,
final String unit, final Collection<String> context);
public Gang getGang(final Faction faction);
public Unit getUnit(final UnitTemplate template);
}
|
package edu.ucar.unidata.rosetta.repository.wizard;
import edu.ucar.unidata.rosetta.domain.Metadata;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.dao.DataRetrievalFailureException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
/**
* Implementation of a metadata DAO.
*
* @author oxelson@ucar.edu
*/
public class JdbcMetadataDao extends JdbcDaoSupport implements MetadataDao {
protected static Logger logger = Logger.getLogger(JdbcMetadataDao.class);
private SimpleJdbcInsert insertActor;
/**
* Looks up and retrieves a list of persisted Metadata objects using the given id.
*
* @param id The id of the corresponding Data object.
* @return The Metadata object.
* @throws DataRetrievalFailureException If unable to lookup Metadata with the given id.
*/
public List<Metadata> lookupMetadata(String id) throws DataRetrievalFailureException {
String sql = "SELECT * FROM metadata WHERE id = ?";
List<Metadata> metadata = getJdbcTemplate().query(sql, new JdbcMetadataDao.MetadataMapper(), id);
if (metadata.isEmpty()) {
String message = "Unable to find persisted metadata corresponding to id " + id;
logger.error(message);
throw new DataRetrievalFailureException(message);
}
return metadata;
}
/**
* Looks up and retrieves a list of persisted Metadata objects using the given id & type.
*
* @param id The id of the corresponding Data object.
* @param type The type of the Metadata.
* @return The Metadata object.
* @throws DataRetrievalFailureException If unable to lookup Metadata with the given id & type.
*/
@Override
public List<Metadata> lookupMetadata(String id,String type) throws DataRetrievalFailureException {
String sql = "SELECT * FROM metadata WHERE id = ? AND type = ?";
List<Metadata> metadata = getJdbcTemplate().query(sql, new JdbcMetadataDao.MetadataMapper(), id, type);
if (metadata.isEmpty()) {
String message = "Unable to find persisted metadata corresponding to id " + id + " and type " + type;
logger.error(message);
throw new DataRetrievalFailureException(message);
}
return metadata;
}
/**
* Persists the information in the given list of metadata objects.
*
* @param metadataList The list of Metadata objects to persist.
* @throws DataRetrievalFailureException If unable to persist the Metadata objects.
*/
public void persistMetadata(List<Metadata> metadataList) throws DataRetrievalFailureException {
for (Metadata metadata : metadataList)
persistMetadata(metadata);
}
/**
* Persists the information in the give metadata object.
*
* @param metadata The Metadata object to persist.
* @throws DataRetrievalFailureException If unable to persist the Metadata object.
*/
public void persistMetadata(Metadata metadata) throws DataRetrievalFailureException {
// Persist the metadata object.
this.insertActor = new SimpleJdbcInsert(getDataSource()).withTableName("metadata");
SqlParameterSource parameters = new BeanPropertySqlParameterSource(metadata);
int rowsAffected = insertActor.execute(parameters);
if (rowsAffected <= 0) {
String message = "Unable to persist Metadata object " + metadata.toString();
logger.error(message);
throw new DataRetrievalFailureException(message);
} else {
logger.info("Metadata object persisted " + metadata.toString());
}
}
/**
* Updated the information corresponding to the given list of metadata objects.
*
* @param metadataList The list of metadata objects to update.
* @throws DataRetrievalFailureException If unable to update persisted Metadata objects.
*/
public void updatePersistedMetadata(List<Metadata> metadataList) throws DataRetrievalFailureException {
for (Metadata metadata : metadataList)
updatePersistedMetadata(metadata);
}
/**
* Updated the information corresponding to the given metadata object.
*
* @param metadata The metadata object to update.
* @throws DataRetrievalFailureException If unable to update persisted Metadata object.
*/
public void updatePersistedMetadata(Metadata metadata) throws DataRetrievalFailureException {
String sql = "UPDATE metadata SET " +
"type = ?, " +
"metadataKey = ?, " +
"metadataValue = ?, " +
"WHERE id = ?";
int rowsAffected = getJdbcTemplate().update(sql, new Object[] {
// order matters here
metadata.getType(),
metadata.getMetadataKey(),
metadata.getMetadataValue(),
metadata.getId()
});
if (rowsAffected <= 0) {
String message ="Unable to update persisted Metadata object " + metadata.toString();
logger.error(message);
throw new DataRetrievalFailureException(message);
} else {
logger.info("Updated persisted Metadata object " + metadata.toString());
}
}
/**
* Deletes the persisted metadata information using the given id.
*
* @param id The id of the metadata information to delete.
* @throws DataRetrievalFailureException If unable to delete persisted metadata information.
*/
public void deletePersistedMetadata(String id) throws DataRetrievalFailureException {
String sql = "DELETE FROM metadata WHERE id = ?";
int rowsAffected = getJdbcTemplate().update(sql, id);
if (rowsAffected <= 0) {
String message = "Unable to delete metadata entries corresponding to id " + id;
logger.error(message);
throw new DataRetrievalFailureException(message);
} else {
logger.info("Deleted metadata entries corresponding to id " + id);
}
}
/**
* Deletes the persisted metadata object information using the given id & type.
*
* @param id The id of the metadata information to delete.
* @param type The type of the metadata information to delete.
* @throws DataRetrievalFailureException If unable to delete persisted metadata information.
*/
public void deletePersistedMetadata(String id, String type) throws DataRetrievalFailureException {
String sql = "DELETE FROM metadata WHERE id = ? AND type =?";
int rowsAffected = getJdbcTemplate().update(sql, id);
if (rowsAffected <= 0) {
String message = "Unable to delete metadata entries corresponding to id " + id + " and type " + type;
logger.error(message);
throw new DataRetrievalFailureException(message);
} else {
logger.info("Deleted metadata entries corresponding to id " + id + " and type " + type);
}
}
/**
* This MetadataMapper only used by JdbcMetadataDao.
*/
private static class MetadataMapper implements RowMapper<Metadata> {
/**
* Maps each row of metadata in the ResultSet to the Metadata object.
*
* @param rs The ResultSet to be mapped.
* @param rowNum The number of the current row.
* @return The populated Metadata object.
* @throws SQLException If an SQLException is encountered getting column values.
*/
public Metadata mapRow(ResultSet rs, int rowNum) throws SQLException {
Metadata metadata = new Metadata();
metadata.setId(rs.getString("id"));
metadata.setType(rs.getString("type"));
metadata.setMetadataKey(rs.getString("metadataKey"));
metadata.setMetadataValue(rs.getString("metadataValue"));
return metadata;
}
}
}
|
package ee.tkasekamp.vickywaranalyzer.controller.box;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.image.ImageView;
import ee.tkasekamp.vickywaranalyzer.controller.tab.AbstractController;
import ee.tkasekamp.vickywaranalyzer.core.Country;
import ee.tkasekamp.vickywaranalyzer.core.War;
import ee.tkasekamp.vickywaranalyzer.gui.ObservableJoinedCountry;
import ee.tkasekamp.vickywaranalyzer.service.ModelService;
public class WarCountryBox extends AbstractController {
@FXML
private ImageView flag;
@FXML
private Label originalLabel;
@FXML
private Label originalHelper;
@FXML
private Label totalLossesLabel;
@FXML
private Label totalShipLossesLabel;
@FXML
private TableView<ObservableJoinedCountry> table;
@FXML
private TableColumn<ObservableJoinedCountry, ImageView> colFlag;
@FXML
private TableColumn<ObservableJoinedCountry, String> colName;
@FXML
private TableColumn<ObservableJoinedCountry, String> colStartDate;
@FXML
private TableColumn<ObservableJoinedCountry, String> colEndDate;
@FXML
private Label warHelper;
@FXML
private Label warLabel;
/** Attacker or defender */
private String side;
private ModelService modelService;
private ObservableList<ObservableJoinedCountry> tableContent;
public void init(ModelService modelService, String side) {
this.side = side;
this.modelService = modelService;
tableContent = FXCollections.observableArrayList();
colName.setCellValueFactory(new PropertyValueFactory<ObservableJoinedCountry, String>(
"officialName"));
colFlag.setCellValueFactory(new PropertyValueFactory<ObservableJoinedCountry, ImageView>(
"flag"));
colStartDate
.setCellValueFactory(new PropertyValueFactory<ObservableJoinedCountry, String>(
"joinDate"));
colEndDate
.setCellValueFactory(new PropertyValueFactory<ObservableJoinedCountry, String>(
"endDate"));
setHelperLabels(side);
}
@Override
public void reset() {
warLabel.setText("");
originalLabel.setText("");
totalLossesLabel.setText("");
totalShipLossesLabel.setText("");
tableContent.clear(); // Clearing list
}
public void populate(War war) {
reset();
if (side == "Attacker")
populateAttacker(war);
else
populateDefender(war);
}
private void populateAttacker(War war) {
/* If there is no attacker, the flag will be the original attacker's */
if (war.getAttacker().equals("")) {
for (Country country : modelService.getCountries()) {
if (war.getOriginalAttacker().equals(country.getTag())) {
flag.setImage(country.getFlag());
originalLabel.setText(country.getOfficialName());
}
}
// Hiding the labels as there is no use for them
warLabel.setVisible(false);
warHelper.setVisible(false);
} else {
for (Country country : modelService.getCountries()) {
if (war.getAttacker().equals(country.getTag())) {
flag.setImage(country.getFlag());
}
}
// Showing labels and giving value
warLabel.setVisible(true);
warHelper.setVisible(true);
warLabel.setText(war.getOriginalAttackerOfficial());
}
/*
* Comparing war.countrylist items to reference.countrylist items Join
* type true for attackers
*/
for (int i = 0; i < war.getCountryList().length; i++) {
for (Country country : modelService.getCountries()) {
if (country.getTag().equals(war.getCountryList()[i].getTag())
&& war.getCountryList()[i].isJoinType()) {
/* Creating a row with items from both classes */
ObservableJoinedCountry temp = new ObservableJoinedCountry(
country.getOfficialName(), country.getFlag(),
war.getCountryList()[i].getStartDate(),
war.getCountryList()[i].getEndDate());
tableContent.add(temp);
break;
}
}
}
/* Adding the countries to table */
table.setItems(tableContent);
}
private void populateDefender(War war) {
/* If there is no defender, the flag will be the original defender's */
if (war.getDefender().equals("")) {
for (Country country : modelService.getCountries()) {
if (war.getOriginalDefender().equals(country.getTag())) {
flag.setImage(country.getFlag());
originalLabel.setText(country.getOfficialName());
}
}
// Hiding the labels as there is no use for them
warLabel.setVisible(false);
warHelper.setVisible(false);
} else {
for (Country country : modelService.getCountries()) {
if (war.getDefender().equals(country.getTag())) {
flag.setImage(country.getFlag());
}
}
// Showing labels and giving value
warLabel.setVisible(true);
warHelper.setVisible(true);
warLabel.setText(war.getOriginalDefenderOfficial());
}
/*
* Comparing war.countrylist items to reference.countrylist items Join
* type true for attackers
*/
for (int i = 0; i < war.getCountryList().length; i++) {
for (Country country : modelService.getCountries()) {
if (country.getTag().equals(war.getCountryList()[i].getTag())
&& !war.getCountryList()[i].isJoinType()) {
/* Creating a row with items from both classes */
ObservableJoinedCountry temp = new ObservableJoinedCountry(
country.getOfficialName(), country.getFlag(),
war.getCountryList()[i].getStartDate(),
war.getCountryList()[i].getEndDate());
tableContent.add(temp);
break;
}
}
}
/* Adding the countries to table */
table.setItems(tableContent);
}
public void setTotalLosses(int totalLosses, int totalShipLosses) {
totalLossesLabel.setText(Integer.toString(totalLosses));
totalShipLossesLabel.setText(Integer.toString(totalShipLosses));
}
private void setHelperLabels(String side) {
originalHelper.setText("Original " + side.toLowerCase() + ":");
warHelper.setText(side + ":");
}
}
|
package io.scalecube.gateway.benchmarks.example;
import io.scalecube.gateway.examples.StreamRequest;
import java.time.Duration;
import java.util.stream.LongStream;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
public class ExampleServiceImpl implements ExampleService {
@Override
public Mono<String> one(String name) {
return Mono.just("Echo:" + name);
}
@Override
public Flux<Long> manyStream(Long cnt) {
return Flux.fromStream(LongStream.range(0, cnt).boxed())
.publishOn(Schedulers.parallel(), Integer.MAX_VALUE)
.onBackpressureDrop();
}
@Override
public Flux<Long> manyStreamWithBackpressureDrop(Long cnt) {
return Flux.fromStream(LongStream.range(0, cnt).boxed())
.publishOn(Schedulers.parallel(), Integer.MAX_VALUE)
.onBackpressureDrop();
}
@Override
public Flux<Long> requestInfiniteStream(StreamRequest request) {
Flux<Flux<Long>> fluxes = Flux
.interval(Duration.ofMillis(request.getIntervalMillis()))
.map(tick -> Flux.create(s -> {
for (int i = 0; i < request.getMessagesPerInterval(); i++) {
s.next(System.currentTimeMillis());
}
s.complete();
}));
return Flux.concat(fluxes)
.publishOn(Schedulers.parallel(), Integer.MAX_VALUE)
.onBackpressureDrop();
}
}
|
package liquibase.database.typeconversion.ext;
import liquibase.database.structure.Column;
import liquibase.database.structure.type.*;
import liquibase.database.Database;
import liquibase.database.core.H2Database;
import liquibase.database.core.HsqlDatabase;
import liquibase.exception.UnexpectedLiquibaseException;
import liquibase.util.StringUtils;
import java.lang.reflect.Field;
import java.sql.Types;
import java.util.Arrays;
import java.util.List;
public class GenericTypeConverter extends liquibase.database.typeconversion.core.AbstractTypeConverter {
public int getPriority() {
return 1500;
}
protected static final List<Integer> oneParam = Arrays.asList(
Types.CHAR,
-15, // Types.NCHAR in java 1.6,
Types.VARCHAR,
-9, //Types.NVARCHAR in java 1.6,
Types.VARBINARY,
Types.DOUBLE,
Types.FLOAT
);
protected static final List<Integer> twoParams = Arrays.asList(
Types.DECIMAL,
Types.NUMERIC,
Types.REAL
);
@Override
public NumberType getNumberType() {
return new NumberType("NUMERIC");
}
@Override
public boolean supports(final Database database) {
return true;
}
public String convertToDatabaseTypeString(Column referenceColumn, Database database) {
final StringBuilder retval = new StringBuilder();
try {
retval.append(getSqlTypeName(referenceColumn.getDataType()));
}
catch (Exception e) {
retval.append(referenceColumn.getTypeName());
}
final boolean hasOneParam = oneParam.contains(referenceColumn.getDataType());
final boolean hasTwoParams = twoParams.contains(referenceColumn.getDataType());
if (hasOneParam || hasTwoParams) {
retval.append("(").append(referenceColumn.getColumnSize());
if (hasTwoParams) {
retval.append(",").append(referenceColumn.getDecimalDigits());
}
retval.append(")");
}
return retval.toString();
}
protected String getSqlTypeName(final int type) throws Exception {
for (final Field field : Types.class.getFields()) {
final int sql_type = field.getInt(null);
if (type == sql_type) {
return "java.sql.Types." + field.getName();
}
}
return null;
}
protected DataType getDataType(String columnTypeString, Boolean autoIncrement, String dataTypeName, String precision, String additionalInformation) {
// Translate type to database-specific type, if possible
DataType returnTypeName = null;
if (dataTypeName.equalsIgnoreCase("BIGINT")) {
returnTypeName = getBigIntType();
} else if (dataTypeName.equalsIgnoreCase("NUMBER")
|| dataTypeName.equalsIgnoreCase("DECIMAL")
|| dataTypeName.equalsIgnoreCase("NUMERIC")) {
returnTypeName = getNumberType();
} else if (dataTypeName.equalsIgnoreCase("BLOB")) {
returnTypeName = getBlobType();
} else if (dataTypeName.equalsIgnoreCase("BOOLEAN")) {
returnTypeName = getBooleanType();
} else if (dataTypeName.equalsIgnoreCase("CHAR")) {
returnTypeName = getCharType();
} else if (dataTypeName.equalsIgnoreCase("CLOB")) {
returnTypeName = getClobType();
} else if (dataTypeName.equalsIgnoreCase("CURRENCY")) {
returnTypeName = getCurrencyType();
} else if (dataTypeName.equalsIgnoreCase("DATE") || dataTypeName.equalsIgnoreCase(getDateType().getDataTypeName())) {
returnTypeName = getDateType();
} else if (dataTypeName.equalsIgnoreCase("DATETIME") || dataTypeName.equalsIgnoreCase(getDateTimeType().getDataTypeName())) {
returnTypeName = getDateTimeType();
} else if (dataTypeName.equalsIgnoreCase("DOUBLE")) {
returnTypeName = getDoubleType();
} else if (dataTypeName.equalsIgnoreCase("FLOAT")) {
returnTypeName = getFloatType();
} else if (dataTypeName.equalsIgnoreCase("INT")) {
returnTypeName = getIntType();
} else if (dataTypeName.equalsIgnoreCase("INTEGER")) {
returnTypeName = getIntType();
} else if (dataTypeName.equalsIgnoreCase("LONGBLOB")) {
returnTypeName = getLongBlobType();
} else if (dataTypeName.equalsIgnoreCase("LONGVARBINARY")) {
returnTypeName = getBlobType();
} else if (dataTypeName.equalsIgnoreCase("LONGVARCHAR")) {
returnTypeName = getClobType();
} else if (dataTypeName.equalsIgnoreCase("SMALLINT")) {
returnTypeName = getSmallIntType();
} else if (dataTypeName.equalsIgnoreCase("TEXT")) {
returnTypeName = getClobType();
} else if (dataTypeName.equalsIgnoreCase("TIME") || dataTypeName.equalsIgnoreCase(getTimeType().getDataTypeName())) {
returnTypeName = getTimeType();
} else if (dataTypeName.toUpperCase().contains("TIMESTAMP")) {
returnTypeName = getDateTimeType();
} else if (dataTypeName.equalsIgnoreCase("TINYINT")) {
returnTypeName = getTinyIntType();
} else if (dataTypeName.equalsIgnoreCase("UUID")) {
returnTypeName = getUUIDType();
} else if (dataTypeName.equalsIgnoreCase("VARCHAR")) {
returnTypeName = getVarcharType();
} else if (dataTypeName.equalsIgnoreCase("NVARCHAR")) {
returnTypeName = getNVarcharType();
} else {
return new CustomType(columnTypeString,0,2);
}
if (returnTypeName == null) {
throw new UnexpectedLiquibaseException("Could not determine " + dataTypeName + " for " + this.getClass().getName());
}
addPrecisionToType(precision, returnTypeName);
returnTypeName.setAdditionalInformation(additionalInformation);
return returnTypeName;
}
}
|
package me.deftware.mixin.mixins.network;
import me.deftware.client.framework.event.events.EventAnimation;
import me.deftware.client.framework.event.events.EventChunk;
import me.deftware.client.framework.event.events.EventChunkDataReceive;
import me.deftware.client.framework.event.events.EventKnockback;
import me.deftware.client.framework.network.NetworkHandler;
import me.deftware.client.framework.registry.BlockRegistry;
import me.deftware.client.framework.world.block.Block;
import me.deftware.client.framework.world.player.PlayerEntry;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.network.ClientPlayNetworkHandler;
import net.minecraft.network.packet.s2c.play.*;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.ChunkSectionPos;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author Deftware
*/
@Mixin(ClientPlayNetworkHandler.class)
public class MixinNetHandlerPlayClient implements NetworkHandler {
@Override
public List<PlayerEntry> _getPlayerList() {
return ((ClientPlayNetworkHandler) (Object) this).getPlayerList()
.stream().map(PlayerEntry.class::cast).collect(Collectors.toList());
}
@Unique
private final EventAnimation eventAnimation = new EventAnimation();
@Inject(method = "onEntityStatus", at = @At("HEAD"), cancellable = true)
public void onEntityStatus(EntityStatusS2CPacket packet, CallbackInfo ci) {
if (packet.getStatus() == 35) {
eventAnimation.create(EventAnimation.AnimationType.Totem);
eventAnimation.broadcast();
if (eventAnimation.isCanceled()) {
ci.cancel();
}
}
}
@Inject(method = "onExplosion", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/network/ClientPlayerEntity;setVelocity(Lnet/minecraft/util/math/Vec3d;)V"), cancellable = true)
private void onExplosion(ExplosionS2CPacket packet, CallbackInfo ci) {
EventKnockback event = new EventKnockback(packet.getPlayerVelocityX(), packet.getPlayerVelocityY(), packet.getPlayerVelocityZ()).broadcast();
if (!event.isCanceled()) {
MinecraftClient.getInstance().player.setVelocity(
MinecraftClient.getInstance().player.getVelocity().add(event.getX(), event.getY(), event.getZ())
);
}
ci.cancel();
}
@Inject(method = "onChunkData", at = @At("HEAD"), cancellable = true)
public void onReceiveChunkData(ChunkDataS2CPacket packet, CallbackInfo ci) {
EventChunkDataReceive event = new EventChunkDataReceive(packet).broadcast();
if (event.isCanceled()) {
ci.cancel();
}
}
@Inject(method = "onBlockUpdate", at = @At("HEAD"))
private void onBlockUpdate(BlockUpdateS2CPacket packet, CallbackInfo ci) {
BlockPos pos = packet.getPos();
int chunkX = pos.getX() >> 4, chunkZ = pos.getZ() >> 4, chunkY = pos.getY() >> 4;
int x = pos.getX() - (chunkX << 4), z = pos.getZ() - (chunkZ << 4), y = pos.getY() & 0xF;
short[] positions = { (short) ((x << 8) | (z << 4) | y) };
Block[] blocks = { BlockRegistry.INSTANCE.getBlock(packet.getState().getBlock()) };
new EventChunk.EventDeltaChunk(
chunkX, chunkY, chunkZ,
positions, blocks
).broadcast();
}
@Inject(method = "onChunkDeltaUpdate", at = @At("HEAD"))
private void onChunkDeltaPacket(ChunkDeltaUpdateS2CPacket packet, CallbackInfo ci) {
ChunkDeltaAccessor accessor = (ChunkDeltaAccessor) packet;
Block[] blocks = Arrays.stream(accessor.getBlockStates())
.map(s -> BlockRegistry.INSTANCE.getBlock(s.getBlock()))
.toArray(Block[]::new);
ChunkSectionPos pos = accessor.getSectionPos();
new EventChunk.EventDeltaChunk(
pos.getX(), pos.getY(), pos.getZ(),
accessor.getPositions(), blocks
).broadcast();
}
@Redirect(method = "onGameJoin", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/ClientBrandRetriever;getClientModName()Ljava/lang/String;"))
private String onGameJoin$GetClientBrand() {
return "vanilla";
}
}
|
package net.ttddyy.dsproxy.proxy;
import net.ttddyy.dsproxy.ConnectionInfo;
import net.ttddyy.dsproxy.listener.MethodExecutionListenerUtils;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import static java.lang.Boolean.TRUE;
import static java.lang.String.format;
/**
* Allows {@link java.sql.ResultSet} to be consumed more than once.
*
* @author Liam Williams
* @see net.ttddyy.dsproxy.proxy.jdk.ResultSetInvocationHandler
* @since 1.4
*/
public class RepeatableReadResultSetProxyLogic implements ResultSetProxyLogic {
private static final Set<String> METHODS_TO_INTERCEPT = Collections.unmodifiableSet(
new HashSet<String>() {
{
// getDeclaredMethods does NOT include parent class methods(e.g: Wrapper#unwrap()"
for (Method method : ResultSet.class.getDeclaredMethods()) {
add(method.getName());
}
add("toString");
add("getTarget"); // from ProxyJdbcObject
}
}
);
private static final Object UNCONSUMED_RESULT_COLUMN = new Object();
public static class Builder {
private ResultSet resultSet;
private ConnectionInfo connectionInfo;
private ProxyConfig proxyConfig;
private Map<String, Integer> columnNameToIndex;
private int columnCount;
public static Builder create() {
return new Builder();
}
public RepeatableReadResultSetProxyLogic build() {
RepeatableReadResultSetProxyLogic logic = new RepeatableReadResultSetProxyLogic();
logic.resultSet = this.resultSet;
logic.connectionInfo = this.connectionInfo;
logic.proxyConfig = this.proxyConfig;
logic.columnNameToIndex = this.columnNameToIndex;
logic.columnCount = this.columnCount;
return logic;
}
public Builder resultSet(ResultSet resultSet) {
this.resultSet = resultSet;
return this;
}
public Builder connectionInfo(ConnectionInfo connectionInfo) {
this.connectionInfo = connectionInfo;
return this;
}
public Builder proxyConfig(ProxyConfig proxyConfig) {
this.proxyConfig = proxyConfig;
return this;
}
public Builder columnNameToIndex(Map<String, Integer> columnNameToIndex) {
this.columnNameToIndex = columnNameToIndex;
return this;
}
public Builder columnCount(int columnCount) {
this.columnCount = columnCount;
return this;
}
}
private Map<String, Integer> columnNameToIndex;
private ResultSet resultSet;
private ConnectionInfo connectionInfo;
private int columnCount;
private ProxyConfig proxyConfig;
private int resultPointer;
private boolean resultSetConsumed;
private boolean closed;
private Object[] currentResult;
private final List<Object[]> cachedResults = new ArrayList<Object[]>();
@Override
public Object invoke(Method method, Object[] args) throws Throwable {
return MethodExecutionListenerUtils.invoke(new MethodExecutionListenerUtils.MethodExecutionCallback() {
@Override
public Object execute(Object proxyTarget, Method method, Object[] args) throws Throwable {
return performQueryExecutionListener(method, args);
}
}, this.proxyConfig, this.resultSet, this.connectionInfo, method, args);
}
private Object performQueryExecutionListener(Method method, Object[] args) throws Throwable {
final String methodName = method.getName();
if (!METHODS_TO_INTERCEPT.contains(methodName)) {
return MethodUtils.proceedExecution(method, this.resultSet, args);
}
// special treat for toString method
if ("toString".equals(methodName)) {
final StringBuilder sb = new StringBuilder();
sb.append(this.resultSet.getClass().getSimpleName());
sb.append(" [");
sb.append(this.resultSet.toString());
sb.append("]");
return sb.toString(); // differentiate toString message.
} else if ("getTarget".equals(methodName)) {
// ProxyJdbcObject interface has a method to return original object.
return this.resultSet;
}
if (methodName.equals("getMetaData")) {
return method.invoke(this.resultSet, args);
} else if (methodName.equals("close")) {
this.closed = true;
return method.invoke(this.resultSet, args);
} else if (methodName.equals("isClosed")) {
return method.invoke(this.resultSet, args);
}
if (this.closed) {
throw new SQLException("Already closed");
}
if (this.resultSetConsumed) {
if (isGetMethod(method)) {
return handleGetMethodUsingCache(args);
}
if (isNextMethod(method)) {
return handleNextMethodUsingCache();
}
} else {
if (isGetMethod(method)) {
return handleGetMethodByDelegating(method, args);
}
boolean isNextMethod = isNextMethod(method);
if (isNextMethod || isBeforeFirstMethod(method)) {
beforeNextOrBeforeFirst();
}
if (isNextMethod) {
return handleNextMethodByDelegating(method, args);
}
if (isBeforeFirstMethod(method)) {
resultPointer = -1;
resultSetConsumed = true;
return null;
}
}
throw new UnsupportedOperationException(format("Method '%s' is not supported by this proxy", method));
}
private void beforeNextOrBeforeFirst() throws SQLException {
if (currentResult == null) {
return;
}
for (int i = 1; i < currentResult.length; i++) {
Object resultColumn = currentResult[i];
if (resultColumn != UNCONSUMED_RESULT_COLUMN) {
continue;
}
currentResult[i] = resultSet.getObject(i);
}
}
private Object handleNextMethodByDelegating(Method method, Object[] args) throws IllegalAccessException, InvocationTargetException {
Object result = method.invoke(resultSet, args);
if (TRUE.equals(result)) {
currentResult = new Object[columnCount + 1];
Arrays.fill(this.currentResult, UNCONSUMED_RESULT_COLUMN);
cachedResults.add(currentResult);
}
return result;
}
private Object handleGetMethodByDelegating(Method method, Object[] args) throws SQLException, IllegalAccessException, InvocationTargetException {
int columnIndex = determineColumnIndex(args);
Object result = method.invoke(resultSet, args);
currentResult[columnIndex] = result;
return result;
}
private Object handleNextMethodUsingCache() {
if (resultPointer < cachedResults.size() - 1) {
resultPointer++;
currentResult = cachedResults.get(resultPointer);
return true;
} else {
resultPointer++;
currentResult = null;
return false;
}
}
private Object handleGetMethodUsingCache(Object[] args) throws SQLException {
if (resultPointer == -1) {
throw new SQLException("Result set not advanced. Call next before any get method!");
} else if (resultPointer < cachedResults.size()) {
int columnIndex = determineColumnIndex(args);
return currentResult[columnIndex];
} else {
throw new SQLException(format("Result set exhausted. There were %d result(s) only", cachedResults.size()));
}
}
private boolean isGetMethod(Method method) {
return method.getName().startsWith("get") && method.getParameterTypes().length > 0;
}
private boolean isNextMethod(Method method) {
return method.getName().equals("next");
}
private boolean isBeforeFirstMethod(Method method) {
return method.getName().equals("beforeFirst");
}
private int determineColumnIndex(Object[] args) throws SQLException {
Object lookup = args[0];
if (lookup instanceof Integer) {
return (Integer) lookup;
}
String columnName = (String) lookup;
Integer indexForColumnName = columnNameToIndex(columnName);
if (indexForColumnName != null) {
return indexForColumnName;
} else {
throw new SQLException(format("Unknown column name '%s'", columnName));
}
}
private Integer columnNameToIndex(String columnName) {
return columnNameToIndex.get(columnName.toUpperCase());
}
}
|
package org.ambraproject.wombat.config;
import com.google.common.collect.ImmutableSet;
import org.ambraproject.wombat.config.site.RequestMappingContext;
import org.ambraproject.wombat.config.site.RequestMappingContextDictionary;
import org.ambraproject.wombat.config.site.Site;
import org.ambraproject.wombat.config.site.SiteResolver;
import org.ambraproject.wombat.config.site.SiteSet;
import org.ambraproject.wombat.config.site.url.Link;
import org.ambraproject.wombat.util.ClientEndpoint;
import org.apache.commons.io.Charsets;
import org.jasig.cas.client.session.SingleSignOutFilter;
import org.jasig.cas.client.validation.Assertion;
import org.jasig.cas.client.validation.Cas20ServiceTicketValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AuthenticationDetailsSource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.cas.ServiceProperties;
import org.springframework.security.cas.authentication.CasAuthenticationProvider;
import org.springframework.security.cas.userdetails.AbstractCasAssertionUserDetailsService;
import org.springframework.security.cas.web.CasAuthenticationEntryPoint;
import org.springframework.security.cas.web.CasAuthenticationFilter;
import org.springframework.security.cas.web.authentication.ServiceAuthenticationDetails;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.AuthenticationUserDetailsService;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.util.AntPathMatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SpringSecurityConfiguration extends WebSecurityConfigurerAdapter {
private static final Logger log = LoggerFactory.getLogger(SpringSecurityConfiguration.class);
@Autowired
private SiteSet siteSet;
@Autowired
private SiteResolver siteResolver;
@Autowired
private RequestMappingContextDictionary requestMappingContextDictionary;
@Autowired
private RuntimeConfiguration runtimeConfiguration;
private static final String CAS_VALIDATION_URI = "/j_spring_cas_security_check";
private static final String CAS_LOGOUT_URI = "/j_spring_cas_security_logout";
private static final String CAS_AUTH_KEY = "casAuthProviderKey";
private static final String LOGOUT_HANDLER_NAME = "userLogout"; // corresponds to @RequestHandler annotation name attribute
private static final String USER_AUTH_INTERCEPT_PATTERN = "user/secure/**";
private static final String NEW_COMMENT_AUTH_INTERCEPT_PATTERN = "article/comments/new**";
private static final String FLAG_COMMENT_AUTH_INTERCEPT_PATTERN = "article/comments/flag**";
private static final ImmutableSet<String> CACHED_RESOURCE_HANDLERS = new ImmutableSet.Builder<String>()
.add("staticResource")
.add("repoObject")
.add("versionedRepoObject")
.add("repoObjectUsingPublicUrl")
.add("figureImage")
.build();
@Bean
public ServiceProperties serviceProperties() {
ServiceProperties serviceProperties = new ServiceProperties();
serviceProperties.setService(CAS_VALIDATION_URI);
serviceProperties.setSendRenew(false);
serviceProperties.setAuthenticateAllArtifacts(true);
return serviceProperties;
}
@Bean
public Cas20ServiceTicketValidator cas20ServiceTicketValidator() {
return new Cas20ServiceTicketValidator(runtimeConfiguration.getCasConfiguration().getCasUrl());
}
@Bean
public AuthenticationUserDetailsService authenticationUserDetailsService() {
return new AbstractCasAssertionUserDetailsService() {
@Override
protected UserDetails loadUserDetails(Assertion assertion) {
final List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
return new User(assertion.getPrincipal().getName(), "NO_PASSWORD", true, true, true, true, grantedAuthorities);
}
};
}
@Bean
public CasAuthenticationProvider casAuthenticationProvider() {
CasAuthenticationProvider casAuthenticationProvider = new CasAuthenticationProvider();
casAuthenticationProvider.setAuthenticationUserDetailsService(authenticationUserDetailsService());
casAuthenticationProvider.setServiceProperties(serviceProperties());
casAuthenticationProvider.setTicketValidator(cas20ServiceTicketValidator());
casAuthenticationProvider.setKey(CAS_AUTH_KEY);
return casAuthenticationProvider;
}
@Bean
public CasAuthenticationFilter casAuthenticationFilter() throws Exception {
CasAuthenticationFilter casAuthenticationFilter = new CasAuthenticationFilter();
casAuthenticationFilter.setAuthenticationManager(authenticationManager());
casAuthenticationFilter.setServiceProperties(serviceProperties());
casAuthenticationFilter.setAuthenticationDetailsSource(dynamicServiceResolver());
casAuthenticationFilter.setFilterProcessesUrl(CAS_VALIDATION_URI);
return casAuthenticationFilter;
}
@Bean
AuthenticationDetailsSource<HttpServletRequest,
ServiceAuthenticationDetails> dynamicServiceResolver() {
return request -> {
String url = getCasValidationPath(request);
return (ServiceAuthenticationDetails) () -> url;
};
}
@Bean
public SingleSignOutFilter singleSignOutFilter() {
// This filter handles a Single Logout Request from the CAS Server
return new SingleSignOutFilter();
}
@Bean
public LogoutFilter requestLogoutFilter() {
// This filter redirects to the CAS Server to signal Single Logout should be performed
SecurityContextLogoutHandler logoutHandler = new SecurityContextLogoutHandler();
logoutHandler.setClearAuthentication(true);
logoutHandler.setInvalidateHttpSession(true);
LogoutFilter logoutFilter = new LogoutFilter(getLogoutSuccessHandler(), logoutHandler);
logoutFilter.setFilterProcessesUrl(CAS_LOGOUT_URI);
return logoutFilter;
}
@Bean
public LogoutSuccessHandler getLogoutSuccessHandler() {
return (httpServletRequest, httpServletResponse, authentication) -> {
if (authentication != null && authentication.getDetails() != null) {
try {
httpServletRequest.getSession().invalidate();
} catch (IllegalStateException e) {
// session is already invalid, so nothing to do, but log as error since it may indicate a config issue
log.error("Attempted to log out of an already logged out session");
}
}
validateHostname(httpServletRequest);
String logoutServiceUrl = Link.toSitelessHandler()
.toPattern(requestMappingContextDictionary, LOGOUT_HANDLER_NAME).build()
.get(httpServletRequest);
httpServletResponse.setStatus(HttpServletResponse.SC_OK);
httpServletResponse.sendRedirect(runtimeConfiguration.getCasConfiguration().getLogoutUrl()
+ "?service=" + URLEncoder.encode(logoutServiceUrl, Charsets.UTF_8.name()));
};
}
@Override
public void configure(WebSecurity web) throws Exception {
// Allow internal or external resource requests bypass spring security, and thereby avoid the acquisition
// of default cache control headers which would prevent client-side caching.
web.ignoring().requestMatchers((RequestMatcher) request ->
CACHED_RESOURCE_HANDLERS.stream()
.map(handlerName -> requestMappingContextDictionary.getPattern(handlerName, siteResolver.resolveSite(request)))
.filter(Objects::nonNull)
.map(RequestMappingContext::getPattern)
.anyMatch(handlerPattern -> new AntPathMatcher().match(handlerPattern, request.getServletPath()))
);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilter(casAuthenticationFilter())
.addFilterBefore(requestLogoutFilter(), LogoutFilter.class)
.addFilterBefore(singleSignOutFilter(), CasAuthenticationFilter.class)
.authorizeRequests().antMatchers(USER_AUTH_INTERCEPT_PATTERN).fullyAuthenticated()
.and().authorizeRequests().antMatchers(NEW_COMMENT_AUTH_INTERCEPT_PATTERN).fullyAuthenticated()
.and().authorizeRequests().antMatchers(FLAG_COMMENT_AUTH_INTERCEPT_PATTERN).fullyAuthenticated();
http.exceptionHandling().authenticationEntryPoint(casAuthenticationEntryPoint());
http.csrf().disable();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(casAuthenticationProvider());
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
public CasAuthenticationEntryPoint casAuthenticationEntryPoint() {
CasAuthenticationEntryPoint casAuthenticationEntryPoint = new CasAuthenticationEntryPoint() {
@Override
protected String createServiceUrl(final HttpServletRequest request, final HttpServletResponse response) {
return getCasValidationPath(request);
}
};
casAuthenticationEntryPoint.setLoginUrl(runtimeConfiguration.getCasConfiguration().getLoginUrl());
casAuthenticationEntryPoint.setServiceProperties(serviceProperties());
return casAuthenticationEntryPoint;
}
private String getCasValidationPath(HttpServletRequest request) {
validateHostname(request);
return Link.toSitelessHandler().toPath(CAS_VALIDATION_URI).get(request);
}
private void validateHostname(HttpServletRequest request) {
ClientEndpoint clientEndpoint = ClientEndpoint.get(request);
Set<String> hostNames = siteSet.getSites().stream()
.map((Site site) -> site.getRequestScheme().getHostName())
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toSet());
if (!hostNames.isEmpty() && !hostNames.contains(clientEndpoint.getHostname())) {
throw new AccessDeniedException(String.format("Attempt to validate against foreign hostname %s. " +
"Possible hijack attempt.", clientEndpoint.getHostname()));
}
}
}
|
package model;
import java.io.IOException;
import org.apache.log4j.Logger;
public class ShellNotificationTarget implements NotificationTarget {
static Logger logger = Logger.getLogger(ShellNotificationTarget.class);
String template;
Runtime runtime;
int suppressedMinutes = 0;
public ShellNotificationTarget(String template) {
this.template = template;
this.runtime = Runtime.getRuntime();
}
public void suppressUntil(int contestMinutes) {
this.suppressedMinutes = contestMinutes;
}
@Override
public void notify(LoggableEvent event) {
if (event.time < suppressedMinutes) {
return;
}
String command = substituteTags(event);
try {
logger.debug(String.format("Executing: %s", command));
runtime.exec(command);
} catch (IOException e) {
logger.error(String.format("Error executing '%s':%s", command, e));
}
}
private String substituteTags(LoggableEvent event) {
String output = template;
if (event.team != null) {
output = output.replace("{teamId}", Integer.toString(event.team.getTeamNumber()));
}
if (event.submission != null) {
output = output.replace("{runId}", Integer.toString(event.submission.id));
}
if (event.submission != null) {
output = output.replace("{problemLetter}", event.submission.problem.getLetter());
}
output = output.replace("{time}", Integer.toString(event.time));
if (event.supplements != null) {
for (String key : event.supplements.keySet()) {
String value = event.supplements.get(key);
output = output.replace("{"+key+"}", value);
}
}
return output;
}
}
|
package org.cyclops.integratedtunnels.core;
import com.google.common.collect.Lists;
import net.minecraft.block.Block;
import net.minecraft.block.SoundType;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraft.world.WorldServer;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.ForgeEventFactory;
import net.minecraftforge.event.world.BlockEvent;
import org.cyclops.commoncapabilities.api.ingredient.IIngredientMatcher;
import org.cyclops.commoncapabilities.api.ingredient.IngredientComponent;
import org.cyclops.commoncapabilities.api.ingredient.storage.IIngredientComponentStorage;
import org.cyclops.cyclopscore.helper.BlockHelpers;
import org.cyclops.cyclopscore.helper.Helpers;
import org.cyclops.cyclopscore.ingredient.collection.FilteredIngredientCollectionIterator;
import org.cyclops.integratedtunnels.GeneralConfig;
import org.cyclops.integratedtunnels.IntegratedTunnels;
import org.cyclops.integratedtunnels.api.world.IBlockBreakHandler;
import org.cyclops.integratedtunnels.api.world.IBlockBreakHandlerRegistry;
import org.cyclops.integratedtunnels.api.world.IBlockPlaceHandler;
import org.cyclops.integratedtunnels.api.world.IBlockPlaceHandlerRegistry;
import org.cyclops.integratedtunnels.core.helper.obfuscation.ObfuscationHelpers;
import javax.annotation.Nonnull;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
/**
* An item storage for world block placement.
* @author rubensworks
*/
public class ItemStorageBlockWrapper implements IIngredientComponentStorage<ItemStack, Integer> {
private final boolean writeOnly;
private final WorldServer world;
private final BlockPos pos;
private final EnumFacing side;
private final EnumHand hand;
private final boolean blockUpdate;
private final int fortune;
private final boolean silkTouch;
private final boolean ignoreReplacable;
private final boolean breakOnNoDrops;
private IBlockBreakHandler blockBreakHandler = null;
private List<ItemStack> cachedDrops = null;
public ItemStorageBlockWrapper(boolean writeOnly, WorldServer world, BlockPos pos, EnumFacing side, EnumHand hand,
boolean blockUpdate, int fortune, boolean silkTouch, boolean ignoreReplacable,
boolean breakOnNoDrops) {
this.writeOnly = writeOnly;
this.world = world;
this.pos = pos;
this.side = side;
this.hand = hand;
this.blockUpdate = blockUpdate;
this.fortune = fortune;
this.silkTouch = silkTouch;
this.ignoreReplacable = ignoreReplacable;
this.breakOnNoDrops = breakOnNoDrops;
}
protected void sendBlockUpdate() {
world.neighborChanged(pos, Blocks.AIR, pos);
}
protected IBlockBreakHandler getBlockBreakHandler(IBlockState blockState, World world, BlockPos pos, EntityPlayer player) {
return IntegratedTunnels._instance.getRegistryManager().getRegistry(IBlockBreakHandlerRegistry.class)
.getHandler(blockState, world, pos, player);
}
protected void removeBlock(IBlockState blockState, EntityPlayer player) {
if (blockBreakHandler != null) {
blockBreakHandler.breakBlock(blockState, world, pos, player);
} else {
blockState.getBlock().removedByPlayer(blockState, world, pos, player, false);
}
if (GeneralConfig.worldInteractionEvents) {
world.playEvent(2001, pos, Block.getStateId(blockState)); // Particles + Sound
}
if (blockUpdate) {
sendBlockUpdate();
}
}
protected List<ItemStack> getItemStacks() {
if (writeOnly) {
if (!world.isAirBlock(pos)) {
boolean isDestReplaceable = world.getBlockState(pos).getBlock().isReplaceable(world, pos);
if (!isDestReplaceable || !ignoreReplacable) {
IBlockState blockState = world.getBlockState(pos);
return Lists.newArrayList(BlockHelpers.getItemStackFromBlockState(blockState));
}
}
} else {
if (cachedDrops != null) {
return cachedDrops;
}
if (!world.isAirBlock(pos)) {
IBlockState blockState = world.getBlockState(pos);
EntityPlayer player = PlayerHelpers.getFakePlayer(world);
PlayerHelpers.setPlayerState(player, hand, pos, 0, 0, 0, side, false);
blockBreakHandler = getBlockBreakHandler(blockState, world, pos, player);
if (blockBreakHandler != null) {
cachedDrops = blockBreakHandler.getDrops(blockState, world, pos, player);
} else {
BlockEvent.BreakEvent blockBreakEvent = new BlockEvent.BreakEvent(world, pos, blockState, player);
if (!MinecraftForge.EVENT_BUS.post(blockBreakEvent)) {
boolean doSilkTouch = silkTouch && blockState.getBlock().canSilkHarvest(world, pos, blockState, player);
List<ItemStack> drops;
if (doSilkTouch) {
drops = Lists.newArrayList(ObfuscationHelpers.getSilkTouchDrop(blockState));
} else {
// Create a mutable arraylist, because the given one may not be mutable.
drops = Lists.newArrayList(blockState.getBlock().getDrops(world, pos, blockState, fortune));
}
float dropChance = ForgeEventFactory.fireBlockHarvesting(drops, world, pos, blockState, fortune,
1, doSilkTouch, player);
if (drops.size() == 0) {
// Remove the block if it dropped nothing (and will drop nothing)
if (breakOnNoDrops) {
removeBlock(blockState, player);
}
drops = Lists.newArrayList(ItemStack.EMPTY);
} else {
// Make sure there are no empty stacks in the list
Iterator<ItemStack> it = drops.iterator();
while (it.hasNext()) {
if (it.next().isEmpty()) {
it.remove();
}
}
}
if (world.rand.nextFloat() <= dropChance) {
return cachedDrops = drops;
}
}
}
}
}
return Lists.newArrayList(ItemStack.EMPTY);
}
protected IBlockPlaceHandler getBlockPlaceHandler(ItemStack itemStack, World world, BlockPos pos, EnumFacing side,
float hitX, float hitY, float hitZ, EntityPlayer player) {
return IntegratedTunnels._instance.getRegistryManager().getRegistry(IBlockPlaceHandlerRegistry.class)
.getHandler(itemStack, world, pos, side, hitX, hitY, hitZ, player);
}
protected ItemStack setItemStack(ItemStack itemStack, boolean simulate) {
if (!itemStack.isEmpty() && itemStack.getCount() == 1) {
Item item = itemStack.getItem();
if (item instanceof ItemBlock) {
ItemBlock itemBlock = (ItemBlock) item;
EntityPlayer player = PlayerHelpers.getFakePlayer(world);
PlayerHelpers.setPlayerState(player, hand, pos, 0, 0, 0, side, false);
IBlockPlaceHandler blockPlaceHandler = getBlockPlaceHandler(itemStack, world, pos, side.getOpposite(),
0, 0, 0, player);
if (blockPlaceHandler != null) {
blockPlaceHandler.placeBlock(itemStack, world, pos, side.getOpposite(), 0, 0, 0, player);
} else {
IBlockState blockState = itemBlock.getBlock().getStateForPlacement(world, pos, side.getOpposite(),
0, 0, 0, itemStack.getMetadata(), player, hand);
if (world.mayPlace(itemBlock.getBlock(), pos, false, side.getOpposite(), null)
&& (simulate || itemBlock
.placeBlockAt(itemStack, player, world, pos, side.getOpposite(), 0, 0, 0, blockState))) {
if (!simulate) {
itemBlock.getBlock().onBlockPlacedBy(world, pos, blockState, player, itemStack);
if (GeneralConfig.worldInteractionEvents) {
SoundType soundtype = world.getBlockState(pos).getBlock().getSoundType(world.getBlockState(pos), world, pos, player);
world.playSound(player, pos, soundtype.getPlaceSound(), SoundCategory.BLOCKS, (soundtype.getVolume() + 1.0F) / 2.0F, soundtype.getPitch() * 0.8F); // Sound
}
if (blockUpdate) {
sendBlockUpdate();
}
}
return ItemStack.EMPTY;
}
}
}
}
return itemStack;
}
@Override
public IngredientComponent<ItemStack, Integer> getComponent() {
return IngredientComponent.ITEMSTACK;
}
@Override
public Iterator<ItemStack> iterator() {
return Lists.newArrayList(getItemStacks()).iterator();
}
@Override
public Iterator<ItemStack> iterator(@Nonnull ItemStack prototype, Integer matchCondition) {
return new FilteredIngredientCollectionIterator<>(this, getComponent().getMatcher(), prototype, matchCondition);
}
@Override
public long getMaxQuantity() {
return 1;
}
@Override
public ItemStack insert(@Nonnull ItemStack stack, boolean simulate) {
List<ItemStack> itemStacks = getItemStacks();
if (itemStacks.size() > 0) {
ItemStack itemStack = itemStacks.get(0);
if (!itemStack.isEmpty()) {
return stack;
}
}
if (stack.isEmpty()) {
return stack;
}
ItemStack remaining = stack.copy();
if (!setItemStack(remaining.splitStack(1), simulate).isEmpty()) {
return stack;
}
return remaining;
}
protected void postExtract() {
boolean allEmpty = true;
for (ItemStack stack : getItemStacks()) {
if (!stack.isEmpty()) {
allEmpty = false;
break;
}
}
if (allEmpty) {
IBlockState blockState = world.getBlockState(pos);
EntityPlayer player = PlayerHelpers.getFakePlayer(world);
player.setActiveHand(hand);
removeBlock(blockState, player);
}
}
@Override
public ItemStack extract(@Nonnull ItemStack prototype, Integer matchCondition, boolean simulate) {
IIngredientMatcher<ItemStack, Integer> matcher = getComponent().getMatcher();
Integer quantityFlag = getComponent().getPrimaryQuantifier().getMatchCondition();
Integer subMatchCondition = matcher.withoutCondition(matchCondition, quantityFlag);
List<ItemStack> itemStacks = getItemStacks();
if (itemStacks.isEmpty()) {
return ItemStack.EMPTY;
}
ListIterator<ItemStack> it = itemStacks.listIterator();
while (it.hasNext()) {
ItemStack itemStack = it.next();
if (matcher.matches(prototype, itemStack, subMatchCondition)
&& (!matcher.hasCondition(matchCondition, quantityFlag) || itemStack.getCount() >= prototype.getCount())) {
itemStack = itemStack.copy();
ItemStack ret = itemStack.splitStack(Helpers.castSafe(prototype.getCount()));
if (!simulate) {
if (itemStack.isEmpty()) {
it.remove();
} else {
it.set(itemStack);
}
}
// Check if all items have been extracted, if so, remove block
if (!simulate) {
postExtract();
}
return ret;
}
}
return ItemStack.EMPTY;
}
@Override
public ItemStack extract(long maxQuantity, boolean simulate) {
List<ItemStack> itemStacks = getItemStacks();
if (itemStacks.isEmpty()) {
return ItemStack.EMPTY;
}
ItemStack itemStack = itemStacks.get(0);
itemStack = itemStack.copy();
ItemStack ret = itemStack.splitStack(Helpers.castSafe(maxQuantity));
if (!simulate) {
if (itemStack.isEmpty()) {
itemStacks.remove(0);
} else {
itemStacks.set(0, itemStack);
}
}
// Check if all items have been extracted, if so, remove block
if (!simulate) {
postExtract();
}
return ret;
}
}
|
package org.spongepowered.common.mixin.core.world;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import co.aikar.timings.TimingHistory;
import co.aikar.timings.Timings;
import co.aikar.timings.WorldTimingsHandler;
import com.flowpowered.math.vector.Vector3d;
import com.google.common.collect.ImmutableList;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.crash.CrashReport;
import net.minecraft.crash.CrashReportCategory;
import net.minecraft.entity.EnumCreatureType;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.network.Packet;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.management.PlayerManager;
import net.minecraft.server.management.ServerConfigurationManager;
import net.minecraft.tileentity.TileEntityPiston;
import net.minecraft.util.BlockPos;
import net.minecraft.util.IProgressUpdate;
import net.minecraft.util.ITickable;
import net.minecraft.util.ReportedException;
import net.minecraft.world.NextTickListEntry;
import net.minecraft.world.Teleporter;
import net.minecraft.world.WorldServer;
import net.minecraft.world.WorldServer.ServerBlockEventList;
import net.minecraft.world.WorldSettings;
import net.minecraft.world.biome.BiomeGenBase;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.gen.ChunkProviderServer;
import org.apache.logging.log4j.Level;
import org.spongepowered.api.block.ScheduledBlockUpdate;
import org.spongepowered.api.block.tileentity.TileEntity;
import org.spongepowered.api.effect.particle.ParticleEffect;
import org.spongepowered.api.effect.sound.SoundType;
import org.spongepowered.api.entity.Entity;
import org.spongepowered.api.entity.EntityTypes;
import org.spongepowered.api.entity.Transform;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.entity.living.player.User;
import org.spongepowered.api.event.SpongeEventFactory;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.event.cause.NamedCause;
import org.spongepowered.api.event.cause.entity.spawn.SpawnCause;
import org.spongepowered.api.event.cause.entity.spawn.SpawnTypes;
import org.spongepowered.api.event.cause.entity.spawn.WeatherSpawnCause;
import org.spongepowered.api.event.entity.ConstructEntityEvent;
import org.spongepowered.api.event.world.ChangeWorldWeatherEvent;
import org.spongepowered.api.util.annotation.NonnullByDefault;
import org.spongepowered.api.world.GeneratorType;
import org.spongepowered.api.world.GeneratorTypes;
import org.spongepowered.api.world.PortalAgent;
import org.spongepowered.api.world.PortalAgentType;
import org.spongepowered.api.world.PortalAgentTypes;
import org.spongepowered.api.world.storage.WorldProperties;
import org.spongepowered.api.world.storage.WorldStorage;
import org.spongepowered.api.world.weather.Weather;
import org.spongepowered.api.world.weather.Weathers;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import org.spongepowered.asm.mixin.injection.callback.LocalCapture;
import org.spongepowered.common.SpongeImpl;
import org.spongepowered.common.config.SpongeConfig;
import org.spongepowered.common.effect.particle.SpongeParticleEffect;
import org.spongepowered.common.effect.particle.SpongeParticleHelper;
import org.spongepowered.common.event.CauseTracker;
import org.spongepowered.common.event.SpongeCommonEventFactory;
import org.spongepowered.common.interfaces.IMixinNextTickListEntry;
import org.spongepowered.common.interfaces.block.IMixinBlock;
import org.spongepowered.common.interfaces.block.tile.IMixinTileEntity;
import org.spongepowered.common.interfaces.entity.IMixinEntity;
import org.spongepowered.common.interfaces.server.management.IMixinPlayerManager;
import org.spongepowered.common.interfaces.world.IMixinWorldServer;
import org.spongepowered.common.interfaces.world.gen.IMixinChunkProviderServer;
import org.spongepowered.common.mixin.plugin.interfaces.IModData;
import org.spongepowered.common.util.SpongeHooks;
import org.spongepowered.common.util.StaticMixinHelper;
import org.spongepowered.common.util.VecHelper;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;
import java.util.UUID;
import javax.annotation.Nullable;
@NonnullByDefault
@Mixin(WorldServer.class)
public abstract class MixinWorldServer extends MixinWorld implements IMixinWorldServer {
private static final String PROFILER_SS = "Lnet/minecraft/profiler/Profiler;startSection(Ljava/lang/String;)V";
private static final String PROFILER_ESS = "Lnet/minecraft/profiler/Profiler;endStartSection(Ljava/lang/String;)V";
@Shadow @Final private Set<NextTickListEntry> pendingTickListEntriesHashSet;
@Shadow @Final private TreeSet<NextTickListEntry> pendingTickListEntriesTreeSet;
@Shadow private Teleporter worldTeleporter;
@Shadow private ServerBlockEventList[] blockEventQueue;
@Shadow private int blockEventCacheIndex;
@Shadow private int updateEntityTick;
@Shadow @Nullable public abstract net.minecraft.entity.Entity getEntityFromUuid(UUID uuid);
@Shadow public abstract void resetUpdateEntityTick();
@Shadow public abstract PlayerManager getPlayerManager();
protected long weatherStartTime;
protected Weather prevWeather;
private int chunkGCTickCount = 0;
private int chunkGCLoadThreshold = 0;
private int chunkGCTickInterval = 600;
private boolean isCapturingBlocks = false;
@Inject(method = "<init>", at = @At("RETURN"))
public void onConstruct(CallbackInfo ci) {
this.prevWeather = getWeather();
this.weatherStartTime = this.worldInfo.getWorldTotalTime();
PortalAgentType portalAgentType = ((WorldProperties) this.worldInfo).getPortalAgentType();
if (!portalAgentType.equals(PortalAgentTypes.DEFAULT)) {
try {
this.worldTeleporter = (Teleporter) portalAgentType.getPortalAgentClass().getConstructor(new Class<?>[] {WorldServer.class})
.newInstance(new Object[] {this});
} catch (Exception e) {
SpongeImpl.getLogger().log(Level.ERROR, "Could not create PortalAgent of type " + portalAgentType.getId()
+ " for world " + this.getName() + ": " + e.getMessage() + ". Falling back to default...");
}
}
this.timings = new WorldTimingsHandler((net.minecraft.world.World) (Object) this);
this.causeTracker = new CauseTracker((net.minecraft.world.World) (Object) this);
updateWorldGenerator();
this.chunkGCLoadThreshold = this.getActiveConfig().getConfig().getWorld().getChunkLoadThreadhold();
this.chunkGCTickInterval = this.getActiveConfig().getConfig().getWorld().getTickInterval();
}
@Inject(method = "createSpawnPosition(Lnet/minecraft/world/WorldSettings;)V", at = @At("HEAD"), cancellable = true)
public void onCreateSpawnPosition(WorldSettings settings, CallbackInfo ci) {
GeneratorType generatorType = (GeneratorType) settings.getTerrainType();
if (generatorType != null && generatorType.equals(GeneratorTypes.THE_END)) {
this.worldInfo.setSpawn(new BlockPos(55, 60, 0));
ci.cancel();
}
}
@Redirect(method = "updateBlocks", at = @At(value = "INVOKE", target = "Lnet/minecraft/block/Block;randomTick(Lnet/minecraft/world/World;Lnet/minecraft/util/BlockPos;Lnet/minecraft/block/state/IBlockState;Ljava/util/Random;)V"))
public void onUpdateBlocks(Block block, net.minecraft.world.World worldIn, BlockPos pos, IBlockState state, Random rand) {
final CauseTracker causeTracker = this.getCauseTracker();
if (causeTracker.hasTickingBlock() || causeTracker.isIgnoringCaptures()) {
block.randomTick(worldIn, pos, state, rand);
return;
}
causeTracker.randomTickBlock(block, pos, state, rand);
}
@Redirect(method = "updateBlocks", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/WorldServer;isRainingAt(Lnet/minecraft/util/BlockPos;)Z"))
private boolean onLightningCheck(WorldServer world, BlockPos blockPos) {
if (world.isRainingAt(blockPos)) {
Transform<org.spongepowered.api.world.World> transform = new Transform<>((org.spongepowered.api.world.World) this,
VecHelper.toVector(blockPos).toDouble());
SpawnCause cause = WeatherSpawnCause.builder().weather(this.getWeather()).type(SpawnTypes.WEATHER).build();
ConstructEntityEvent.Pre event = SpongeEventFactory.createConstructEntityEventPre(Cause.of(NamedCause.source(cause)),
EntityTypes.LIGHTNING, transform);
SpongeImpl.postEvent(event);
return !event.isCancelled();
}
return false;
}
@Redirect(method = "updateBlockTick", at = @At(value = "INVOKE", target = "Ljava/util/Set;add(Ljava/lang/Object;)Z"), remap = false)
public boolean onQueueScheduledBlockUpdate(Set<NextTickListEntry> pendingSet, Object obj) {
final CauseTracker causeTracker = this.getCauseTracker();
// If we don't have a notifier or the nextticklistentry has one, skip
if (causeTracker.isIgnoringCaptures() || !causeTracker.hasNotifier() || ((IMixinNextTickListEntry) obj).hasSourceUser()) {
pendingSet.add((NextTickListEntry) obj);
return true;
}
IMixinNextTickListEntry nextTickListEntry = (IMixinNextTickListEntry) obj;
User sourceUser = causeTracker.getCurrentNotifier().get();
nextTickListEntry.setSourceUser(sourceUser);
if (causeTracker.hasTickingTileEntity()) {
nextTickListEntry.setCurrentTickTileEntity(causeTracker.getCurrentTickTileEntity().get());
}
if (causeTracker.hasTickingBlock()) {
nextTickListEntry.setCurrentTickBlock(causeTracker.getCurrentTickBlock().get());
}
pendingSet.add((NextTickListEntry) obj);
return true;
}
@Redirect(method = "updateBlockTick", at = @At(value = "INVOKE", target="Lnet/minecraft/block/Block;updateTick(Lnet/minecraft/world/World;Lnet/minecraft/util/BlockPos;Lnet/minecraft/block/state/IBlockState;Ljava/util/Random;)V"))
public void onUpdateBlockTick(Block block, net.minecraft.world.World worldIn, BlockPos pos, IBlockState state, Random rand) {
final CauseTracker causeTracker = this.getCauseTracker();
if (causeTracker.isIgnoringCaptures()) {
block.updateTick(worldIn, pos, state, rand);
return;
}
causeTracker.updateTickBlock(block, pos, state, rand);
}
@Inject(method = "tickUpdates", at = @At(value = "INVOKE_STRING", target = PROFILER_SS, args = "ldc=cleaning"))
private void onTickUpdatesCleanup(boolean flag, CallbackInfoReturnable<Boolean> cir) {
this.timings.scheduledBlocksCleanup.startTiming();
}
@Inject(method = "tickUpdates", at = @At(value = "INVOKE_STRING", target = PROFILER_SS, args = "ldc=ticking"))
private void onTickUpdatesTickingStart(boolean flag, CallbackInfoReturnable<Boolean> cir) {
this.timings.scheduledBlocksCleanup.stopTiming();
this.timings.scheduledBlocksTicking.startTiming();
}
@Inject(method = "tickUpdates", at = @At("RETURN"))
private void onTickUpdatesTickingEnd(CallbackInfoReturnable<Boolean> cir) {
this.timings.scheduledBlocksTicking.stopTiming();
}
// Before ticking pending updates, we need to check if we have any tracking info and set it accordingly
@Inject(method = "tickUpdates", at = @At(value = "INVOKE", target = "Lnet/minecraft/block/Block;updateTick(Lnet/minecraft/world/World;Lnet/minecraft/util/BlockPos;"
+ "Lnet/minecraft/block/state/IBlockState;Ljava/util/Random;)V"), locals = LocalCapture.CAPTURE_FAILHARD)
public void onUpdateTick(boolean p_72955_1_, CallbackInfoReturnable<Boolean> cir, int i, Iterator<NextTickListEntry> iterator, NextTickListEntry nextticklistentry1, int k, IBlockState iblockstate) {
final CauseTracker causeTracker = this.getCauseTracker();
IMixinNextTickListEntry nextTickListEntry = (IMixinNextTickListEntry) nextticklistentry1;
causeTracker.currentPendingBlockUpdate = nextTickListEntry;
}
// This ticks pending updates to blocks, Requires mixin for NextTickListEntry so we use the correct tracking
@Redirect(method = "tickUpdates", at = @At(value = "INVOKE", target = "Lnet/minecraft/block/Block;updateTick(Lnet/minecraft/world/World;Lnet/minecraft/util/BlockPos;"
+ "Lnet/minecraft/block/state/IBlockState;Ljava/util/Random;)V"))
public void onUpdateTick(Block block, net.minecraft.world.World worldIn, BlockPos pos, IBlockState state, Random rand) {
final CauseTracker causeTracker = this.getCauseTracker();
if (causeTracker.isIgnoringCaptures()) {
block.updateTick(worldIn, pos, state, rand);
return;
}
IMixinBlock spongeBlock = (IMixinBlock) block;
spongeBlock.getTimingsHandler().startTiming();
causeTracker.updateTickBlock(block, pos, state, rand);
spongeBlock.getTimingsHandler().stopTiming();
}
@Inject(method = "tick", at = @At(value = "INVOKE_STRING", target = PROFILER_ESS, args = "ldc=tickPending") )
private void onBeginTickBlockUpdate(CallbackInfo ci) {
this.timings.scheduledBlocks.startTiming();
}
@Inject(method = "tick", at = @At(value = "INVOKE_STRING", target = PROFILER_ESS, args = "ldc=tickBlocks") )
private void onAfterTickBlockUpdate(CallbackInfo ci) {
this.timings.scheduledBlocks.stopTiming();
this.timings.chunkTicks.startTiming();
}
@Inject(method = "tick", at = @At(value = "INVOKE_STRING", target = PROFILER_ESS, args = "ldc=chunkMap") )
private void onBeginUpdateBlocks(CallbackInfo ci) {
this.timings.chunkTicks.stopTiming();
this.timings.doChunkMap.startTiming();
}
@Inject(method = "tick", at = @At(value = "INVOKE_STRING", target = PROFILER_ESS, args = "ldc=village") )
private void onBeginUpdateVillage(CallbackInfo ci) {
this.timings.doChunkMap.stopTiming();
this.timings.doVillages.startTiming();
}
@Inject(method = "tick", at = @At(value = "INVOKE_STRING", target = PROFILER_ESS, args = "ldc=portalForcer") )
private void onBeginUpdatePortal(CallbackInfo ci) {
this.timings.doVillages.stopTiming();
this.timings.doPortalForcer.startTiming();
}
@Inject(method = "tick", at = @At(value = "INVOKE", target = "Lnet/minecraft/profiler/Profiler;endSection()V") )
private void onEndUpdatePortal(CallbackInfo ci) {
this.timings.doPortalForcer.stopTiming();
}
@Inject(method = "tick", at = @At("RETURN"))
public void onTickEnd(CallbackInfo ci) {
// Make sure we clear our current notifier
this.getCauseTracker().setCurrentNotifier(null);
// Clean up any leaked chunks
this.doChunkGC();
}
// Chunk GC
private void doChunkGC() {
this.chunkGCTickCount++;
ChunkProviderServer chunkProviderServer = (ChunkProviderServer) this.getChunkProvider();
int chunkLoadCount = this.getChunkProvider().getLoadedChunkCount();
if (chunkLoadCount >= this.chunkGCLoadThreshold && this.chunkGCLoadThreshold > 0) {
chunkLoadCount = 0;
} else if (this.chunkGCTickCount >= this.chunkGCTickInterval && this.chunkGCTickInterval > 0) {
this.chunkGCTickCount = 0;
} else {
return;
}
for (Chunk chunk : chunkProviderServer.loadedChunks) {
// If a player is currently using the chunk, skip it
if (((IMixinPlayerManager) this.getPlayerManager()).isChunkInUse(chunk.xPosition, chunk.zPosition)) {
continue;
}
// Queue chunk for unload
chunkProviderServer.dropChunk(chunk.xPosition, chunk.zPosition);
SpongeHooks.logChunkGCQueueUnload(chunkProviderServer.worldObj, chunk);
}
}
@Inject(method = "saveAllChunks", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/gen/ChunkProviderServer;func_152380_a()Ljava/util/List;"), cancellable = true)
public void onSaveAllChunks(boolean saveAllChunks, IProgressUpdate progressCallback, CallbackInfo ci) {
// The chunk GC handles all queuing for chunk unloads so we cancel here to avoid it during a save.
if (this.chunkGCTickInterval > 0) {
ci.cancel();
}
}
/**
* @author blood - May 26th, 2016
*
* @reason Rewritten due to the amount of injections required for both
* timing and capturing.
*/
@Overwrite
public void updateEntities()
{
if (this.playerEntities.isEmpty()) {
if (this.updateEntityTick++ >= 1200) {
return;
}
} else {
this.resetUpdateEntityTick();
}
this.theProfiler.startSection("entities");
this.theProfiler.startSection("global");
// Sponge start
this.timings.entityTick.startTiming();
co.aikar.timings.TimingHistory.entityTicks += this.loadedEntityList.size();
// Sponge end
for (int i = 0; i < this.weatherEffects.size(); ++i)
{
net.minecraft.entity.Entity entity = this.weatherEffects.get(i);
IMixinEntity spongeEntity = (IMixinEntity) entity; // Sponge
try
{
++entity.ticksExisted;
// Sponge start - handle tracking and timings
boolean captureBlocks = this.causeTracker.isCapturingBlocks();
this.causeTracker.setCaptureBlocks(true);
this.causeTracker.preTrackEntity(spongeEntity);
spongeEntity.getTimingsHandler().startTiming();
entity.onUpdate();
spongeEntity.getTimingsHandler().stopTiming();
updateRotation(entity);
SpongeCommonEventFactory.handleEntityMovement(entity);
this.causeTracker.postTrackEntity();
this.causeTracker.setCaptureBlocks(captureBlocks);
// Sponge end
}
catch (Throwable throwable2)
{
spongeEntity.getTimingsHandler().stopTiming(); // Sponge
CrashReport crashreport = CrashReport.makeCrashReport(throwable2, "Ticking entity");
CrashReportCategory crashreportcategory = crashreport.makeCategory("Entity being ticked");
if (entity == null)
{
crashreportcategory.addCrashSection("Entity", "~~NULL~~");
}
else
{
entity.addEntityCrashInfo(crashreportcategory);
}
throw new ReportedException(crashreport);
}
if (entity.isDead)
{
this.weatherEffects.remove(i
}
}
// Sponge start
this.timings.entityTick.stopTiming();
this.timings.entityRemoval.startTiming();
// Sponge end
this.theProfiler.endStartSection("remove");
this.loadedEntityList.removeAll(this.unloadedEntityList);
for (int k = 0; k < this.unloadedEntityList.size(); ++k)
{
net.minecraft.entity.Entity entity1 = this.unloadedEntityList.get(k);
int j = entity1.chunkCoordX;
int l1 = entity1.chunkCoordZ;
if (entity1.addedToChunk && this.isChunkLoaded(j, l1, true))
{
this.getChunkFromChunkCoords(j, l1).removeEntity(entity1);
}
}
for (int l = 0; l < this.unloadedEntityList.size(); ++l)
{
this.onEntityRemoved(this.unloadedEntityList.get(l));
}
this.unloadedEntityList.clear();
this.theProfiler.endStartSection("regular");
this.timings.entityRemoval.stopTiming(); // Sponge
for (int i1 = 0; i1 < this.loadedEntityList.size(); ++i1)
{
net.minecraft.entity.Entity entity2 = this.loadedEntityList.get(i1);
IMixinEntity spongeEntity = (IMixinEntity) entity2; // Sponge
if (entity2.ridingEntity != null)
{
if (!entity2.ridingEntity.isDead && entity2.ridingEntity.riddenByEntity == entity2)
{
continue;
}
entity2.ridingEntity.riddenByEntity = null;
entity2.ridingEntity = null;
}
this.theProfiler.startSection("tick");
this.timings.entityTick.startTiming();
if (!entity2.isDead)
{
try
{
spongeEntity.getTimingsHandler().startTiming(); // Sponge
this.updateEntity(entity2);
spongeEntity.getTimingsHandler().stopTiming(); // Sponge
}
catch (Throwable throwable1)
{
spongeEntity.getTimingsHandler().stopTiming(); // Sponge
CrashReport crashreport1 = CrashReport.makeCrashReport(throwable1, "Ticking entity");
CrashReportCategory crashreportcategory2 = crashreport1.makeCategory("Entity being ticked");
entity2.addEntityCrashInfo(crashreportcategory2);
throw new ReportedException(crashreport1);
}
}
this.timings.entityTick.stopTiming(); // Sponge
this.theProfiler.endSection();
this.theProfiler.startSection("remove");
this.timings.entityRemoval.startTiming(); // Sponge
if (entity2.isDead)
{
int k1 = entity2.chunkCoordX;
int i2 = entity2.chunkCoordZ;
if (entity2.addedToChunk && this.isChunkLoaded(k1, i2, true))
{
this.getChunkFromChunkCoords(k1, i2).removeEntity(entity2);
}
this.loadedEntityList.remove(i1
this.onEntityRemoved(entity2);
}
this.timings.entityRemoval.stopTiming();
this.theProfiler.endSection();
}
this.theProfiler.endStartSection("blockEntities");
// Sponge start - moved up to clean up tile entities before ticking
this.timings.tileEntityRemoval.startTiming();
if (!this.tileEntitiesToBeRemoved.isEmpty())
{
this.tickableTileEntities.removeAll(this.tileEntitiesToBeRemoved);
this.loadedTileEntityList.removeAll(this.tileEntitiesToBeRemoved);
this.tileEntitiesToBeRemoved.clear();
}
this.timings.tileEntityRemoval.stopTiming();
// Sponge end
this.processingLoadedTiles = true;
Iterator<net.minecraft.tileentity.TileEntity> iterator = this.tickableTileEntities.iterator();
while (iterator.hasNext())
{
this.timings.tileEntityTick.startTiming(); // Sponge
net.minecraft.tileentity.TileEntity tileentity = iterator.next();
IMixinTileEntity spongeTile = (IMixinTileEntity) tileentity;
if (!tileentity.isInvalid() && tileentity.hasWorldObj())
{
BlockPos blockpos = tileentity.getPos();
if (this.isBlockLoaded(blockpos) && this.worldBorder.contains(blockpos))
{
try
{
// Sponge start - handle captures and timings
boolean captureBlocks = this.causeTracker.isCapturingBlocks();
this.causeTracker.setCaptureBlocks(true);
this.causeTracker.preTrackTileEntity((TileEntity) tileentity);
spongeTile.getTimingsHandler().startTiming();
((ITickable)tileentity).update();
spongeTile.getTimingsHandler().stopTiming();
this.causeTracker.postTrackTileEntity();
this.causeTracker.setCaptureBlocks(captureBlocks);
// Sponge end
}
catch (Throwable throwable)
{
spongeTile.getTimingsHandler().stopTiming(); // Sponge
CrashReport crashreport2 = CrashReport.makeCrashReport(throwable, "Ticking block entity");
CrashReportCategory crashreportcategory1 = crashreport2.makeCategory("Block entity being ticked");
tileentity.addInfoToCrashReport(crashreportcategory1);
throw new ReportedException(crashreport2);
}
}
}
// Sponge start
this.timings.tileEntityTick.stopTiming();
this.timings.tileEntityRemoval.startTiming();
// Sponge end
if (tileentity.isInvalid())
{
iterator.remove();
this.loadedTileEntityList.remove(tileentity);
if (this.isBlockLoaded(tileentity.getPos()))
{
this.getChunkFromBlockCoords(tileentity.getPos()).removeTileEntity(tileentity.getPos());
}
}
this.timings.tileEntityRemoval.stopTiming(); // Sponge
}
this.processingLoadedTiles = false;
this.timings.tileEntityPending.startTiming(); // Sponge
this.theProfiler.endStartSection("pendingBlockEntities");
if (!this.addedTileEntityList.isEmpty())
{
for (int j1 = 0; j1 < this.addedTileEntityList.size(); ++j1)
{
net.minecraft.tileentity.TileEntity tileentity1 = this.addedTileEntityList.get(j1);
if (!tileentity1.isInvalid())
{
if (!this.loadedTileEntityList.contains(tileentity1))
{
this.addTileEntity(tileentity1);
}
if (this.isBlockLoaded(tileentity1.getPos()))
{
this.getChunkFromBlockCoords(tileentity1.getPos()).addTileEntity(tileentity1.getPos(), tileentity1);
}
this.markBlockForUpdate(tileentity1.getPos());
}
}
this.addedTileEntityList.clear();
}
this.timings.tileEntityPending.stopTiming(); // Sponge
TimingHistory.tileEntityTicks += this.loadedTileEntityList.size(); // Sponge
this.theProfiler.endSection();
this.theProfiler.endSection();
}
@Override
public Collection<ScheduledBlockUpdate> getScheduledUpdates(int x, int y, int z) {
BlockPos position = new BlockPos(x, y, z);
ImmutableList.Builder<ScheduledBlockUpdate> builder = ImmutableList.builder();
for (NextTickListEntry sbu : this.pendingTickListEntriesTreeSet) {
if (sbu.position.equals(position)) {
builder.add((ScheduledBlockUpdate) sbu);
}
}
return builder.build();
}
private NextTickListEntry tmpScheduledObj;
@Redirect(method = "updateBlockTick(Lnet/minecraft/util/BlockPos;Lnet/minecraft/block/Block;II)V",
at = @At(value = "INVOKE", target = "Lnet/minecraft/world/NextTickListEntry;setPriority(I)V"))
private void onUpdateScheduledBlock(NextTickListEntry sbu, int priority) {
this.onCreateScheduledBlockUpdate(sbu, priority);
}
@Redirect(method = "scheduleBlockUpdate(Lnet/minecraft/util/BlockPos;Lnet/minecraft/block/Block;II)V",
at = @At(value = "INVOKE", target = "Lnet/minecraft/world/NextTickListEntry;setPriority(I)V"))
private void onCreateScheduledBlockUpdate(NextTickListEntry sbu, int priority) {
final CauseTracker causeTracker = this.getCauseTracker();
if (causeTracker.isIgnoringCaptures()) {
this.tmpScheduledObj = sbu;
return;
}
sbu.setPriority(priority);
((IMixinNextTickListEntry) sbu).setWorld((WorldServer) (Object) this);
if (!((net.minecraft.world.World)(Object) this).isBlockLoaded(sbu.position)) {
this.tmpScheduledObj = sbu;
return;
}
this.tmpScheduledObj = sbu;
}
@Override
public ScheduledBlockUpdate addScheduledUpdate(int x, int y, int z, int priority, int ticks) {
BlockPos pos = new BlockPos(x, y, z);
((WorldServer) (Object) this).scheduleBlockUpdate(pos, getBlockState(pos).getBlock(), ticks, priority);
ScheduledBlockUpdate sbu = (ScheduledBlockUpdate) this.tmpScheduledObj;
this.tmpScheduledObj = null;
return sbu;
}
@Override
public void removeScheduledUpdate(int x, int y, int z, ScheduledBlockUpdate update) {
// Note: Ignores position argument
this.pendingTickListEntriesHashSet.remove(update);
this.pendingTickListEntriesTreeSet.remove(update);
}
@Redirect(method = "updateAllPlayersSleepingFlag()V", at = @At(value = "INVOKE",
target = "Lnet/minecraft/entity/player/EntityPlayer;isSpectator()Z"))
public boolean isSpectatorOrIgnored(EntityPlayer entityPlayer) {
// spectators are excluded from the sleep tally in vanilla
// this redirect expands that check to include sleep-ignored players as well
boolean ignore = entityPlayer instanceof Player && ((Player)entityPlayer).isSleepingIgnored();
return ignore || entityPlayer.isSpectator();
}
@Redirect(method = "areAllPlayersAsleep()Z", at = @At(value = "INVOKE",
target = "Lnet/minecraft/entity/player/EntityPlayer;isPlayerFullyAsleep()Z"))
public boolean isPlayerFullyAsleep(EntityPlayer entityPlayer) {
// if isPlayerFullyAsleep() returns false areAllPlayerAsleep() breaks its loop and returns false
// this redirect forces it to return true if the player is sleep-ignored even if they're not sleeping
boolean ignore = entityPlayer instanceof Player && ((Player)entityPlayer).isSleepingIgnored();
return ignore || entityPlayer.isPlayerFullyAsleep();
}
@Redirect(method = "areAllPlayersAsleep()Z", at = @At(value = "INVOKE",
target = "Lnet/minecraft/entity/player/EntityPlayer;isSpectator()Z"))
public boolean isSpectatorAndNotIgnored(EntityPlayer entityPlayer) {
// if a player is marked as a spectator areAllPlayersAsleep() breaks its loop and returns false
// this redirect forces it to return false if a player is sleep-ignored even if they're a spectator
boolean ignore = entityPlayer instanceof Player && ((Player)entityPlayer).isSleepingIgnored();
return !ignore && entityPlayer.isSpectator();
}
@Override
public Optional<Entity> getEntity(UUID uuid) {
return Optional.ofNullable((Entity) this.getEntityFromUuid(uuid));
}
@Inject(method = "getSpawnListEntryForTypeAt", at = @At("HEAD"))
private void onGetSpawnList(EnumCreatureType creatureType, BlockPos pos, CallbackInfoReturnable<BiomeGenBase.SpawnListEntry> callbackInfo) {
StaticMixinHelper.gettingSpawnList = true;
}
@Inject(method = "newExplosion", at = @At(value = "HEAD"))
public void onExplosionHead(net.minecraft.entity.Entity entityIn, double x, double y, double z, float strength, boolean isFlaming, boolean isSmoking, CallbackInfoReturnable<net.minecraft.world.Explosion> cir) {
this.processingExplosion = true;
this.isCapturingBlocks = this.causeTracker.isCapturingBlocks();
this.causeTracker.setCaptureBlocks(false);
}
@Inject(method = "newExplosion", at = @At(value = "RETURN"))
public void onExplosionReturn(net.minecraft.entity.Entity entityIn, double x, double y, double z, float strength, boolean isFlaming, boolean isSmoking, CallbackInfoReturnable<net.minecraft.world.Explosion> cir) {
this.processingExplosion = false;
this.causeTracker.setCaptureBlocks(this.isCapturingBlocks);
}
@Override
public WorldStorage getWorldStorage() {
return (WorldStorage) ((WorldServer) (Object) this).theChunkProviderServer;
}
@Override
public PortalAgent getPortalAgent() {
return (PortalAgent) this.worldTeleporter;
}
@Override
public void playSound(SoundType sound, Vector3d position, double volume) {
this.playSound(sound, position, volume, 1);
}
@Override
public void playSound(SoundType sound, Vector3d position, double volume, double pitch) {
this.playSound(sound, position, volume, pitch, 0);
}
@Override
public void playSound(SoundType sound, Vector3d position, double volume, double pitch, double minVolume) {
this.playSoundEffect(position.getX(), position.getY(), position.getZ(), sound.getId(), (float) Math.max(minVolume, volume), (float) pitch);
}
@Override
public void spawnParticles(ParticleEffect particleEffect, Vector3d position) {
this.spawnParticles(particleEffect, position, Integer.MAX_VALUE);
}
@Override
public void spawnParticles(ParticleEffect particleEffect, Vector3d position, int radius) {
checkNotNull(particleEffect, "The particle effect cannot be null!");
checkNotNull(position, "The position cannot be null");
checkArgument(radius > 0, "The radius has to be greater then zero!");
List<Packet<?>> packets = SpongeParticleHelper.toPackets((SpongeParticleEffect) particleEffect, position);
if (!packets.isEmpty()) {
ServerConfigurationManager manager = MinecraftServer.getServer().getConfigurationManager();
double x = position.getX();
double y = position.getY();
double z = position.getZ();
for (Packet<?> packet : packets) {
manager.sendToAllNear(x, y, z, radius, this.provider.getDimensionId(), packet);
}
}
}
@Override
public Weather getWeather() {
if (this.worldInfo.isThundering()) {
return Weathers.THUNDER_STORM;
} else if (this.worldInfo.isRaining()) {
return Weathers.RAIN;
} else {
return Weathers.CLEAR;
}
}
@Override
public long getRemainingDuration() {
Weather weather = getWeather();
if (weather.equals(Weathers.CLEAR)) {
if (this.worldInfo.getCleanWeatherTime() > 0) {
return this.worldInfo.getCleanWeatherTime();
} else {
return Math.min(this.worldInfo.getThunderTime(), this.worldInfo.getRainTime());
}
} else if (weather.equals(Weathers.THUNDER_STORM)) {
return this.worldInfo.getThunderTime();
} else if (weather.equals(Weathers.RAIN)) {
return this.worldInfo.getRainTime();
}
return 0;
}
@Override
public long getRunningDuration() {
return this.worldInfo.getWorldTotalTime() - this.weatherStartTime;
}
@Override
public void setWeather(Weather weather) {
if (weather.equals(Weathers.CLEAR)) {
this.setWeather(weather, (300 + this.rand.nextInt(600)) * 20);
} else {
this.setWeather(weather, 0);
}
}
@Override
public void setWeather(Weather weather, long duration) {
if (weather.equals(Weathers.CLEAR)) {
this.worldInfo.setCleanWeatherTime((int) duration);
this.worldInfo.setRainTime(0);
this.worldInfo.setThunderTime(0);
this.worldInfo.setRaining(false);
this.worldInfo.setThundering(false);
} else if (weather.equals(Weathers.RAIN)) {
this.worldInfo.setCleanWeatherTime(0);
this.worldInfo.setRainTime((int) duration);
this.worldInfo.setThunderTime((int) duration);
this.worldInfo.setRaining(true);
this.worldInfo.setThundering(false);
} else if (weather.equals(Weathers.THUNDER_STORM)) {
this.worldInfo.setCleanWeatherTime(0);
this.worldInfo.setRainTime((int) duration);
this.worldInfo.setThunderTime((int) duration);
this.worldInfo.setRaining(true);
this.worldInfo.setThundering(true);
}
}
@Inject(method = "updateWeather", at = @At(value = "RETURN"))
public void onUpdateWeatherReturn(CallbackInfo ci) {
Weather weather = getWeather();
int duration = (int) getRemainingDuration();
if (this.prevWeather != weather && duration > 0) {
ChangeWorldWeatherEvent event = SpongeEventFactory.createChangeWorldWeatherEvent(Cause.of(NamedCause.source(this)), duration, duration,
weather, weather, this.prevWeather, this);
SpongeImpl.postEvent(event);
if (event.isCancelled()) {
this.setWeather(this.prevWeather);
} else {
this.setWeather(event.getWeather(), event.getDuration());
this.prevWeather = event.getWeather();
this.weatherStartTime = this.worldInfo.getWorldTotalTime();
}
}
}
@Override
public long getWeatherStartTime() {
return this.weatherStartTime;
}
@Override
public void setWeatherStartTime(long weatherStartTime) {
this.weatherStartTime = weatherStartTime;
}
@Override
public void setActiveConfig(SpongeConfig<?> config) {
this.activeConfig = config;
// update cached settings
this.chunkGCLoadThreshold = this.activeConfig.getConfig().getWorld().getChunkLoadThreadhold();
this.chunkGCTickInterval = this.activeConfig.getConfig().getWorld().getTickInterval();
if (this.getChunkProvider() != null) {
final IMixinChunkProviderServer mixinChunkProvider = (IMixinChunkProviderServer) this.getChunkProvider();
final int maxChunkUnloads = this.activeConfig.getConfig().getWorld().getMaxChunkUnloads();
mixinChunkProvider.setMaxChunkUnloads(maxChunkUnloads < 1 ? 1 : maxChunkUnloads);
((ChunkProviderServer) this.getChunkProvider()).chunkLoadOverride = !this.activeConfig.getConfig().getWorld().getDenyChunkRequests();
for (net.minecraft.entity.Entity entity : this.loadedEntityList) {
if (entity instanceof IModData) {
IModData spongeEntity = (IModData) entity;
spongeEntity.requiresCacheRefresh(true);
}
}
}
}
@Override
public int getChunkGCTickInterval() {
return this.chunkGCTickInterval;
}
}
|
package models;
import javax.persistence.*;
import java.util.List;
import java.util.Date;
import play.db.jpa.*;
@Entity
public class Weight extends Model {
public int kg;
public int lb;
public Date date;
@ManyToOne
public User user;
public Weight(User user, int quantity, String type) {
// add user
this.user = user;
// add date as now
this.date = new Date();
if (type.equals("kg")) {
this.kg = quantity;
this.lb = kgToLb(quantity);
} else {
this.kg = lbToKg(quantity);
this.lb = quantity;
}
}
// convenience - default to kg
public Weight(User user, int quantity) {
this(user, quantity, "kg");
}
/*
* Conversions - always return ints
*/
private int kgToLb(int quantity) {
return quantity;
}
private int lbToKg(int quantity) {
return quantity;
}
public String toString() {
// TODO add date
return user.name + " - " + kg;
}
}
|
package team.creative.creativecore.client.render.text;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.blaze3d.vertex.Tesselator;
import net.minecraft.client.ComponentCollector;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Font;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.locale.Language;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.FormattedText;
import net.minecraft.network.chat.Style;
import net.minecraft.util.StringDecomposer;
import team.creative.creativecore.common.gui.Align;
import team.creative.creativecore.common.util.mc.ColorUtils;
import team.creative.creativecore.common.util.text.IAdvancedTextComponent;
import team.creative.creativecore.common.util.type.SingletonList;
public class CompiledText {
private static final Font font = Minecraft.getInstance().font;
private int maxWidth;
private int maxHeight;
public int usedWidth;
public int usedHeight;
public int lineSpacing = 2;
public boolean shadow = true;
public int defaultColor = ColorUtils.WHITE;
public Align alignment = Align.LEFT;
private List<CompiledLine> lines;
private List<Component> original;
public CompiledText(int width, int height) {
this.maxWidth = width;
this.maxHeight = height;
setText(Collections.EMPTY_LIST);
}
public void setMaxHeight(int height) {
this.maxHeight = height;
}
public void setDimension(int width, int height) {
this.maxWidth = width;
this.maxHeight = height;
compile();
}
public int getMaxWidht() {
return maxWidth;
}
public int getMaxHeight() {
return maxHeight;
}
public void setText(Component component) {
setText(new SingletonList<Component>(component));
}
public void setText(List<Component> components) {
this.original = components;
compile();
}
private void compile() {
List<Component> copy = new ArrayList<>();
for (Component component : original)
copy.add(component.copy());
lines = new ArrayList<>();
compileNext(null, true, copy);
}
private CompiledLine compileNext(CompiledLine currentLine, boolean newLine, List<? extends FormattedText> components) {
for (FormattedText component : components) {
if (newLine)
lines.add(currentLine = new CompiledLine());
currentLine = compileNext(currentLine, component);
}
return currentLine;
}
private CompiledLine compileNext(CompiledLine currentLine, boolean newLine, FormattedText component) {
if (newLine)
lines.add(currentLine = new CompiledLine());
return compileNext(currentLine, component);
}
private CompiledLine compileNext(CompiledLine currentLine, FormattedText component) {
List<Component> siblings = null;
if (component instanceof Component && !((Component) component).getSiblings().isEmpty()) {
siblings = new ArrayList<>(((Component) component).getSiblings());
((Component) component).getSiblings().clear();
}
FormattedText next = currentLine.add(component);
if (next != null) {
lines.add(currentLine = new CompiledLine());
currentLine = compileNext(currentLine, false, next);
}
if (siblings != null)
currentLine = compileNext(currentLine, false, siblings);
return currentLine;
}
public int getTotalHeight() {
int height = -lineSpacing;
for (CompiledLine line : lines)
height += line.height + lineSpacing;
return height;
}
public void render(PoseStack stack) {
if (lines == null)
return;
usedWidth = 0;
usedHeight = -lineSpacing;
stack.pushPose();
for (CompiledLine line : lines) {
switch (alignment) {
case LEFT:
line.render(stack);
usedWidth = Math.max(usedWidth, line.width);
break;
case CENTER:
stack.pushPose();
stack.translate(maxWidth / 2 - line.width / 2, 0, 0);
line.render(stack);
usedWidth = Math.max(usedWidth, maxWidth);
stack.popPose();
break;
case RIGHT:
stack.pushPose();
stack.translate(maxWidth - line.width, 0, 0);
line.render(stack);
usedWidth = Math.max(usedWidth, maxWidth);
stack.popPose();
break;
case STRETCH:
break;
default:
break;
}
int height = line.height + lineSpacing;
stack.translate(0, height, 0);
usedHeight += height;
if (usedHeight > maxHeight)
break;
}
stack.popPose();
}
public class CompiledLine {
private List<FormattedText> components = new ArrayList<>();
private int height = 0;
private int width = 0;
public CompiledLine() {
}
public void render(PoseStack stack) {
int xOffset = 0;
MultiBufferSource.BufferSource renderType = MultiBufferSource.immediate(Tesselator.getInstance().getBuilder());
for (FormattedText text : components) {
int height;
int width;
if (text instanceof IAdvancedTextComponent) {
width = ((IAdvancedTextComponent) text).getWidth(font);
height = ((IAdvancedTextComponent) text).getHeight(font);
} else {
width = font.width(text);
height = font.lineHeight;
}
int yOffset = 0;
if (height < this.height)
yOffset = (this.height - height) / 2;
stack.pushPose();
stack.translate(xOffset, yOffset, 0);
if (text instanceof IAdvancedTextComponent)
((IAdvancedTextComponent) text).render(stack, font, defaultColor);
else {
font.drawInBatch(Language.getInstance().getVisualOrder(text), 0, 0, defaultColor, shadow, stack.last().pose(), renderType, false, 0, 15728880);
renderType.endBatch();
}
stack.popPose();
xOffset += width;
}
}
public void updateDimension(int width, int height) {
this.width = Math.max(width, this.width);
this.height = Math.max(height, this.height);
}
public FormattedText add(FormattedText component) {
int remainingWidth = maxWidth - width;
if (component instanceof IAdvancedTextComponent) {
IAdvancedTextComponent advanced = (IAdvancedTextComponent) component;
if (advanced.isEmpty())
return null;
int textWidth = advanced.getWidth(font);
if (remainingWidth > textWidth) {
components.add(advanced);
updateDimension(width + textWidth, advanced.getHeight(font));
return null;
} else if (advanced.canSplit()) {
List<IAdvancedTextComponent> remaining = advanced.split(remainingWidth, width == 0);
IAdvancedTextComponent toAdd = remaining.remove(0);
components.add(toAdd);
updateDimension(width + toAdd.getWidth(font), toAdd.getHeight(font));
if (remaining.isEmpty())
return null;
else
return remaining.get(0);
} else if (width == 0) {
components.add(advanced);
updateDimension(width + textWidth, advanced.getHeight(font));
return null;
} else
return advanced;
}
int textWidth = font.width(component);
if (remainingWidth >= textWidth) {
components.add(component);
updateDimension(width + textWidth, font.lineHeight);
return null;
} else {
FormattedTextSplit split = splitByWidth(component, remainingWidth, Style.EMPTY, width == 0);
if (split != null && (split.head != null || width == 0)) {
if (split.head != null) {
updateDimension(width + font.width(split.head), font.lineHeight);
components.add(split.head);
return split.tail;
}
updateDimension(width + font.width(split.tail), font.lineHeight);
components.add(split.tail);
return null;
} else
return component;
}
}
}
public FormattedTextSplit splitByWidth(FormattedText text, int width, Style style, boolean force) {
final WidthLimitedCharSink charSink = new WidthLimitedCharSink(width, font.getSplitter());
ComponentCollector head = new ComponentCollector();
ComponentCollector tail = new ComponentCollector();
text.visit(new FormattedText.StyledContentConsumer<FormattedText>() {
@Override
public Optional<FormattedText> accept(Style style, String text) {
charSink.resetPosition();
if (!StringDecomposer.iterateFormatted(text, style, charSink)) {
Linebreaker breaker = charSink.lastBreaker();
if (force || breaker != null) {
String sHead;
String sTail;
if (breaker != null) {
int pos = charSink.lastBreakerPos();
sHead = text.substring(0, pos + (breaker.includeChar && breaker.head ? 1 : 0));
sTail = text.substring(pos + (breaker.includeChar && !breaker.head ? 0 : 1));
} else {
sHead = text.substring(0, charSink.getPosition());
sTail = text.substring(charSink.getPosition());
}
if (!sHead.isEmpty())
head.append(FormattedText.of(sHead, style));
if (!sTail.isEmpty())
tail.append(FormattedText.of(sTail, style));
} else
tail.append(FormattedText.of(text, style));
} else if (!text.isEmpty())
head.append(FormattedText.of(text, style));
return Optional.empty();
}
}, style).orElse(null);
return new FormattedTextSplit(head, tail);
}
static class FormattedTextSplit {
public final FormattedText head;
public final FormattedText tail;
public FormattedTextSplit(FormattedText head, FormattedText tail) {
this.head = head;
this.tail = tail;
}
public FormattedTextSplit(ComponentCollector head, ComponentCollector tail) {
this.head = head.getResult();
this.tail = tail.getResult();
}
}
public int getTotalWidth() {
return calculateWidth(0, true, original);
}
private int calculateWidth(int width, boolean newLine, List<? extends FormattedText> components) {
for (FormattedText component : components) {
int result = calculateWidth(component);
if (newLine)
width = Math.max(width, result);
else
width += result;
}
return width;
}
private int calculateWidth(FormattedText component) {
int width = 0;
if (component instanceof IAdvancedTextComponent) {
IAdvancedTextComponent advanced = (IAdvancedTextComponent) component;
if (!advanced.isEmpty())
width += advanced.getWidth(font);
} else
width += font.width(component);
if (component instanceof Component && !((Component) component).getSiblings().isEmpty())
width += calculateWidth(0, false, ((Component) component).getSiblings());
return width;
}
public CompiledText copy() {
CompiledText copy = new CompiledText(maxWidth, maxHeight);
copy.alignment = alignment;
copy.lineSpacing = lineSpacing;
copy.shadow = shadow;
List<Component> components = new ArrayList<>();
for (Component component : original) {
components.add(component.copy());
}
copy.setText(components);
return copy;
}
public static CompiledText createAnySize() {
return new CompiledText(Integer.MAX_VALUE, Integer.MAX_VALUE);
}
}
|
package uk.ac.ebi.pride.psmindex.search.indexer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.PageRequest;
import uk.ac.ebi.pride.jmztab.model.MZTabFile;
import uk.ac.ebi.pride.psmindex.search.model.Psm;
import uk.ac.ebi.pride.psmindex.search.service.PsmIndexService;
import uk.ac.ebi.pride.psmindex.search.service.PsmSearchService;
import uk.ac.ebi.pride.psmindex.search.util.PsmMzTabBuilder;
import java.util.LinkedList;
import java.util.List;
public class ProjectPsmsIndexer {
private static Logger logger = LoggerFactory.getLogger(ProjectPsmsIndexer.class.getName());
private PsmSearchService psmSearchService;
private PsmIndexService psmIndexService;
public ProjectPsmsIndexer(PsmSearchService psmSearchService, PsmIndexService psmIndexService) {
this.psmSearchService = psmSearchService;
this.psmIndexService = psmIndexService;
}
public void indexAllPsmsForProjectAndAssay(String projectAccession, String assayAccession, MZTabFile mzTabFile){
List<Psm> psms = new LinkedList<Psm>();
long startTime;
long endTime;
startTime = System.currentTimeMillis();
// build PSMs from mzTabFiles
try {
if (mzTabFile != null) {
psms = PsmMzTabBuilder.readPsmsFromMzTabFile(projectAccession, assayAccession, mzTabFile);
}
} catch (Exception e) { // we need to recover from any exception when reading the mzTab file so the whole process can continue
logger.error("Cannot get psms from PROJECT:" + projectAccession + "and ASSAY:" + assayAccession );
logger.error("Reason: ");
e.printStackTrace();
}
endTime = System.currentTimeMillis();
logger.info("Found " + psms.size() + " psms "
+ " for PROJECT:" + projectAccession
+ " and ASSAY:" + assayAccession
+ " in " + (double) (endTime - startTime) / 1000.0 + " seconds");
// add all PSMs to index
startTime = System.currentTimeMillis();
psmIndexService.save(psms);
logger.debug("COMMITTED " + psms.size() +
" psms from PROJECT:" + projectAccession +
" ASSAY:" + assayAccession);
endTime = System.currentTimeMillis();
logger.info("DONE indexing all PSMs for project " + projectAccession + " in " + (double) (endTime - startTime) / 1000.0 + " seconds");
}
public void deleteAllPsmsForProject(String projectAccession) {
int MAX_PAGE_SIZE = 1000;
long proteinCount = psmSearchService.countByProjectAccession(projectAccession);
List<Psm> initialProteinsFound;
while (0 < proteinCount) {
for (int i = 0; i < (proteinCount / MAX_PAGE_SIZE) + 1; i++) {
initialProteinsFound =
psmSearchService
.findByProjectAccession(projectAccession, new PageRequest(i, MAX_PAGE_SIZE))
.getContent();
psmIndexService.delete(initialProteinsFound);
}
proteinCount = psmSearchService.countByProjectAccession(projectAccession);
}
}
}
|
package address;
import java.io.IOException;
import database.TableData;
import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.stage.Modality;
import javafx.stage.Stage;
import address.model.Car;
import address.view.CarEditDialogController;
import address.view.CarOverviewController;
public class MainApp extends Application {
private Stage primaryStage;
private BorderPane rootLayout;
private ObservableList<Car> carData;
public MainApp(){
TableData tableData = new TableData();
carData = tableData.getAvaibleCar();
}
public void start(Stage primaryStage) {
this.primaryStage = primaryStage;
this.primaryStage.setTitle("CarLoan");
initRootLayout();
showCarOverview();
}
public void initRootLayout(){
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainApp.class.getResource("/address/view/RootLayout.fxml"));
try {
rootLayout = (BorderPane)loader.load();
} catch (IOException e) {
e.printStackTrace();
}
Scene scene = new Scene(rootLayout);
primaryStage.setScene(scene);
primaryStage.show();
}
public void showCarOverview(){
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainApp.class.getResource("/address/view/CarOverview.fxml"));
AnchorPane carOverview=null;
try {
carOverview = (AnchorPane) loader.load();
} catch (IOException e) {
e.printStackTrace();
}
rootLayout.setCenter(carOverview);
CarOverviewController controller = loader.getController();
controller.setMainApp(this);
}
public Stage getPrimaryStage() {
return primaryStage;
}
public ObservableList<Car> getCarData() {
return carData;
}
public boolean showCarEditDialog(Car car) {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainApp.class.getResource("/address/view/CarEditDialog.fxml"));
AnchorPane page = null;
try {
page = (AnchorPane) loader.load();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Stage dialogStage = new Stage();
dialogStage.setTitle("Edit Car");
dialogStage.initModality(Modality.WINDOW_MODAL);
dialogStage.initOwner(primaryStage);
Scene scene = new Scene(page);
dialogStage.setScene(scene);
CarEditDialogController controller = loader.getController();
controller.setDialogStage(dialogStage);
controller.setCar(car);
dialogStage.showAndWait();
return controller.isOkClicked();
}
public static void main(String[] args) {
launch(args);
}
}
|
package com.exedio.cope;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
final class WrittenState extends State implements Database.ResultSetHandler<Void>
{
private final Row row;
private long lastUsageMillis;
WrittenState(final Connection connection, final Item item)
{
super( item );
row = new Row();
type.getModel().getDatabase().load( connection, this );
lastUsageMillis = System.currentTimeMillis();
}
WrittenState(final State original)
{
super( original.item );
row = original.stealValues();
if(row==null) throw new RuntimeException(original.getClass().getName());
lastUsageMillis = System.currentTimeMillis();
}
@Override
Object get(FunctionField field)
{
return field.get(row);
}
@Override
<E> State put(final Transaction transaction, final FunctionField<E> field, final E value)
{
return new ModifiedState(transaction, this).put(transaction, field, value);
}
@Override
State write(final Transaction transaction, final Map<BlobColumn, byte[]> blobs)
{
if(blobs!=null && !blobs.isEmpty())
type.getModel().getDatabase().store(transaction.getConnection(), this, true, blobs);
return this;
}
@Override
State delete(Transaction transaction)
{
return new DeletedState( transaction, this );
}
@Override
Object store(final Column column)
{
//throw new RuntimeException();
// needed for blobs
return row.get(column);
}
@Override
Row stealValues()
{
return new Row(row);
}
@Override
boolean exists()
{
return true;
}
// implementation of ResultSetHandler
public Void handle(final ResultSet resultSet) throws SQLException
{
if(!resultSet.next())
throw new NoSuchItemException(item);
int columnIndex = 1;
for(Type itype = type; itype!=null; itype = itype.supertype)
{
for(final Column column : itype.getTable().getColumns())
{
if(!(column instanceof BlobColumn))
column.load(resultSet, columnIndex++, row);
}
}
return null;
}
void notifyUsed()
{
lastUsageMillis = System.currentTimeMillis();
}
long getLastUsageMillis()
{
return lastUsageMillis;
}
@Override
public String toStringWithValues()
{
return toString()+row.toString();
}
}
|
package com.vidinoti.pixlive;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.Pair;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import com.vidinoti.android.vdarsdk.DeviceCameraImageSender;
import com.vidinoti.android.vdarsdk.VDARAnnotationView;
import com.vidinoti.android.vdarsdk.VDARPrior;
import com.vidinoti.android.vdarsdk.VDARRemoteController;
import com.vidinoti.android.vdarsdk.VDARSDKController;
import com.vidinoti.android.vdarsdk.VDARSDKControllerEventReceiver;
import com.vidinoti.android.vdarsdk.VDARTagPrior;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.engine.SystemWebView;
import org.json.JSONArray;
import org.json.JSONException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
import java.util.concurrent.Callable;
/**
* This class echoes a string called from JavaScript.
*/
public class PixLive extends CordovaPlugin implements VDARSDKControllerEventReceiver {
private static final String TAG ="PixLiveCordova";
/** Your Project ID in Google APIs Console for Push Notification (GCM) */
//private static final String GOOGLE_API_PROJECT_ID_FOR_NOTIFICATIONS = "000000";
class CordovaARView extends VDARAnnotationView {
public boolean touchEnabled = true;
public CordovaARView(android.content.Context context, boolean renderCamera) {
super(context,renderCamera);
}
public void setTouchEnabled(boolean val) {
touchEnabled = val;
}
@Override
public boolean onTouchEvent (MotionEvent event) {
if(!touchEnabled) {
return false;
}
return true;
}
}
private HashMap<Integer, CordovaARView> arViews = new HashMap<Integer, CordovaARView>();
private DeviceCameraImageSender imageSender = null;
static void startSDK(final Context c, final String storage, final String licenseKey) {
if(VDARSDKController.getInstance()!=null) {
return;
}
VDARSDKController.startSDK(c, storage, licenseKey);
/* Comment out to disable QR code detection */
VDARSDKController.getInstance().setEnableCodesRecognition(true);
// VDARRemoteController.getInstance().setUseRemoteTestServer(true);
/* Enable push notifications */
//VDARSDKController.getInstance().setNotificationsSupport(true, GOOGLE_API_PROJECT_ID_FOR_NOTIFICATIONS);
}
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if (action.equals("init") && args.length()>=2) {
String url = args.getString(0);
String key = args.getString(1);
this.init(url,key, callbackContext);
return true;
} else if (action.equals("createARView") && args.length()>=5) {
int x = args.getInt(0);
int y = args.getInt(1);
int width = args.getInt(2);
int height = args.getInt(3);
int ctrlID = args.getInt(4);
this.createARView(x, y, width, height, ctrlID, args.length()>=6 ? args.getBoolean(5) : true, callbackContext);
return true;
} else if (action.equals("beforeLeave") && args.length()>=1) {
int ctrlID = args.getInt(0);
this.beforeLeave(ctrlID, callbackContext);
return true;
} else if (action.equals("afterLeave") && args.length()>=1) {
int ctrlID = args.getInt(0);
this.afterLeave(ctrlID, callbackContext);
return true;
} else if (action.equals("beforeEnter") && args.length()>=1) {
int ctrlID = args.getInt(0);
this.beforeEnter(ctrlID, callbackContext);
return true;
} else if (action.equals("afterEnter") && args.length()>=1) {
int ctrlID = args.getInt(0);
this.afterEnter(ctrlID, callbackContext);
return true;
}else if (action.equals("destroy") && args.length()>=1) {
int ctrlID = args.getInt(0);
this.destroy(ctrlID, callbackContext);
return true;
}else if (action.equals("resize") && args.length()>=5) {
int x = args.getInt(1);
int y = args.getInt(2);
int width = args.getInt(3);
int height = args.getInt(4);
int ctrlID = args.getInt(0);
this.resize(x, y, width, height,ctrlID, callbackContext);
return true;
}else if (action.equals("synchronize")) {
ArrayList<String> list = new ArrayList<String>();
if(args.length()>0) {
JSONArray a = args.getJSONArray(0);
for (int i=0; i<a.length(); i++) {
list.add( a.getString(i) );
}
}
this.synchronize(list,callbackContext);
return true;
} else if (action.equals("enableTouch")) {
this.enableTouch();
return true;
} else if (action.equals("disableTouch")) {
this.disableTouch();
return true;
}
return false;
}
private void enableTouch() {
for(Map.Entry<Integer,CordovaARView> s : arViews.entrySet()) {
s.getValue().setTouchEnabled(true);
}
}
private void disableTouch() {
for(Map.Entry<Integer,CordovaARView> s : arViews.entrySet()) {
s.getValue().setTouchEnabled(false);
}
}
private void synchronize(ArrayList<String> tags, final CallbackContext callbackContext) {
final ArrayList<VDARPrior> priors = new ArrayList<VDARPrior>();
for(String s : tags) {
priors.add(new VDARTagPrior(s));
}
VDARSDKController.getInstance().addNewAfterLoadingTask(new Runnable() {
@Override
public void run() {
VDARRemoteController.getInstance().syncRemoteContextsAsynchronouslyWithPriors(priors, new Observer() {
@Override
public void update(Observable observable, Object data) {
VDARRemoteController.ObserverUpdateInfo info = (VDARRemoteController.ObserverUpdateInfo) data;
if (info.isCompleted()) {
if(info.getError()==null) {
JSONArray ctx = new JSONArray(info.getFetchedContexts());
callbackContext.success(ctx);
} else {
callbackContext.error(info.getError());
}
}
}
});
}
});
}
private void beforeLeave(final int ctrlID, CallbackContext callbackContext) {
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
VDARAnnotationView view = arViews.get(ctrlID);
if (view != null) {
view.onPause();
VDARSDKController.getInstance().onPause();
view.setVisibility(View.GONE);
}
}
});
}
private void afterLeave(final int ctrlID, CallbackContext callbackContext) {
}
private void beforeEnter(final int ctrlID, CallbackContext callbackContext) {
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
VDARAnnotationView view = arViews.get(ctrlID);
if (view != null) {
VDARSDKController.getInstance().onResume();
view.onResume();
view.setVisibility(View.VISIBLE);
}
}
});
}
private void afterEnter(final int ctrlID, CallbackContext callbackContext) {
}
private void resize(final int x, final int y, final int width, final int height, final int ctrlID, CallbackContext callbackContext)
{
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
VDARAnnotationView annotationView = arViews.get(ctrlID);
if (annotationView != null) {
DisplayMetrics displaymetrics = new DisplayMetrics();
cordova.getActivity().getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
annotationView.setVisibility(View.VISIBLE);
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams)annotationView.getLayoutParams();
params.leftMargin = (int) Math.round(x * displaymetrics.scaledDensity);
params.topMargin = (int) Math.round(y * displaymetrics.scaledDensity);
params.width = (int) Math.round(width * displaymetrics.scaledDensity);
params.height = (int) Math.round(height * displaymetrics.scaledDensity);
annotationView.setLayoutParams(params);
annotationView.requestLayout();
}
}
});
}
private void destroy(final int ctrlID, CallbackContext callbackContext) {
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
VDARAnnotationView view = arViews.get(ctrlID);
if (view != null) {
if (view.getParent() != null) {
((FrameLayout) view.getParent()).removeView(view);
}
arViews.remove(ctrlID);
}
}
});
}
private void createARView(final int x,final int y, final int width, final int height, final int ctrlID, final boolean insertBelow, final CallbackContext callbackContext) {
if (!DeviceCameraImageSender.doesSupportDirectRendering()) {
VDARSDKController.log(Log.ERROR,TAG,"This device is not supporting SurfaceView and is therefore not supported with PixLive SDK.");
throw new RuntimeException("Device not supporting direct rendering");
}
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
try {
imageSender = new DeviceCameraImageSender(null);
} catch (IOException e) {
VDARSDKController.log(Log.ERROR, TAG, Log.getStackTraceString(e));
}
VDARSDKController.getInstance().setImageSender(imageSender);
CordovaARView annotationView = new CordovaARView(cordova.getActivity(),true);
DisplayMetrics displaymetrics = new DisplayMetrics();
cordova.getActivity().getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
SystemWebView v = (SystemWebView)webView.getView();
v.setBackgroundColor(Color.TRANSPARENT);
if (Build.VERSION.SDK_INT >= 11) {
v.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
/* for(int i=0;i<v.getChildCount();i++) {
v.getChildAt(i).setBackgroundColor(0);
if (Build.VERSION.SDK_INT >= 11) {
v.getChildAt(i).setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
}*/
// Add the view to the hierarchy
FrameLayout frameLayout = (FrameLayout) webView.getView().getParent();
annotationView.setVisibility(View.VISIBLE);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams((int)Math.round(width*displaymetrics.scaledDensity), (int)Math.round(height*displaymetrics.scaledDensity));
params.leftMargin = (int)Math.round(x*displaymetrics.scaledDensity);
params.topMargin = (int)Math.round(y*displaymetrics.scaledDensity);
annotationView.setLayoutParams(params);
frameLayout.addView(annotationView,0);
arViews.put(ctrlID, annotationView);
VDARSDKController.getInstance().setActivity(cordova.getActivity());
VDARSDKController.getInstance().onResume();
annotationView.onResume();
}
});
}
private void init(String storageURL, String licenseKey, CallbackContext callbackContext) {
try {
startSDK(cordova.getActivity(), new URL(storageURL).getPath(), licenseKey);
} catch(MalformedURLException e) {
VDARSDKController.log(Log.ERROR,TAG,"Invalid storage URL: "+storageURL+". PixLive SDK cannot start.");
return;
}
VDARSDKController.getInstance().setEnableCodesRecognition(true);
VDARSDKController.getInstance().setActivity(cordova.getActivity());
VDARSDKController.getInstance().registerEventReceiver(this);
}
public void onCodesRecognized(java.util.ArrayList<com.vidinoti.android.vdarsdk.VDARCode> arrayList) {
}
public void onFatalError(java.lang.String s) {
}
public void onPresentAnnotations() {
}
public void onAnnotationsHidden() {
}
public void onTrackingStarted(int i, int i1) {
}
public void onEnterContext(com.vidinoti.android.vdarsdk.VDARContext vdarContext) {
}
public void onExitContext(com.vidinoti.android.vdarsdk.VDARContext vdarContext) {
}
}
|
package server;
import common.*;
import java.util.*;
public class Player implements MapObject {
public static final int distance=5;
public static final int BaseHealth=10; //Randomly picked
Coordinate C;
Hashtable<Resource,Integer> Inventory;
Stack<Update> updateLog;
boolean admin;
int Health;
int MaxHealth;
int ID;
int Power;
public Player(int id, boolean admn)
{
ID=id;
admin=admn;
MaxHealth=BaseHealth;
Health=BaseHealth;
Power=1;
C=DataBase.GetPlayerCoordinate(id);
Inventory = new Hashtable<Resource,Integer>();
updateLog = new Stack<Update>();
WorldMap.getInstance();
//TODO add inventory
}
/* (non-Javadoc)
* @see server.MapObject#Coordinates()
*/
@Override
public Coordinate Coordinates() {
// TODO Auto-generated method stub
return C;
}
/**
* Attempts to move this player to a new location.
* @param co Coordinate to move into
* @return Success if moved, Failure if destination is unreachable or occupied.
*/
public boolean Move(Coordinate co)
{
if(admin)
{
C = co;
return true;
}
Tile dest = WorldMap.getInstance().get_tile_at(co, true);
if(dest.canMoveOn())
{
C = co;
dest.setMapObjectType(MapObjectType.PLAYER);
WorldMap.getInstance().update_tile(dest);
return true;
}
return false;
}
/* (non-Javadoc)
* @see server.MapObject#Resource()
*/
@Override
public common.Resource Resource() {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see server.MapObject#Health()
*/
@Override
public int Health() {
return Health;
}
public void setHealth(int nHealth)
{
Health=nHealth;
}
public int view_distance()
{
return distance;
}
@Override
public void Damage(int amount) {
Health=Health-amount;
}
public boolean isAdmin()
{
return admin;
}
/**
* Checks if player can see the Tile he asked to see.
* @return
*/
public boolean see_Tile(Coordinate Co)
{
if(!admin && Co.distance(C)>distance) return false;
return true;
}
/**
* Checks if player can see the Tile he asked to see.
* @return
*/
public boolean change_Tile(Tile Ti)
{
if(!admin && Ti.getCoordinate().distance(C)>distance) return false;
//TODO Check inventory
WorldMap.getInstance().update_tile(Ti);
return true;
}
/**
* True if there's a MapObject in the target Tile
* @return
*/
public boolean object_in_tile(Coordinate co)
{
return WorldMap.getInstance().get_tile_at(co, false).getMapObjectType()!=null;
}
/**
* Attack a monster or mapobject
* @param Co
* @return
*/
public boolean attack(Coordinate Co)
{
if(!admin && Co.distance(C)>distance) return false;
Resource r = WorldMap.getInstance().get_resource(Co,Power);
if(r!=null)
{
if(Inventory.get(r)!=null) Inventory.put(r,Inventory.get(r)+1);
else Inventory.put(r,1);
}
return true;
}
/**
* Attempts to gather ground
* @param Co
* @return
*/
public boolean gather_ground(Coordinate Co)
{
if(!admin && Co.distance(C)>distance) return false;
Resource r = WorldMap.getInstance().get_floor_resource(Co);
if(r!=null)
{
if(Inventory.get(r)!=null) Inventory.put(r,Inventory.get(r)+1);
else Inventory.put(r,1);
}
return true;
}
/**
* Removes the player from the map
*/
public void logout()
{
WorldMap.getInstance().logout(this);
}
/**
* Used by WorldMap to let player know something near them happened.
* @param Up
*/
public void add_event_to_stack(Update Up)
{
updateLog.push(Up);
}
/**
* Returns ONE event if there are any in stack.
* If the stack is empty, null is returned.
* @return an Update object event, if any.
*/
public Update getEvents()
{
try
{
return updateLog.pop();
}
catch (EmptyStackException e)
{
return null;
}
}
}
|
package nl.jft.logic.match;
import nl.jft.logic.participant.Participant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
/**
* A {@code Match} is a game between two {@link nl.jft.logic.participant.Participant participants}. {@link Goal goals}
* can be scored, and added, in a {@code Match} to determine the winning {@code Participant}.
*
* @author Lesley
*/
public class Match {
private final List<Goal> goals = new ArrayList<>();
private final List<Rule> rules = new ArrayList<>();
private final Participant firstParticipant;
private final Participant secondParticipant;
/**
* Initializes a new {@code Match} with the given {@link Participant participants}.
*
* @param firstParticipant The first {@code Participant} of this {@code Match}, should not be {@code null}.
* @param secondParticipant The second {@code Participant} of this {@code Match}, should not be {@code null}.
*/
public Match(Participant firstParticipant, Participant secondParticipant) {
this.firstParticipant = Objects.requireNonNull(firstParticipant);
this.secondParticipant = Objects.requireNonNull(secondParticipant);
}
public void addGoal(Goal goal) {
synchronized (goals) {
goals.add(Objects.requireNonNull(goal));
}
}
/**
* Removes a {@link Goal} from this {@code Match}.
*
* @param goal The {@code Goal} to remove from this {@code Match}, should not be {@code null}.
* @throws NullPointerException If the specified {@code Goal} is {@code null}.
*/
public void removeGoal(Goal goal) {
synchronized (goals) {
goals.remove(Objects.requireNonNull(goal));
}
}
/**
* Adds a {@link Rule} to this {@code Match}.
*
* @param rule The {@code Rule} to add to this {@code Match}, should not be {@code null}.
* @throws NullPointerException If the specified {@code Rule} is {@code null}.
*/
public void addRule(Rule rule) {
synchronized (rules) {
rules.add(Objects.requireNonNull(rule));
}
}
/**
* Removes a {@link Rule} from this {@code Match}.
*
* @param rule The {@code Rule} to remove from this {@code Match}, should not be {@code null}.
* @throws NullPointerException If the specified {@code Rule} is {@code null}.
*/
public void removeRule(Rule rule) {
synchronized (rules) {
rules.remove(Objects.requireNonNull(rule));
}
}
/**
* Gets all {@link Goal Goals} from this {@code Match}.
*
* @return A {@link List} containing all {@code Goals} added to this {@code Match}.
*/
public List<Goal> getGoals() {
synchronized (goals) {
return Collections.unmodifiableList(goals);
}
}
/**
* Gets all {@link Rule Rules} from this {@code Match}.
*
* @return A {@link List} containing all {@code Rules} added to this {@code Match}.
*/
public List<Rule> getRules() {
synchronized (rules) {
return Collections.unmodifiableList(rules);
}
}
/**
* Gets the first {@link Participant} competing in this {@code Match}.
*
* @return The first {@code Participant} competing in this {@code Match}.
*/
public Participant getFirstParticipant() {
return firstParticipant;
}
/**
* Gets the second {@link Participant} competing in this {@code Match}.
*
* @return The second {@code Participant} competing in this {@code Match}.
*/
public Participant getSecondParticipant() {
return secondParticipant;
}
}
|
package logbook.data.context;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedMap;
import java.util.concurrent.ConcurrentSkipListMap;
import javax.json.JsonArray;
import javax.json.JsonNumber;
import javax.json.JsonObject;
import javax.json.JsonValue;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.ToolTip;
import logbook.config.AppConfig;
import logbook.config.KdockConfig;
import logbook.config.QuestConfig;
import logbook.config.bean.QuestBean;
import logbook.constants.AppConstants;
import logbook.data.Data;
import logbook.data.DataQueue;
import logbook.data.EventSender;
import logbook.data.event.CallScript;
import logbook.data.event.Material;
import logbook.data.event.Nyukyo;
import logbook.data.event.PresetSelect;
import logbook.data.event.RemodelSlot;
import logbook.data.event.SlotExchangeIndex;
import logbook.dto.BattleDto;
import logbook.dto.BattleResultDto;
import logbook.dto.CreateItemDto;
import logbook.dto.DeckMissionDto;
import logbook.dto.DockDto;
import logbook.dto.GetShipDto;
import logbook.dto.ItemDto;
import logbook.dto.MissionResultDto;
import logbook.dto.NdockDto;
import logbook.dto.QuestDto;
import logbook.dto.ResourceDto;
import logbook.dto.ShipDto;
import logbook.dto.ShipInfoDto;
import logbook.gui.ApplicationMain;
import logbook.gui.logic.CreateReportLogic;
import logbook.internal.Deck;
import logbook.internal.Item;
import logbook.internal.QuestDue;
import logbook.internal.Ship;
import logbook.internal.ShipStyle;
import logbook.internal.SortiePhase;
import logbook.thread.PlayerThread;
import logbook.util.JsonUtils;
public final class GlobalContext {
private GlobalContext() {
}
private static class LoggerHolder {
private static final Logger LOG = LogManager.getLogger(GlobalContext.class);
}
private static class GlobalContextHolder {
private static final EventSender SENDER = new EventSender();
static {
SENDER.addEventListener(new CallScript());
SENDER.addEventListener(new RemodelSlot());
SENDER.addEventListener(new Material());
SENDER.addEventListener(new Nyukyo());
SENDER.addEventListener(new PresetSelect());
SENDER.addEventListener(new SlotExchangeIndex());
}
}
private static List<GetShipDto> getShipList = new ArrayList<GetShipDto>();
private static Map<String, ResourceDto> getShipResource = new HashMap<String, ResourceDto>();
private static List<CreateItemDto> createItemList = new ArrayList<CreateItemDto>();
private static List<BattleResultDto> battleResultList = new ArrayList<BattleResultDto>();
private static List<MissionResultDto> missionResultList = new ArrayList<MissionResultDto>();
private static int hqLevel;
private static int maxChara;
private static int maxSlotitem;
private static String lastBuildKdock;
private static List<BattleDto> battleList = new ArrayList<BattleDto>();
private static boolean bossArrive = false;
private static SortiePhase sortiePhase = SortiePhase.BATTLE_RESULT;
private static int battleCount = 0;
private static DeckMissionDto[] deckMissions = new DeckMissionDto[] { DeckMissionDto.EMPTY, DeckMissionDto.EMPTY,
DeckMissionDto.EMPTY };
private static Map<String, DockDto> dock = new HashMap<String, DockDto>();
private static NdockDto[] ndocks = new NdockDto[] { NdockDto.EMPTY, NdockDto.EMPTY, NdockDto.EMPTY,
NdockDto.EMPTY };
/** Map */
private static SortedMap<Integer, QuestDto> questMap = new ConcurrentSkipListMap<Integer, QuestDto>();
private static boolean[] isSortie = new boolean[4];
/** (START) */
private static boolean isStart;
private static int mapAreaNo;
private static int mapInfoNo;
private static int mapCellNo;
private static int mapBossCellNo;
private static int eventId;
private static int combined;
private final EventSender sender = new EventSender();
/**
* @return No
*/
public static int getMapAreaNo() {
return mapAreaNo;
}
/**
* @return No
*/
public static int getMapInfoNo() {
return mapInfoNo;
}
/**
* @return No
*/
public static int getMapCellNo() {
return mapCellNo;
}
/**
* @return
*/
public static boolean isBossArrive() {
return bossArrive;
}
/**
* @return
*/
public static SortiePhase getSortiePhase() {
return sortiePhase;
}
/**
* @return
*/
public static int getBattleCount() {
return battleCount;
}
/**
* @return Lv
*/
public static int hqLevel() {
return hqLevel;
}
/**
* @return
*/
public static int maxChara() {
return maxChara;
}
/**
* @return
*/
public static int maxSlotitem() {
return maxSlotitem;
}
/**
* @return List
*/
public static List<GetShipDto> getGetshipList() {
return getShipList;
}
/**
* @return List
*/
public static List<CreateItemDto> getCreateItemList() {
return createItemList;
}
/**
* @return List
*/
public static List<BattleDto> getBattleList() {
return battleList;
}
/**
* @return List
*/
public static List<BattleResultDto> getBattleResultList() {
return battleResultList;
}
/**
* @return
*/
public static List<MissionResultDto> getMissionResultList() {
return missionResultList;
}
/**
* @return
*/
public static DeckMissionDto[] getDeckMissions() {
return deckMissions;
}
/**
* @return
*/
public static NdockDto[] getNdocks() {
return ndocks;
}
/**
* @return
*/
public static EventSender getEventSender() {
return GlobalContextHolder.SENDER;
}
/**
*
*
* @param ship
* @return true
*/
public static boolean isNdock(ShipDto ship) {
return isNdock(ship.getId());
}
/**
*
* @param ship ID
* @return true
*/
public static boolean isNdock(long ship) {
for (NdockDto ndock : ndocks) {
if (ship == ndock.getNdockid()) {
return true;
}
}
return false;
}
/**
*
*
* @param idstr
* @return true
*/
public static boolean isMission(String idstr) {
int id = Integer.parseInt(idstr);
for (int i = 0; i < deckMissions.length; i++) {
if ((deckMissions[i].getMission() != null) && (deckMissions[i].getFleetid() == id)) {
return true;
}
}
return false;
}
/**
* @return
*/
public static DockDto getDock(String id) {
return dock.get(id);
}
/**
*
* @return
*/
public static Map<Integer, QuestDto> getQuest() {
return questMap;
}
/**
*
* @return
*/
public static boolean isSortie(String idstr) {
int id = Integer.parseInt(idstr);
return isSortie[id - 1];
}
/**
*
*
* @return true
*/
public static boolean updateContext() {
boolean update = false;
Data data;
while ((data = DataQueue.poll()) != null) {
update = true;
getEventSender().syncSendEvent(data.getDataType(), data);
switch (data.getDataType()) {
case CHARGE:
doCharge(data);
break;
case CHANGE:
doChange(data);
break;
case PORT:
doPort(data);
break;
case SLOTITEM_MEMBER:
doSlotitemMember(data);
break;
case SHIP3:
doShip3(data);
break;
case SHIP2:
doShip2(data);
break;
case SHIP_DECK:
doShipDeck(data);
break;
case BASIC:
doBasic(data);
break;
case REQUIRE_INFO:
doRequireInfo(data);
break;
case MISSION_START:
doMission(data);
break;
case MISSION_RESULT:
doMissionResult(data);
break;
case NDOCK:
doNdock(data);
break;
case SPEED_CHANGE:
doSpeedChange(data);
break;
case CREATE_SHIP:
doCreateship(data);
break;
case KDOCK:
doKdock(data);
break;
case GET_SHIP:
doGetship(data);
break;
case CREATE_ITEM:
doCreateitem(data);
break;
case DESTROY_SHIP:
doDestroyShip(data);
break;
case DESTROY_ITEM2:
doDestroyItem2(data);
break;
case POWERUP:
doPowerup(data);
break;
case BATTLE:
doBattle(data, false, false);
break;
case BATTLE_MIDNIGHT:
doBattle(data, true, false);
break;
case BATTLE_SP_MIDNIGHT:
doBattle(data, true, false);
break;
case BATTLE_NIGHT_TO_DAY:
doBattle(data, false, true);
break;
case BATTLE_AIRBATTLE:
doBattle(data, false, false);
break;
case BATTLE_LD_AIRBATTLE:
doBattle(data, false, false);
break;
case COMBINED_BATTLE_AIRBATTLE:
doBattle(data, false, false);
break;
case COMBINED_BATTLE_LD_AIRBATTLE:
doBattle(data, false, false);
break;
case COMBINED_BATTLE:
doBattle(data, false, false);
break;
case COMBINED_BATTLE_WATER:
doBattle(data, false, false);
break;
case COMBINED_BATTLE_EC:
doBattle(data, false, false);
break;
case COMBINED_BATTLE_EACH:
doBattle(data, false, false);
break;
case COMBINED_BATTLE_EACH_WATER:
doBattle(data, false, false);
break;
case COMBINED_BATTLE_EC_MIDNIGHT:
doBattle(data, true, false);
break;
case COMBINED_BATTLE_EC_NIGHT_TO_DAY:
doBattle(data, true, true);
break;
case COMBINED_BATTLE_MIDNIGHT:
doBattle(data, true, false);
break;
case COMBINED_BATTLE_SP_MIDNIGHT:
doBattle(data, true, false);
break;
case BATTLE_RESULT:
doBattleresult(data);
break;
case COMBINED_BATTLE_RESULT:
doBattleresult(data);
break;
case DECK:
doDeck(data);
break;
case START:
doStart(data);
break;
case NEXT:
doNext(data);
break;
case QUEST_LIST:
doQuest(data);
break;
case QUEST_CLEAR:
doQuestClear(data);
break;
case START2:
doStart2(data);
break;
case PRACTICE_RESULT:
doPracticeResult(data);
break;
case NYUKYO:
doNyukyo(data);
break;
default:
break;
}
}
return update;
}
/**
*
* @param data
*/
private static void doCharge(Data data) {
try {
JsonObject apidata = data.getJsonObject().getJsonObject("api_data");
if (apidata != null) {
JsonArray ships = apidata.getJsonArray("api_ship");
for (JsonValue shipval : ships) {
JsonObject shipobj = (JsonObject) shipval;
Long shipid = shipobj.getJsonNumber("api_id").longValue();
int fuel = shipobj.getJsonNumber("api_fuel").intValue();
int bull = shipobj.getJsonNumber("api_bull").intValue();
JsonArray onslot = shipobj.getJsonArray("api_onslot");
ShipDto ship = ShipContext.get().get(shipid);
if (ship != null) {
ship.setFuel(fuel);
ship.setBull(bull);
List<Integer> onslotList = ship.getOnslot();
onslotList.clear();
for (JsonValue jsonValue : onslot) {
JsonNumber value = (JsonNumber) jsonValue;
onslotList.add(Integer.valueOf(value.intValue()));
}
String fleetid = ship.getFleetid();
if (fleetid != null) {
DockDto dockdto = dock.get(fleetid);
if (dockdto != null) {
dockdto.setUpdate(true);
}
}
}
}
Date now = new Date();
for (Integer no : QuestConfig.getNoList()) {
QuestBean bean = QuestConfig.get(no);
if ((bean != null) && bean.getExecuting()) {
bean.countCharge(now);
}
}
QuestConfig.store();
addConsole("");
}
} catch (Exception e) {
LoggerHolder.LOG.warn("", e);
LoggerHolder.LOG.warn(data);
}
}
/**
*
* @param data
*/
private static void doChange(Data data) {
try {
String fleetid = data.getField("api_id");
long shipid = Long.parseLong(data.getField("api_ship_id"));
int shipidx = Integer.parseInt(data.getField("api_ship_idx"));
DockDto dockdto = dock.get(fleetid);
if (dockdto != null) {
if (shipid == -2L) {
dockdto.removeOthers();
} else if (shipid == -1L) {
dockdto.removeShip(shipidx);
} else {
ShipDto rship = ShipContext.get().get(shipid);
DockDto otherDock = dock.get(rship.getFleetid());
if (shipidx < dockdto.size()) {
if (otherDock != null)
otherDock.displaceShip(otherDock.indexOf(rship), dockdto.replaceShip(shipidx, rship));
else
dockdto.replaceShip(shipidx, rship);
} else {
if (otherDock != null)
otherDock.removeShip(otherDock.indexOf(rship));
dockdto.addShip(rship);
}
}
ShipContext.setSecretary(dock.get("1").getShips().get(0));
}
} catch (Exception e) {
LoggerHolder.LOG.warn("", e);
LoggerHolder.LOG.warn(data);
}
}
/**
*
* @param data
*/
private static void doRequireInfo(Data data) {
try {
JsonObject apidata = data.getJsonObject().getJsonObject("api_data");
if (apidata != null) {
JsonArray apiSlotItem = apidata.getJsonArray("api_slot_item");
doSlotitemMemberSub(apiSlotItem);
addConsole("");
}
} catch (Exception e) {
LoggerHolder.LOG.warn("", e);
LoggerHolder.LOG.warn(data);
}
}
/**
*
* @param data
*/
private static void doPort(Data data) {
try {
JsonObject apidata = data.getJsonObject().getJsonObject("api_data");
if (apidata != null) {
Arrays.fill(isSortie, false);
JsonObject apiBasic = apidata.getJsonObject("api_basic");
doBasicSub(apiBasic);
addConsole("");
JsonArray apiShip = apidata.getJsonArray("api_ship");
Set<Long> portShips = new HashSet<>();
long last = ShipContext.getMaxShipID();
long max = -1;
Set<ShipInfoDto> newShips = new HashSet<>();
Set<ShipInfoDto> oldShips = new HashSet<>();
for (int i = 0; i < apiShip.size(); i++) {
ShipDto ship = new ShipDto((JsonObject) apiShip.get(i));
Long key = Long.valueOf(ship.getId());
ShipContext.get().put(key, ship);
portShips.add(key);
if (key > last)
newShips.add(ship.getShipInfo());
else
oldShips.add(ship.getShipInfo());
if (key > max)
max = key;
}
ShipContext.setMaxShipID(max);
// port
for (Entry<Long, ShipDto> entry : ShipContext.get().entrySet()) {
if (!portShips.contains(entry.getKey())) {
for (Long item : entry.getValue().getItemId()) {
ItemContext.get().remove(item);
ItemContext.level().remove(item);
ItemContext.alv().remove(item);
}
ShipContext.get().remove(entry.getKey());
}
}
if (AppConfig.get().isNoticeNewShip() && !oldShips.isEmpty()) {
StringBuilder sb = new StringBuilder();
sb.append(AppConstants.MESSAGE_NEW_SHIP).append("\n");
boolean show = false;
for (ShipInfoDto ship : newShips) {
boolean isNew = true;
for (ShipInfoDto old : oldShips)
if (ship.compareShipIncludeAfter(old)) {
isNew = false;
break;
}
if (isNew) {
if (show)
sb.append(", ");
else
show = true;
sb.append(ship.getName());
}
}
if (show) {
String mes = sb.toString();
Display.getDefault().asyncExec(() -> {
ToolTip tip = new ToolTip(ApplicationMain.getWindow().getShell(), SWT.BALLOON
| SWT.ICON_INFORMATION);
tip.setText("");
tip.setMessage(mes);
ApplicationMain.getWindow().getTrayItem().setToolTip(tip);
tip.setVisible(true);
});
}
}
JsonArray apiDeckPort = apidata.getJsonArray("api_deck_port");
doDeck(apiDeckPort);
addConsole("");
JsonArray apiNdock = apidata.getJsonArray("api_ndock");
doNdockSub(apiNdock);
addConsole("");
deckMissions = new DeckMissionDto[] { DeckMissionDto.EMPTY, DeckMissionDto.EMPTY,
DeckMissionDto.EMPTY };
for (int i = 1; i < apiDeckPort.size(); i++) {
JsonObject object = (JsonObject) apiDeckPort.get(i);
JsonArray jmission = object.getJsonArray("api_mission");
int section = ((JsonNumber) jmission.get(1)).intValue();
long milis = ((JsonNumber) jmission.get(2)).longValue();
long fleetid = object.getJsonNumber("api_id").longValue();
doMissionSub(fleetid, section, milis);
}
addConsole("");
combined = 0;
if (apidata.containsKey("api_combined_flag")) {
combined = apidata.getJsonNumber("api_combined_flag").intValue();
addConsole("");
}
}
} catch (Exception e) {
LoggerHolder.LOG.warn("", e);
LoggerHolder.LOG.warn(data);
}
}
/**
*
* @param data
*/
private static void doBattle(Data data, boolean night, boolean nightToDay) {
try {
JsonObject apidata = data.getJsonObject().getJsonObject("api_data");
battleList.add(new BattleDto(apidata, night, nightToDay, combined));
if (sortiePhase != SortiePhase.BATTLE)
battleCount++;
sortiePhase = SortiePhase.BATTLE;
addConsole("");
} catch (Exception e) {
LoggerHolder.LOG.warn("", e);
LoggerHolder.LOG.warn(data);
}
}
/**
*
* @param data
*/
private static void doBattleresult(Data data) {
try {
if (battleList.size() != 0) {
JsonObject apidata = data.getJsonObject().getJsonObject("api_data");
BattleResultDto dto = new BattleResultDto(apidata, mapCellNo, mapBossCellNo, bossArrive, isStart,
battleList.toArray(new BattleDto[0]));
battleResultList.add(dto);
CreateReportLogic.storeBattleResultReport(dto);
battleList.clear();
BattleDto last = dto.getBattles()[dto.getBattles().length - 1];
boolean s = "S".equals(dto.getRank());
boolean a = s || "A".equals(dto.getRank());
boolean win = a || "B".equals(dto.getRank());
int ap = 0;
int cv = 0;
int ss = 0;
for (int i = 0; i < last.getEnemy1().size(); ++i) {
if (last.getEndEnemy1Hp()[i] <= 0) {
switch (last.getEnemy1().get(i).getType()) {
case "":
ap++;
break;
case "":
case "":
cv++;
break;
case "":
ss++;
break;
}
}
}
Date now = new Date();
for (Integer no : QuestConfig.getNoList()) {
QuestBean bean = QuestConfig.get(no);
if ((bean != null) && bean.getExecuting()) {
if (win) {
bean.countBattleWin(now);
}
if (s) {
bean.countBattleWinS(now);
}
if (bossArrive) {
bean.countBossArrive(now);
if (win) {
bean.countBossWin(now);
switch (mapAreaNo) {
case 1:
if ((mapInfoNo == 4) && s) {
bean.countBoss1_4WinS(now);
}
if ((mapInfoNo == 5) && a) {
bean.countBoss1_5WinA(now);
}
break;
case 2:
bean.countBoss2Win(now);
break;
case 3:
if (mapInfoNo >= 3) {
bean.countBoss3_3pWin(now);
}
break;
case 4:
bean.countBoss4Win(now);
if (mapInfoNo == 4) {
bean.countBoss4_4Win(now);
}
break;
case 5:
if ((mapInfoNo == 2) && s) {
bean.countBoss5_2WinS(now);
}
break;
case 6:
if ((mapInfoNo == 1) && s) {
bean.countBoss6_1WinS(now);
}
break;
}
}
}
Calendar c = Calendar.getInstance();
c.setTime(now);
for (int i = 0; i < ap; ++i) {
bean.countDefeatAP(c.getTime());
c.add(Calendar.MILLISECOND, -1);
}
c.setTime(now);
for (int i = 0; i < cv; ++i) {
bean.countDefeatCV(c.getTime());
c.add(Calendar.MILLISECOND, -1);
}
c.setTime(now);
for (int i = 0; i < ss; ++i) {
bean.countDefeatSS(c.getTime());
c.add(Calendar.MILLISECOND, -1);
}
}
}
QuestConfig.store();
List<ShipDto> sps = new ArrayList<ShipDto>();
for (int i = 0; i < AppConstants.MAX_CHARA; i++) {
if ((last.getMaxFriend1Hp()[i] > 0)
&& ((last.getEndFriend1Hp()[i] * 4) <= last.getMaxFriend1Hp()[i])) {
sps.add(last.getFriends().get(0).getShips().get(i));
}
if ((last.getMaxFriend2Hp()[i] > 0)
&& ((last.getEndFriend2Hp()[i] * 4) <= last.getMaxFriend2Hp()[i])) {
sps.add(last.getFriends().get(1).getShips().get(i));
}
}
if (!sps.isEmpty()) {
Thread th = new Thread() {
private List<ShipDto> ships;
public Thread set(List<ShipDto> ships) {
this.ships = ships;
return this;
}
@Override
public void run() {
try {
sleep(8000);
} catch (InterruptedException e) {
}
Display.getDefault().asyncExec(new PostFatal(this.ships));
}
class PostFatal implements Runnable {
private final List<ShipDto> ships;
public PostFatal(List<ShipDto> ships) {
super();
this.ships = ships;
}
@Override
public void run() {
if (AppConfig.get().isBalloonBybadlyDamage()) {
StringBuilder sb = new StringBuilder();
sb.append(AppConstants.MESSAGE_STOP_SORTIE);
sb.append("\n");
for (ShipDto shipDto : this.ships) {
sb.append(shipDto.getName());
sb.append("(" + shipDto.getLv() + ")");
sb.append(" : ");
List<ItemDto> items = shipDto.getItem();
List<String> names = new ArrayList<String>();
for (ItemDto itemDto : items) {
if (itemDto != null) {
names.add(itemDto.getName());
}
}
sb.append(StringUtils.join(names, ","));
sb.append("\n");
}
ToolTip tip = new ToolTip(ApplicationMain.getWindow().getShell(), SWT.BALLOON
| SWT.ICON_ERROR);
tip.setText("");
tip.setMessage(sb.toString());
ApplicationMain.getWindow().getTrayItem().setToolTip(tip);
tip.setVisible(true);
}
PlayerThread.randomBadlySoundPlay();
}
}
}.set(sps);
th.start();
}
}
sortiePhase = SortiePhase.BATTLE_RESULT;
isStart = false;
addConsole("");
} catch (Exception e) {
LoggerHolder.LOG.warn("", e);
LoggerHolder.LOG.warn(data);
}
}
/**
* ()
* @param data
*/
private static void doCreateship(Data data) {
try {
String kdockid = data.getField("api_kdock_id");
ResourceDto resource = new ResourceDto(
data.getField("api_large_flag"),
data.getField("api_item1"),
data.getField("api_item2"),
data.getField("api_item3"),
data.getField("api_item4"),
data.getField("api_item5"),
ShipContext.getSecretary(), hqLevel);
lastBuildKdock = kdockid;
getShipResource.put(kdockid, resource);
KdockConfig.store(kdockid, resource);
Date now = new Date();
for (Integer no : QuestConfig.getNoList()) {
QuestBean bean = QuestConfig.get(no);
if ((bean != null) && bean.getExecuting()) {
bean.countCreateShip(now);
}
}
QuestConfig.store();
addConsole("()");
} catch (Exception e) {
LoggerHolder.LOG.warn("()", e);
LoggerHolder.LOG.warn(data);
}
}
/**
*
* @param data
*/
private static void doKdock(Data data) {
try {
if (lastBuildKdock != null) {
ResourceDto resource = getShipResource.get(lastBuildKdock);
if (resource != null) {
int freecount = 0;
JsonArray apidata = data.getJsonObject().getJsonArray("api_data");
for (int i = 0; i < apidata.size(); i++) {
int state = ((JsonObject) apidata.get(i)).getJsonNumber("api_state").intValue();
if (state == 0) {
freecount++;
}
}
resource.setFreeDock(Integer.toString(freecount));
KdockConfig.store(lastBuildKdock, resource);
}
}
addConsole("");
} catch (Exception e) {
LoggerHolder.LOG.warn("", e);
LoggerHolder.LOG.warn(data);
}
}
/**
* ()
* @param data
*/
private static void doGetship(Data data) {
try {
JsonObject apidata = data.getJsonObject().getJsonObject("api_data");
String dock = data.getField("api_kdock_id");
if (!apidata.isNull("api_slotitem")) {
JsonArray slotitem = apidata.getJsonArray("api_slotitem");
for (int i = 0; i < slotitem.size(); i++) {
JsonObject object = (JsonObject) slotitem.get(i);
int typeid = object.getJsonNumber("api_slotitem_id").intValue();
Long id = object.getJsonNumber("api_id").longValue();
ItemDto item = Item.get(typeid);
if (item != null) {
ItemContext.get().put(id, item);
}
}
}
JsonObject apiShip = apidata.getJsonObject("api_ship");
ShipDto ship = new ShipDto(apiShip);
ShipContext.get().put(Long.valueOf(ship.getId()), ship);
ResourceDto resource = getShipResource.get(dock);
if (resource == null) {
resource = KdockConfig.load(dock);
}
GetShipDto dto = new GetShipDto(ship, resource);
getShipList.add(dto);
CreateReportLogic.storeCreateShipReport(dto);
getShipResource.remove(dock);
KdockConfig.remove(dock);
addConsole("()");
} catch (Exception e) {
LoggerHolder.LOG.warn("()", e);
LoggerHolder.LOG.warn(data);
}
}
/**
*
*
* @param data
*/
private static void doCreateitem(Data data) {
try {
JsonObject apidata = data.getJsonObject().getJsonObject("api_data");
ResourceDto resources = new ResourceDto(data.getField("api_item1"), data.getField("api_item2"),
data.getField("api_item3"), data.getField("api_item4"), ShipContext.getSecretary(), hqLevel);
CreateItemDto createitem = new CreateItemDto(apidata, resources);
if (createitem.isCreateFlag()) {
JsonObject object = apidata.getJsonObject("api_slot_item");
int typeid = object.getJsonNumber("api_slotitem_id").intValue();
Long id = object.getJsonNumber("api_id").longValue();
ItemDto item = Item.get(typeid);
if (item != null) {
ItemContext.get().put(id, item);
createitem.setName(item.getName());
createitem.setType(item.getType());
createItemList.add(createitem);
}
} else {
createItemList.add(createitem);
}
Date now = new Date();
for (Integer no : QuestConfig.getNoList()) {
QuestBean bean = QuestConfig.get(no);
if ((bean != null) && bean.getExecuting()) {
bean.countCreateItem(now);
}
}
QuestConfig.store();
CreateReportLogic.storeCreateItemReport(createitem);
addConsole("");
} catch (Exception e) {
LoggerHolder.LOG.warn("", e);
LoggerHolder.LOG.warn(data);
}
}
/**
*
*
* @param data
*/
private static void doSlotitemMember(Data data) {
try {
JsonArray apidata = data.getJsonObject().getJsonArray("api_data");
doSlotitemMemberSub(apidata);
addConsole("");
} catch (Exception e) {
LoggerHolder.LOG.warn("", e);
LoggerHolder.LOG.warn(data);
}
}
/**
*
*
* @param data
*/
private static void doSlotitemMemberSub(JsonArray apidata) {
ItemContext.get().clear();
ItemContext.level().clear();
for (int i = 0; i < apidata.size(); i++) {
JsonObject object = (JsonObject) apidata.get(i);
int typeid = object.getJsonNumber("api_slotitem_id").intValue();
int level = object.getJsonNumber("api_level").intValue();
int alv = -1;
if (object.containsKey("api_alv")) {
alv = object.getJsonNumber("api_alv").intValue();
}
Long id = object.getJsonNumber("api_id").longValue();
ItemDto item = Item.get(typeid);
if (item != null) {
ItemContext.get().put(id, item);
ItemContext.level().put(id, level);
if (alv > 0) {
ItemContext.alv().put(id, alv);
} else {
ItemContext.alv().remove(id);
}
}
}
}
/**
*
*
* @param data
*/
private static void doShip3(Data data) {
try {
JsonObject apidata = data.getJsonObject().getJsonObject("api_data");
String shipidstr = data.getField("api_shipid");
JsonArray shipdata = apidata.getJsonArray("api_ship_data");
if (shipidstr != null) {
Long shipid = Long.parseLong(shipidstr);
for (int i = 0; i < shipdata.size(); i++) {
ShipDto ship = new ShipDto((JsonObject) shipdata.get(i));
ShipContext.get().put(shipid, ship);
}
} else {
ShipContext.get().clear();
for (int i = 0; i < shipdata.size(); i++) {
ShipDto ship = new ShipDto((JsonObject) shipdata.get(i));
ShipContext.get().put(Long.valueOf(ship.getId()), ship);
}
}
doDeck(apidata.getJsonArray("api_deck_data"));
addConsole("");
} catch (Exception e) {
LoggerHolder.LOG.warn("", e);
LoggerHolder.LOG.warn(data);
}
}
/**
*
*
* @param data
*/
private static void doShip2(Data data) {
try {
JsonArray apidata = data.getJsonObject().getJsonArray("api_data");
ShipContext.get().clear();
for (int i = 0; i < apidata.size(); i++) {
ShipDto ship = new ShipDto((JsonObject) apidata.get(i));
ShipContext.get().put(Long.valueOf(ship.getId()), ship);
}
doDeck(data.getJsonObject().getJsonArray("api_data_deck"));
addConsole("");
} catch (Exception e) {
LoggerHolder.LOG.warn("", e);
LoggerHolder.LOG.warn(data);
}
}
/**
*
*
* @param data
*/
private static void doShipDeck(Data data) {
try {
JsonObject apidata = data.getJsonObject().getJsonObject("api_data");
JsonArray shipData = apidata.getJsonArray("api_ship_data");
for (int i = 0; i < shipData.size(); i++) {
ShipDto ship = new ShipDto((JsonObject) shipData.get(i));
ShipContext.get().put(Long.valueOf(ship.getId()), ship);
}
doDeck(apidata.getJsonArray("api_deck_data"));
} catch (Exception e) {
LoggerHolder.LOG.warn("", e);
LoggerHolder.LOG.warn(data);
}
}
/**
*
*
* @param data
*/
private static void doDeck(Data data) {
try {
JsonArray apidata = data.getJsonObject().getJsonArray("api_data");
for (DockDto dockdto : dock.values()) {
for (ShipDto ship : dockdto.getShips()) {
ship.setFleetid("");
}
}
doDeck(apidata);
addConsole("");
} catch (Exception e) {
LoggerHolder.LOG.warn("", e);
LoggerHolder.LOG.warn(data);
}
}
/**
*
*
* @param apidata
*/
private static void doDeck(JsonArray apidata) {
dock.clear();
for (int i = 0; i < apidata.size(); i++) {
JsonObject jsonObject = (JsonObject) apidata.get(i);
String fleetid = Long.toString(jsonObject.getJsonNumber("api_id").longValue());
String name = jsonObject.getString("api_name");
JsonArray apiship = jsonObject.getJsonArray("api_ship");
DockDto dockdto = new DockDto(fleetid, name);
dock.put(fleetid, dockdto);
for (int j = 0; j < apiship.size(); j++) {
Long shipid = Long.valueOf(((JsonNumber) apiship.get(j)).longValue());
ShipDto ship = ShipContext.get().get(shipid);
if (ship != null) {
dockdto.addShip(ship);
if ((i == 0) && (j == 0)) {
ShipContext.setSecretary(ship);
}
ship.setFleetid(fleetid);
}
}
}
}
/**
*
* @param data
*/
private static void doDestroyShip(Data data) {
try {
Long shipid = Long.parseLong(data.getField("api_ship_id"));
ShipDto ship = ShipContext.get().get(shipid);
if (ship != null) {
List<Long> items = ship.getItemId();
for (Long item : items) {
ItemContext.get().remove(item);
ItemContext.level().remove(item);
ItemContext.alv().remove(item);
}
ShipContext.get().remove(ship.getId());
DockDto dockdto = dock.get(ship.getFleetid());
if (dockdto != null)
dockdto.removeShip(dockdto.indexOf(ship));
}
Date now = new Date();
for (Integer no : QuestConfig.getNoList()) {
QuestBean bean = QuestConfig.get(no);
if ((bean != null) && bean.getExecuting()) {
bean.countDestroyShip(now);
}
}
QuestConfig.store();
addConsole("");
} catch (Exception e) {
LoggerHolder.LOG.warn("", e);
LoggerHolder.LOG.warn(data);
}
}
/**
*
* @param data
*/
private static void doDestroyItem2(Data data) {
try {
String itemids = data.getField("api_slotitem_ids");
for (String itemid : itemids.split(",")) {
Long item = Long.parseLong(itemid);
ItemContext.get().remove(item);
ItemContext.level().remove(item);
ItemContext.alv().remove(item);
}
Date now = new Date();
for (Integer no : QuestConfig.getNoList()) {
QuestBean bean = QuestConfig.get(no);
if ((bean != null) && bean.getExecuting()) {
bean.countDestroyItem(now);
}
}
QuestConfig.store();
addConsole("");
} catch (Exception e) {
LoggerHolder.LOG.warn("", e);
LoggerHolder.LOG.warn(data);
}
}
/**
*
* @param data
*/
private static void doPowerup(Data data) {
try {
String shipids = data.getField("api_id_items");
for (String shipid : shipids.split(",")) {
ShipDto ship = ShipContext.get().get(Long.parseLong(shipid));
if (ship != null) {
List<Long> items = ship.getItemId();
for (Long item : items) {
ItemContext.get().remove(item);
ItemContext.level().remove(item);
ItemContext.alv().remove(item);
}
ShipContext.get().remove(ship.getId());
}
}
if (data.getJsonObject().getJsonObject("api_data").getJsonNumber("api_powerup_flag").intValue() != 0) {
Date now = new Date();
for (Integer no : QuestConfig.getNoList()) {
QuestBean bean = QuestConfig.get(no);
if ((bean != null) && bean.getExecuting()) {
bean.countPowerUp(now);
}
}
QuestConfig.store();
}
addConsole("");
} catch (Exception e) {
LoggerHolder.LOG.warn("", e);
LoggerHolder.LOG.warn(data);
}
}
/**
*
*
* @param data
*/
private static void doBasic(Data data) {
try {
JsonObject apidata = data.getJsonObject().getJsonObject("api_data");
doBasicSub(apidata);
addConsole("");
} catch (Exception e) {
LoggerHolder.LOG.warn("", e);
LoggerHolder.LOG.warn(data);
}
}
/**
*
*
* @param apidata
*/
private static void doBasicSub(JsonObject apidata) {
hqLevel = apidata.getJsonNumber("api_level").intValue();
maxChara = apidata.getJsonNumber("api_max_chara").intValue();
maxSlotitem = apidata.getJsonNumber("api_max_slotitem").intValue();
}
/**
*
*
* @param data
*/
private static void doMission(Data data) {
try {
JsonObject apidata = data.getJsonObject().getJsonObject("api_data");
doMissionSub(Long.parseLong(data.getField("api_deck_id")),
Integer.parseInt(data.getField("api_mission_id")),
apidata.getJsonNumber("api_complatetime").longValue());
addConsole("");
} catch (Exception e) {
LoggerHolder.LOG.warn("", e);
LoggerHolder.LOG.warn(data);
}
}
/**
*
*
* @param data
*/
private static void doMissionSub(long fleetId, int missionId, long milis) {
String mission = null;
if (missionId != 0) {
mission = Deck.get(missionId);
if (mission == null) {
mission = "<UNKNOWN>";
}
}
DockDto dockdto = dock.get(Long.toString(fleetId));
Set<Long> ships = new LinkedHashSet<Long>();
for (ShipDto s : dockdto.getShips()) {
long shipid = s.getId();
if (shipid != -1) {
ships.add(shipid);
}
}
Date time = null;
if (milis > 0) {
time = new Date(milis);
}
deckMissions[(int) (fleetId - 2)] = new DeckMissionDto(dockdto.getName(), mission, time, fleetId, ships);
}
/**
* ()
*
* @param data
*/
private static void doMissionResult(Data data) {
try {
JsonObject apidata = data.getJsonObject().getJsonObject("api_data");
MissionResultDto result = new MissionResultDto();
int clearResult = apidata.getJsonNumber("api_clear_result").intValue();
result.setClearResult(clearResult);
result.setQuestName(apidata.getString("api_quest_name"));
if (clearResult != 0) {
JsonArray material = apidata.getJsonArray("api_get_material");
result.setFuel(material.getJsonNumber(0).toString());
result.setAmmo(material.getJsonNumber(1).toString());
result.setMetal(material.getJsonNumber(2).toString());
result.setBauxite(material.getJsonNumber(3).toString());
Date now = new Date();
for (Integer no : QuestConfig.getNoList()) {
QuestBean bean = QuestConfig.get(no);
if ((bean != null) && bean.getExecuting()) {
bean.countMissionSuccess(now);
}
}
QuestConfig.store();
}
CreateReportLogic.storeCreateMissionReport(result);
missionResultList.add(result);
addConsole("()");
} catch (Exception e) {
LoggerHolder.LOG.warn("()", e);
LoggerHolder.LOG.warn(data);
}
}
/**
*
* @param data
*/
private static void doNdock(Data data) {
try {
JsonArray apidata = data.getJsonObject().getJsonArray("api_data");
doNdockSub(apidata);
addConsole("");
} catch (Exception e) {
LoggerHolder.LOG.warn("", e);
LoggerHolder.LOG.warn(data);
}
}
/**
*
* @param apidata
*/
private static void doNdockSub(JsonArray apidata) {
NdockDto[] newNdocks = new NdockDto[] { NdockDto.EMPTY, NdockDto.EMPTY, NdockDto.EMPTY, NdockDto.EMPTY };
for (int i = 0; i < apidata.size(); i++) {
JsonObject object = (JsonObject) apidata.get(i);
long id = object.getJsonNumber("api_ship_id").longValue();
long milis = object.getJsonNumber("api_complete_time").longValue();
Date time = null;
if (milis > 0) {
time = new Date(milis);
}
newNdocks[i] = new NdockDto(id, time);
if ((id == 0) && (ndocks[i].getNdockid() > 0)) {
processSpeedChange(i);
}
}
ndocks = newNdocks;
}
/**
*
* @param data
*/
private static void doSpeedChange(Data data) {
try {
String ndockIdStr = data.getField("api_ndock_id");
if (ndockIdStr != null) {
int ndockId = Integer.parseInt(ndockIdStr);
processSpeedChange(ndockId - 1);
}
addConsole("");
} catch (Exception e) {
LoggerHolder.LOG.warn("", e);
LoggerHolder.LOG.warn(data);
}
}
/**
*
* @param ndockId
*/
private static void processSpeedChange(int ndockId) {
NdockDto ndock = ndocks[ndockId];
ndocks[ndockId] = new NdockDto(0, null);
ShipDto ship = ShipContext.get().get(ndock.getNdockid());
if (ship != null) {
ship.setNowHp(ship.getMaxhp());
ship.setDocktime(0);
String fleetid = ship.getFleetid();
if (fleetid != null) {
DockDto dockdto = dock.get(fleetid);
if (dockdto != null) {
dockdto.setUpdate(true);
}
}
}
}
/**
*
*
* @param data
*/
private static void doQuest(Data data) {
try {
JsonObject apidata = data.getJsonObject().getJsonObject("api_data");
if (!apidata.isNull("api_list")) {
JsonArray apilist = apidata.getJsonArray("api_list");
for (JsonValue value : apilist) {
if (value instanceof JsonObject) {
JsonObject questobject = (JsonObject) value;
QuestDto quest = new QuestDto();
quest.setNo(questobject.getInt("api_no"));
quest.setCategory(questobject.getInt("api_category"));
quest.setType(questobject.getInt("api_type"));
quest.setState(questobject.getInt("api_state"));
quest.setTitle(questobject.getString("api_title"));
quest.setDetail(questobject.getString("api_detail"));
JsonArray material = questobject.getJsonArray("api_get_material");
quest.setFuel(material.getJsonNumber(0).toString());
quest.setAmmo(material.getJsonNumber(1).toString());
quest.setMetal(material.getJsonNumber(2).toString());
quest.setBauxite(material.getJsonNumber(3).toString());
quest.setBonusFlag(questobject.getInt("api_bonus_flag"));
quest.setProgressFlag(questobject.getInt("api_progress_flag"));
QuestBean bean = QuestConfig.get(quest.getNo());
if (bean == null) {
bean = new QuestBean();
}
switch (quest.getType()) {
case 1:
bean.setDue(QuestDue.getDaily());
break;
case 2:
bean.setDue(QuestDue.getWeekly());
break;
case 3:
bean.setDue(QuestDue.getMonthly());
break;
case 5:
switch (quest.getNo()) {
case 211:
case 212:
bean.setDue(QuestDue.getDaily());
break;
}
}
bean.setExecuting(quest.getState() == 2);
QuestConfig.put(quest.getNo(), bean);
questMap.put(quest.getNo(), quest);
}
}
QuestConfig.store();
}
addConsole("");
} catch (Exception e) {
LoggerHolder.LOG.warn("", e);
LoggerHolder.LOG.warn(data);
}
}
/**
*
*
* @param data
*/
private static void doQuestClear(Data data) {
try {
String idstr = data.getField("api_quest_id");
if (idstr != null) {
Integer id = Integer.valueOf(idstr);
questMap.remove(id);
QuestConfig.remove(id);
}
} catch (Exception e) {
LoggerHolder.LOG.warn("", e);
LoggerHolder.LOG.warn(data);
}
}
/**
*
*
* @param data
*/
private static void doStart(Data data) {
try {
String idstr = data.getField("api_deck_id");
if (idstr != null) {
int id = Integer.parseInt(idstr);
isSortie[id - 1] = true;
}
if (combined != 0) {
isSortie[1] = true;
}
isStart = true;
JsonObject obj = data.getJsonObject().getJsonObject("api_data");
mapAreaNo = obj.getJsonNumber("api_maparea_id").intValue();
mapInfoNo = obj.getJsonNumber("api_mapinfo_no").intValue();
mapCellNo = obj.getJsonNumber("api_no").intValue();
mapBossCellNo = obj.getJsonNumber("api_bosscell_no").intValue();
eventId = obj.getJsonNumber("api_event_id").intValue();
int color = obj.getJsonNumber("api_color_no").intValue();
bossArrive = (color == 5) || (color == 8);
Date now = new Date();
for (Integer no : QuestConfig.getNoList()) {
QuestBean bean = QuestConfig.get(no);
if ((bean != null) && bean.getExecuting()) {
bean.countSortie(now);
}
}
QuestConfig.store();
battleCount = 0;
sortiePhase = SortiePhase.MAP;
addConsole("");
} catch (Exception e) {
LoggerHolder.LOG.warn("", e);
LoggerHolder.LOG.warn(data);
}
}
/**
*
*
* @param data
*/
private static void doNext(Data data) {
try {
JsonObject obj = data.getJsonObject().getJsonObject("api_data");
mapAreaNo = obj.getJsonNumber("api_maparea_id").intValue();
mapInfoNo = obj.getJsonNumber("api_mapinfo_no").intValue();
mapCellNo = obj.getJsonNumber("api_no").intValue();
mapBossCellNo = obj.getJsonNumber("api_bosscell_no").intValue();
eventId = obj.getJsonNumber("api_event_id").intValue();
int color = obj.getJsonNumber("api_color_no").intValue();
bossArrive = (color == 5) || (color == 8);
sortiePhase = SortiePhase.MAP;
addConsole("");
} catch (Exception e) {
LoggerHolder.LOG.warn("", e);
LoggerHolder.LOG.warn(data);
}
}
/**
*
*
* @param data
*/
private static void doStart2(Data data) {
try {
JsonObject obj = data.getJsonObject().getJsonObject("api_data");
if (obj != null) {
JsonArray apiMstShip = obj.getJsonArray("api_mst_ship");
for (int i = 0; i < apiMstShip.size(); i++) {
JsonObject object = (JsonObject) apiMstShip.get(i);
int id = object.getJsonNumber("api_id").intValue();
Ship.set(id, toShipInfoDto(object));
}
addConsole("");
JsonArray apiMstSlotitem = obj.getJsonArray("api_mst_slotitem");
for (int i = 0; i < apiMstSlotitem.size(); i++) {
JsonObject object = (JsonObject) apiMstSlotitem.get(i);
ItemDto item = new ItemDto(object);
int id = object.getJsonNumber("api_id").intValue();
Item.set(id, item);
}
addConsole("");
}
addConsole("");
} catch (Exception e) {
LoggerHolder.LOG.warn("", e);
LoggerHolder.LOG.warn(data);
}
}
/**
*
* @param data
*/
private static void doPracticeResult(Data data) {
try {
JsonObject obj = data.getJsonObject().getJsonObject("api_data");
if (obj != null) {
String rank = obj.getString("api_win_rank");
boolean win = "B".equals(rank) || "A".equals(rank) || "S".equals(rank);
Date now = new Date();
for (Integer no : QuestConfig.getNoList()) {
QuestBean bean = QuestConfig.get(no);
if ((bean != null) && bean.getExecuting()) {
bean.countPractice(now);
if (win) {
bean.countPracticeWin(now);
}
}
}
QuestConfig.store();
addConsole("");
}
} catch (Exception e) {
LoggerHolder.LOG.warn("", e);
LoggerHolder.LOG.warn(data);
}
}
/**
*
* @param data
*/
private static void doNyukyo(Data data) {
try {
Date now = new Date();
for (Integer no : QuestConfig.getNoList()) {
QuestBean bean = QuestConfig.get(no);
if ((bean != null) && bean.getExecuting()) {
bean.countRepair(now);
}
}
QuestConfig.store();
addConsole("");
} catch (Exception e) {
LoggerHolder.LOG.warn("", e);
LoggerHolder.LOG.warn(data);
}
}
/**
*
*
* @param object
* @return
*/
private static ShipInfoDto toShipInfoDto(JsonObject object) {
String name = object.getString("api_name");
if ("".equals(name)) {
return ShipInfoDto.EMPTY;
}
String yomi = object.getString("api_yomi");
if ("-".equals(yomi)) {
yomi = "";
}
int shipid = 0;
if (object.containsKey("api_id")) {
shipid = JsonUtils.getInt(object.get("api_id"));
}
String stype = "";
if (object.containsKey("api_stype")) {
stype = ShipStyle.get(JsonUtils.getInt(object.get("api_stype")));
}
int afterlv = 0;
if (object.containsKey("api_afterlv")) {
afterlv = JsonUtils.getInt(object.get("api_afterlv"));
}
int aftershipid = 0;
if (object.containsKey("api_aftershipid")) {
aftershipid = JsonUtils.getInt(object.get("api_aftershipid"));
}
int slotNum = 0;
if (object.containsKey("api_slot_num")) {
slotNum = JsonUtils.getInt(object.get("api_slot_num"));
}
int maxFuel = 0;
if (object.containsKey("api_fuel_max")) {
maxFuel = JsonUtils.getInt(object.get("api_fuel_max"));
}
int maxBull = 0;
if (object.containsKey("api_bull_max")) {
maxBull = JsonUtils.getInt(object.get("api_bull_max"));
}
int ctype = 0;
if (object.containsKey("api_ctype")) {
ctype = JsonUtils.getInt(object.get("api_ctype"));
}
return new ShipInfoDto(shipid, name, yomi, stype, afterlv, aftershipid, slotNum, maxFuel, maxBull, ctype);
}
/**
*
*
* @param message
*/
private static void addConsole(Object message) {
ConsoleContext.log(message);
}
}
|
/**
* No Rights Reserved.
* This program and the accompanying materials
* are made available under the terms of the Public Domain.
*/
package logbook.gui.widgets;
import java.text.MessageFormat;
import java.util.BitSet;
import java.util.List;
import javax.annotation.CheckForNull;
import logbook.config.AppConfig;
import logbook.constants.AppConstants;
import logbook.data.context.GlobalContext;
import logbook.dto.DockDto;
import logbook.dto.ShipDto;
import logbook.gui.ApplicationMain;
import logbook.gui.logic.Sound;
import logbook.internal.EvaluateExp;
import logbook.internal.SeaExp;
import logbook.util.CalcExpUtils;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.ToolTip;
import org.eclipse.wb.swt.SWTResourceManager;
public class FleetComposite extends Composite {
private static final int WARN = 1;
private static final int FATAL = 2;
private static final int POSTED_BADLY = 3;
private static final int MAXCHARA = 6;
private final CTabItem tab;
private final ApplicationMain main;
private final Font large;
private final Font small;
private DockDto dock;
private final Composite fleetGroup;
private final BitSet state = new BitSet();
private long cond;
private String clearDate;
private boolean badlyDamage;
private final Label[] iconLabels = new Label[MAXCHARA];
private final Label[] nameLabels = new Label[MAXCHARA];
private final Label[] hpLabels = new Label[MAXCHARA];
private final Label[] hpgaugeLabels = new Label[MAXCHARA];
private final Label[] hpmsgLabels = new Label[MAXCHARA];
private final Label[] condLabels = new Label[MAXCHARA];
private final Label[] condstLabels = new Label[MAXCHARA];
private final Label[] bullstLabels = new Label[MAXCHARA];
private final Label[] fuelstLabels = new Label[MAXCHARA];
private final Label[] nextLabels = new Label[MAXCHARA];
private final StyledText message;
/**
* @param parent
* @param tabItem
*/
public FleetComposite(CTabFolder parent, CTabItem tabItem, ApplicationMain main) {
super(parent, SWT.NONE);
this.tab = tabItem;
this.main = main;
this.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
GridLayout glParent = new GridLayout(1, false);
glParent.horizontalSpacing = 0;
glParent.marginTop = 0;
glParent.marginWidth = 0;
glParent.marginHeight = 0;
glParent.marginBottom = 0;
glParent.verticalSpacing = 0;
this.setLayout(glParent);
FontData normalfd = parent.getShell().getFont().getFontData()[0];
FontData largefd = new FontData(normalfd.getName(), normalfd.getHeight() + 2, normalfd.getStyle());
FontData smallfd = new FontData(normalfd.getName(), normalfd.getHeight() - 1, normalfd.getStyle());
this.large = new Font(Display.getCurrent(), largefd);
this.small = new Font(Display.getCurrent(), smallfd);
this.fleetGroup = new Composite(this, SWT.NONE);
this.fleetGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
GridLayout glShipGroup = new GridLayout(3, false);
glShipGroup.horizontalSpacing = 0;
glShipGroup.marginTop = 0;
glShipGroup.marginWidth = 1;
glShipGroup.marginHeight = 0;
glShipGroup.marginBottom = 0;
glShipGroup.verticalSpacing = 0;
this.fleetGroup.setLayout(glShipGroup);
this.init();
Label separator = new Label(this, SWT.SEPARATOR | SWT.HORIZONTAL);
separator.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
this.message = new StyledText(this, SWT.READ_ONLY | SWT.WRAP);
this.message.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
this.message.setWordWrap(true);
this.message.setBackground(this.getBackground());
this.fleetGroup.layout();
}
private void init() {
for (int i = 0; i < MAXCHARA; i++) {
Label iconlabel = new Label(this.fleetGroup, SWT.NONE);
GridData gdIconlabel = new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1);
gdIconlabel.widthHint = 16;
iconlabel.setLayoutData(gdIconlabel);
Label namelabel = new Label(this.fleetGroup, SWT.NONE);
namelabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
namelabel.setFont(this.large);
namelabel.setText("");
Composite hpComposite = new Composite(this.fleetGroup, SWT.NONE);
GridLayout glHp = new GridLayout(3, false);
glHp.horizontalSpacing = 0;
glHp.marginTop = 0;
glHp.marginWidth = 1;
glHp.marginHeight = 0;
glHp.marginBottom = 0;
glHp.verticalSpacing = 0;
hpComposite.setLayout(glHp);
hpComposite.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
Label hp = new Label(hpComposite, SWT.NONE);
hp.setFont(this.small);
Label hpgauge = new Label(hpComposite, SWT.NONE);
Label hpmsg = new Label(hpComposite, SWT.NONE);
hpmsg.setText("");
new Label(this.fleetGroup, SWT.NONE);
Composite stateComposite = new Composite(this.fleetGroup, SWT.NONE);
GridLayout glState = new GridLayout(4, false);
glState.horizontalSpacing = 0;
glState.marginTop = 0;
glState.marginWidth = 0;
glState.marginHeight = 0;
glState.marginBottom = 0;
glState.verticalSpacing = 0;
stateComposite.setLayout(glState);
stateComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
Label condst = new Label(stateComposite, SWT.NONE);
condst.setText("");
Label fuelst = new Label(stateComposite, SWT.NONE);
fuelst.setText("");
Label bullst = new Label(stateComposite, SWT.NONE);
bullst.setText("");
Label next = new Label(stateComposite, SWT.NONE);
next.setFont(this.small);
next.setText("");
Label cond = new Label(this.fleetGroup, SWT.NONE);
cond.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
cond.setText("49 cond.");
this.iconLabels[i] = iconlabel;
this.nameLabels[i] = namelabel;
this.hpLabels[i] = hp;
this.hpgaugeLabels[i] = hpgauge;
this.hpmsgLabels[i] = hpmsg;
this.condLabels[i] = cond;
this.condstLabels[i] = condst;
this.bullstLabels[i] = bullst;
this.fuelstLabels[i] = fuelst;
this.nextLabels[i] = next;
}
}
/**
*
*
* @param dock
*/
public void updateFleet(DockDto dock) {
if (this.dock == dock) {
return;
}
this.getShell().setRedraw(false);
this.dock = dock;
this.state.set(WARN, false);
this.state.set(FATAL, false);
this.cond = 49;
this.clearDate = null;
this.badlyDamage = false;
this.message.setText("");
List<ShipDto> ships = dock.getShips();
for (int i = ships.size(); i < MAXCHARA; i++) {
this.iconLabels[i].setImage(null);
this.nameLabels[i].setText("");
this.hpLabels[i].setText("");
this.hpgaugeLabels[i].setImage(null);
this.hpmsgLabels[i].setText("");
this.condLabels[i].setText("");
this.condstLabels[i].setText("");
this.bullstLabels[i].setText("");
this.fuelstLabels[i].setText("");
this.nextLabels[i].setText("");
}
for (int i = 0; i < ships.size(); i++) {
ShipDto ship = ships.get(i);
BitSet shipstatus = new BitSet();
long nowhp = ship.getNowhp();
// MaxHP
long maxhp = ship.getMaxhp();
float hpratio = (float) nowhp / (float) maxhp;
long cond = ship.getCond();
int bull = ship.getBull();
// Max
int bullmax = ship.getBullMax();
float bullraito = bullmax != 0 ? (float) bull / (float) bullmax : 1f;
int fuel = ship.getFuel();
// Max
int fuelmax = ship.getFuelMax();
float fuelraito = fuelmax != 0 ? (float) fuel / (float) fuelmax : 1f;
if (this.cond > cond) {
this.cond = cond;
this.clearDate = ship.getCondClearDate();
}
if (hpratio <= AppConstants.BADLY_DAMAGE) {
if (AppConfig.get().isFatalBybadlyDamage()) {
this.state.set(FATAL);
shipstatus.set(FATAL);
}
this.badlyDamage = true;
this.hpmsgLabels[i].setText("");
this.hpmsgLabels[i].setBackground(SWTResourceManager.getColor(AppConstants.COND_RED_COLOR));
this.hpmsgLabels[i].setForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
} else if (hpratio <= AppConstants.HALF_DAMAGE) {
if (AppConfig.get().isWarnByHalfDamage()) {
this.state.set(WARN);
shipstatus.set(WARN);
}
this.hpmsgLabels[i].setText("");
this.hpmsgLabels[i].setBackground(SWTResourceManager.getColor(AppConstants.COND_ORANGE_COLOR));
this.hpmsgLabels[i].setForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
} else if (hpratio <= AppConstants.SLIGHT_DAMAGE) {
this.hpmsgLabels[i].setText("");
this.hpmsgLabels[i].setBackground(null);
this.hpmsgLabels[i].setForeground(null);
} else {
this.hpmsgLabels[i].setText("");
this.hpmsgLabels[i].setBackground(null);
this.hpmsgLabels[i].setForeground(null);
}
this.condstLabels[i].setText("");
if (cond >= 49) {
this.condstLabels[i].setEnabled(false);
} else {
this.condstLabels[i].setEnabled(true);
}
this.fuelstLabels[i].setText("");
if (fuelraito >= 1f) {
this.fuelstLabels[i].setEnabled(false);
this.fuelstLabels[i].setForeground(null);
} else {
if (AppConfig.get().isWarnByNeedSupply()) {
this.state.set(WARN);
shipstatus.set(WARN);
}
this.fuelstLabels[i].setEnabled(true);
if (fuelraito <= AppConstants.EMPTY_SUPPLY) {
this.fuelstLabels[i].setForeground(SWTResourceManager.getColor(AppConstants.COND_RED_COLOR));
} else if (fuelraito <= AppConstants.LOW_SUPPLY) {
this.fuelstLabels[i].setForeground(SWTResourceManager.getColor(AppConstants.COND_ORANGE_COLOR));
}
}
this.bullstLabels[i].setText("");
if (bullraito >= 1f) {
this.bullstLabels[i].setEnabled(false);
this.bullstLabels[i].setBackground(null);
this.bullstLabels[i].setForeground(null);
} else {
if (AppConfig.get().isWarnByNeedSupply()) {
this.state.set(WARN);
shipstatus.set(WARN);
}
this.bullstLabels[i].setEnabled(true);
if (bullraito <= AppConstants.EMPTY_SUPPLY) {
this.bullstLabels[i].setForeground(SWTResourceManager.getColor(AppConstants.COND_RED_COLOR));
} else if (bullraito <= AppConstants.LOW_SUPPLY) {
this.bullstLabels[i].setForeground(SWTResourceManager.getColor(AppConstants.COND_ORANGE_COLOR));
}
}
if (AppConfig.get().isDisplayCount()) {
Integer nextcount = this.getNextCount(ship, i == 0);
if (nextcount != null) {
this.nextLabels[i].setText(MessageFormat.format("{0}", nextcount));
} else {
this.nextLabels[i].setText("");
}
}
if (cond <= AppConstants.COND_RED) {
if (AppConfig.get().isWarnByCondState()) {
this.state.set(WARN);
shipstatus.set(WARN);
}
this.condLabels[i].setForeground(SWTResourceManager.getColor(AppConstants.COND_RED_COLOR));
this.condstLabels[i].setForeground(SWTResourceManager.getColor(AppConstants.COND_RED_COLOR));
} else if (cond <= AppConstants.COND_ORANGE) {
if (AppConfig.get().isWarnByCondState()) {
this.state.set(WARN);
shipstatus.set(WARN);
}
this.condLabels[i].setForeground(SWTResourceManager.getColor(AppConstants.COND_ORANGE_COLOR));
this.condstLabels[i].setForeground(SWTResourceManager.getColor(AppConstants.COND_ORANGE_COLOR));
} else if (cond >= AppConstants.COND_GREEN) {
this.condLabels[i].setForeground(SWTResourceManager.getColor(AppConstants.COND_GREEN_COLOR));
this.condstLabels[i].setForeground(SWTResourceManager.getColor(AppConstants.COND_GREEN_COLOR));
} else {
this.condLabels[i].setForeground(null);
this.condstLabels[i].setForeground(null);
}
if (shipstatus.get(FATAL)) {
this.iconLabels[i].setImage(SWTResourceManager.getImage(FleetComposite.class,
AppConstants.R_ICON_EXCLAMATION));
} else if (shipstatus.get(WARN)) {
this.iconLabels[i].setImage(SWTResourceManager
.getImage(FleetComposite.class, AppConstants.R_ICON_ERROR));
} else {
this.iconLabels[i].setImage(null);
}
this.nameLabels[i].setText(ship.getName());
this.nameLabels[i].setToolTipText(MessageFormat.format(AppConstants.TOOLTIP_FLEETTAB_SHIP, nowhp, maxhp,
fuel, fuelmax, bull, bullmax, ship.getNext()));
this.hpLabels[i].setText(MessageFormat.format("{0}/{1} ", nowhp, maxhp));
this.hpgaugeLabels[i].setImage(this.getHpGaugeImage(hpratio));
this.condLabels[i].setText(MessageFormat.format("{0} cond.", cond));
this.bullstLabels[i].getParent().layout();
}
boolean isBathwater = false;
for (ShipDto shipDto : ships) {
if (GlobalContext.isNdock(shipDto)) {
isBathwater = true;
break;
}
}
int seiku = 0;
for (ShipDto shipDto : ships) {
seiku += shipDto.getSeiku();
}
if (GlobalContext.isMission(this.dock.getId())) {
StyleRange style = new StyleRange();
style.fontStyle = SWT.BOLD;
style.foreground = SWTResourceManager.getColor(SWT.COLOR_DARK_BLUE);
this.addStyledText(this.message, AppConstants.MESSAGE_MISSION, style);
} else if (isBathwater) {
StyleRange style = new StyleRange();
style.fontStyle = SWT.BOLD;
style.foreground = SWTResourceManager.getColor(SWT.COLOR_DARK_BLUE);
this.addStyledText(this.message,
MessageFormat.format(AppConstants.MESSAGE_BAD, AppConstants.MESSAGE_BATHWATER), style);
} else if (this.badlyDamage) {
StyleRange style = new StyleRange();
style.fontStyle = SWT.BOLD;
style.underline = true;
style.underlineStyle = SWT.UNDERLINE_SQUIGGLE;
style.underlineColor = SWTResourceManager.getColor(SWT.COLOR_RED);
style.foreground = SWTResourceManager.getColor(SWT.COLOR_RED);
this.addStyledText(this.message,
MessageFormat.format(AppConstants.MESSAGE_BAD, AppConstants.MESSAGE_BADLY_DAMAGE), style);
} else {
StyleRange style = new StyleRange();
style.fontStyle = SWT.BOLD;
style.foreground = SWTResourceManager.getColor(SWT.COLOR_DARK_GREEN);
this.addStyledText(this.message, AppConstants.MESSAGE_GOOD, style);
}
if (!GlobalContext.isSortie(this.dock.getId())) {
this.state.set(POSTED_BADLY, false);
}
if (this.clearDate != null) {
this.addStyledText(this.message, MessageFormat.format(AppConstants.MESSAGE_COND, this.clearDate), null);
}
this.addStyledText(this.message, MessageFormat.format(AppConstants.MESSAGE_SEIKU, seiku), null);
this.updateTabIcon();
this.postFatal();
this.fleetGroup.layout();
this.getShell().setRedraw(true);
}
private void updateTabIcon() {
if (this.state.get(FATAL)) {
this.tab.setImage(SWTResourceManager.getImage(FleetComposite.class, AppConstants.R_ICON_EXCLAMATION));
} else if (this.state.get(WARN)) {
this.tab.setImage(SWTResourceManager.getImage(FleetComposite.class, AppConstants.R_ICON_ERROR));
} else {
this.tab.setImage(null);
}
}
private void postFatal() {
if (this.badlyDamage && !this.state.get(POSTED_BADLY) && GlobalContext.isSortie(this.dock.getId())) {
ToolTip tip = new ToolTip(this.getShell(), SWT.BALLOON
| SWT.ICON_ERROR);
tip.setText("");
tip.setMessage(AppConstants.MESSAGE_STOP_SORTIE);
this.main.getTrayItem().setToolTip(tip);
tip.setVisible(true);
Sound.randomBadlySoundPlay();
this.state.set(POSTED_BADLY);
}
}
/**
* HP
* @param hpratio HP
* @return HP
*/
private Image getHpGaugeImage(float hpratio) {
return SWTResourceManager
.getImage(
FleetComposite.class,
AppConstants.R_HPGAUGE_IMAGES[(int) Math.floor(hpratio
* (AppConstants.R_HPGAUGE_IMAGES.length - 1))]);
}
/**
*
*
* @param text StyledText
* @param str
* @param style
*/
private void addStyledText(StyledText text, String str, StyleRange style) {
StyleRange[] oldranges = text.getStyleRanges();
String beforeText = text.getText();
StyleRange addStyle = style;
if (addStyle == null) {
addStyle = new StyleRange();
}
addStyle.start = beforeText.length();
addStyle.length = str.length();
StyleRange[] ranges = new StyleRange[oldranges.length + 1];
for (int i = 0; i < oldranges.length; i++) {
ranges[i] = oldranges[i];
}
ranges[oldranges.length] = addStyle;
text.setText(beforeText + str);
text.setStyleRanges(ranges);
}
/**
*
*
* @param ship
* @param isFlagship
* @return
*/
@CheckForNull
private Integer getNextCount(ShipDto ship, boolean isFlagship) {
Long nextexp = CalcExpUtils.getNextLvExp((int) ship.getLv());
if (nextexp != null) {
long needexp = nextexp - ship.getExp();
// Exp
Integer baseexp = SeaExp.get().get(AppConfig.get().getDefaultSea());
Double eval = EvaluateExp.get().get(AppConfig.get().getDefaultEvaluate());
if ((baseexp != null) && (eval != null)) {
long getexpd = CalcExpUtils.getExp(baseexp, eval, isFlagship, false);
int count = CalcExpUtils.getCount(needexp, getexpd);
return Integer.valueOf(count);
}
}
return null;
}
@Override
public void dispose() {
super.dispose();
this.large.dispose();
this.small.dispose();
}
}
|
package me.Salt.Command;
import me.Salt.Permissions.Permission;
import net.dv8tion.jda.core.entities.User;
import java.util.HashMap;
import java.util.List;
public class CommandDescription {
private HashMap<String, Boolean> parameters;
private HashMap<String, Boolean> definers;
private String name;
private String description;
private User author;
private boolean isComplete;
private boolean supportsPermissions;
private List<Permission> requiredPermissions;
private String helpMessage;
private boolean deprecated;
private List<String> commandCallers; //What text is to be identified by the program as pointing to this command
public CommandDescription(HashMap<String, Boolean> parameters, HashMap<String, Boolean> definers, String name, String description, User author, boolean isComplete, boolean supportsPermissions, List<Permission> requiredPermissions, String helpMessage, boolean deprecated, List<String> commandCallers) {
this.parameters = parameters;
this.definers = definers;
this.name = name;
this.description = description;
this.author = author;
this.isComplete = isComplete;
this.supportsPermissions = supportsPermissions;
this.requiredPermissions = requiredPermissions;
this.helpMessage = helpMessage;
this.deprecated = deprecated;
this.commandCallers = commandCallers;
}
public HashMap<String, Boolean> getParameters() {
return parameters;
}
public HashMap<String, Boolean> getDefiners() {
return definers;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public User getAuthor() {
return author;
}
public boolean isComplete() {
return isComplete;
}
public boolean isSupportsPermissions() {
return supportsPermissions;
}
public List<Permission> getRequiredPermissions() {
return requiredPermissions;
}
public String getHelpMessage() {
return helpMessage;
}
public boolean isDeprecated() {
return deprecated;
}
public List<String> getCommandCallers() {
return commandCallers;
}
@Override
public String toString() {
return "CommandDescription{" +
"name='" + name + '\'' +
", description='" + description + '\'' +
", author='" + author.getName() + '\'' +
", helpMessage='" + helpMessage + '\'' +
'}';
}
}
|
package me.vrekt.lunar.input;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class InputListener implements KeyListener {
private static boolean keyData[] = new boolean[256];
private static Long keyStart[] = new Long[256];
/**
* Return if the key is down.
*/
public static boolean isKeyDown(int key) {
return keyData[key];
}
/*
* Returns the amount of time the key has been depressed.
* @return The amount of time the key has been depressed, in milliseconds.
*/
public static long keyDownDuration(int key) {
Long start = keyStart[key];
if (keyStart[key] != null) {
return System.currentTimeMillis() - start;
}
else {
return 0;
}
}
@Override
public void keyPressed(KeyEvent event) {
keyData[event.getKeyCode()] = true;
keyStart[event.getKeyCode()] = System.currentTimeMillis();
}
@Override
public void keyReleased(KeyEvent event) {
keyData[event.getKeyCode()] = false;
keyStart[event.getKeyCode()] = null;
}
@Override
public void keyTyped(KeyEvent event) {
}
}
|
package lombok.javac.apt;
import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Filer;
import javax.annotation.processing.Messager;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.tools.Diagnostic.Kind;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import lombok.Lombok;
import lombok.core.DiagnosticsReceiver;
import lombok.javac.JavacTransformer;
import com.sun.source.util.TreePath;
import com.sun.source.util.Trees;
import com.sun.tools.javac.jvm.ClassWriter;
import com.sun.tools.javac.main.JavaCompiler;
import com.sun.tools.javac.processing.JavacFiler;
import com.sun.tools.javac.processing.JavacProcessingEnvironment;
import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
import com.sun.tools.javac.util.Context;
/**
* This Annotation Processor is the standard injection mechanism for lombok-enabling the javac compiler.
*
* To actually enable lombok in a javac compilation run, this class should be in the classpath when
* running javac; that's the only requirement.
*/
@SupportedAnnotationTypes("*")
public class LombokProcessor extends AbstractProcessor {
private static final String GRADLE_INCREMENTAL_FILER_CLASS =
"org.gradle.api.internal.tasks.compile.processing.IncrementalFiler";
private ProcessingEnvironment processingEnv;
private JavacProcessingEnvironment javacProcessingEnv;
private JavacFiler javacFiler;
private JavacTransformer transformer;
private Trees trees;
private boolean lombokDisabled = false;
/** {@inheritDoc} */
@Override public void init(ProcessingEnvironment procEnv) {
super.init(procEnv);
if (System.getProperty("lombok.disable") != null) {
lombokDisabled = true;
return;
}
this.processingEnv = procEnv;
this.javacProcessingEnv = getJavacProcessingEnvironment(procEnv);
this.javacFiler = getJavacFiler(procEnv.getFiler());
placePostCompileAndDontMakeForceRoundDummiesHook();
trees = Trees.instance(javacProcessingEnv);
transformer = new JavacTransformer(procEnv.getMessager(), trees);
SortedSet<Long> p = transformer.getPriorities();
if (p.isEmpty()) {
this.priorityLevels = new long[] {0L};
this.priorityLevelsRequiringResolutionReset = new HashSet<Long>();
} else {
this.priorityLevels = new long[p.size()];
int i = 0;
for (Long prio : p) this.priorityLevels[i++] = prio;
this.priorityLevelsRequiringResolutionReset = transformer.getPrioritiesRequiringResolutionReset();
}
}
private static final String JPE = "com.sun.tools.javac.processing.JavacProcessingEnvironment";
private static final Field javacProcessingEnvironment_discoveredProcs = getFieldAccessor(JPE, "discoveredProcs");
private static final Field discoveredProcessors_procStateList = getFieldAccessor(JPE + "$DiscoveredProcessors", "procStateList");
private static final Field processorState_processor = getFieldAccessor(JPE + "$processor", "processor");
private static final Field getFieldAccessor(String typeName, String fieldName) {
try {
Class<?> c = Class.forName(typeName);
Field f = c.getDeclaredField(fieldName);
f.setAccessible(true);
return f;
} catch (ClassNotFoundException e) {
return null;
} catch (NoSuchFieldException e) {
return null;
}
}
// The intent of this method is to have lombok emit a warning if it's not 'first in line'. However, pragmatically speaking, you're always looking at one of two cases:
// (A) The other processor(s) running before lombok require lombok to have run or they crash. So, they crash, and unfortunately we are never even init-ed; the warning is never emitted.
// (B) The other processor(s) don't care about it at all. So, it doesn't actually matter that lombok isn't first.
// Hence, for now, no warnings.
@SuppressWarnings("unused")
private String listAnnotationProcessorsBeforeOurs() {
try {
Object discoveredProcessors = javacProcessingEnvironment_discoveredProcs.get(this.javacProcessingEnv);
ArrayList<?> states = (ArrayList<?>) discoveredProcessors_procStateList.get(discoveredProcessors);
if (states == null || states.isEmpty()) return null;
if (states.size() == 1) return processorState_processor.get(states.get(0)).getClass().getName();
int idx = 0;
StringBuilder out = new StringBuilder();
for (Object processState : states) {
idx++;
String name = processorState_processor.get(processState).getClass().getName();
if (out.length() > 0) out.append(", ");
out.append("[").append(idx).append("] ").append(name);
}
return out.toString();
} catch (Exception e) {
return null;
}
}
private void placePostCompileAndDontMakeForceRoundDummiesHook() {
stopJavacProcessingEnvironmentFromClosingOurClassloader();
forceMultipleRoundsInNetBeansEditor();
Context context = javacProcessingEnv.getContext();
disablePartialReparseInNetBeansEditor(context);
try {
Method keyMethod = Context.class.getDeclaredMethod("key", Class.class);
keyMethod.setAccessible(true);
Object key = keyMethod.invoke(context, JavaFileManager.class);
Field htField = Context.class.getDeclaredField("ht");
htField.setAccessible(true);
@SuppressWarnings("unchecked")
Map<Object,Object> ht = (Map<Object,Object>) htField.get(context);
final JavaFileManager originalFiler = (JavaFileManager) ht.get(key);
if (!(originalFiler instanceof InterceptingJavaFileManager)) {
final Messager messager = processingEnv.getMessager();
DiagnosticsReceiver receiver = new MessagerDiagnosticsReceiver(messager);
JavaFileManager newFilerManager = new InterceptingJavaFileManager(originalFiler, receiver);
ht.put(key, newFilerManager);
Field filerFileManagerField = JavacFiler.class.getDeclaredField("fileManager");
filerFileManagerField.setAccessible(true);
filerFileManagerField.set(javacFiler, newFilerManager);
replaceFileManagerJdk9(context, newFilerManager);
}
} catch (Exception e) {
throw Lombok.sneakyThrow(e);
}
}
private void replaceFileManagerJdk9(Context context, JavaFileManager newFiler) {
try {
JavaCompiler compiler = (JavaCompiler) JavaCompiler.class.getDeclaredMethod("instance", Context.class).invoke(null, context);
try {
Field fileManagerField = JavaCompiler.class.getDeclaredField("fileManager");
fileManagerField.setAccessible(true);
fileManagerField.set(compiler, newFiler);
}
catch (Exception e) {}
try {
Field writerField = JavaCompiler.class.getDeclaredField("writer");
writerField.setAccessible(true);
ClassWriter writer = (ClassWriter) writerField.get(compiler);
Field fileManagerField = ClassWriter.class.getDeclaredField("fileManager");
fileManagerField.setAccessible(true);
fileManagerField.set(writer, newFiler);
}
catch (Exception e) {}
}
catch (Exception e) {
}
}
private void forceMultipleRoundsInNetBeansEditor() {
try {
Field f = JavacProcessingEnvironment.class.getDeclaredField("isBackgroundCompilation");
f.setAccessible(true);
f.set(javacProcessingEnv, true);
} catch (NoSuchFieldException e) {
// only NetBeans has it
} catch (Throwable t) {
throw Lombok.sneakyThrow(t);
}
}
private void disablePartialReparseInNetBeansEditor(Context context) {
try {
Class<?> cancelServiceClass = Class.forName("com.sun.tools.javac.util.CancelService");
Method cancelServiceInstace = cancelServiceClass.getDeclaredMethod("instance", Context.class);
Object cancelService = cancelServiceInstace.invoke(null, context);
if (cancelService == null) return;
Field parserField = cancelService.getClass().getDeclaredField("parser");
parserField.setAccessible(true);
Object parser = parserField.get(cancelService);
Field supportsReparseField = parser.getClass().getDeclaredField("supportsReparse");
supportsReparseField.setAccessible(true);
supportsReparseField.set(parser, false);
} catch (ClassNotFoundException e) {
// only NetBeans has it
} catch (NoSuchFieldException e) {
// only NetBeans has it
} catch (Throwable t) {
throw Lombok.sneakyThrow(t);
}
}
private static ClassLoader wrapClassLoader(final ClassLoader parent) {
return new ClassLoader() {
public Class<?> loadClass(String name) throws ClassNotFoundException {
return parent.loadClass(name);
}
public String toString() {
return parent.toString();
}
public URL getResource(String name) {
return parent.getResource(name);
}
public Enumeration<URL> getResources(String name) throws IOException {
return parent.getResources(name);
}
public InputStream getResourceAsStream(String name) {
return parent.getResourceAsStream(name);
}
public void setDefaultAssertionStatus(boolean enabled) {
parent.setDefaultAssertionStatus(enabled);
}
public void setPackageAssertionStatus(String packageName, boolean enabled) {
parent.setPackageAssertionStatus(packageName, enabled);
}
public void setClassAssertionStatus(String className, boolean enabled) {
parent.setClassAssertionStatus(className, enabled);
}
public void clearAssertionStatus() {
parent.clearAssertionStatus();
}
};
}
private void stopJavacProcessingEnvironmentFromClosingOurClassloader() {
try {
Field f = JavacProcessingEnvironment.class.getDeclaredField("processorClassLoader");
f.setAccessible(true);
ClassLoader unwrapped = (ClassLoader) f.get(javacProcessingEnv);
if (unwrapped == null) return;
ClassLoader wrapped = wrapClassLoader(unwrapped);
f.set(javacProcessingEnv, wrapped);
} catch (NoSuchFieldException e) {
// Some versions of javac have this (and call close on it), some don't. I guess this one doesn't have it.
} catch (Throwable t) {
throw Lombok.sneakyThrow(t);
}
}
private final IdentityHashMap<JCCompilationUnit, Long> roots = new IdentityHashMap<JCCompilationUnit, Long>();
private long[] priorityLevels;
private Set<Long> priorityLevelsRequiringResolutionReset;
/** {@inheritDoc} */
@Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (lombokDisabled) return false;
if (roundEnv.processingOver()) return false;
// We have: A sorted set of all priority levels: 'priorityLevels'
// Step 1: Take all CUs which aren't already in the map. Give them the first priority level.
String randomModuleName = null;
for (Element element : roundEnv.getRootElements()) {
if (randomModuleName == null) randomModuleName = getModuleNameFor(element);
JCCompilationUnit unit = toUnit(element);
if (unit == null) continue;
if (roots.containsKey(unit)) continue;
roots.put(unit, priorityLevels[0]);
}
while (true) {
// Step 2: For all CUs (in the map, not the roundEnv!), run them across all handlers at their current prio level.
for (long prio : priorityLevels) {
List<JCCompilationUnit> cusForThisRound = new ArrayList<JCCompilationUnit>();
for (Map.Entry<JCCompilationUnit, Long> entry : roots.entrySet()) {
Long prioOfCu = entry.getValue();
if (prioOfCu == null || prioOfCu != prio) continue;
cusForThisRound.add(entry.getKey());
}
transformer.transform(prio, javacProcessingEnv.getContext(), cusForThisRound);
}
// Step 3: Push up all CUs to the next level. Set level to null if there is no next level.
Set<Long> newLevels = new HashSet<Long>();
for (int i = priorityLevels.length - 1; i >= 0; i
Long curLevel = priorityLevels[i];
Long nextLevel = (i == priorityLevels.length - 1) ? null : priorityLevels[i + 1];
List<JCCompilationUnit> cusToAdvance = new ArrayList<JCCompilationUnit>();
for (Map.Entry<JCCompilationUnit, Long> entry : roots.entrySet()) {
if (curLevel.equals(entry.getValue())) {
cusToAdvance.add(entry.getKey());
newLevels.add(nextLevel);
}
}
for (JCCompilationUnit unit : cusToAdvance) {
roots.put(unit, nextLevel);
}
}
newLevels.remove(null);
// Step 4: If ALL values are null, quit. Else, either do another loop right now or force a resolution reset by forcing a new round in the annotation processor.
if (newLevels.isEmpty()) return false;
newLevels.retainAll(priorityLevelsRequiringResolutionReset);
if (!newLevels.isEmpty()) {
// Force a new round to reset resolution. The next round will cause this method (process) to be called again.
forceNewRound(randomModuleName, javacFiler);
return false;
}
// None of the new levels need resolution, so just keep going.
}
}
private int dummyCount = 0;
private void forceNewRound(String randomModuleName, JavacFiler filer) {
if (!filer.newFiles()) {
try {
String name = "lombok.dummy.ForceNewRound" + (dummyCount++);
if (randomModuleName != null) name = randomModuleName + "/" + name;
JavaFileObject dummy = filer.createSourceFile(name);
Writer w = dummy.openWriter();
w.close();
} catch (Exception e) {
e.printStackTrace();
processingEnv.getMessager().printMessage(Kind.WARNING,
"Can't force a new processing round. Lombok won't work.");
}
}
}
private String getModuleNameFor(Element element) {
while (element != null) {
if (element.getKind().name().equals("MODULE")) {
String n = element.getSimpleName().toString().trim();
return n.isEmpty() ? null : n;
}
Element n = element.getEnclosingElement();
if (n == element) return null;
element = n;
}
return null;
}
private JCCompilationUnit toUnit(Element element) {
TreePath path = trees == null ? null : trees.getPath(element);
if (path == null) return null;
return (JCCompilationUnit) path.getCompilationUnit();
}
/**
* We just return the latest version of whatever JDK we run on. Stupid? Yeah, but it's either that or warnings on all versions but 1.
*/
@Override public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latest();
}
/**
* This class casts the given processing environment to a JavacProcessingEnvironment. In case of
* gradle incremental compilation, the delegate ProcessingEnvironment of the gradle wrapper is returned.
*/
public JavacProcessingEnvironment getJavacProcessingEnvironment(ProcessingEnvironment procEnv) {
final Class<?> procEnvClass = procEnv.getClass();
if (procEnv.getClass().getName().equals("org.gradle.api.internal.tasks.compile.processing.IncrementalProcessingEnvironment")) {
try {
Field field = procEnvClass.getDeclaredField("delegate");
field.setAccessible(true);
Object delegate = field.get(procEnv);
return (JavacProcessingEnvironment) delegate;
} catch (final Exception e) {
e.printStackTrace();
procEnv.getMessager().printMessage(Kind.WARNING,
"Can't get the delegate of the gradle IncrementalProcessingEnvironment. Lombok won't work.");
}
}
return (JavacProcessingEnvironment) procEnv;
}
/**
* This class casts the given filer to a JavacFiler. In case of
* gradle incremental compilation, the delegate Filer of the gradle wrapper is returned.
*/
public JavacFiler getJavacFiler(Filer filer) {
try {
final Class<?> filerClass = filer.getClass();
final Class<?> filerSuperClass = filerClass.getSuperclass();
if (filerSuperClass.getName().equals(GRADLE_INCREMENTAL_FILER_CLASS)) {
// Gradle before 4.8
return tryGetJavacFilerDelegate(filerSuperClass, filer);
} else if (filer.getClass().getName().equals(GRADLE_INCREMENTAL_FILER_CLASS)) {
// Gradle 4.8 and above
return tryGetJavacFilerDelegate(filerClass, filer);
}
} catch (final Exception e) {
e.printStackTrace();
processingEnv.getMessager().printMessage(Kind.WARNING,
"Can't get the delegate of the gradle IncrementalFiler. Lombok won't work.");
}
return (JavacFiler) filer;
}
private JavacFiler tryGetJavacFilerDelegate(Class<?> filerDelegateClass, Object instance) throws Exception {
Field field = filerDelegateClass.getDeclaredField("delegate");
field.setAccessible(true);
Object delegate = field.get(instance);
return (JavacFiler) delegate;
}
}
|
package de.sebhn.algorithm.excersise5;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
class DLXNode { // represents 1 element or header
DLXNode C; // reference to column-header
DLXNode L, R, U, D; // left, right, up, down references
int posH;
int posV;
static int indexLength;
static DLXNode[] headers;
static int matrixLine;
static int maxNumber;
static int n;
DLXNode() {
C = L = R = U = D = this;
} // supports circular lists
/**
* search tries to find and count all complete coverings of the DLX matrix. Is a recursive,
* depth-first, backtracking algorithm that finds all solutions to the exact cover problem encoded
* in the DLX matrix. each time all columns are covered, static long cnt is increased
*
* @param int k: number of level
*
*/
static int cnt;
static DLXNode h;
public static void search(int k) { // finds & counts solutions
if (h.R == h) {
cnt++;
return;
} // if empty: count & done
DLXNode c = h.R; // choose next column c
cover(c); // remove c from columns
for (DLXNode r = c.D; r != c; r = r.D) { // forall rows with 1 in c
for (DLXNode j = r.R; j != r; j = j.R) // forall 1-elements in row
cover(j.C); // remove column
search(k + 1); // recursion
for (DLXNode j = r.L; j != r; j = j.L) // forall 1-elements in row
uncover(j.C); // backtrack: un-remove
}
uncover(c); // un-remove c to columns
}
/**
* cover "covers" a column c of the DLX matrix column c will no longer be found in the column list
* rows i with 1 element in column c will no longer be found in other column lists than c so
* column c and rows i are invisible after execution of cover
*
* @param DLXNode c: header element of column that has to be covered
*
*/
public static void cover(DLXNode c) { // remove column c
c.R.L = c.L; // remove header
c.L.R = c.R; // .. from row list
for (DLXNode i = c.D; i != c; i = i.D) // forall rows with 1
for (DLXNode j = i.R; i != j; j = j.R) { // forall elem in row
j.D.U = j.U; // remove row element
j.U.D = j.D; // .. from column list
}
}
/**
* uncover "uncovers" a column c of the DLX matrix all operations of cover are undone so column c
* and rows i are visible again after execution of uncover
*
* @param DLXNode c: header element of column that has to be uncovered
*
*/
public static void uncover(DLXNode c) {// undo remove col c
for (DLXNode i = c.U; i != c; i = i.U) // forall rows with 1
for (DLXNode j = i.L; i != j; j = j.L) { // forall elem in row
j.D.U = j; // un-remove row elem
j.U.D = j; // .. to column list
}
c.R.L = c; // un-remove header
c.L.R = c; // .. to row list
}
public static void main(String[] args) {
cnt = 0; // set counter for solutions to zero
h = new DLXNode(); // create header
h.posH = 0;
h.posV = 0;
n = 5;
matrixLine = 1;
maxNumber = n * 6;
addHeader(maxNumber);
/*
* for (int i = 0; i < amountOfHeaders; i++) { DLXNodeOld columnNode = gotoIndex(i);
* System.out.println("Header-Column: " + columnNode.posH); System.out.println("Row x: " +
* columnNode.posV); DLXNodeOld verticaclNode = columnNode.D; System.out.println("Row o: " +
* verticaclNode.posV); do { verticaclNode = verticaclNode.D; // if (verticaclNode.posV != -1) {
* System.out.println("Row i: " + verticaclNode.posV); // } } while
* (!columnNode.equals(verticaclNode)); }
*/
long start = System.nanoTime();
createMono();
calcCross();
// calcMono();
calcU_UP();
calcU_DOWN();
calcU_LEFT();
calcU_RIGHT();
calcL_R0();
calcL_R1();
calcL_R2();
calcL_R3();
calcL_R4();
calcL_R5();
calcL_R6();
calcL_R7();
long ende = System.nanoTime();
System.out.println((ende - start) / 100000 + "ms for matrix generation");
// DLXNodeOld node = h.R;
// for (int i = 0; i < maxNumber + 1; i++) {
// System.out.print(node.posV + " " + node.posH + " | ");
// node = node.R;
start = System.nanoTime();
search(0);
ende = System.nanoTime();
System.out.println((ende - start) / 1000000000 + "s for search");
System.out.println(matrixLine + " possible solutions");
}
/**
* create headers
*/
public static void addHeader(int n) {
indexLength = n;
headers = new DLXNode[n + 1];
headers[0] = h;
DLXNode tempNode;
int x = 0;
for (int i = 0; i < n; i++) {
DLXNode node = new DLXNode();
node.posH = ++x; // set index to header
node.posV = 0; // set vertical position to 0 to signal header
headers[x] = node;
if (h.L == h) {
// connect header to node
h.L = node;
h.R = node;
// connect node to header
node.L = h;
node.R = h;
} else {
tempNode = h.L; // goto last header
tempNode.R = node; // connect old last node to new node
node.L = tempNode; // connect new node to old last node
node.R = h; // connect last new node to header
h.L = node; // connect header to last new node
}
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + posH;
result = prime * result + posV;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
} else if (obj == null || getClass() != obj.getClass()) {
return false;
}
DLXNode other = (DLXNode) obj;
if (posH != other.posH) {
return false;
} else if (posV != other.posV) {
return false;
}
return true;
}
private static DLXNode gotoIndex(int posH) {
DLXNode node = new DLXNode();
node = h.R;
for (int i = 0; i < posH; i++) {
node = node.R;
}
return node;
}
private static DLXNode gotoHeaderIndex(int posH) {
return headers[posH];
}
private static void addNode(int posV, int posH) {
System.out.println("add node: posV=" + posV + " posH=" + posH);
DLXNode node = new DLXNode();
DLXNode temp = gotoHeaderIndex(posH); // goto header index
node.posH = posH;
node.posV = posV;
node.C = temp; // direct link to header
if (temp.D == node.C) { // add node if there are no other nodes
temp.U = node;
temp.D = node;
node.U = temp;
node.D = temp;
connectRight(node);
connectLeft(node);
return;
} else {
for (int i = 0; i < 6; i++) {
temp = temp.D;
if (temp.posV < posV) {
temp = temp.D;
if (temp == temp.C) { // add node if its the highest index
temp = temp.U;
temp.D = node;
node.U = temp;
node.D = node.C;
node.C.U = node;
connectRight(node);
connectLeft(node);
return;
}
}
if (temp.posV > posV) {
temp = temp.U;
node.D = temp.D; // connect node to higher node
temp.D.U = node; // connect higher node to node
temp.D = node; // connect lower node to node
node.U = temp; // connect node to lower node}
connectRight(node);
connectLeft(node);
return;
}
}
}
}
public static void connectRight(DLXNode node) {
// connection to the right
int posV = node.posV;
DLXNode temp = node;
for (int i = 0; i < indexLength; i++) {
temp = temp.C.R;
while (temp.D != temp.C) {
temp = temp.D;
if (temp.posV == posV) {
node.R = temp;
temp.L = node;
// System.out.println("connected right " + node.posV + " " + node.posH + " mit " +
// temp.posV
// + " " + temp.posH);
return;
} else {
}
}
}
}
public static void connectLeft(DLXNode node) {
// connection to the right
int posV = node.posV;
DLXNode temp = node;
for (int i = 0; i < indexLength; i++) {
temp = temp.C.L;
while (temp.D != temp.C) {
temp = temp.D;
if (temp.posV == posV) {
temp.R = node;
node.L = temp;
// System.out.println("connected left " + node.posV + " " + node.posH + " mit " +
// temp.posV
// + " " + temp.posH);
return;
} else {
}
}
}
}
public static void calcCross() {
int a = 2;
int b = 7;
int c = 8;
int d = 9;
int e = 14;
List<Integer> figure = Arrays.asList(a, b, c, d, e);
int width = 3;
int height = 3;
calculateFiguresPosition(figure, height, width);
}
public static void calcU_UP() {
calculateFiguresPosition(Arrays.asList(1, 2, 8, 13, 14), 4, 3);
}
public static void calcU_DOWN() {
calculateFiguresPosition(Arrays.asList(1, 2, 7, 13, 14), 4, 3);
}
public static void calcU_LEFT() {
calculateFiguresPosition(Arrays.asList(1, 3, 7, 9, 8), 3, 2);
}
public static void calcU_RIGHT() {
calculateFiguresPosition(Arrays.asList(1, 2, 3, 9, 7), 3, 2);
}
/**
* |<br>
* |<br>
* |_<br>
*/
public static void calcL_R0() {
calculateFiguresPosition(Arrays.asList(1, 2, 3, 4, 10), 2, 2);
}
public static void calcL_R1() {
calculateFiguresPosition(Arrays.asList(2, 8, 14, 20, 19), 4, 4);
}
/**
* _<br>
* .|<br>
* .|<br>
* .|<br>
* .|
*/
public static void calcL_R2() {
calculateFiguresPosition(Arrays.asList(1, 7, 8, 9, 10), 2, 2);
}
public static void calcL_R3() {
calculateFiguresPosition(Arrays.asList(1, 2, 13, 7, 19), 4, 4);
}
/**
* .|<br>
* .|<br>
* _|<br>
*/
public static void calcL_R4() {
calculateFiguresPosition(Arrays.asList(7, 8, 9, 10, 4), 2, 2);
}
public static void calcL_R5() {
calculateFiguresPosition(Arrays.asList(1, 7, 13, 19, 20), 4, 4);
}
public static void calcL_R6() {
calculateFiguresPosition(Arrays.asList(1, 2, 8, 14, 20), 4, 4);
}
/**
* ._<br>
* |<br>
* |<br>
* |
*/
public static void calcL_R7() {
calculateFiguresPosition(Arrays.asList(1, 2, 3, 4, 7), 2, 2);
}
public static void calcMono() {
for (int i = 0; i < maxNumber; i++) {
addNode(matrixLine, i + 1);
matrixLine++;
}
}
public static void createMono() {
for (int i = 0; i < maxNumber; i++) {
DLXNode node = new DLXNode();
node.posH = i + 1;
node.posV = matrixLine;
// System.out.println("add node: posV=" + node.posV + " posH=" + node.posH);
matrixLine++;
node.C = gotoHeaderIndex(node.posH);
node.U = gotoHeaderIndex(node.posH).U;
gotoHeaderIndex(node.posH).U.D = node;
gotoHeaderIndex(node.posH).U = node;
node.D = node.C;
}
}
private static void calculateFiguresPosition(List<Integer> figures, int downShifts, int width) {
int shiftsRight = n - width;
if (shiftsRight > n || shiftsRight < 0) {
System.out.println("no positions, cant fit figure");
return;
}
insertFigure(figures);
for (int i = 0; i < downShifts; i++) {
List<Integer> plusSixFigures = new ArrayList<>(figures);
shiftRight(shiftsRight, plusSixFigures);
shiftDown(figures);
}
shiftRight(shiftsRight, figures);
}
private static void shiftRight(int shiftsRight, List<Integer> plusSixFigures) {
for (int g = 0; g < shiftsRight; g++) {
shiftOneRight(plusSixFigures);
}
}
private static void insertFigure(List<Integer> figures) {
DLXNode[] array = new DLXNode[5];
int arrayIndex = 0;
for (Integer integer : figures) {
// addNode(matrixLine, integer);
array[arrayIndex] = createNode(matrixLine, integer);
arrayIndex++;
}
createLine(array);
matrixLine++;
}
private static void shiftDown(List<Integer> figures) {
DLXNode[] array = new DLXNode[5];
int arrayIndex = 0;
for (int j = 0; j < figures.size(); j++) {
int elementPlusOne = figures.get(j) + 1;
figures.set(j, elementPlusOne);
// addNode(matrixLine, elementPlusOne);
array[arrayIndex] = createNode(matrixLine, elementPlusOne);
arrayIndex++;
}
createLine(array);
matrixLine++;
}
private static void shiftOneRight(List<Integer> plusSixFigures) {
DLXNode[] array = new DLXNode[5];
int arrayIndex = 0;
for (int j = 0; j < plusSixFigures.size(); j++) {
Integer current = plusSixFigures.get(j);
current += 6;
plusSixFigures.set(j, current);
// addNode(matrixLine, current);
array[arrayIndex] = createNode(matrixLine, current);
arrayIndex++;
}
createLine(array);
matrixLine++;
}
private static void calculateFiguresPosition(List<Integer> figures, int downShifts) {
insertFigure(figures);
DLXNode[] al = new DLXNode[5];
int arrayIndex = 0;
for (int i = 0; i <= downShifts; i++) {
ArrayList<Integer> plusSixFigures = new ArrayList<>(figures);
int currentMaxHorizontal = plusSixFigures.get(plusSixFigures.size() - 1) + 6;
while (currentMaxHorizontal <= maxNumber) {
shiftOneRight(plusSixFigures);
currentMaxHorizontal = plusSixFigures.get(plusSixFigures.size() - 1) + 6;
}
int currentMaxVertical = figures.get(figures.size() - 2) + 1;
boolean hasNotReachedVerticalEnd = currentMaxVertical < 13;
for (int j = 0; j < figures.size() && hasNotReachedVerticalEnd; j++) {
int elementPlusOne = figures.get(j) + 1;
figures.set(j, elementPlusOne);
// addNode(matrixLine, elementPlusOne);
al[arrayIndex] = createNode(matrixLine, elementPlusOne);
arrayIndex++;
}
if (hasNotReachedVerticalEnd) {
matrixLine++;
createLine(al);
}
al = new DLXNode[5];
}
}
private static DLXNode createNode(int posV, int posH) {
// System.out.println("add node: posV=" + posV + " posH=" + posH);
DLXNode node = new DLXNode();
node.posV = posV;
node.posH = posH;
return node;
}
private static void createLine(DLXNode[] array) {
for (int i = 0; i < array.length; i++) {
/**
* chain up down
*/
array[i].C = gotoHeaderIndex(array[i].posH);
array[i].U = gotoHeaderIndex(array[i].posH).U;
gotoHeaderIndex(array[i].posH).U.D = array[i];
array[i].D = gotoHeaderIndex(array[i].posH);
gotoHeaderIndex(array[i].posH).U = array[i];
if (i == 0) {
/**
* chain left right for first element
*/
array[i].L = array[array.length - 1];
array[i].R = array[i + 1];
} else if (i == array.length - 1) {
/**
* chain left right for last element
*/
array[i].L = array[i - 1];
array[i].R = array[0];
} else {
/**
* chain left right for other elements
*/
array[i].L = array[i - 1];
array[i].R = array[i + 1];
}
}
}
}
|
package de.tourenplaner.server;
import de.tourenplaner.database.*;
import de.tourenplaner.utils.SHA1;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBufferInputStream;
import org.jboss.netty.handler.codec.http.HttpRequest;
import org.jboss.netty.handler.codec.http.HttpResponseStatus;
import java.io.IOException;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
/**
* @author Christoph Haag, Sascha Meusel, Niklas Schnelle, Peter Vollmer
*
*/
public class PrivateHandler extends RequestHandler {
private static Logger log = Logger.getLogger("de.tourenplaner.server");
private final DatabaseManager dbm;
private final Authorizer authorizer;
private static final ObjectMapper mapper = new ObjectMapper();
public PrivateHandler(Authorizer authorizer, DatabaseManager dbm) {
super(null);
this.dbm = dbm;
this.authorizer = authorizer;
}
/**
* Extracts and parses the JSON encoded content of the given HttpRequest, in
* case of error sends a EBADJSON answer to the client and returns null,
* the connection will be closed afterwards.
*
* @param request HttpRequest
* @return Returns parsed json map or null in case of an error
* @throws IOException Thrown if error message sending or reading json content fails
* @throws JsonMappingException Thrown if mapping json content fails
*/
private Map<String, Object> getJSONContent(final HttpRequest request) throws IOException {
Map<String, Object> objmap = null;
final ChannelBuffer content = request.getContent();
if (content.readableBytes() > 0) {
try {
objmap = mapper.readValue(new ChannelBufferInputStream(content), new TypeReference<Map<String, Object>>() {
});
} catch (JsonParseException e) {
responder.writeErrorMessage("EBADJSON", "Could not parse supplied JSON", e.getMessage(),
HttpResponseStatus.BAD_REQUEST);
objmap = null;
}
} else {
responder.writeErrorMessage("EBADJSON", "Could not parse supplied JSON", "Content is empty",
HttpResponseStatus.BAD_REQUEST);
}
return objmap;
}
/**
* If authorization is okay, but no admin, registration fails. If no
* authorization as admin, the new registered user will not be registered as
* admin, even if json admin flag is true.
*
* @param request HttpRequest
* @throws SQLFeatureNotSupportedException
* Thrown if a function is not supported by driver.
* @throws SQLException
* Thrown if de.tourenplaner.database query fails
* @throws JsonMappingException
* Thrown if mapping object to json fails
* @throws JsonGenerationException
* Thrown if generating json fails
* @throws IOException
* Thrown if error message sending or reading/writing json content fails
*/
public void handleRegisterUser(final HttpRequest request) throws IOException, SQLException {
UserDataset authenticatedUser = null;
// if no authorization header keep on with adding not verified user
if (request.getHeader("Authorization") != null) {
authenticatedUser = authorizer.auth(request);
if (authenticatedUser == null) {
// auth(request) sent error response
return;
}
if (!authenticatedUser.admin) {
responder.writeErrorMessage("ENOTADMIN", "You are not an admin",
"A logged in user has to be admin to register users.", HttpResponseStatus.FORBIDDEN);
return;
}
}
Map<String, Object> objmap = getJSONContent(request);
// getJSONContent adds error-message to responder
// if json object is bad or if there is no json object
// so no further handling needed if objmap == null
if (objmap == null) {
log.warning("Failed, bad json object.");
return;
}
if ( !(objmap.get("email") instanceof String) || !(objmap.get("password") instanceof String)
|| !(objmap.get("firstname") instanceof String) || !(objmap.get("lastname") instanceof String)
|| !(objmap.get("address") instanceof String) ) {
responder.writeErrorMessage("EBADJSON", "Could not parse supplied JSON",
"JSON user object was not correct (needs email, password, firstname, lastname, address)",
HttpResponseStatus.BAD_REQUEST);
return;
}
final String email = (String) objmap.get("email");
final String pw = (String) objmap.get("password");
final String firstName = (String) objmap.get("firstname");
final String lastName = (String) objmap.get("lastname");
final String address = (String) objmap.get("address");
if ((pw == null) || (email == null) || (firstName == null) || (lastName == null) || (address == null)) {
responder.writeErrorMessage("EBADJSON", "Could not parse supplied JSON",
"JSON user object was not correct (needs email, password, firstname, lastname, address)",
HttpResponseStatus.BAD_REQUEST);
return;
}
final String salt = authorizer.generateSalt();
final String toHash = SHA1.SHA1(pw + ':' + salt);
UserDataset newUser;
// if there is no authorization, add user but without verification
if (authenticatedUser == null) {
// if there is no authorization as admin, the new registered user will
// never be registered as admin, even if json admin flag is true
newUser = dbm.addNewUser(email, toHash, salt, firstName, lastName, address, false);
} else {
boolean adminFlag = false;
if (objmap.get("admin") != null) {
// if (objmap.get("admin") is null, then "instanceof Boolean" would be always false
// so following check makes only sense if objmap.get("admin") != null
if ( !(objmap.get("admin") instanceof Boolean) ) {
responder.writeErrorMessage("EBADJSON", "Could not parse supplied JSON",
"JSON user object was not correct (\"admin\" should be boolean)",
HttpResponseStatus.BAD_REQUEST);
return;
}
adminFlag = (Boolean) objmap.get("admin");
}
newUser = dbm.addNewVerifiedUser(email, toHash, salt, firstName, lastName, address, adminFlag);
}
if ( newUser == null) {
responder.writeErrorMessage("EREGISTERED", "This email is already registered", null,
HttpResponseStatus.FORBIDDEN);
return;
}
responder.writeJSON(newUser, HttpResponseStatus.OK);
log.finest("RegisterUser successful.");
}
/**
* Authenticates the client and sends the corresponding user object as json to the client.
*
* @param request HttpRequest
* @throws SQLException Thrown if de.tourenplaner.database query fails
* @throws JsonGenerationException Thrown if generating json fails
* @throws JsonMappingException Thrown if mapping object to json fails
* @throws IOException Thrown if error message sending or writing json content fails
*/
public void handleAuthUser(final HttpRequest request) throws IOException, SQLException {
UserDataset user = authorizer.auth(request);
if (user != null) {
responder.writeJSON(user, HttpResponseStatus.OK);
}
}
/**
* Sends the data of one user as json to the client.
*
* @param request HttpRequest
* @param parameters map with url parameters from client
* @throws SQLException Thrown if de.tourenplaner.database query fails
* @throws JsonMappingException Thrown if mapping object to json fails
* @throws JsonGenerationException Thrown if generating json fails
* @throws IOException Thrown if error message sending or writing json content fails
*/
public void handleGetUser(final HttpRequest request, Map<String, List<String>> parameters)
throws IOException, SQLException {
UserDataset user = authorizer.auth(request);
// authentication needed, auth(request) responses with error if auth fails
if (user == null) {
return;
}
int userID;
UserDataset selectedUser;
if (parameters.containsKey("id")) {
userID = parseUserIdParameter(parameters.get("id").get(0), user, false);
// if parameter is invalid, an error response is sent from parseUserIdParameter.
// the if and return is needed exactly here, because following methods could send more responses,
// but only one response per http request is allowed (else Exceptions will be thrown)
if (userID < 0) {
return;
}
selectedUser = dbm.getUser(userID);
} else {
selectedUser = user;
}
if (selectedUser == null) {
responder.writeErrorMessage("ENOUSERID", "The given user id is unknown to this de.tourenplaner.server",
"The id is not in the de.tourenplaner.database", HttpResponseStatus.NOT_FOUND);
return;
}
responder.writeJSON(selectedUser, HttpResponseStatus.OK);
log.finest("GetUser successful.");
}
/**
* Updates the data of a user.
*
* @param request HttpRequest
* @param parameters map with url parameters from client
* @throws SQLException Thrown if de.tourenplaner.database query fails
* @throws JsonMappingException Thrown if mapping object to json fails
* @throws JsonGenerationException Thrown if generating json fails
* @throws IOException Thrown if error message sending or reading/writing json content fails
*/
public void handleUpdateUser(final HttpRequest request, Map<String, List<String>> parameters)
throws IOException, SQLException {
UserDataset user = authorizer.auth(request);
// authentication needed, auth(request) responses with error if auth fails
if (user == null) {
return;
}
Map<String, Object> objmap = getJSONContent(request);
// getJSONContent adds error-message to responder
// if json object is bad or if there is no json object
// so no further handling needed if objmap == null
if (objmap == null) {
log.warning("Failed, bad json object.");
return;
}
int userID;
boolean isAdmin = user.admin;
UserDataset selectedUser;
if (parameters.containsKey("id")) {
userID = parseUserIdParameter(parameters.get("id").get(0), user, false);
// if parameter is invalid, an error response is sent from parseUserIdParameter.
// the if and return is needed exactly here, because following methods could send more responses,
// but only one response per http request is allowed (else Exceptions will be thrown)
if (userID < 0) {
return;
}
selectedUser = dbm.getUser(userID);
if (selectedUser == null) {
responder.writeErrorMessage("ENOUSERID", "The given user id is unknown to this de.tourenplaner.server",
"The id is not in the de.tourenplaner.database", HttpResponseStatus.NOT_FOUND);
return;
}
} else {
selectedUser = user;
}
if (objmap.get("password") != null && (objmap.get("password") instanceof String)) {
selectedUser.salt = authorizer.generateSalt();
selectedUser.passwordhash = SHA1.SHA1((String) objmap.get("password") + ':' + selectedUser.salt);
}
if (isAdmin) {
if (objmap.get("email") != null && (objmap.get("email") instanceof String)) {
selectedUser.email = (String) objmap.get("email");
}
if (objmap.get("firstname") != null && (objmap.get("firstname") instanceof String)) {
selectedUser.firstName = (String) objmap.get("firstname");
}
if (objmap.get("lastname") != null && (objmap.get("lastname") instanceof String)) {
selectedUser.lastName = (String) objmap.get("lastname");
}
if (objmap.get("address") != null && (objmap.get("address") instanceof String)) {
selectedUser.address = (String) objmap.get("address");
}
// the user with id = 1 should always be admin, so no admin flag changing
if (selectedUser.userid != 1 && objmap.get("admin") != null && (objmap.get("admin") instanceof Boolean)) {
selectedUser.admin = (Boolean) objmap.get("admin");
}
// the user with id = 1 should always be verified, so no status changing
if (selectedUser.userid != 1 && objmap.get("status") != null && (objmap.get("status") instanceof String)) {
String status = (String) objmap.get("status");
UserStatusEnum previousStatus = selectedUser.status;
try {
selectedUser.status = UserStatusEnum.valueOf(status);
} catch (IllegalArgumentException e) {
responder.writeErrorMessage("EBADJSON", "Could not parse supplied JSON",
"JSON user object was not correct (\"status\" was not a valid value)",
HttpResponseStatus.BAD_REQUEST);
return;
}
if (previousStatus == UserStatusEnum.needs_verification
&& selectedUser.status == UserStatusEnum.verified) {
selectedUser.verifiedDate = new Date(System.currentTimeMillis());
}
}
}
int rowsChanged = dbm.updateUser(selectedUser);
if (rowsChanged == -1) {
responder.writeErrorMessage("EREGISTERED", "This email is already registered", null,
HttpResponseStatus.FORBIDDEN);
return;
}
responder.writeJSON(selectedUser, HttpResponseStatus.OK);
log.finest("UpdateUser successful.");
}
/**
* Sends the JsonRequest of the request with the given id to the client.
*
* @param request HttpRequest
* @param parameters map with url parameters from client
* @throws SQLException Thrown if de.tourenplaner.database query fails
* @throws IOException Thrown if error message sending or writing content fails
*/
public void handleGetRequest(final HttpRequest request, Map<String, List<String>> parameters) throws IOException, SQLException {
UserDataset user = authorizer.auth(request);
// authentication needed, auth(request) responses with error if auth fails
if (user == null) {
return;
}
int requestID;
JSONObject jsonObject;
if (parameters.containsKey("id")) {
requestID = parseRequestIdParameter(parameters.get("id").get(0));
// if parameter is invalid, an error response is sent from parseUserIdParameter.
// the if and return is needed exactly here, because following methods could send more responses,
// but only one response per http request is allowed (else Exceptions will be thrown)
if (requestID < 0) {
return;
}
jsonObject = dbm.getJsonRequest(requestID);
if (jsonObject == null) {
responder.writeErrorMessage("ENOREQUESTID", "The given request id is unknown to this de.tourenplaner.server",
"The id is not in the de.tourenplaner.database", HttpResponseStatus.NOT_FOUND);
return;
}
} else {
responder.writeErrorMessage("ENOREQUESTID", "The request request id is unknown to this de.tourenplaner.server",
"You must send an id parameter", HttpResponseStatus.NOT_FOUND);
return;
}
if (user.userid != jsonObject.getUserID() && !user.admin) {
responder.writeErrorMessage("ENOTADMIN", "You are not an admin",
"You cannot view the json object of another user because you are not an admin",
HttpResponseStatus.FORBIDDEN);
return;
}
responder.writeByteArray(jsonObject.getJsonByteArray(), HttpResponseStatus.OK);
log.finest("GetRequest successful.");
}
/**
* Sends the JsonResponse of the request with the given id to the client.
*
* @param request HttpRequest
* @param parameters map with url parameters from client
* @throws SQLException Thrown if de.tourenplaner.database query fails
* @throws IOException Thrown if error message sending or writing content fails
*/
public void handleGetResponse(final HttpRequest request, Map<String, List<String>> parameters) throws IOException, SQLException {
UserDataset user = authorizer.auth(request);
// authentication needed, auth(request) responses with error if auth fails
if (user == null) {
return;
}
int requestID;
JSONObject jsonObject;
if (parameters.containsKey("id")) {
requestID = parseRequestIdParameter(parameters.get("id").get(0));
// if parameter is invalid, an error response is sent from parseUserIdParameter.
// the if and return is needed exactly here, because following methods could send more responses,
// but only one response per http request is allowed (else Exceptions will be thrown)
if (requestID < 0) {
return;
}
jsonObject = dbm.getJsonResponse(requestID);
if (jsonObject == null) {
responder.writeErrorMessage("ENOREQUESTID", "The given request id is unknown to this de.tourenplaner.server",
"The id is not in the de.tourenplaner.database", HttpResponseStatus.NOT_FOUND);
return;
}
} else {
responder.writeErrorMessage("ENOREQUESTID", "The request request id is unknown to this de.tourenplaner.server",
"You must send an id parameter", HttpResponseStatus.NOT_FOUND);
return;
}
if (user.userid != jsonObject.getUserID() && !user.admin) {
responder.writeErrorMessage("ENOTADMIN", "You are not an admin",
"You cannot view the json object of another user because you are not an admin",
HttpResponseStatus.FORBIDDEN);
return;
}
responder.writeByteArray(jsonObject.getJsonByteArray(), HttpResponseStatus.OK);
log.finest("GetResponse successful.");
}
/**
* Sends a list with requests as json to the client.
*
* @param request HttpRequest
* @param parameters map with url parameters from client
* @throws SQLException Thrown if de.tourenplaner.database query fails
* @throws JsonGenerationException Thrown if generating json fails
* @throws JsonMappingException Thrown if mapping object to json fails
* @throws IOException Thrown if error message sending or writing json content fails
*/
public void handleListRequests(final HttpRequest request, Map<String, List<String>> parameters)
throws SQLException, IOException {
UserDataset user = authorizer.auth(request);
// authentication needed, auth(request) responses with error if auth
// fails
if (user == null) {
return;
}
int limit = extractNaturalIntParameter(parameters, "limit");
// if parameter is invalid, an error response is sent from extractNaturalIntParameter.
// the if and return is needed exactly here, because following methods could send more responses,
// but only one response per http request is allowed (else Exceptions will be thrown)
if (limit < 0) {
return;
}
int offset = extractNaturalIntParameter(parameters, "offset");
// if parameter is invalid, an error response is sent from extractNaturalIntParameter.
// the if and return is needed exactly here, because following methods could send more responses,
// but only one response per http request is allowed (else Exceptions will be thrown)
if (offset < 0) {
return;
}
Integer userID;
boolean allRequests = false;
if (parameters.containsKey("id")) {
userID = parseUserIdParameter(parameters.get("id").get(0), user, true);
// if parameter is invalid, an error response is sent from parseUserIdParameter.
// the if and return is needed exactly here, because following methods could send more responses,
// but only one response per http request is allowed (else Exceptions will be thrown)
if (userID != null && userID < 0) {
return;
}
if (userID == null) {
allRequests = true;
}
} else {
userID = user.userid;
}
List<RequestDataset> requestDatasetList;
int count;
if (allRequests) {
requestDatasetList = dbm.getAllRequests(limit, offset);
count = dbm.getNumberOfRequests();
} else {
requestDatasetList = dbm.getRequests(userID, limit, offset);
count = dbm.getNumberOfRequestsWithUserId(userID);
}
Map<String, Object> responseMap = new HashMap<String, Object>(2);
responseMap.put("number", count);
responseMap.put("requests", requestDatasetList);
responder.writeJSON(responseMap, HttpResponseStatus.OK);
log.finest("ListRequests successful.");
}
/**
* Sends a list with users as json to the client.
*
* @param request HttpRequest
* @param parameters map with url parameters from client
* @throws SQLException Thrown if de.tourenplaner.database query fails
* @throws JsonGenerationException Thrown if generating json fails
* @throws JsonMappingException Thrown if mapping object to json fails
* @throws IOException Thrown if error message sending or writing json content fails
*/
public void handleListUsers(final HttpRequest request, Map<String, List<String>> parameters)
throws SQLException, IOException {
UserDataset user = authorizer.auth(request);
// authentication needed, auth(request) responses with error if auth fails
if (user == null) {
return;
}
if (!user.admin) {
responder.writeErrorMessage("ENOTADMIN", "You are not an admin", "You must be admin to list users",
HttpResponseStatus.FORBIDDEN);
return;
}
int limit = extractNaturalIntParameter(parameters, "limit");
// if parameter is invalid, an error response is sent from extractNaturalIntParameter.
// the if and return is needed exactly here, because following methods could send more responses,
// but only one response per http request is allowed (else Exceptions will be thrown)
if (limit < 0) {
return;
}
int offset = extractNaturalIntParameter(parameters, "offset");
// if parameter is invalid, an error response is sent from extractNaturalIntParameter.
// the if and return is needed exactly here, because following methods could send more responses,
// but only one response per http request is allowed (else Exceptions will be thrown)
if (offset < 0) {
return;
}
List<UserDataset> userDatasetList;
userDatasetList = dbm.getAllUsers(limit, offset);
int count = dbm.getNumberOfUsers();
Map<String, Object> responseMap = new HashMap<String, Object>(2);
responseMap.put("number", count);
responseMap.put("users", userDatasetList);
responder.writeJSON(responseMap, HttpResponseStatus.OK);
log.finest("ListUsers successful.");
}
/**
* Sets the status flag of the user to deleted.
*
* @param request HttpRequest
* @param parameters map with url parameters from client
* @throws IOException Thrown if error message sending fails
* @throws SQLException Thrown if de.tourenplaner.database query fails
*/
public void handleDeleteUser(final HttpRequest request, Map<String, List<String>> parameters)
throws IOException, SQLException {
UserDataset user = authorizer.auth(request);
// authentication needed, auth(request) responses with error if auth fails
if (user == null) {
return;
}
int userID;
if (parameters.containsKey("id")) {
userID = parseUserIdParameter(parameters.get("id").get(0), user, false);
// if parameter is invalid, an error response is sent from parseUserIdParameter.
// the if and return is needed exactly here, because following methods could send more responses,
// but only one response per http request is allowed (else Exceptions will be thrown)
if (userID < 0) {
return;
}
} else {
responder.writeErrorMessage("ENOUSERID", "The given user id is unknown to this de.tourenplaner.server",
"You must send an id parameter", HttpResponseStatus.NOT_FOUND);
return;
}
// the user with id = 1 should always be verified, so no status changing
if (userID != 1) {
if (dbm.updateUserStatusToDeleted(userID) != 1) {
responder.writeErrorMessage("ENOUSERID", "The given user id is unknown to this de.tourenplaner.server",
"The id is not in the de.tourenplaner.database", HttpResponseStatus.NOT_FOUND);
return;
}
}
responder.writeStatusResponse(HttpResponseStatus.OK);
log.finest("DeleteUser successful.");
}
/**
* Returns the parsed number or -1 if parameter is invalid (not a natural number) and will then
* response to request with error message.
* @param parameterValue the value of the id parameter as String
* @return Returns the parsed number or -1 if parameter is invalid (not a natural number)
* @throws IOException Thrown if error message sending fails
*/
private int parseRequestIdParameter(String parameterValue) throws IOException {
if (parameterValue == null) {
responder.writeErrorMessage("ENOREQUESTID", "The given request id is unknown to this de.tourenplaner.server",
"The given id is null", HttpResponseStatus.NOT_FOUND);
return -1;
}
int requestID;
try {
requestID = Integer.parseInt(parameterValue);
} catch (NumberFormatException e) {
requestID = -1;
}
if (requestID < 0) {
responder.writeErrorMessage("ENOREQUESTID", "The given request id is unknown to this de.tourenplaner.server",
"The given id is not an allowed number (positive or zero)", HttpResponseStatus.NOT_FOUND);
return requestID;
}
return requestID;
}
/**
* Returns the parsed number or -1 if parameter is invalid (not a natural number) and will then
* response to request with error message. But the authenticated user must be an admin (will be checked by this
* method) or an error message will be sent. If "id=all" is allowed and the value of the parameter is "all",
* this method will return null.
* @param parameterValue the value of the id parameter as String
* @param authenticatedUser UserDataset of the user who sent the request
* @param valueAllIsAllowed determines if id=all is allowed for the parameter
* @return Returns the parsed number or -1 if parameter is invalid (not a natural number).
* If "id=all" is allowed and the value of the parameter is "all",
* this method will return null.
* @throws IOException Thrown if error message sending fails
*/
private Integer parseUserIdParameter(String parameterValue, UserDataset authenticatedUser,
boolean valueAllIsAllowed) throws IOException {
if (!authenticatedUser.admin) {
responder.writeErrorMessage("ENOTADMIN", "You are not an admin",
"You must be admin if you want to use the id parameter", HttpResponseStatus.FORBIDDEN);
return -1;
}
if (parameterValue == null) {
responder.writeErrorMessage("ENOUSERID", "The given user id is unknown to this de.tourenplaner.server",
"The given id is null", HttpResponseStatus.NOT_FOUND);
return -1;
}
int userID;
if ("all".equals(parameterValue) && valueAllIsAllowed) {
return null;
} else {
try {
userID = Integer.parseInt(parameterValue);
} catch (NumberFormatException e) {
userID = -1;
}
}
if (userID < 0) {
responder.writeErrorMessage("ENOUSERID", "The given user id is unknown to this de.tourenplaner.server",
"The given id is not an allowed number (positive or zero)", HttpResponseStatus.NOT_FOUND);
return userID;
}
return userID;
}
/**
* Returns the parsed number or -1 if parameter is invalid (missing or not a natural number)
* and will then response to request with error message.
* @param parameters map with url parameters from client
* @param name the name of the parameter
* @return Returns the parsed number or -1 if parameter is invalid (missing or not a natural number)
* @throws IOException Thrown if error message sending fails
*/
private int extractNaturalIntParameter(Map<String, List<String>> parameters, String name) throws IOException {
int param = -1;
if (!parameters.containsKey(name)) {
responder.writeErrorMessage('E' + name.toUpperCase(), "The given " + name + " is invalid",
"You must send a " + name + " parameter", HttpResponseStatus.BAD_REQUEST);
return -1;
}
if (parameters.get(name).get(0) != null) {
try {
param = Integer.parseInt(parameters.get(name).get(0));
} catch (NumberFormatException e) {
param = -1;
}
}
if (param < 0) {
responder.writeErrorMessage('E' + name.toUpperCase(), "The given " + name + " is invalid",
"You must send a " + name + " parameter", HttpResponseStatus.BAD_REQUEST);
return -1;
}
return param;
}
}
|
package mj.jmex.visualfx;
import com.jme3.asset.AssetManager;
import com.jme3.export.InputCapsule;
import com.jme3.export.JmeExporter;
import com.jme3.export.JmeImporter;
import com.jme3.export.OutputCapsule;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.math.FastMath;
import com.jme3.post.Filter;
import com.jme3.renderer.RenderManager;
import com.jme3.renderer.Renderer;
import com.jme3.renderer.ViewPort;
import com.jme3.renderer.queue.RenderQueue;
import com.jme3.texture.Image.Format;
import com.jme3.texture.Texture;
import com.jme3.texture.Texture2D;
import java.io.IOException;
import java.util.ArrayList;
/**
* This bloom filter uses mipmaps of the main scene to generate a large
* bloom effect.
* The final result is a scene texture with blur of the bright parts, which is
* calculated by summing over the mipmap levels using the intensity equation:
* <code>final_color=bloomFactor*sum(mipmap_color*bloomPower^level)</code>
* <p>
* Adjustment of the bloom inensity and the downsampling coefficient shall be
* chosen very carefully.
*/
public class MipmapBloomFilter extends Filter
{
private Quality quality=Quality.High;
private GlowMode glowMode=GlowMode.Scene;
private float exposurePower=3.0f;
private float exposureCutOff=0.0f;
private float bloomFactor=0.2f;
private float bloomPower=1.8f;
private float downSamplingCoef=2.0f;
private Pass preGlowPass;
private Pass extractPass;
private Material extractMat;
private int screenWidth;
private int screenHeight;
private RenderManager renderManager;
private ViewPort viewPort;
private AssetManager assetManager;
private int initialWidth;
private int initialHeight;
private final int numPasses=8;
private Format texFormat=Format.RGB111110F;
/**
* GlowMode specifies if the glow will be applied to the whole scene, or to
* objects that have aglow color or a glow map.
*/
public enum GlowMode
{ /**
* Apply bloom filter to bright areas in the scene. (Default)
*/
Scene,
/**
* Apply bloom only to objects that have a glow map or a glow color.
*/
Objects,
/**
* Apply bloom to both bright parts of the scene and objects with glow map.
*/
SceneAndObjects;
}
/**
* The Quality can be adjusted to achieve better results at lower
* performance.
*/
public enum Quality
{
/**
* Uses an additional gaussian blur to smooth each mipmap level. (Default)
*/
High,
/**
* Lower quality but better performance mode.
*/
Low;
}
/**
* Instantiates a new bloom filter.
*/
public MipmapBloomFilter()
{
super("MipmapBloomFilter");
}
/**
* Instantiates a new bloom filter with the specified GlowMode.
* @param glowMode
*/
public MipmapBloomFilter(GlowMode glowMode)
{ this();
this.glowMode=glowMode;
}
/**
* Instantiates a new bloom filter with the specified quality.
* @param quality
*/
public MipmapBloomFilter(Quality quality)
{ this();
this.quality=quality;
}
/**
* Instantiates a new bloom filter with the specified quality and GlowMode.
* @param quality
* @param glowMode
*/
public MipmapBloomFilter(Quality quality, GlowMode glowMode)
{ this();
this.quality=quality;
this.glowMode=glowMode;
}
@Override
protected void initFilter(final AssetManager manager,
RenderManager renderManager, ViewPort vp, int w, int h)
{
this.renderManager=renderManager;
this.viewPort=vp;
this.assetManager=manager;
this.initialWidth=w;
this.initialHeight=h;
// Configure the preGlowPass, for use with GlowMode.SceneAndObjects and
// GlowMode.Objects.
screenWidth=(int)Math.max(1.0, (w/downSamplingCoef));
screenHeight=(int)Math.max(1.0, (h/downSamplingCoef));
if (glowMode!=GlowMode.Scene)
{ preGlowPass=new Pass();
preGlowPass.init(renderManager.getRenderer(), screenWidth, screenHeight,
texFormat, Format.Depth);
}
postRenderPasses=new ArrayList<Pass>();
// Configure extractPass, extracting bright pixels from the scene.
extractMat=new Material(manager, "Common/MatDefs/Post/BloomExtract.j3md");
extractPass=new Pass()
{
@Override
public boolean requiresSceneAsTexture() {return true;}
@Override
public void beforeRender() {
extractMat.setFloat("ExposurePow", exposurePower);
extractMat.setFloat("ExposureCutoff", exposureCutOff);
if (glowMode!=GlowMode.Scene) {
extractMat.setTexture("GlowMap", preGlowPass.getRenderedTexture());
}
extractMat.setBoolean("Extract", glowMode!=GlowMode.Objects);
}
};
extractPass.init(renderManager.getRenderer(), initialWidth, initialHeight,
texFormat, Format.Depth, 1, extractMat);
extractPass.getRenderedTexture().setMagFilter(Texture.MagFilter.Bilinear);
extractPass.getRenderedTexture().setMinFilter(Texture.MinFilter.Trilinear);
postRenderPasses.add(extractPass);
// Configure mipmap blur passes.
// The mipmaps will be generated with according width and height, that can be
// specified implicitly with the downSamplingFactor.
final Pass[] mmPasses=new Pass[numPasses];
final Texture2D[] mipmaps=new Texture2D[numPasses];
for (int ii=0; ii<numPasses; ii++)
{
final int passWidth=(int)(initialWidth/FastMath.pow(downSamplingCoef,
(ii+1)));
final int passHeight=(int)(initialHeight/FastMath.pow(downSamplingCoef,
(ii+1)));
final Material passMat=new Material(manager,
"MatDefs/MipmapBloom/MipmapSampler.j3md");
final int jj=ii;
mmPasses[jj]=new Pass()
{
@Override
public void beforeRender()
{
if (jj==0)
passMat.setTexture("Texture", extractPass.getRenderedTexture());
else
passMat.setTexture("Texture", mmPasses[jj-1]
.getRenderedTexture());
passMat.setFloat("Dx", 0.5f/(float)passWidth);
passMat.setFloat("Dy", 0.5f/(float)passHeight);
}
};
mmPasses[jj].init(renderManager.getRenderer(), passWidth,
passHeight, texFormat, Format.Depth, 1, passMat);
mmPasses[jj].getRenderedTexture().setMagFilter(
Texture.MagFilter.Bilinear);
mmPasses[jj].getRenderedTexture().setMinFilter(
Texture.MinFilter.Trilinear);
postRenderPasses.add(mmPasses[jj]);
// In high quality mode each mipmap will be blurred with a gaussian blur,
// which makes the result much smoother.
if (quality==Quality.High)
mipmaps[jj]=gaussianBlur(manager, mmPasses[jj].getRenderedTexture());
else
mipmaps[jj]=mmPasses[jj].getRenderedTexture();
}
// Accumulate mipmaps to the final image.
material=new Material(manager, "MatDefs/MipmapBloom/Accumulation.j3md");
for (int ii=0; ii<numPasses; ii++)
material.setTexture("Texture"+(ii+1), mipmaps[ii]);
setBloomIntensity(bloomFactor, bloomPower);
}
/**
* Adds an additional Gaussian blur (one horizontal and one vertical pass) to
* the specified texture.
*
* @param manager
* @param texture A single mipmap texture here.
* @return
*/
private Texture2D gaussianBlur(AssetManager manager, final Texture2D texture)
{
// Configure horizontal blur pass.
final Material hBlurMat=new Material(manager,
"MatDefs/MipmapBloom/HGaussianBlur.j3md");
final Pass hBlur=new Pass()
{ @Override
public void beforeRender()
{ hBlurMat.setTexture("Texture", texture);
hBlurMat.setFloat("Size", texture.getImage().getWidth());
hBlurMat.setFloat("Scale", 0.5f);
}
};
hBlur.init(renderManager.getRenderer(), screenWidth, screenHeight,
texFormat, Format.Depth, 1, hBlurMat);
hBlur.getRenderedTexture().setMagFilter(Texture.MagFilter.Bilinear);
hBlur.getRenderedTexture().setMinFilter(Texture.MinFilter.Trilinear);
postRenderPasses.add(hBlur);
// Configure vertical blur pass.
final Material vBlurMat=new Material(manager,
"MatDefs/MipmapBloom/VGaussianBlur.j3md");
final Pass vBlur=new Pass()
{ @Override
public void beforeRender()
{ vBlurMat.setTexture("Texture", hBlur.getRenderedTexture());
vBlurMat.setFloat("Size", texture.getImage().getHeight());
vBlurMat.setFloat("Scale", 0.5f);
}
};
vBlur.init(renderManager.getRenderer(), screenWidth, screenHeight,
texFormat, Format.Depth, 1, vBlurMat);
vBlur.getRenderedTexture().setMagFilter(Texture.MagFilter.Bilinear);
vBlur.getRenderedTexture().setMinFilter(Texture.MinFilter.Trilinear);
postRenderPasses.add(vBlur);
return vBlur.getRenderedTexture();
}
/**
* Reinitializes the filter by calling initFilter.
*/
protected void reInitFilter()
{
initFilter(assetManager, renderManager, viewPort, initialWidth,
initialHeight);
}
/**
* Provides the premultiplication factor of the intensity equation.
*
* @return
*/
public float getBloomFactor() {return bloomFactor;}
@Override
protected Material getMaterial() {return material;}
/**
* Extracts the material's Glow techniques (if specified) and renders it into
* the preGlowPass, if GlowMode is not Scene.
*
* @param queue The queue of the rendered scene.
*/
@Override
protected void postQueue(RenderQueue queue)
{ if (glowMode!=GlowMode.Scene)
{ renderManager.getRenderer().setBackgroundColor(ColorRGBA.BlackNoAlpha);
renderManager.getRenderer().setFrameBuffer(
preGlowPass.getRenderFrameBuffer());
renderManager.getRenderer().clearBuffers(true, true, true);
renderManager.setForcedTechnique("Glow");
renderManager.renderViewPortQueues(viewPort, false);
renderManager.setForcedTechnique(null);
renderManager.getRenderer().setFrameBuffer(
viewPort.getOutputFrameBuffer());
}
}
@Override
protected void cleanUpFilter(Renderer r)
{ if (glowMode!=GlowMode.Scene)
preGlowPass.cleanup(r);
}
/**
* Provides the power coefficient of the intensity equation.
* @return The power coefficient.
*/
public float getBloomPower() {return bloomPower;}
/**
* Sets weight factors for each mipmap by calculating the intensity equation
* (see above).
*
* @param bloomFactor A constant premultiplication factor that should be
* less than 1.
* @param bloomPower A greater value increases the bloom intensity of each
* mipmap level.
*/
public void setBloomIntensity(float bloomFactor, float bloomPower)
{ if (material!=null)
{
for (int ii=0; ii<numPasses; ii++)
{
float wt=bloomFactor*FastMath.pow(bloomPower, ii);
material.setFloat("Weight"+(ii+1), wt);
}
}
this.bloomFactor=bloomFactor;
this.bloomPower=bloomPower;
}
/**
* Provides the exposure cutoff.
* @return Exposure cutoff.
*/
public float getExposureCutOff() {return exposureCutOff;}
/**
* Define the color threshold on which the bloom will be applied (0.0 to 1.0)
* @param exposureCutOff The color threshold value.
*/
public void setExposureCutOff(float exposureCutOff)
{ this.exposureCutOff=exposureCutOff;
}
/**
* Provides the exposure power of the intensity equation.
* @return
*/
public float getExposurePower() {return exposurePower;}
/**
* Sets the exposure power value of the intensity equation (see above).
* @param exposurePower
*/
public void setExposurePower(float exposurePower)
{ this.exposurePower=exposurePower;
}
/**
* Sets the glow mode of the bloom filter.
* @param glowMode See above.
*/
public void setGlowMode(GlowMode glowMode)
{ this.glowMode=glowMode;
if (assetManager!=null) // Dirty initialization check.
reInitFilter();
}
/**
* Sets the quality of the bloom filter.
* @param enabled <code>true</code> for <code>Quality.High</code>.
*/
public void setHighQuality(boolean enabled)
{ this.quality=enabled? Quality.High:Quality.Low;
if (assetManager!=null) // Dirty initialization check.
reInitFilter();
}
/**
* Provides the downSampling coefficient of the mipmap levels.
* @return The downsampling coefficient.
*/
public float getDownSamplingCoef() {return downSamplingCoef;}
/**
* Sets the downsampling coefficient.
* Each mipmap (starting with level 0) will have a reduced size defined by:
* <code>mipmap_size=framebuffer_size/pow(downSamplingCoef^(level+1))</code>.
* <p>
* A lower value means less blur at higher computational cost, as the last level
* will have a high resolution. The coefficient shall therefore be chosen in
* such a way, that the highest (7th) level will have a resolution of just a few
* pixels.
*
* @param downSamplingCoef The downsampling coefficient.
*/
public void setDownSamplingCoef(float downSamplingCoef)
{
this.downSamplingCoef=downSamplingCoef;
if (assetManager!=null) // dirty isInitialised check
reInitFilter();
}
@Override
public void write(JmeExporter ex) throws IOException
{ super.write(ex);
OutputCapsule oc=ex.getCapsule(this);
oc.write(quality, "quality", Quality.High);
oc.write(glowMode, "glowMode", GlowMode.Scene);
oc.write(exposurePower, "exposurePower", 5.0f);
oc.write(exposureCutOff, "exposureCutOff", 0.0f);
oc.write(bloomFactor, "bloomFactor", 0.2f);
oc.write(bloomPower, "bloomIntensity", 2.0f);
oc.write(downSamplingCoef, "downSamplingFactor", 1);
}
@Override
public void read(JmeImporter im) throws IOException
{ super.read(im);
InputCapsule ic=im.getCapsule(this);
quality=ic.readEnum("quality", Quality.class, Quality.High);
glowMode=ic.readEnum("glowMode", GlowMode.class, GlowMode.Scene);
exposurePower=ic.readFloat("exposurePower", 5.0f);
exposureCutOff=ic.readFloat("exposureCutOff", 0.0f);
bloomFactor=ic.readFloat("bloomFactor", 0.2f);
bloomPower=ic.readFloat("bloomIntensity", 2.0f);
downSamplingCoef=ic.readFloat("downSamplingFactor", 1);
}
}
|
package som.interpreter.nodes;
import som.compiler.AccessModifier;
import som.compiler.ClassBuilder.ClassDefinitionId;
import som.interpreter.TruffleCompiler;
import som.interpreter.TypesGen;
import som.interpreter.nodes.dispatch.AbstractDispatchNode;
import som.interpreter.nodes.dispatch.DispatchChain.Cost;
import som.interpreter.nodes.dispatch.GenericDispatchNode;
import som.interpreter.nodes.dispatch.LexicallyBoundDispatchNode;
import som.interpreter.nodes.dispatch.SuperDispatchNode;
import som.interpreter.nodes.dispatch.UninitializedDispatchNode;
import som.interpreter.nodes.literals.BlockNode;
import som.interpreter.nodes.nary.EagerBinaryPrimitiveNode;
import som.interpreter.nodes.nary.EagerTernaryPrimitiveNode;
import som.interpreter.nodes.nary.EagerUnaryPrimitiveNode;
import som.interpreter.nodes.specialized.AndMessageNodeFactory;
import som.interpreter.nodes.specialized.AndMessageNodeFactory.AndBoolMessageNodeFactory;
import som.interpreter.nodes.specialized.IfFalseMessageNodeGen;
import som.interpreter.nodes.specialized.IfTrueIfFalseMessageNodeGen;
import som.interpreter.nodes.specialized.IfTrueMessageNodeGen;
import som.interpreter.nodes.specialized.IntDownToDoMessageNodeGen;
import som.interpreter.nodes.specialized.IntToByDoMessageNodeGen;
import som.interpreter.nodes.specialized.IntToDoMessageNodeGen;
import som.interpreter.nodes.specialized.NotMessageNodeFactory;
import som.interpreter.nodes.specialized.OrMessageNodeGen;
import som.interpreter.nodes.specialized.OrMessageNodeGen.OrBoolMessageNodeGen;
import som.interpreter.nodes.specialized.whileloops.WhileWithDynamicBlocksNode;
import som.interpreter.nodes.specialized.whileloops.WhileWithStaticBlocksNode.WhileFalseStaticBlocksNode;
import som.interpreter.nodes.specialized.whileloops.WhileWithStaticBlocksNode.WhileTrueStaticBlocksNode;
import som.primitives.BlockPrimsFactory.ValueNonePrimFactory;
import som.primitives.BlockPrimsFactory.ValueOnePrimFactory;
import som.primitives.EqualsEqualsPrimFactory;
import som.primitives.EqualsPrimFactory;
import som.primitives.IntegerPrimsFactory.AbsPrimFactory;
import som.primitives.IntegerPrimsFactory.LeftShiftPrimFactory;
import som.primitives.IntegerPrimsFactory.ToPrimFactory;
import som.primitives.IntegerPrimsFactory.UnsignedRightShiftPrimFactory;
import som.primitives.MethodPrimsFactory.InvokeOnPrimFactory;
import som.primitives.SizeAndLengthPrimFactory;
import som.primitives.UnequalsPrimFactory;
import som.primitives.arithmetic.AdditionPrimFactory;
import som.primitives.arithmetic.DividePrimFactory;
import som.primitives.arithmetic.DoubleDivPrimFactory;
import som.primitives.arithmetic.GreaterThanPrimFactory;
import som.primitives.arithmetic.LessThanOrEqualPrimFactory;
import som.primitives.arithmetic.LessThanPrimFactory;
import som.primitives.arithmetic.ModuloPrimFactory;
import som.primitives.arithmetic.MultiplicationPrimFactory;
import som.primitives.arithmetic.RemainderPrimFactory;
import som.primitives.arithmetic.SubtractionPrimFactory;
import som.primitives.arrays.AtPrimFactory;
import som.primitives.arrays.AtPutPrimFactory;
import som.primitives.arrays.DoIndexesPrimFactory;
import som.primitives.arrays.DoPrimFactory;
import som.primitives.arrays.NewPrimFactory;
import som.primitives.arrays.PutAllNodeFactory;
import som.primitives.arrays.ToArgumentsArrayNodeGen;
import som.primitives.bitops.BitAndPrimFactory;
import som.primitives.bitops.BitXorPrimFactory;
import som.vm.NotYetImplementedException;
import som.vm.constants.Classes;
import som.vmobjects.SArray;
import som.vmobjects.SBlock;
import som.vmobjects.SSymbol;
import com.oracle.truffle.api.CompilerAsserts;
import com.oracle.truffle.api.frame.VirtualFrame;
import com.oracle.truffle.api.nodes.ExplodeLoop;
import com.oracle.truffle.api.nodes.NodeCost;
import com.oracle.truffle.api.source.SourceSection;
public final class MessageSendNode {
public static AbstractMessageSendNode createMessageSend(final SSymbol selector,
final ExpressionNode[] arguments, final SourceSection source) {
return new UninitializedMessageSendNode(selector, arguments, source);
}
public static AbstractMessageSendNode adaptSymbol(final SSymbol newSelector,
final AbstractMessageSendNode node) {
assert node instanceof UninitializedMessageSendNode;
return new UninitializedMessageSendNode(newSelector, node.argumentNodes,
node.getSourceSection());
}
public static AbstractMessageSendNode createForPerformNodes(final SSymbol selector) {
return new UninitializedSymbolSendNode(selector, null, null);
}
public static GenericMessageSendNode createGeneric(final SSymbol selector,
final ExpressionNode[] argumentNodes, final SourceSection source) {
if (argumentNodes[0] instanceof ISpecialSend) {
throw new NotYetImplementedException();
} else {
return new GenericMessageSendNode(selector, argumentNodes,
new UninitializedDispatchNode(selector, AccessModifier.PUBLIC), source);
}
}
public abstract static class AbstractMessageSendNode extends ExpressionNode
implements PreevaluatedExpression {
@Children protected final ExpressionNode[] argumentNodes;
protected AbstractMessageSendNode(final ExpressionNode[] arguments,
final SourceSection source) {
super(source);
this.argumentNodes = arguments;
}
public boolean isSpecialSend() {
return argumentNodes[0] instanceof ISpecialSend;
}
@Override
public final Object executeGeneric(final VirtualFrame frame) {
Object[] arguments = evaluateArguments(frame);
return doPreEvaluated(frame, arguments);
}
@ExplodeLoop
private Object[] evaluateArguments(final VirtualFrame frame) {
Object[] arguments = new Object[argumentNodes.length];
for (int i = 0; i < argumentNodes.length; i++) {
arguments[i] = argumentNodes[i].executeGeneric(frame);
assert arguments[i] != null;
}
return arguments;
}
}
public abstract static class AbstractUninitializedMessageSendNode
extends AbstractMessageSendNode {
protected final SSymbol selector;
protected AbstractUninitializedMessageSendNode(final SSymbol selector,
final ExpressionNode[] arguments,
final SourceSection source) {
super(arguments, source);
this.selector = selector;
}
@Override
public String toString() {
return "UninitMsgSend(" + selector.toString() + ")";
}
public SSymbol getSelector() {
return selector;
}
@Override
public final Object doPreEvaluated(final VirtualFrame frame,
final Object[] arguments) {
return specialize(arguments).
doPreEvaluated(frame, arguments);
}
private PreevaluatedExpression specialize(final Object[] arguments) {
TruffleCompiler.transferToInterpreterAndInvalidate("Specialize Message Node");
// first option is a super send, super sends are treated specially because
// the receiver class is lexically determined
if (isSpecialSend()) {
return makeSpecialSend();
}
// We treat super sends separately for simplicity, might not be the
// optimal solution, especially in cases were the knowledge of the
// receiver class also allows us to do more specific things, but for the
// moment we will leave it at this.
// TODO: revisit, and also do more specific optimizations for super sends.
// let's organize the specializations by number of arguments
// perhaps not the best, but one simple way to just get some order into
// the chaos.
switch (argumentNodes.length) {
case 1: return specializeUnary(arguments);
case 2: return specializeBinary(arguments);
case 3: return specializeTernary(arguments);
case 4: return specializeQuaternary(arguments);
}
return makeOrdenarySend();
}
protected abstract PreevaluatedExpression makeSpecialSend();
private GenericMessageSendNode makeOrdenarySend() {
GenericMessageSendNode send = new GenericMessageSendNode(selector,
argumentNodes,
new UninitializedDispatchNode(selector, AccessModifier.PUBLIC),
getSourceSection());
return replace(send);
}
protected PreevaluatedExpression specializeUnary(final Object[] args) {
Object receiver = args[0];
switch (selector.getString()) {
// eagerly but cautious:
case "size":
if (receiver instanceof SArray) {
return replace(new EagerUnaryPrimitiveNode(selector,
argumentNodes[0], SizeAndLengthPrimFactory.create(null)));
}
break;
case "value":
if (receiver instanceof SBlock || receiver instanceof Boolean) {
return replace(new EagerUnaryPrimitiveNode(selector,
argumentNodes[0], ValueNonePrimFactory.create(null)));
}
break;
case "not":
if (receiver instanceof Boolean) {
return replace(new EagerUnaryPrimitiveNode(selector,
argumentNodes[0], NotMessageNodeFactory.create(getSourceSection(), null)));
}
break;
case "abs":
if (receiver instanceof Long) {
return replace(new EagerUnaryPrimitiveNode(selector,
argumentNodes[0], AbsPrimFactory.create(null)));
}
}
return makeOrdenarySend();
}
protected PreevaluatedExpression specializeBinary(final Object[] arguments) {
switch (selector.getString()) {
case "at:":
if (arguments[0] instanceof SArray) {
return replace(new EagerBinaryPrimitiveNode(selector, argumentNodes[0],
argumentNodes[1],
AtPrimFactory.create(null, null)));
}
break;
case "new:":
if (arguments[0] == Classes.arrayClass) {
return replace(new EagerBinaryPrimitiveNode(selector, argumentNodes[0],
argumentNodes[1],
NewPrimFactory.create(null, null)));
}
break;
case "doIndexes:":
if (arguments[0] instanceof SArray) {
return replace(new EagerBinaryPrimitiveNode(selector, argumentNodes[0],
argumentNodes[1],
DoIndexesPrimFactory.create(null, null)));
}
break;
case "do:":
if (arguments[0] instanceof SArray) {
return replace(new EagerBinaryPrimitiveNode(selector, argumentNodes[0],
argumentNodes[1],
DoPrimFactory.create(null, null)));
}
break;
case "putAll:":
return replace(new EagerBinaryPrimitiveNode(selector,
argumentNodes[0], argumentNodes[1],
PutAllNodeFactory.create(null, null, SizeAndLengthPrimFactory.create(null))));
case "whileTrue:": {
if (argumentNodes[1] instanceof BlockNode &&
argumentNodes[0] instanceof BlockNode) {
BlockNode argBlockNode = (BlockNode) argumentNodes[1];
SBlock argBlock = (SBlock) arguments[1];
return replace(new WhileTrueStaticBlocksNode(
(BlockNode) argumentNodes[0], argBlockNode,
(SBlock) arguments[0],
argBlock, getSourceSection()));
}
break; // use normal send
}
case "whileFalse:":
if (argumentNodes[1] instanceof BlockNode &&
argumentNodes[0] instanceof BlockNode) {
BlockNode argBlockNode = (BlockNode) argumentNodes[1];
SBlock argBlock = (SBlock) arguments[1];
return replace(new WhileFalseStaticBlocksNode(
(BlockNode) argumentNodes[0], argBlockNode,
(SBlock) arguments[0], argBlock, getSourceSection()));
}
break; // use normal send
case "and:":
case "&&":
if (arguments[0] instanceof Boolean) {
if (argumentNodes[1] instanceof BlockNode) {
return replace(AndMessageNodeFactory.create((SBlock) arguments[1],
getSourceSection(), argumentNodes[0], argumentNodes[1]));
} else if (arguments[1] instanceof Boolean) {
return replace(AndBoolMessageNodeFactory.create(getSourceSection(),
argumentNodes[0], argumentNodes[1]));
}
}
break;
case "or:":
case "||":
if (arguments[0] instanceof Boolean) {
if (argumentNodes[1] instanceof BlockNode) {
return replace(OrMessageNodeGen.create((SBlock) arguments[1],
getSourceSection(),
argumentNodes[0], argumentNodes[1]));
} else if (arguments[1] instanceof Boolean) {
return replace(OrBoolMessageNodeGen.create(
getSourceSection(),
argumentNodes[0], argumentNodes[1]));
}
}
break;
case "value:":
if (arguments[0] instanceof SBlock) {
return replace(new EagerBinaryPrimitiveNode(selector, argumentNodes[0],
argumentNodes[1],
ValueOnePrimFactory.create(null, null)));
}
break;
case "ifTrue:":
return replace(IfTrueMessageNodeGen.create(arguments[0],
arguments[1], getSourceSection(),
argumentNodes[0], argumentNodes[1]));
case "ifFalse:":
return replace(IfFalseMessageNodeGen.create(arguments[0],
arguments[1], getSourceSection(),
argumentNodes[0], argumentNodes[1]));
case "to:":
if (arguments[0] instanceof Long) {
return replace(new EagerBinaryPrimitiveNode(selector, argumentNodes[0],
argumentNodes[1],
ToPrimFactory.create(null, null)));
}
break;
// TODO: find a better way for primitives, use annotation or something
case "<":
return replace(new EagerBinaryPrimitiveNode(selector, argumentNodes[0],
argumentNodes[1],
LessThanPrimFactory.create(null, null)));
case "<=":
return replace(new EagerBinaryPrimitiveNode(selector, argumentNodes[0],
argumentNodes[1],
LessThanOrEqualPrimFactory.create(null, null)));
case ">":
return replace(new EagerBinaryPrimitiveNode(selector, argumentNodes[0],
argumentNodes[1],
GreaterThanPrimFactory.create(null, null)));
case "+":
return replace(new EagerBinaryPrimitiveNode(selector, argumentNodes[0],
argumentNodes[1],
AdditionPrimFactory.create(null, null)));
case "-":
return replace(new EagerBinaryPrimitiveNode(selector, argumentNodes[0],
argumentNodes[1],
SubtractionPrimFactory.create(null, null)));
case "*":
return replace(new EagerBinaryPrimitiveNode(selector, argumentNodes[0],
argumentNodes[1],
MultiplicationPrimFactory.create(null, null)));
case "=":
return replace(new EagerBinaryPrimitiveNode(selector, argumentNodes[0],
argumentNodes[1],
EqualsPrimFactory.create(null, null)));
case "<>":
return replace(new EagerBinaryPrimitiveNode(selector, argumentNodes[0],
argumentNodes[1],
UnequalsPrimFactory.create(null, null)));
// TODO: this is not a correct primitive, new an UnequalsUnequalsPrim...
// case "~=":
// return replace(new EagerBinaryPrimitiveNode(selector, argumentNodes[0],
// argumentNodes[1],
// UnequalsPrimFactory.create(null, null)));
case "==":
return replace(new EagerBinaryPrimitiveNode(selector, argumentNodes[0],
argumentNodes[1],
EqualsEqualsPrimFactory.create(null, null)));
case "bitXor:":
return replace(new EagerBinaryPrimitiveNode(selector, argumentNodes[0],
argumentNodes[1],
BitXorPrimFactory.create(null, null)));
case "
return replace(new EagerBinaryPrimitiveNode(selector, argumentNodes[0],
argumentNodes[1],
DoubleDivPrimFactory.create(null, null)));
case "%":
return replace(new EagerBinaryPrimitiveNode(selector, argumentNodes[0],
argumentNodes[1],
ModuloPrimFactory.create(null, null)));
case "rem:":
return replace(new EagerBinaryPrimitiveNode(selector, argumentNodes[0],
argumentNodes[1],
RemainderPrimFactory.create(null, null)));
case "/":
return replace(new EagerBinaryPrimitiveNode(selector, argumentNodes[0],
argumentNodes[1],
DividePrimFactory.create(null, null)));
case "&":
return replace(new EagerBinaryPrimitiveNode(selector, argumentNodes[0],
argumentNodes[1],
BitAndPrimFactory.create(null, null)));
// eagerly but cautious:
case "<<":
if (arguments[0] instanceof Long) {
return replace(new EagerBinaryPrimitiveNode(selector, argumentNodes[0],
argumentNodes[1],
LeftShiftPrimFactory.create(null, null)));
}
break;
case ">>>":
if (arguments[0] instanceof Long) {
return replace(new EagerBinaryPrimitiveNode(selector, argumentNodes[0],
argumentNodes[1],
UnsignedRightShiftPrimFactory.create(null, null)));
}
break;
}
return makeOrdenarySend();
}
protected PreevaluatedExpression specializeTernary(final Object[] arguments) {
switch (selector.getString()) {
case "at:put:":
if (arguments[0] instanceof SArray) {
return replace(new EagerTernaryPrimitiveNode(selector, argumentNodes[0],
argumentNodes[1], argumentNodes[2],
AtPutPrimFactory.create(null, null, null)));
}
break;
case "ifTrue:ifFalse:":
return replace(IfTrueIfFalseMessageNodeGen.create(arguments[0],
arguments[1], arguments[2], argumentNodes[0],
argumentNodes[1], argumentNodes[2]));
case "to:do:":
if (TypesGen.isLong(arguments[0]) &&
(TypesGen.isLong(arguments[1]) ||
TypesGen.isDouble(arguments[1])) &&
TypesGen.isSBlock(arguments[2])) {
return replace(IntToDoMessageNodeGen.create(this,
(SBlock) arguments[2], argumentNodes[0], argumentNodes[1],
argumentNodes[2]));
}
break;
case "downTo:do:":
if (TypesGen.isLong(arguments[0]) &&
(TypesGen.isLong(arguments[1]) ||
TypesGen.isDouble(arguments[1])) &&
TypesGen.isSBlock(arguments[2])) {
return replace(IntDownToDoMessageNodeGen.create(this,
(SBlock) arguments[2], argumentNodes[0], argumentNodes[1],
argumentNodes[2]));
}
break;
case "invokeOn:with:":
return replace(InvokeOnPrimFactory.create(
argumentNodes[0], argumentNodes[1], argumentNodes[2],
ToArgumentsArrayNodeGen.create(null, null)));
}
return makeOrdenarySend();
}
protected PreevaluatedExpression specializeQuaternary(
final Object[] arguments) {
switch (selector.getString()) {
case "to:by:do:":
return replace(IntToByDoMessageNodeGen.create(this,
(SBlock) arguments[3], argumentNodes[0], argumentNodes[1],
argumentNodes[2], argumentNodes[3]));
}
return makeOrdenarySend();
}
}
private static final class UninitializedMessageSendNode
extends AbstractUninitializedMessageSendNode {
protected UninitializedMessageSendNode(final SSymbol selector,
final ExpressionNode[] arguments,
final SourceSection source) {
super(selector, arguments, source);
}
@Override
protected PreevaluatedExpression makeSpecialSend() {
ISpecialSend rcvrNode = (ISpecialSend) argumentNodes[0];
AbstractDispatchNode dispatch;
if (rcvrNode.isSuperSend()) {
dispatch = SuperDispatchNode.create(selector, (ISuperReadNode) rcvrNode);
} else {
dispatch = new LexicallyBoundDispatchNode(selector, rcvrNode.getLexicalClass());
}
GenericMessageSendNode node = new GenericMessageSendNode(selector,
argumentNodes, dispatch, getSourceSection());
return replace(node);
}
}
private static final class UninitializedSymbolSendNode
extends AbstractUninitializedMessageSendNode {
protected UninitializedSymbolSendNode(final SSymbol selector,
final ClassDefinitionId classId, final SourceSection source) {
super(selector, new ExpressionNode[0], source);
}
@Override
public boolean isSpecialSend() {
// TODO: is is correct?
return false;
}
@Override
protected PreevaluatedExpression makeSpecialSend() {
// should never be reached with isSuperSend() returning always false
throw new RuntimeException("A symbol send should never be a special send.");
}
@Override
protected PreevaluatedExpression specializeBinary(final Object[] arguments) {
switch (selector.getString()) {
case "whileTrue:": {
if (arguments[1] instanceof SBlock && arguments[0] instanceof SBlock) {
SBlock argBlock = (SBlock) arguments[1];
return replace(new WhileWithDynamicBlocksNode((SBlock) arguments[0],
argBlock, true, getSourceSection()));
}
break;
}
case "whileFalse:":
if (arguments[1] instanceof SBlock && arguments[0] instanceof SBlock) {
SBlock argBlock = (SBlock) arguments[1];
return replace(new WhileWithDynamicBlocksNode(
(SBlock) arguments[0], argBlock, false, getSourceSection()));
}
break; // use normal send
}
return super.specializeBinary(arguments);
}
}
/// TODO: currently, we do not only specialize the given stuff above, but also what has been classified as 'value' sends in the OMOP branch. Is that a problem?
public static final class GenericMessageSendNode
extends AbstractMessageSendNode {
private final SSymbol selector;
@Child private AbstractDispatchNode dispatchNode;
private GenericMessageSendNode(final SSymbol selector,
final ExpressionNode[] arguments,
final AbstractDispatchNode dispatchNode, final SourceSection source) {
super(arguments, source);
this.selector = selector;
this.dispatchNode = dispatchNode;
}
@Override
public Object doPreEvaluated(final VirtualFrame frame,
final Object[] arguments) {
return dispatchNode.executeDispatch(frame, arguments);
}
public AbstractDispatchNode getDispatchListHead() {
return dispatchNode;
}
public void adoptNewDispatchListHead(final AbstractDispatchNode newHead) {
CompilerAsserts.neverPartOfCompilation();
dispatchNode = insert(newHead);
}
public void replaceDispatchListHead(
final GenericDispatchNode replacement) {
CompilerAsserts.neverPartOfCompilation();
dispatchNode.replace(replacement);
}
@Override
public String toString() {
String file = "";
if (getSourceSection() != null) {
file = " " + getSourceSection().getSource().getName();
file += ":" + getSourceSection().getStartLine();
file += ":" + getSourceSection().getStartColumn();
}
return "GMsgSend(" + selector.getString() + file + ")";
}
@Override
public NodeCost getCost() {
return Cost.getCost(dispatchNode);
}
}
}
|
package st.alr.mqttitude.services;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttTopic;
import st.alr.mqttitude.support.Defaults;
import st.alr.mqttitude.support.Events;
import st.alr.mqttitude.support.MqttPublish;
import st.alr.mqttitude.App;
import st.alr.mqttitude.R;
import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.preference.PreferenceManager;
import android.provider.Settings.Secure;
import android.util.Log;
import de.greenrobot.event.EventBus;
public class ServiceMqtt extends Service implements MqttCallback
{
public static enum MQTT_CONNECTIVITY {
INITIAL, CONNECTING, CONNECTED, DISCONNECTING, DISCONNECTED_WAITINGFORINTERNET, DISCONNECTED_USERDISCONNECT, DISCONNECTED_DATADISABLED, DISCONNECTED
}
private static MQTT_CONNECTIVITY mqttConnectivity = MQTT_CONNECTIVITY.DISCONNECTED;
private short keepAliveSeconds;
private String mqttClientId;
private MqttClient mqttClient;
private static SharedPreferences sharedPreferences;
private static ServiceMqtt instance;
private SharedPreferences.OnSharedPreferenceChangeListener preferencesChangedListener;
private LocalBinder<ServiceMqtt> mBinder;
private Thread workerThread;
private LinkedList<DeferredPublishable> deferredPublishables;
// An alarm for rising in special times to fire the
// pendingIntentPositioning
private AlarmManager alarmManagerPositioning;
// A PendingIntent for calling a receiver in special times
public PendingIntent pendingIntentPositioning;
/**
* @category SERVICE HANDLING
*/
@Override
public void onCreate()
{
super.onCreate();
instance = this;
workerThread = null;
changeMqttConnectivity(MQTT_CONNECTIVITY.INITIAL);
mBinder = new LocalBinder<ServiceMqtt>(this);
keepAliveSeconds = 15 * 60;
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
deferredPublishables = new LinkedList<DeferredPublishable>();
EventBus.getDefault().register(this);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
doStart(intent, startId);
return START_STICKY;
}
private void doStart(final Intent intent, final int startId) {
// init();
Thread thread1 = new Thread() {
@Override
public void run() {
handleStart(intent, startId);
if (this == workerThread) // Clean up worker thread
workerThread = null;
}
@Override
public void interrupt() {
if (this == workerThread) // Clean up worker thread
workerThread = null;
super.interrupt();
}
};
thread1.start();
}
void handleStart(Intent intent, int startId) {
Log.v(this.toString(), "handleStart");
// If there is no mqttClient, something went horribly wrong
// if (mqttClient == null) {
// Log.e(this.toString(), "handleStart: !mqttClient");
// stopSelf();
// return;
// Respect user's wish to stay disconnected
if ((mqttConnectivity == MQTT_CONNECTIVITY.DISCONNECTED_USERDISCONNECT) && startId != -1) {
return;
}
// No need to connect if we're already connecting
if (isConnecting()) {
return;
}
// Respect user's wish to not use data
if (!isBackgroundDataEnabled()) {
Log.e(this.toString(), "handleStart: !isBackgroundDataEnabled");
changeMqttConnectivity(MQTT_CONNECTIVITY.DISCONNECTED_DATADISABLED);
return;
}
// Don't do anything when already connected
if (!isConnected())
{
Log.v(this.toString(), "handleStart: !isConnected");
// Check if there is a data connection
if (isOnline(true))
{
if (connect())
{
Log.v(this.toString(), "handleStart: connectToBroker() == true");
onConnect();
}
}
else
{
Log.e(this.toString(), "handleStart: !isOnline");
changeMqttConnectivity(MQTT_CONNECTIVITY.DISCONNECTED_WAITINGFORINTERNET);
}
}
}
/**
* @category CONNECTION HANDLING
*/
private void init()
{
Log.v(this.toString(), "initMqttClient");
if (mqttClient != null) {
return;
}
try
{
String brokerAddress = sharedPreferences.getString(Defaults.SETTINGS_KEY_BROKER_HOST,
Defaults.VALUE_BROKER_HOST);
String brokerPort = sharedPreferences.getString(Defaults.SETTINGS_KEY_BROKER_PORT,
Defaults.VALUE_BROKER_PORT);
String prefix = getBrokerSecurityMode() == Defaults.VALUE_BROKER_SECURITY_NONE ? "tcp"
: "ssl";
mqttClient = new MqttClient(prefix + "://" + brokerAddress + ":" + brokerPort,
getClientId(), null);
mqttClient.setCallback(this);
} catch (MqttException e)
{
// something went wrong!
mqttClient = null;
changeMqttConnectivity(MQTT_CONNECTIVITY.DISCONNECTED);
}
}
private int getBrokerSecurityMode() {
return sharedPreferences.getInt(Defaults.SETTINGS_KEY_BROKER_SECURITY,
Defaults.VALUE_BROKER_SECURITY_NONE);
}
private javax.net.ssl.SSLSocketFactory getSSLSocketFactory() throws CertificateException,
KeyStoreException, NoSuchAlgorithmException, IOException, KeyManagementException {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream caInput = new BufferedInputStream(new FileInputStream(
sharedPreferences.getString(Defaults.SETTINGS_KEY_BROKER_SECURITY_SSL_CA_PATH, "")));
java.security.cert.Certificate ca;
try {
ca = cf.generateCertificate(caInput);
} finally {
caInput.close();
}
// Create a KeyStore containing our trusted CAs
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
// Create an SSLContext that uses our TrustManager
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);
return context.getSocketFactory();
}
private boolean connect()
{
workerThread = Thread.currentThread(); // We connect, so we're the
// worker thread
Log.v(this.toString(), "connectToBroker");
init();
try
{
changeMqttConnectivity(MQTT_CONNECTIVITY.CONNECTING);
MqttConnectOptions options = new MqttConnectOptions();
if (getBrokerSecurityMode() == Defaults.VALUE_BROKER_SECURITY_SSL_CUSTOMCACRT)
options.setSocketFactory(this.getSSLSocketFactory());
if (!sharedPreferences.getString(Defaults.SETTINGS_KEY_BROKER_PASSWORD, "").equals(""))
options.setPassword(sharedPreferences.getString(
Defaults.SETTINGS_KEY_BROKER_PASSWORD, "").toCharArray());
if (!sharedPreferences.getString(Defaults.SETTINGS_KEY_BROKER_USERNAME, "").equals(""))
options.setUserName(sharedPreferences.getString(
Defaults.SETTINGS_KEY_BROKER_USERNAME, ""));
setWill(options);
options.setKeepAliveInterval(keepAliveSeconds);
options.setConnectionTimeout(10);
mqttClient.connect(options);
changeMqttConnectivity(MQTT_CONNECTIVITY.CONNECTED);
return true;
} catch (Exception e) { // Catch paho and socket factory exceptions
Log.e(this.toString(), e.toString());
// TODO: send reason to user
changeMqttConnectivity(MQTT_CONNECTIVITY.DISCONNECTED);
return false;
}
}
private void setWill(MqttConnectOptions m) {
StringBuffer payload = new StringBuffer();
payload.append("{");
payload.append("\"type\": ").append("\"").append("_lwt").append("\"");
payload.append(", \"tst\": ").append("\"").append((int) (new Date().getTime() / 1000))
.append("\"");
payload.append("}");
m.setWill(mqttClient.getTopic(sharedPreferences.getString(Defaults.SETTINGS_KEY_TOPIC,
Defaults.VALUE_TOPIC)), payload.toString().getBytes(), 0, false);
}
private void onConnect() {
if (!isConnected()) {
Log.e(this.toString(), "onConnect: !isConnected");
}
}
public void disconnect(boolean fromUser)
{
Log.v(this.toString(), "disconnect");
if (fromUser)
changeMqttConnectivity(MQTT_CONNECTIVITY.DISCONNECTED_USERDISCONNECT);
try
{
if (mqttClient != null && mqttClient.isConnected())
{
mqttClient.disconnect();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
mqttClient = null;
if (workerThread != null) {
workerThread.interrupt();
}
}
}
@SuppressLint("Wakelock")
// Lint check derps with the wl.release() call.
@Override
public void connectionLost(Throwable t)
{
// we protect against the phone switching off while we're doing this
// by requesting a wake lock - we request the minimum possible wake
// lock - just enough to keep the CPU running until we've finished
PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MQTT");
wl.acquire();
if (!isOnline(true))
{
changeMqttConnectivity(MQTT_CONNECTIVITY.DISCONNECTED_WAITINGFORINTERNET);
}
else
{
changeMqttConnectivity(MQTT_CONNECTIVITY.DISCONNECTED);
}
wl.release();
}
public void reconnect() {
disconnect(true);
doStart(null, -1);
}
@Override
public void messageArrived(MqttTopic topic, MqttMessage message) throws MqttException {
}
// private boolean publish(String topicStr, String payload, boolean
// retained, int qos) {
// boolean isOnline = isOnline(false);
// boolean isConnected = isConnected();
// if (!isOnline || !isConnected) {
// return false;
// MqttMessage message = new MqttMessage(payload.getBytes());
// message.setQos(qos);
// message.setRetained(retained);
// try
// mqttClient.getTopic(topicStr).publish(message);
// return true;
// } catch (MqttException e)
// Log.e(this.toString(), e.getMessage());
// e.printStackTrace();
// return false;
public void onEvent(Events.MqttConnectivityChanged event) {
mqttConnectivity = event.getConnectivity();
if (event.getConnectivity() == MQTT_CONNECTIVITY.CONNECTED)
publishDeferrables();
}
/**
* @category CONNECTIVITY STATUS
*/
private void changeMqttConnectivity(MQTT_CONNECTIVITY newConnectivity) {
EventBus.getDefault().post(new Events.MqttConnectivityChanged(newConnectivity));
mqttConnectivity = newConnectivity;
}
private boolean isOnline(boolean shouldCheckIfOnWifi)
{
ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null
// && (!shouldCheckIfOnWifi || (netInfo.getType() ==
// ConnectivityManager.TYPE_WIFI))
&& netInfo.isAvailable()
&& netInfo.isConnected();
}
public boolean isConnected()
{
return ((mqttClient != null) && (mqttClient.isConnected() == true));
}
public boolean isConnecting() {
return (mqttClient != null) && mqttConnectivity == MQTT_CONNECTIVITY.CONNECTING;
}
private boolean isBackgroundDataEnabled() {
return isOnline(false);
}
public static MQTT_CONNECTIVITY getConnectivity() {
return mqttConnectivity;
}
/**
* @category MISC
*/
public static ServiceMqtt getInstance() {
return instance;
}
private String getClientId()
{
if (mqttClientId == null)
{
mqttClientId = Secure.getString(getContentResolver(), Secure.ANDROID_ID);
// MQTT specification doesn't allow client IDs longer than 23 chars
if (mqttClientId.length() > 22)
mqttClientId = mqttClientId.substring(0, 22);
}
return mqttClientId;
}
@Override
public IBinder onBind(Intent intent)
{
return mBinder;
}
public class LocalBinder<T> extends Binder
{
private WeakReference<ServiceMqtt> mService;
public LocalBinder(ServiceMqtt service) {
mService = new WeakReference<ServiceMqtt>(service);
}
public ServiceMqtt getService() {
return mService.get();
}
public void close() {
mService = null;
}
}
@Override
public void onDestroy()
{
// disconnect immediately
disconnect(false);
changeMqttConnectivity(MQTT_CONNECTIVITY.DISCONNECTED);
if (mBinder != null) {
mBinder.close();
mBinder = null;
}
sharedPreferences.unregisterOnSharedPreferenceChangeListener(preferencesChangedListener);
if (this.alarmManagerPositioning != null)
this.alarmManagerPositioning.cancel(pendingIntentPositioning);
super.onDestroy();
}
@Override
public void deliveryComplete(MqttDeliveryToken arg0) {
}
public static String getConnectivityText() {
switch (ServiceMqtt.getConnectivity()) {
case CONNECTED:
return App.getInstance().getString(R.string.connectivityConnected);
case CONNECTING:
return App.getInstance().getString(R.string.connectivityConnecting);
case DISCONNECTING:
return App.getInstance().getString(R.string.connectivityDisconnecting);
// More verbose disconnect states could be added here. For now
// any flavor of disconnected is treated the same
default:
return App.getInstance().getString(R.string.connectivityDisconnected);
}
}
private void deferPublish(final DeferredPublishable p) {
p.wait(deferredPublishables, new Runnable() {
@Override
public void run() {
deferredPublishables.remove(p);
if(!p.isPublishing())//might haben that the publish is in progress while the timeout occurs.
p.publishFailed();
}
});
}
public void publish(String topic, String payload) {
publish(topic, payload, false, 0, 0, null);
}
public void publish(String topic, String payload, boolean retained) {
publish(topic, payload, retained, 0, 0, null);
}
public void publish(String topic, String payload, boolean retained, int qos, int timeout,
MqttPublish callback) {
publish(new DeferredPublishable(topic, payload, retained, qos, timeout, callback));
}
private void publish(DeferredPublishable p) {
boolean isOnline = isOnline(false);
boolean isConnected = isConnected();
if (!isOnline || !isConnected) {
deferPublish(p);
return;
}
try
{
p.publishing();
mqttClient.getTopic(p.getTopic()).publish(p);
p.publishSuccessfull();
} catch (MqttException e)
{
Log.e(this.toString(), e.getMessage());
e.printStackTrace();
p.publishFailed();
}
}
private void publishDeferrables() {
for (Iterator<DeferredPublishable> iter = deferredPublishables.iterator(); iter.hasNext(); ) {
DeferredPublishable p = iter.next();
iter.remove();
publish(p);
}
}
private class DeferredPublishable extends MqttMessage {
private Handler timeoutHandler;
private MqttPublish callback;
private String topic;
private int timeout = 0;
private boolean isPublishing;
public DeferredPublishable(String topic, String payload, boolean retained, int qos,
int timeout, MqttPublish callback) {
super(payload.getBytes());
this.setQos(qos);
this.setRetained(retained);
this.callback = callback;
this.topic = topic;
this.timeout = timeout;
}
public void publishFailed() {
if (callback != null)
callback.publishFailed();
}
public void publishSuccessfull() {
if (callback != null)
callback.publishSuccessfull();
cancelWait();
}
public void publishing() {
isPublishing = true;
if (callback != null)
callback.publishing();
}
public boolean isPublishing(){
return isPublishing;
}
public String getTopic() {
return topic;
}
public void cancelWait(){
if(timeoutHandler != null)
this.timeoutHandler.removeCallbacksAndMessages(this);
}
public void wait(LinkedList<DeferredPublishable> queue, Runnable onRemove) {
if (timeoutHandler != null) {
Log.d(this.toString(), "This DeferredPublishable already has a timeout set");
return;
}
// No need signal waiting for timeouts of 0. The command will be
// failed right away
if (callback != null && timeout > 0)
callback.publishWaiting();
queue.addLast(this);
this.timeoutHandler = new Handler();
this.timeoutHandler.postDelayed(onRemove, timeout * 1000);
}
}
}
|
import static org.kohsuke.args4j.ExampleMode.ALL;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;
import org.kohsuke.args4j.ExampleMode;
import org.kohsuke.args4j.spi.BooleanOptionHandler;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Sample program that shows how you can use args4j.
*
* @author
* Kohsuke Kawaguchi (kk@kohsuke.org)
*/
public class SampleMain {
@Option(name="-r",usage="recursively run something")
private boolean recursive;
@Option(name="-o",usage="output to this file",metaVar="OUTPUT")
private File out = new File(".");
@Option(name="-str") // no usage
private String str = "(default value)";
@Option(name="-n",usage="repeat <n> times\nusage can have new lines in it and also it can be verrrrrrrrrrrrrrrrrry long")
private int num = -1;
// using 'handler=...' allows you to specify a custom OptionHandler
// implementation class. This allows you to bind a standard Java type
// with a non-standard option syntax
@Option(name="-custom",handler=BooleanOptionHandler.class)
private boolean data;
// receives other command line parameters than options
@Argument
private List<String> arguments = new ArrayList<String>();
public static void main(String[] args) throws IOException {
new SampleMain().doMain(args);
}
public void doMain(String[] args) throws IOException {
CmdLineParser parser = new CmdLineParser(this);
try {
// parse the arguments.
parser.parseArgument(args);
// you can parse additional arguments if you want.
// parser.parseArgument("more","args");
// after parsing arguments, you should check
// if enough arguments are given.
if( arguments.isEmpty() )
throw new CmdLineException("No argument is given");
} catch( CmdLineException e ) {
// if there's a problem in the command line,
// you'll get this exception. this will report
// an error message.
System.err.println(e.getMessage());
System.err.println("java SampleMain [options...] arguments...");
// print the list of available options
parser.printUsage(System.err);
System.err.println();
// print option sample. This is useful some time
System.err.println(" Example: java SampleMain"+parser.printExample(ALL));
return;
}
// this will redirect the output to the specified output
System.out.println(out);
if( recursive )
System.out.println("-r flag is set");
System.out.println("-str was "+str);
if( num>=0 )
System.out.println("-n was "+num);
// access non-option arguments
System.out.println("other arguments are:");
for( String s : arguments )
System.out.println(s);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.