diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/src/main/java/com/fatwire/cs/profiling/ss/reporting/reporters/NestingTracker.java b/src/main/java/com/fatwire/cs/profiling/ss/reporting/reporters/NestingTracker.java
index fbbfc77..d33554f 100644
--- a/src/main/java/com/fatwire/cs/profiling/ss/reporting/reporters/NestingTracker.java
+++ b/src/main/java/com/fatwire/cs/profiling/ss/reporting/reporters/NestingTracker.java
@@ -1,37 +1,38 @@
package com.fatwire.cs.profiling.ss.reporting.reporters;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.fatwire.cs.profiling.ss.QueryString;
import com.fatwire.cs.profiling.ss.ResultPage;
public class NestingTracker {
private final Map<QueryString, List<QueryString>> pages = new HashMap<QueryString, List<QueryString>>();
public void add(ResultPage page) {
if (!pages.containsKey(page.getUri())) {
pages.put(page.getUri(), page.getMarkers());
}
}
public Set<QueryString> getKeys() {
return pages.keySet();
}
public int getNestingLevel(QueryString qs) {
int level = 0;
if (qs == null)
return 0;
if (pages.containsKey(qs)) {
for (QueryString inner : pages.get(qs)) {
+ level++;
level = level + getNestingLevel(inner);
}
}
return level;
}
}
| true | true | public int getNestingLevel(QueryString qs) {
int level = 0;
if (qs == null)
return 0;
if (pages.containsKey(qs)) {
for (QueryString inner : pages.get(qs)) {
level = level + getNestingLevel(inner);
}
}
return level;
}
| public int getNestingLevel(QueryString qs) {
int level = 0;
if (qs == null)
return 0;
if (pages.containsKey(qs)) {
for (QueryString inner : pages.get(qs)) {
level++;
level = level + getNestingLevel(inner);
}
}
return level;
}
|
diff --git a/Compiler/java/AppleCoreCompiler/CodeGen/SourceFileWriter.java b/Compiler/java/AppleCoreCompiler/CodeGen/SourceFileWriter.java
index 326d249..861b98b 100644
--- a/Compiler/java/AppleCoreCompiler/CodeGen/SourceFileWriter.java
+++ b/Compiler/java/AppleCoreCompiler/CodeGen/SourceFileWriter.java
@@ -1,167 +1,171 @@
/**
* Generic pass for traversing the AST and writing out assembly code.
* Assembler-specific syntax is handled by the Emitter class.
*/
package AppleCoreCompiler.CodeGen;
import AppleCoreCompiler.AST.*;
import AppleCoreCompiler.AST.Node.*;
import AppleCoreCompiler.Errors.*;
import AppleCoreCompiler.AST.Node.RegisterExpression.Register;
import AppleCoreCompiler.AVM.*;
import AppleCoreCompiler.AVM.Instruction.*;
import java.io.*;
import java.util.*;
import java.math.*;
public class SourceFileWriter
extends ASTScanner
implements Pass
{
/* Initialization stuff */
public final NativeCodeEmitter emitter;
public SourceFileWriter(NativeCodeEmitter emitter,
int avmSlot, int avmDrive) {
this.emitter = emitter;
this.avmSlot=avmSlot;
this.avmDrive=avmDrive;
}
public final int avmSlot;
public final int avmDrive;
public void runOn(SourceFile sourceFile)
throws ACCError
{
scan(sourceFile);
}
/**
* The function being processed
*/
protected FunctionDecl currentFunction;
public void visitSourceFile(SourceFile node)
throws ACCError
{
emitter.emitPreamble(node);
emitter.emitSeparatorComment();
emitter.emitComment("Assembly file generated by");
emitter.emitComment("the AppleCore Compiler, v1.0");
emitter.emitSeparatorComment();
if (!node.includeMode) {
emitter.emitIncludeDirective("AVM.PROLOGUE",avmSlot,avmDrive);
FunctionDecl firstFunction = null;
for (Declaration decl : node.decls) {
if (decl instanceof FunctionDecl) {
FunctionDecl functionDecl = (FunctionDecl) decl;
if (firstFunction == null && !functionDecl.isExternal) {
firstFunction = (FunctionDecl) decl;
}
}
}
if (firstFunction != null) {
emitter.emitComment("initial carriage return");
emitter.emitAbsoluteInstruction("JSR","$FD8E");
emitter.emitComment("put DOS in deferred mode");
emitter.emitAbsoluteInstruction("LDA","$AAB6");
emitter.emitInstruction("PHA");
emitter.emitImmediateInstruction("LDY",0);
emitter.emitAbsoluteInstruction("STY","$AAB6");
emitter.emitInstruction("DEY");
emitter.emitAbsoluteInstruction("STY","$D9");
+ emitter.emitComment("patch DOS error handling");
+ emitter.emitAbsoluteInstruction("JSR","AVM.PATCH.DOS");
emitter.emitComment("do main function");
emitter.emitAbsoluteInstruction("JSR",
emitter.makeLabel(firstFunction.name));
+ emitter.emitComment("restore DOS error handling");
+ emitter.emitAbsoluteInstruction("JSR","AVM.UNPATCH.DOS");
emitter.emitComment("put DOS back in direct mode");
emitter.emitInstruction("PLA");
emitter.emitAbsoluteInstruction("STA","$AAB6");
emitter.emitImmediateInstruction("LDY",0);
emitter.emitAbsoluteInstruction("STY","$D9");
emitter.emitComment("exit to BASIC");
emitter.emitAbsoluteInstruction("JMP","$3D3");
}
emitter.emitSeparatorComment();
}
emitter.emitComment("START OF FILE " + node.name);
emitter.emitSeparatorComment();
super.visitSourceFile(node);
emitter.emitSeparatorComment();
emitter.emitComment("END OF FILE " + node.name);
emitter.emitSeparatorComment();
if (!node.includeMode) {
emitter.emitEpilogue(avmSlot,avmDrive);
}
}
public void visitFunctionDecl(FunctionDecl node)
throws ACCError
{
if (!node.isExternal) {
emitter.emitSeparatorComment();
emitter.emitComment("function " + node.name);
emitter.emitSeparatorComment();
for (Instruction inst : node.instructions) {
if (!(inst instanceof LabelInstruction) &&
!(inst instanceof CommentInstruction)) {
emitter.printStream.print("\t");
}
emitter.printStream.println(emitter.makeLabel(inst.toString()));
}
}
}
public void visitIncludeDecl(IncludeDecl node) {
emitter.emitIncludeDecl(node);
}
public void visitDataDecl(DataDecl node)
throws ACCError
{
if (node.label != null)
emitter.emitLabel(node.label);
if (node.stringConstant != null) {
emitter.emitStringConstant(node.stringConstant);
if (node.isTerminatedString) {
emitter.emitStringTerminator();
}
}
else if (node.expr instanceof NumericConstant) {
NumericConstant nc =
(NumericConstant) node.expr;
emitter.emitAsData(nc);
}
else if (node.expr instanceof Identifier) {
Identifier id =
(Identifier) node.expr;
emitter.emitAsData(id);
}
else {
throw new ACCInternalError("invalid data for "+node, node);
}
}
public void visitVarDecl(VarDecl node)
throws ACCError
{
emitter.emitLabel(node.name);
if (node.init == null) {
emitter.emitBlockStorage(node.size);
}
else {
// Previous passes must ensure cast will succeed.
if (!(node.init instanceof NumericConstant)) {
throw new ACCInternalError("non-constant initializer expr for ", node);
}
NumericConstant constant =
(NumericConstant) node.init;
emitter.emitAsData(constant, node.size);
}
}
}
| false | true | public void visitSourceFile(SourceFile node)
throws ACCError
{
emitter.emitPreamble(node);
emitter.emitSeparatorComment();
emitter.emitComment("Assembly file generated by");
emitter.emitComment("the AppleCore Compiler, v1.0");
emitter.emitSeparatorComment();
if (!node.includeMode) {
emitter.emitIncludeDirective("AVM.PROLOGUE",avmSlot,avmDrive);
FunctionDecl firstFunction = null;
for (Declaration decl : node.decls) {
if (decl instanceof FunctionDecl) {
FunctionDecl functionDecl = (FunctionDecl) decl;
if (firstFunction == null && !functionDecl.isExternal) {
firstFunction = (FunctionDecl) decl;
}
}
}
if (firstFunction != null) {
emitter.emitComment("initial carriage return");
emitter.emitAbsoluteInstruction("JSR","$FD8E");
emitter.emitComment("put DOS in deferred mode");
emitter.emitAbsoluteInstruction("LDA","$AAB6");
emitter.emitInstruction("PHA");
emitter.emitImmediateInstruction("LDY",0);
emitter.emitAbsoluteInstruction("STY","$AAB6");
emitter.emitInstruction("DEY");
emitter.emitAbsoluteInstruction("STY","$D9");
emitter.emitComment("do main function");
emitter.emitAbsoluteInstruction("JSR",
emitter.makeLabel(firstFunction.name));
emitter.emitComment("put DOS back in direct mode");
emitter.emitInstruction("PLA");
emitter.emitAbsoluteInstruction("STA","$AAB6");
emitter.emitImmediateInstruction("LDY",0);
emitter.emitAbsoluteInstruction("STY","$D9");
emitter.emitComment("exit to BASIC");
emitter.emitAbsoluteInstruction("JMP","$3D3");
}
emitter.emitSeparatorComment();
}
emitter.emitComment("START OF FILE " + node.name);
emitter.emitSeparatorComment();
super.visitSourceFile(node);
emitter.emitSeparatorComment();
emitter.emitComment("END OF FILE " + node.name);
emitter.emitSeparatorComment();
if (!node.includeMode) {
emitter.emitEpilogue(avmSlot,avmDrive);
}
}
| public void visitSourceFile(SourceFile node)
throws ACCError
{
emitter.emitPreamble(node);
emitter.emitSeparatorComment();
emitter.emitComment("Assembly file generated by");
emitter.emitComment("the AppleCore Compiler, v1.0");
emitter.emitSeparatorComment();
if (!node.includeMode) {
emitter.emitIncludeDirective("AVM.PROLOGUE",avmSlot,avmDrive);
FunctionDecl firstFunction = null;
for (Declaration decl : node.decls) {
if (decl instanceof FunctionDecl) {
FunctionDecl functionDecl = (FunctionDecl) decl;
if (firstFunction == null && !functionDecl.isExternal) {
firstFunction = (FunctionDecl) decl;
}
}
}
if (firstFunction != null) {
emitter.emitComment("initial carriage return");
emitter.emitAbsoluteInstruction("JSR","$FD8E");
emitter.emitComment("put DOS in deferred mode");
emitter.emitAbsoluteInstruction("LDA","$AAB6");
emitter.emitInstruction("PHA");
emitter.emitImmediateInstruction("LDY",0);
emitter.emitAbsoluteInstruction("STY","$AAB6");
emitter.emitInstruction("DEY");
emitter.emitAbsoluteInstruction("STY","$D9");
emitter.emitComment("patch DOS error handling");
emitter.emitAbsoluteInstruction("JSR","AVM.PATCH.DOS");
emitter.emitComment("do main function");
emitter.emitAbsoluteInstruction("JSR",
emitter.makeLabel(firstFunction.name));
emitter.emitComment("restore DOS error handling");
emitter.emitAbsoluteInstruction("JSR","AVM.UNPATCH.DOS");
emitter.emitComment("put DOS back in direct mode");
emitter.emitInstruction("PLA");
emitter.emitAbsoluteInstruction("STA","$AAB6");
emitter.emitImmediateInstruction("LDY",0);
emitter.emitAbsoluteInstruction("STY","$D9");
emitter.emitComment("exit to BASIC");
emitter.emitAbsoluteInstruction("JMP","$3D3");
}
emitter.emitSeparatorComment();
}
emitter.emitComment("START OF FILE " + node.name);
emitter.emitSeparatorComment();
super.visitSourceFile(node);
emitter.emitSeparatorComment();
emitter.emitComment("END OF FILE " + node.name);
emitter.emitSeparatorComment();
if (!node.includeMode) {
emitter.emitEpilogue(avmSlot,avmDrive);
}
}
|
diff --git a/src/org/adblockplus/brazil/RequestHandler.java b/src/org/adblockplus/brazil/RequestHandler.java
index 13e24ea..f1e56c5 100644
--- a/src/org/adblockplus/brazil/RequestHandler.java
+++ b/src/org/adblockplus/brazil/RequestHandler.java
@@ -1,409 +1,411 @@
package org.adblockplus.brazil;
import java.io.BufferedInputStream;
import java.io.EOFException;
import java.io.FilterInputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Properties;
import java.util.zip.GZIPInputStream;
import java.util.zip.InflaterInputStream;
import org.adblockplus.ChunkedOutputStream;
import org.adblockplus.android.AdblockPlus;
import org.literateprograms.BoyerMoore;
import sunlabs.brazil.server.Handler;
import sunlabs.brazil.server.Request;
import sunlabs.brazil.server.Server;
import sunlabs.brazil.util.MatchString;
import sunlabs.brazil.util.http.HttpInputStream;
import sunlabs.brazil.util.http.HttpRequest;
import sunlabs.brazil.util.http.MimeHeaders;
import android.util.Log;
/**
* The <code>RequestHandler</code> implements a proxy service optionally
* modifying output.
* The following configuration parameters are used to initialize this
* <code>Handler</code>:
* <dl class=props>
*
* <dt>prefix, suffix, glob, match
* <dd>Specify the URL that triggers this handler. (See {@link MatchString}).
* <dt>auth
* <dd>The value of the proxy-authenticate header (if any) sent to the upstream proxy
* <dt>proxyHost
* <dd>If specified, the name of the upstream proxy
* <dt>proxyPort
* <dd>The upstream proxy port, if a proxyHost is specified (defaults to 80)
* <dt>proxylog
* <dd>If set all http headers will be logged to the console. This
* is for debugging.
*
* </dl>
*
* A sample set of configuration parameters illustrating how to use this
* handler follows:
*
* <pre>
* handler=adblock
* adblock.class=org.adblockplus.brazil.RequestHandler
* </pre>
*
* See the description under {@link sunlabs.brazil.server.Handler#respond
* respond} for a more detailed explanation.
*/
public class RequestHandler implements Handler
{
public static final String PROXY_HOST = "proxyHost";
public static final String PROXY_PORT = "proxyPort";
public static final String AUTH = "auth";
private AdblockPlus application;
private String prefix;
private String via;
private String proxyHost;
private int proxyPort = 80;
private String auth;
private boolean shouldLog; // if true, log all headers
@Override
public boolean init(Server server, String prefix)
{
this.prefix = prefix;
application = AdblockPlus.getApplication();
Properties props = server.props;
proxyHost = props.getProperty(prefix + PROXY_HOST);
String s = props.getProperty(prefix + PROXY_PORT);
try
{
proxyPort = Integer.decode(s).intValue();
}
catch (Exception e)
{
}
auth = props.getProperty(prefix + AUTH);
shouldLog = (props.getProperty(prefix + "proxylog") != null);
via = " " + server.hostName + ":" + server.listen.getLocalPort() + " (" + server.name + ")";
return true;
}
@Override
public boolean respond(Request request) throws IOException
{
boolean block = false;
String reqHost = null;
String refHost = null;
try
{
reqHost = (new URL(request.url)).getHost();
refHost = (new URL(request.getRequestHeader("referer"))).getHost();
}
catch (MalformedURLException e)
{
}
try
{
block = application.matches(request.url, request.query, reqHost, refHost, request.getRequestHeader("accept"));
}
catch (Exception e)
{
Log.e(prefix, "Filter error", e);
}
request.log(Server.LOG_LOG, prefix, block + ": " + request.url);
if (block)
{
request.sendError(403, "Blocked by Adblock Plus");
return true;
}
if (request.url.startsWith("http:") == false && request.url.startsWith("https:") == false)
{
return false;
}
String url = request.url;
if ((request.query != null) && (request.query.length() > 0))
{
url += "?" + request.query;
}
int count = request.server.requestCount;
if (shouldLog)
{
System.err.println(dumpHeaders(count, request, request.headers, true));
}
/*
* "Proxy-Connection" may be used (instead of just "Connection")
* to keep alive a connection between a client and this proxy.
*/
String pc = request.headers.get("Proxy-Connection");
if (pc != null)
{
request.connectionHeader = "Proxy-Connection";
request.keepAlive = pc.equalsIgnoreCase("Keep-Alive");
}
HttpRequest.removePointToPointHeaders(request.headers, false);
HttpRequest target = new HttpRequest(url);
try
{
target.setMethod(request.method);
request.headers.copyTo(target.requestHeaders);
if (proxyHost != null)
{
target.setProxy(proxyHost, proxyPort);
if (auth != null)
{
target.requestHeaders.add("Proxy-Authorization", auth);
}
}
if (request.postData != null)
{
OutputStream out = target.getOutputStream();
out.write(request.postData);
out.close();
}
target.connect();
if (shouldLog)
{
System.err.println(" " + target.status + "\n" + dumpHeaders(count, request, target.responseHeaders, false));
}
HttpRequest.removePointToPointHeaders(target.responseHeaders, true);
target.responseHeaders.copyTo(request.responseHeaders);
try
{
request.responseHeaders.add("Via", target.status.substring(0, 8) + via);
}
catch (StringIndexOutOfBoundsException e)
{
request.responseHeaders.add("Via", via);
}
// Detect if we need to add ElemHide filters
String type = request.responseHeaders.get("Content-Type");
String selectors = null;
if (type != null && type.toLowerCase().startsWith("text/html"))
{
selectors = application.getSelectorsForDomain(reqHost);
}
// If no filters are applicable just pass through the response
if (selectors == null || target.getResponseCode() != 200)
{
int contentLength = target.getContentLength();
if (contentLength == 0)
{
// we do not use request.sendResponse to avoid arbitrary
// 200 -> 204 response code conversion
request.sendHeaders(-1, null, -1);
}
else
{
request.sendResponse(target.getInputStream(), contentLength, null, target.getResponseCode());
}
}
// Insert filters otherwise
else
{
HttpInputStream his = target.getInputStream();
int size = target.getContentLength();
if (size < 0)
{
size = Integer.MAX_VALUE;
}
FilterInputStream in = null;
FilterOutputStream out = null;
// Detect if content needs decoding
String encodingHeader = request.responseHeaders.get("Content-Encoding");
if (encodingHeader != null)
{
encodingHeader = encodingHeader.toLowerCase();
if (encodingHeader.equals("gzip") || encodingHeader.equals("x-gzip"))
{
in = new GZIPInputStream(his);
request.responseHeaders.remove("Content-Length");
request.responseHeaders.remove("Content-Encoding");
out = new ChunkedOutputStream(request.out);
request.responseHeaders.add("Transfer-Encoding", "chunked");
+ size = Integer.MAX_VALUE;
}
else if (encodingHeader.equals("compress") || encodingHeader.equals("x-compress"))
{
in = new InflaterInputStream(his);
request.responseHeaders.remove("Content-Length");
request.responseHeaders.remove("Content-Encoding");
out = new ChunkedOutputStream(request.out);
request.responseHeaders.add("Transfer-Encoding", "chunked");
+ size = Integer.MAX_VALUE;
}
else
{
// Unsupported encoding, proxy content as-is
in = new BufferedInputStream(his);
out = request.out;
selectors = null;
}
}
request.sendHeaders(-1, null, -1);
byte[] buf = new byte[Math.min(4096, size)];
Log.e(prefix, request.url);
boolean sent = selectors == null;
// TODO Do we need to set encoding here?
BoyerMoore matcher = new BoyerMoore("<html".getBytes());
while (size > 0)
{
out.flush();
count = in.read(buf, 0, Math.min(buf.length, size));
if (count < 0)
{
break;
}
size -= count;
try
{
// Search for <html> tag
if (! sent && count > 0)
{
List<Integer> matches = matcher.match(buf, 0, count);
if (! matches.isEmpty())
{
// TODO Do we need to set encoding here?
byte[] addon = selectors.getBytes();
// Add selectors right before match
int m = matches.get(0);
out.write(buf, 0, m);
out.write(addon);
out.write(buf, m, count - m);
sent = true;
continue;
}
}
out.write(buf, 0, count);
}
catch (IOException e)
{
break;
}
}
// The correct way would be to close ChunkedOutputStream
// but we can not do it because underlying output stream is
// used later in caller code. So we use this ugly hack:
try
{
((ChunkedOutputStream)out).writeFinalChunk();
}
catch (ClassCastException e)
{
// ignore
}
}
}
catch (InterruptedIOException e)
{
/*
* Read timeout while reading from the remote side. We use a
* read timeout in case the target never responds.
*/
request.sendError(408, "Timeout / No response");
}
catch (EOFException e)
{
request.sendError(500, "No response");
}
catch (UnknownHostException e)
{
request.sendError(500, "Unknown host");
}
catch (ConnectException e)
{
request.sendError(500, "Connection refused");
}
catch (IOException e)
{
/*
* An IOException will happen if we can't communicate with the
* target or the client. Rather than attempting to discriminate,
* just send an error message to the client, and let the send
* fail if the client was the one that was in error.
*/
String msg = "Error from proxy";
if (e.getMessage() != null)
{
msg += ": " + e.getMessage();
}
request.sendError(500, msg);
Log.e(prefix, msg, e);
}
finally
{
target.close();
}
return true;
}
/**
* Dump the headers on stderr
*/
public static String dumpHeaders(int count, Request request, MimeHeaders headers, boolean sent)
{
String prompt;
StringBuffer sb = new StringBuffer();
String label = " " + count;
label = label.substring(label.length() - 4);
if (sent)
{
prompt = label + "> ";
sb.append(prompt).append(request.toString()).append("\n");
}
else
{
prompt = label + "< ";
}
for (int i = 0; i < headers.size(); i++)
{
sb.append(prompt).append(headers.getKey(i));
sb.append(": ").append(headers.get(i)).append("\n");
}
return (sb.toString());
}
}
| false | true | public boolean respond(Request request) throws IOException
{
boolean block = false;
String reqHost = null;
String refHost = null;
try
{
reqHost = (new URL(request.url)).getHost();
refHost = (new URL(request.getRequestHeader("referer"))).getHost();
}
catch (MalformedURLException e)
{
}
try
{
block = application.matches(request.url, request.query, reqHost, refHost, request.getRequestHeader("accept"));
}
catch (Exception e)
{
Log.e(prefix, "Filter error", e);
}
request.log(Server.LOG_LOG, prefix, block + ": " + request.url);
if (block)
{
request.sendError(403, "Blocked by Adblock Plus");
return true;
}
if (request.url.startsWith("http:") == false && request.url.startsWith("https:") == false)
{
return false;
}
String url = request.url;
if ((request.query != null) && (request.query.length() > 0))
{
url += "?" + request.query;
}
int count = request.server.requestCount;
if (shouldLog)
{
System.err.println(dumpHeaders(count, request, request.headers, true));
}
/*
* "Proxy-Connection" may be used (instead of just "Connection")
* to keep alive a connection between a client and this proxy.
*/
String pc = request.headers.get("Proxy-Connection");
if (pc != null)
{
request.connectionHeader = "Proxy-Connection";
request.keepAlive = pc.equalsIgnoreCase("Keep-Alive");
}
HttpRequest.removePointToPointHeaders(request.headers, false);
HttpRequest target = new HttpRequest(url);
try
{
target.setMethod(request.method);
request.headers.copyTo(target.requestHeaders);
if (proxyHost != null)
{
target.setProxy(proxyHost, proxyPort);
if (auth != null)
{
target.requestHeaders.add("Proxy-Authorization", auth);
}
}
if (request.postData != null)
{
OutputStream out = target.getOutputStream();
out.write(request.postData);
out.close();
}
target.connect();
if (shouldLog)
{
System.err.println(" " + target.status + "\n" + dumpHeaders(count, request, target.responseHeaders, false));
}
HttpRequest.removePointToPointHeaders(target.responseHeaders, true);
target.responseHeaders.copyTo(request.responseHeaders);
try
{
request.responseHeaders.add("Via", target.status.substring(0, 8) + via);
}
catch (StringIndexOutOfBoundsException e)
{
request.responseHeaders.add("Via", via);
}
// Detect if we need to add ElemHide filters
String type = request.responseHeaders.get("Content-Type");
String selectors = null;
if (type != null && type.toLowerCase().startsWith("text/html"))
{
selectors = application.getSelectorsForDomain(reqHost);
}
// If no filters are applicable just pass through the response
if (selectors == null || target.getResponseCode() != 200)
{
int contentLength = target.getContentLength();
if (contentLength == 0)
{
// we do not use request.sendResponse to avoid arbitrary
// 200 -> 204 response code conversion
request.sendHeaders(-1, null, -1);
}
else
{
request.sendResponse(target.getInputStream(), contentLength, null, target.getResponseCode());
}
}
// Insert filters otherwise
else
{
HttpInputStream his = target.getInputStream();
int size = target.getContentLength();
if (size < 0)
{
size = Integer.MAX_VALUE;
}
FilterInputStream in = null;
FilterOutputStream out = null;
// Detect if content needs decoding
String encodingHeader = request.responseHeaders.get("Content-Encoding");
if (encodingHeader != null)
{
encodingHeader = encodingHeader.toLowerCase();
if (encodingHeader.equals("gzip") || encodingHeader.equals("x-gzip"))
{
in = new GZIPInputStream(his);
request.responseHeaders.remove("Content-Length");
request.responseHeaders.remove("Content-Encoding");
out = new ChunkedOutputStream(request.out);
request.responseHeaders.add("Transfer-Encoding", "chunked");
}
else if (encodingHeader.equals("compress") || encodingHeader.equals("x-compress"))
{
in = new InflaterInputStream(his);
request.responseHeaders.remove("Content-Length");
request.responseHeaders.remove("Content-Encoding");
out = new ChunkedOutputStream(request.out);
request.responseHeaders.add("Transfer-Encoding", "chunked");
}
else
{
// Unsupported encoding, proxy content as-is
in = new BufferedInputStream(his);
out = request.out;
selectors = null;
}
}
request.sendHeaders(-1, null, -1);
byte[] buf = new byte[Math.min(4096, size)];
Log.e(prefix, request.url);
boolean sent = selectors == null;
// TODO Do we need to set encoding here?
BoyerMoore matcher = new BoyerMoore("<html".getBytes());
while (size > 0)
{
out.flush();
count = in.read(buf, 0, Math.min(buf.length, size));
if (count < 0)
{
break;
}
size -= count;
try
{
// Search for <html> tag
if (! sent && count > 0)
{
List<Integer> matches = matcher.match(buf, 0, count);
if (! matches.isEmpty())
{
// TODO Do we need to set encoding here?
byte[] addon = selectors.getBytes();
// Add selectors right before match
int m = matches.get(0);
out.write(buf, 0, m);
out.write(addon);
out.write(buf, m, count - m);
sent = true;
continue;
}
}
out.write(buf, 0, count);
}
catch (IOException e)
{
break;
}
}
// The correct way would be to close ChunkedOutputStream
// but we can not do it because underlying output stream is
// used later in caller code. So we use this ugly hack:
try
{
((ChunkedOutputStream)out).writeFinalChunk();
}
catch (ClassCastException e)
{
// ignore
}
}
}
catch (InterruptedIOException e)
{
/*
* Read timeout while reading from the remote side. We use a
* read timeout in case the target never responds.
*/
request.sendError(408, "Timeout / No response");
}
catch (EOFException e)
{
request.sendError(500, "No response");
}
catch (UnknownHostException e)
{
request.sendError(500, "Unknown host");
}
catch (ConnectException e)
{
request.sendError(500, "Connection refused");
}
catch (IOException e)
{
/*
* An IOException will happen if we can't communicate with the
* target or the client. Rather than attempting to discriminate,
* just send an error message to the client, and let the send
* fail if the client was the one that was in error.
*/
String msg = "Error from proxy";
if (e.getMessage() != null)
{
msg += ": " + e.getMessage();
}
request.sendError(500, msg);
Log.e(prefix, msg, e);
}
finally
{
target.close();
}
return true;
}
| public boolean respond(Request request) throws IOException
{
boolean block = false;
String reqHost = null;
String refHost = null;
try
{
reqHost = (new URL(request.url)).getHost();
refHost = (new URL(request.getRequestHeader("referer"))).getHost();
}
catch (MalformedURLException e)
{
}
try
{
block = application.matches(request.url, request.query, reqHost, refHost, request.getRequestHeader("accept"));
}
catch (Exception e)
{
Log.e(prefix, "Filter error", e);
}
request.log(Server.LOG_LOG, prefix, block + ": " + request.url);
if (block)
{
request.sendError(403, "Blocked by Adblock Plus");
return true;
}
if (request.url.startsWith("http:") == false && request.url.startsWith("https:") == false)
{
return false;
}
String url = request.url;
if ((request.query != null) && (request.query.length() > 0))
{
url += "?" + request.query;
}
int count = request.server.requestCount;
if (shouldLog)
{
System.err.println(dumpHeaders(count, request, request.headers, true));
}
/*
* "Proxy-Connection" may be used (instead of just "Connection")
* to keep alive a connection between a client and this proxy.
*/
String pc = request.headers.get("Proxy-Connection");
if (pc != null)
{
request.connectionHeader = "Proxy-Connection";
request.keepAlive = pc.equalsIgnoreCase("Keep-Alive");
}
HttpRequest.removePointToPointHeaders(request.headers, false);
HttpRequest target = new HttpRequest(url);
try
{
target.setMethod(request.method);
request.headers.copyTo(target.requestHeaders);
if (proxyHost != null)
{
target.setProxy(proxyHost, proxyPort);
if (auth != null)
{
target.requestHeaders.add("Proxy-Authorization", auth);
}
}
if (request.postData != null)
{
OutputStream out = target.getOutputStream();
out.write(request.postData);
out.close();
}
target.connect();
if (shouldLog)
{
System.err.println(" " + target.status + "\n" + dumpHeaders(count, request, target.responseHeaders, false));
}
HttpRequest.removePointToPointHeaders(target.responseHeaders, true);
target.responseHeaders.copyTo(request.responseHeaders);
try
{
request.responseHeaders.add("Via", target.status.substring(0, 8) + via);
}
catch (StringIndexOutOfBoundsException e)
{
request.responseHeaders.add("Via", via);
}
// Detect if we need to add ElemHide filters
String type = request.responseHeaders.get("Content-Type");
String selectors = null;
if (type != null && type.toLowerCase().startsWith("text/html"))
{
selectors = application.getSelectorsForDomain(reqHost);
}
// If no filters are applicable just pass through the response
if (selectors == null || target.getResponseCode() != 200)
{
int contentLength = target.getContentLength();
if (contentLength == 0)
{
// we do not use request.sendResponse to avoid arbitrary
// 200 -> 204 response code conversion
request.sendHeaders(-1, null, -1);
}
else
{
request.sendResponse(target.getInputStream(), contentLength, null, target.getResponseCode());
}
}
// Insert filters otherwise
else
{
HttpInputStream his = target.getInputStream();
int size = target.getContentLength();
if (size < 0)
{
size = Integer.MAX_VALUE;
}
FilterInputStream in = null;
FilterOutputStream out = null;
// Detect if content needs decoding
String encodingHeader = request.responseHeaders.get("Content-Encoding");
if (encodingHeader != null)
{
encodingHeader = encodingHeader.toLowerCase();
if (encodingHeader.equals("gzip") || encodingHeader.equals("x-gzip"))
{
in = new GZIPInputStream(his);
request.responseHeaders.remove("Content-Length");
request.responseHeaders.remove("Content-Encoding");
out = new ChunkedOutputStream(request.out);
request.responseHeaders.add("Transfer-Encoding", "chunked");
size = Integer.MAX_VALUE;
}
else if (encodingHeader.equals("compress") || encodingHeader.equals("x-compress"))
{
in = new InflaterInputStream(his);
request.responseHeaders.remove("Content-Length");
request.responseHeaders.remove("Content-Encoding");
out = new ChunkedOutputStream(request.out);
request.responseHeaders.add("Transfer-Encoding", "chunked");
size = Integer.MAX_VALUE;
}
else
{
// Unsupported encoding, proxy content as-is
in = new BufferedInputStream(his);
out = request.out;
selectors = null;
}
}
request.sendHeaders(-1, null, -1);
byte[] buf = new byte[Math.min(4096, size)];
Log.e(prefix, request.url);
boolean sent = selectors == null;
// TODO Do we need to set encoding here?
BoyerMoore matcher = new BoyerMoore("<html".getBytes());
while (size > 0)
{
out.flush();
count = in.read(buf, 0, Math.min(buf.length, size));
if (count < 0)
{
break;
}
size -= count;
try
{
// Search for <html> tag
if (! sent && count > 0)
{
List<Integer> matches = matcher.match(buf, 0, count);
if (! matches.isEmpty())
{
// TODO Do we need to set encoding here?
byte[] addon = selectors.getBytes();
// Add selectors right before match
int m = matches.get(0);
out.write(buf, 0, m);
out.write(addon);
out.write(buf, m, count - m);
sent = true;
continue;
}
}
out.write(buf, 0, count);
}
catch (IOException e)
{
break;
}
}
// The correct way would be to close ChunkedOutputStream
// but we can not do it because underlying output stream is
// used later in caller code. So we use this ugly hack:
try
{
((ChunkedOutputStream)out).writeFinalChunk();
}
catch (ClassCastException e)
{
// ignore
}
}
}
catch (InterruptedIOException e)
{
/*
* Read timeout while reading from the remote side. We use a
* read timeout in case the target never responds.
*/
request.sendError(408, "Timeout / No response");
}
catch (EOFException e)
{
request.sendError(500, "No response");
}
catch (UnknownHostException e)
{
request.sendError(500, "Unknown host");
}
catch (ConnectException e)
{
request.sendError(500, "Connection refused");
}
catch (IOException e)
{
/*
* An IOException will happen if we can't communicate with the
* target or the client. Rather than attempting to discriminate,
* just send an error message to the client, and let the send
* fail if the client was the one that was in error.
*/
String msg = "Error from proxy";
if (e.getMessage() != null)
{
msg += ": " + e.getMessage();
}
request.sendError(500, msg);
Log.e(prefix, msg, e);
}
finally
{
target.close();
}
return true;
}
|
diff --git a/src/main/java/com/tp/action/ViewSourceAction.java b/src/main/java/com/tp/action/ViewSourceAction.java
index f1e991f..a7e0d82 100644
--- a/src/main/java/com/tp/action/ViewSourceAction.java
+++ b/src/main/java/com/tp/action/ViewSourceAction.java
@@ -1,84 +1,84 @@
package com.tp.action;
import java.io.File;
import java.io.OutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Namespace;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.opensymphony.xwork2.ActionSupport;
import com.tp.utils.ServletUtils;
import com.tp.utils.Struts2Utils;
@Namespace("/report")
public class ViewSourceAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private Logger logger = LoggerFactory.getLogger(ViewSourceAction.class);
private String path;
private long MAX_FILE_SIZE = 30000000;
private String userDir = System.getProperty("user.dir");
@Override
public String execute() throws Exception {
return SUCCESS;
}
public String view() throws Exception {
try {
HttpServletResponse response = Struts2Utils.getResponse();
HttpServletRequest request = Struts2Utils.getRequest();
String userDir = System.getProperty("user.dir");
String download = request.getParameter("download");
String fname = request.getParameter("fname");
if (StringUtils.isBlank(fname)) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "fname parametter is required.");
return null;
}
path = StringUtils.strip(path, null);
File file;
if (StringUtils.isBlank(path) && userDir != null) {
file = new File(userDir + "/logs", fname);
} else {
file = new File(path, fname);
}
OutputStream output = response.getOutputStream();
if (!file.exists()) {
Struts2Utils.renderText("文件不存在");
return null;
}
if (file.length() > MAX_FILE_SIZE && download == null) {
Struts2Utils.renderText("文件过大,请带上下载参数download=true保存到本地");
return null;
}
if (download != null) {
ServletUtils.setFileDownloadHeader(response, file.getName());
}
FileUtils.copyFile(file, output);
output.flush();
} catch (Exception e) {
- logger.error(e.getMessage() + "下载日志文件时非正常中断");
+ logger.warn(e.getMessage() + "下载日志文件时非正常中断");
}
return null;
}
public void setPath(String path) {
this.path = path;
}
public String getUserDir() {
return userDir;
}
}
| true | true | public String view() throws Exception {
try {
HttpServletResponse response = Struts2Utils.getResponse();
HttpServletRequest request = Struts2Utils.getRequest();
String userDir = System.getProperty("user.dir");
String download = request.getParameter("download");
String fname = request.getParameter("fname");
if (StringUtils.isBlank(fname)) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "fname parametter is required.");
return null;
}
path = StringUtils.strip(path, null);
File file;
if (StringUtils.isBlank(path) && userDir != null) {
file = new File(userDir + "/logs", fname);
} else {
file = new File(path, fname);
}
OutputStream output = response.getOutputStream();
if (!file.exists()) {
Struts2Utils.renderText("文件不存在");
return null;
}
if (file.length() > MAX_FILE_SIZE && download == null) {
Struts2Utils.renderText("文件过大,请带上下载参数download=true保存到本地");
return null;
}
if (download != null) {
ServletUtils.setFileDownloadHeader(response, file.getName());
}
FileUtils.copyFile(file, output);
output.flush();
} catch (Exception e) {
logger.error(e.getMessage() + "下载日志文件时非正常中断");
}
return null;
}
| public String view() throws Exception {
try {
HttpServletResponse response = Struts2Utils.getResponse();
HttpServletRequest request = Struts2Utils.getRequest();
String userDir = System.getProperty("user.dir");
String download = request.getParameter("download");
String fname = request.getParameter("fname");
if (StringUtils.isBlank(fname)) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "fname parametter is required.");
return null;
}
path = StringUtils.strip(path, null);
File file;
if (StringUtils.isBlank(path) && userDir != null) {
file = new File(userDir + "/logs", fname);
} else {
file = new File(path, fname);
}
OutputStream output = response.getOutputStream();
if (!file.exists()) {
Struts2Utils.renderText("文件不存在");
return null;
}
if (file.length() > MAX_FILE_SIZE && download == null) {
Struts2Utils.renderText("文件过大,请带上下载参数download=true保存到本地");
return null;
}
if (download != null) {
ServletUtils.setFileDownloadHeader(response, file.getName());
}
FileUtils.copyFile(file, output);
output.flush();
} catch (Exception e) {
logger.warn(e.getMessage() + "下载日志文件时非正常中断");
}
return null;
}
|
diff --git a/asm/test/conform/org/objectweb/asm/ClassWriterComputeFramesTest.java b/asm/test/conform/org/objectweb/asm/ClassWriterComputeFramesTest.java
index cba27b28..573aa1aa 100644
--- a/asm/test/conform/org/objectweb/asm/ClassWriterComputeFramesTest.java
+++ b/asm/test/conform/org/objectweb/asm/ClassWriterComputeFramesTest.java
@@ -1,265 +1,269 @@
/***
* ASM tests
* Copyright (c) 2000-2011 INRIA, France Telecom
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.objectweb.asm;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.lang.instrument.Instrumentation;
import java.security.ProtectionDomain;
import junit.framework.TestSuite;
import org.objectweb.asm.util.TraceClassVisitor;
/**
* ClassWriter tests.
*
* @author Eric Bruneton
*/
public class ClassWriterComputeFramesTest extends AbstractTest {
public static void premain(final String agentArgs,
final Instrumentation inst) {
inst.addTransformer(new ClassFileTransformer() {
public byte[] transform(final ClassLoader loader,
final String className, final Class<?> classBeingRedefined,
final ProtectionDomain domain, final byte[] classFileBuffer)
throws IllegalClassFormatException {
String n = className.replace('/', '.');
if (n.indexOf("junit") != -1 || n.startsWith("invalid.")) {
return null;
}
if (agentArgs.length() == 0 || n.indexOf(agentArgs) != -1) {
return transformClass(n, classFileBuffer);
} else {
return null;
}
}
});
}
static byte[] transformClass(final String n, final byte[] clazz) {
ClassReader cr = new ClassReader(clazz);
ClassWriter cw = new ComputeClassWriter(ClassWriter.COMPUTE_FRAMES);
cr.accept(new ClassVisitor(Opcodes.ASM4, cw) {
@Override
public void visit(final int version, final int access,
final String name, final String signature,
final String superName, final String[] interfaces) {
// Set V1_7 version to prevent fallback to old verifier.
super.visit((version & 0xFFFF) < Opcodes.V1_7 ? Opcodes.V1_7
: version, access, name, signature, superName,
interfaces);
}
}, ClassReader.SKIP_FRAMES);
return cw.toByteArray();
}
public static TestSuite suite() throws Exception {
TestSuite suite = new ClassWriterComputeFramesTest().getSuite();
suite.addTest(new VerifierTest());
return suite;
}
@Override
public void test() throws Exception {
try {
Class.forName(n, true, getClass().getClassLoader());
} catch (NoClassDefFoundError ncdfe) {
// ignored
} catch (UnsatisfiedLinkError ule) {
// ignored
} catch (ClassFormatError cfe) {
fail(cfe.getMessage());
} catch (VerifyError ve) {
String s = n.replace('.', '/') + ".class";
InputStream is = getClass().getClassLoader().getResourceAsStream(s);
ClassReader cr = new ClassReader(is);
byte[] b = transformClass("", cr.b);
StringWriter sw1 = new StringWriter();
StringWriter sw2 = new StringWriter();
sw2.write(ve.toString() + "\n");
ClassVisitor cv1 = new TraceClassVisitor(new PrintWriter(sw1));
ClassVisitor cv2 = new TraceClassVisitor(new PrintWriter(sw2));
cr.accept(cv1, 0);
new ClassReader(b).accept(cv2, 0);
String s1 = sw1.toString();
String s2 = sw2.toString();
assertEquals("different data", s1, s2);
}
}
}
/**
* A ClassWriter that computes the common super class of two classes without
* actually loading them with a ClassLoader.
*
* @author Eric Bruneton
*/
class ComputeClassWriter extends ClassWriter {
private ClassLoader l = getClass().getClassLoader();
public ComputeClassWriter(final int flags) {
super(flags);
}
@Override
protected String getCommonSuperClass(final String type1, final String type2) {
try {
ClassReader info1 = typeInfo(type1);
ClassReader info2 = typeInfo(type2);
if ((info1.getAccess() & Opcodes.ACC_INTERFACE) != 0) {
if (typeImplements(type2, info2, type1)) {
return type1;
- } else {
- return "java/lang/Object";
}
+ if ((info2.getAccess() & Opcodes.ACC_INTERFACE) != 0) {
+ if (typeImplements(type1, info1, type2)) {
+ return type2;
+ }
+ }
+ return "java/lang/Object";
}
if ((info2.getAccess() & Opcodes.ACC_INTERFACE) != 0) {
if (typeImplements(type1, info1, type2)) {
return type2;
} else {
return "java/lang/Object";
}
}
StringBuilder b1 = typeAncestors(type1, info1);
StringBuilder b2 = typeAncestors(type2, info2);
String result = "java/lang/Object";
int end1 = b1.length();
int end2 = b2.length();
while (true) {
int start1 = b1.lastIndexOf(";", end1 - 1);
int start2 = b2.lastIndexOf(";", end2 - 1);
if (start1 != -1 && start2 != -1
&& end1 - start1 == end2 - start2) {
String p1 = b1.substring(start1 + 1, end1);
String p2 = b2.substring(start2 + 1, end2);
if (p1.equals(p2)) {
result = p1;
end1 = start1;
end2 = start2;
} else {
return result;
}
} else {
return result;
}
}
} catch (IOException e) {
throw new RuntimeException(e.toString());
}
}
/**
* Returns the internal names of the ancestor classes of the given type.
*
* @param type
* the internal name of a class or interface.
* @param info
* the ClassReader corresponding to 'type'.
* @return a StringBuilder containing the ancestor classes of 'type',
* separated by ';'. The returned string has the following format:
* ";type1;type2 ... ;typeN", where type1 is 'type', and typeN is a
* direct subclass of Object. If 'type' is Object, the returned
* string is empty.
* @throws IOException
* if the bytecode of 'type' or of some of its ancestor class
* cannot be loaded.
*/
private StringBuilder typeAncestors(String type, ClassReader info)
throws IOException {
StringBuilder b = new StringBuilder();
while (!"java/lang/Object".equals(type)) {
b.append(';').append(type);
type = info.getSuperName();
info = typeInfo(type);
}
return b;
}
/**
* Returns true if the given type implements the given interface.
*
* @param type
* the internal name of a class or interface.
* @param info
* the ClassReader corresponding to 'type'.
* @param itf
* the internal name of a interface.
* @return true if 'type' implements directly or indirectly 'itf'
* @throws IOException
* if the bytecode of 'type' or of some of its ancestor class
* cannot be loaded.
*/
private boolean typeImplements(String type, ClassReader info, String itf)
throws IOException {
while (!"java/lang/Object".equals(type)) {
String[] itfs = info.getInterfaces();
for (int i = 0; i < itfs.length; ++i) {
if (itfs[i].equals(itf)) {
return true;
}
}
for (int i = 0; i < itfs.length; ++i) {
if (typeImplements(itfs[i], typeInfo(itfs[i]), itf)) {
return true;
}
}
type = info.getSuperName();
info = typeInfo(type);
}
return false;
}
/**
* Returns a ClassReader corresponding to the given class or interface.
*
* @param type
* the internal name of a class or interface.
* @return the ClassReader corresponding to 'type'.
* @throws IOException
* if the bytecode of 'type' cannot be loaded.
*/
private ClassReader typeInfo(final String type) throws IOException {
InputStream is = l.getResourceAsStream(type + ".class");
try {
return new ClassReader(is);
} finally {
is.close();
}
}
}
| false | true | protected String getCommonSuperClass(final String type1, final String type2) {
try {
ClassReader info1 = typeInfo(type1);
ClassReader info2 = typeInfo(type2);
if ((info1.getAccess() & Opcodes.ACC_INTERFACE) != 0) {
if (typeImplements(type2, info2, type1)) {
return type1;
} else {
return "java/lang/Object";
}
}
if ((info2.getAccess() & Opcodes.ACC_INTERFACE) != 0) {
if (typeImplements(type1, info1, type2)) {
return type2;
} else {
return "java/lang/Object";
}
}
StringBuilder b1 = typeAncestors(type1, info1);
StringBuilder b2 = typeAncestors(type2, info2);
String result = "java/lang/Object";
int end1 = b1.length();
int end2 = b2.length();
while (true) {
int start1 = b1.lastIndexOf(";", end1 - 1);
int start2 = b2.lastIndexOf(";", end2 - 1);
if (start1 != -1 && start2 != -1
&& end1 - start1 == end2 - start2) {
String p1 = b1.substring(start1 + 1, end1);
String p2 = b2.substring(start2 + 1, end2);
if (p1.equals(p2)) {
result = p1;
end1 = start1;
end2 = start2;
} else {
return result;
}
} else {
return result;
}
}
} catch (IOException e) {
throw new RuntimeException(e.toString());
}
}
| protected String getCommonSuperClass(final String type1, final String type2) {
try {
ClassReader info1 = typeInfo(type1);
ClassReader info2 = typeInfo(type2);
if ((info1.getAccess() & Opcodes.ACC_INTERFACE) != 0) {
if (typeImplements(type2, info2, type1)) {
return type1;
}
if ((info2.getAccess() & Opcodes.ACC_INTERFACE) != 0) {
if (typeImplements(type1, info1, type2)) {
return type2;
}
}
return "java/lang/Object";
}
if ((info2.getAccess() & Opcodes.ACC_INTERFACE) != 0) {
if (typeImplements(type1, info1, type2)) {
return type2;
} else {
return "java/lang/Object";
}
}
StringBuilder b1 = typeAncestors(type1, info1);
StringBuilder b2 = typeAncestors(type2, info2);
String result = "java/lang/Object";
int end1 = b1.length();
int end2 = b2.length();
while (true) {
int start1 = b1.lastIndexOf(";", end1 - 1);
int start2 = b2.lastIndexOf(";", end2 - 1);
if (start1 != -1 && start2 != -1
&& end1 - start1 == end2 - start2) {
String p1 = b1.substring(start1 + 1, end1);
String p2 = b2.substring(start2 + 1, end2);
if (p1.equals(p2)) {
result = p1;
end1 = start1;
end2 = start2;
} else {
return result;
}
} else {
return result;
}
}
} catch (IOException e) {
throw new RuntimeException(e.toString());
}
}
|
diff --git a/modules/cpr/src/main/java/org/atmosphere/container/JettyWebSocketUtil.java b/modules/cpr/src/main/java/org/atmosphere/container/JettyWebSocketUtil.java
index 51fdf9921..6a83630bf 100644
--- a/modules/cpr/src/main/java/org/atmosphere/container/JettyWebSocketUtil.java
+++ b/modules/cpr/src/main/java/org/atmosphere/container/JettyWebSocketUtil.java
@@ -1,107 +1,106 @@
/*
* Copyright 2012 Jeanfrancois Arcand
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.atmosphere.container;
import org.atmosphere.cpr.ApplicationConfig;
import org.atmosphere.cpr.AsynchronousProcessor;
import org.atmosphere.cpr.AtmosphereServlet;
import org.atmosphere.websocket.WebSocket;
import org.eclipse.jetty.websocket.WebSocketFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import static org.atmosphere.cpr.HeaderConfig.WEBSOCKET_UPGRADE;
public class JettyWebSocketUtil {
private static final Logger logger = LoggerFactory.getLogger(JettyWebSocketUtil.class);
public final static AtmosphereServlet.Action doService(AsynchronousProcessor cometSupport,
HttpServletRequest req,
HttpServletResponse res,
WebSocketFactory webSocketFactory) throws IOException, ServletException {
boolean webSocketEnabled = false;
if (req.getHeaders("Connection") != null && req.getHeaders("Connection").hasMoreElements()) {
String[] e = req.getHeaders("Connection").nextElement().split(",");
for (String upgrade : e) {
if (upgrade.trim().equalsIgnoreCase(WEBSOCKET_UPGRADE)) {
webSocketEnabled = true;
break;
}
}
}
Boolean b = (Boolean) req.getAttribute(WebSocket.WEBSOCKET_INITIATED);
if (b == null) b = Boolean.FALSE;
if (!webSocketEnabled) {
- logger.error("Invalid WebSocketRequest: No Connection header with browser {}.", req.getHeader("User-Agent"));
return null;
} else {
if (webSocketFactory != null && !b) {
req.setAttribute(WebSocket.WEBSOCKET_INITIATED, true);
webSocketFactory.acceptWebSocket(req, res);
return new AtmosphereServlet.Action();
}
AtmosphereServlet.Action action = cometSupport.suspended(req, res);
if (action.type == AtmosphereServlet.Action.TYPE.SUSPEND) {
logger.debug("Suspending response: {}", res);
} else if (action.type == AtmosphereServlet.Action.TYPE.RESUME) {
logger.debug("Resume response: {}", res);
req.setAttribute(WebSocket.WEBSOCKET_RESUME, true);
}
return action;
}
}
public final static WebSocketFactory getFactory(final AtmosphereServlet.AtmosphereConfig config) {
WebSocketFactory webSocketFactory = new WebSocketFactory(new WebSocketFactory.Acceptor() {
public boolean checkOrigin(HttpServletRequest request, String origin) {
// Allow all origins
logger.debug("WebSocket-checkOrigin request {} with origin {}", request.getRequestURI(), origin);
return true;
}
public org.eclipse.jetty.websocket.WebSocket doWebSocketConnect(HttpServletRequest request, String protocol) {
logger.debug("WebSocket-connect request {} with protocol {}", request.getRequestURI(), protocol);
return new JettyWebSocketHandler(request, config.getServlet(), config.getServlet().getWebSocketProtocol());
}
});
int bufferSize = 8192;
if (config.getInitParameter(ApplicationConfig.WEBSOCKET_BUFFER_SIZE) != null) {
bufferSize = Integer.valueOf(config.getInitParameter(ApplicationConfig.WEBSOCKET_BUFFER_SIZE));
}
logger.info("WebSocket Buffer side {}", bufferSize);
webSocketFactory.setBufferSize(bufferSize);
int timeOut = 5 * 60000;
if (config.getInitParameter(ApplicationConfig.WEBSOCKET_IDLETIME) != null) {
timeOut = Integer.valueOf(config.getInitParameter(ApplicationConfig.WEBSOCKET_IDLETIME));
}
logger.info("WebSocket idle timeout {}", timeOut);
webSocketFactory.setMaxIdleTime(timeOut);
return webSocketFactory;
}
}
| true | true | public final static AtmosphereServlet.Action doService(AsynchronousProcessor cometSupport,
HttpServletRequest req,
HttpServletResponse res,
WebSocketFactory webSocketFactory) throws IOException, ServletException {
boolean webSocketEnabled = false;
if (req.getHeaders("Connection") != null && req.getHeaders("Connection").hasMoreElements()) {
String[] e = req.getHeaders("Connection").nextElement().split(",");
for (String upgrade : e) {
if (upgrade.trim().equalsIgnoreCase(WEBSOCKET_UPGRADE)) {
webSocketEnabled = true;
break;
}
}
}
Boolean b = (Boolean) req.getAttribute(WebSocket.WEBSOCKET_INITIATED);
if (b == null) b = Boolean.FALSE;
if (!webSocketEnabled) {
logger.error("Invalid WebSocketRequest: No Connection header with browser {}.", req.getHeader("User-Agent"));
return null;
} else {
if (webSocketFactory != null && !b) {
req.setAttribute(WebSocket.WEBSOCKET_INITIATED, true);
webSocketFactory.acceptWebSocket(req, res);
return new AtmosphereServlet.Action();
}
AtmosphereServlet.Action action = cometSupport.suspended(req, res);
if (action.type == AtmosphereServlet.Action.TYPE.SUSPEND) {
logger.debug("Suspending response: {}", res);
} else if (action.type == AtmosphereServlet.Action.TYPE.RESUME) {
logger.debug("Resume response: {}", res);
req.setAttribute(WebSocket.WEBSOCKET_RESUME, true);
}
return action;
}
}
| public final static AtmosphereServlet.Action doService(AsynchronousProcessor cometSupport,
HttpServletRequest req,
HttpServletResponse res,
WebSocketFactory webSocketFactory) throws IOException, ServletException {
boolean webSocketEnabled = false;
if (req.getHeaders("Connection") != null && req.getHeaders("Connection").hasMoreElements()) {
String[] e = req.getHeaders("Connection").nextElement().split(",");
for (String upgrade : e) {
if (upgrade.trim().equalsIgnoreCase(WEBSOCKET_UPGRADE)) {
webSocketEnabled = true;
break;
}
}
}
Boolean b = (Boolean) req.getAttribute(WebSocket.WEBSOCKET_INITIATED);
if (b == null) b = Boolean.FALSE;
if (!webSocketEnabled) {
return null;
} else {
if (webSocketFactory != null && !b) {
req.setAttribute(WebSocket.WEBSOCKET_INITIATED, true);
webSocketFactory.acceptWebSocket(req, res);
return new AtmosphereServlet.Action();
}
AtmosphereServlet.Action action = cometSupport.suspended(req, res);
if (action.type == AtmosphereServlet.Action.TYPE.SUSPEND) {
logger.debug("Suspending response: {}", res);
} else if (action.type == AtmosphereServlet.Action.TYPE.RESUME) {
logger.debug("Resume response: {}", res);
req.setAttribute(WebSocket.WEBSOCKET_RESUME, true);
}
return action;
}
}
|
diff --git a/src/mediafire/cz/vity/freerapid/plugins/services/mediafire/MediafireRunner.java b/src/mediafire/cz/vity/freerapid/plugins/services/mediafire/MediafireRunner.java
index 6341921d..35898b28 100644
--- a/src/mediafire/cz/vity/freerapid/plugins/services/mediafire/MediafireRunner.java
+++ b/src/mediafire/cz/vity/freerapid/plugins/services/mediafire/MediafireRunner.java
@@ -1,268 +1,272 @@
package cz.vity.freerapid.plugins.services.mediafire;
import cz.vity.freerapid.plugins.exceptions.*;
import cz.vity.freerapid.plugins.services.mediafire.js.JsDocument;
import cz.vity.freerapid.plugins.services.mediafire.js.JsElement;
import cz.vity.freerapid.plugins.webclient.AbstractRunner;
import cz.vity.freerapid.plugins.webclient.FileState;
import cz.vity.freerapid.plugins.webclient.utils.PlugUtils;
import cz.vity.freerapid.utilities.LogUtils;
import org.apache.commons.httpclient.HttpMethod;
import sun.org.mozilla.javascript.internal.Context;
import sun.org.mozilla.javascript.internal.Scriptable;
import sun.org.mozilla.javascript.internal.ScriptableObject;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Logger;
import java.util.regex.Matcher;
/**
* @author Ladislav Vitasek, Ludek Zika, ntoskrnl
*/
public class MediafireRunner extends AbstractRunner {
public final static Logger logger = Logger.getLogger(MediafireRunner.class.getName());
private final static String SCRIPT_HEADER =
"function alert(s) { Packages.cz.vity.freerapid.plugins.services.mediafire.MediafireRunner.logger.warning('JS: ' + s); }\n" +
"function aa(s) { alert(s); }\n" +
"var document = new JsDocument();\n" +
"function dummyparent() {\n" +
" this.document = document;\n" +
"}\n" +
"var parent = new dummyparent();\n";
@Override
public void runCheck() throws Exception {
super.runCheck();
final HttpMethod method = getGetMethod(fileURL);
if (makeRedirectedRequest(method)) {
checkProblems();
checkNameAndSize();
} else {
checkProblems();
throw new ServiceConnectionProblemException();
}
}
@Override
public void run() throws Exception {
super.run();
HttpMethod method = getGetMethod(fileURL);
if (makeRedirectedRequest(method)) {
checkProblems();
if (isList()) {
runList();
return;
}
checkNameAndSize();
while (getContentAsString().contains("dh('');")) { //handle password
HttpMethod postPwd = getMethodBuilder()
.setReferer(fileURL)
.setBaseURL("http://www.mediafire.com/")
.setActionFromFormByName("form_password", true)
.setAndEncodeParameter("downloadp", getPassword())
.toPostMethod();
if (!makeRedirectedRequest(postPwd)) {
throw new ServiceConnectionProblemException("Some issue while posting password");
}
}
method = findDownloadUrl();
setFileStreamContentTypes("text/plain");
if (!tryDownloadAndSaveFile(method)) {
checkProblems();
throw new ServiceConnectionProblemException("Error starting download");
}
} else {
checkProblems();
throw new ServiceConnectionProblemException();
}
}
private HttpMethod findDownloadUrl() throws Exception {
final List<String> elementsOnPage = findElementsOnPage();
final Context context = Context.enter();
try {
final Scriptable scope = prepareContext(context);
final HttpMethod method = findFirstUrl(context, scope);
if (!makeRedirectedRequest(method)) {
checkProblems();
throw new ServiceConnectionProblemException();
}
return findSecondUrl(elementsOnPage, context, scope);
} finally {
Context.exit();
}
}
private Scriptable prepareContext(final Context context) throws ErrorDuringDownloadingException {
final Scriptable scope = context.initStandardObjects();
try {
ScriptableObject.defineClass(scope, JsDocument.class);
ScriptableObject.defineClass(scope, JsElement.class);
context.evaluateString(scope, SCRIPT_HEADER, "<script>", 1, null);
} catch (Exception e) {
throw new PluginImplementationException("Script header execution failed", e);
}
return scope;
}
private List<String> findElementsOnPage() throws ErrorDuringDownloadingException {
final List<String> list = new LinkedList<String>();
final Matcher matcher = getMatcherAgainstContent("<div[^<>]*?id=\"([^\"]+?)\"[^<>]*?>Preparing download");
while (matcher.find()) {
list.add(matcher.group(1));
}
if (list.isEmpty()) {
throw new PluginImplementationException("Element IDs not found");
}
return list;
}
private HttpMethod findFirstUrl(final Context context, final Scriptable scope) throws ErrorDuringDownloadingException {
Matcher matcher = getMatcherAgainstContent("(?s)value=\"download\">\\s*?<script[^<>]*?>(?:<!\\-\\-)?(.+?)</script>");
if (!matcher.find()) {
throw new PluginImplementationException("First JavaScript not found");
}
final String rawScript = matcher.group(1);
//logger.info(rawScript);
- final int lastFunctionIndex = rawScript.lastIndexOf("function ");
+ matcher = PlugUtils.matcher("function\\s*?[a-z\\d]+?\\(", rawScript);
+ int lastFunctionIndex = -1;
+ while (matcher.find()) {
+ lastFunctionIndex = matcher.start();
+ }
if (lastFunctionIndex < 0) {
logger.warning(rawScript);
throw new PluginImplementationException("Last function in first JavaScript not found");
}
// gysl8luzk='';oq1w66x=unescape(......; var cb=Math.random();
//(.....................................) <-- this part is what we want
matcher = PlugUtils.matcher("((?:eval\\(\")?[a-z\\d]+?\\s*?=\\s*?\\\\?'\\\\?';\\s*?[a-z\\d]+?\\s*?=\\s*?unescape\\(.+?;)[^;]+?Math\\.random\\(\\)", rawScript);
if (!matcher.find(lastFunctionIndex)) {
logger.warning(rawScript);
throw new PluginImplementationException("Error parsing last function in first JavaScript");
}
final String partOfFunction = matcher.group(1);
//logger.info(partOfFunction);
final String preparedScript = rawScript.replace("setTimeout(", "return '/dynamic/download.php?qk=' + qk + '&pk1=' + pk1 + '&r=' + pKr; setTimeout(");
final String script = new StringBuilder(preparedScript.length() + 1 + partOfFunction.length())
.append(preparedScript)
.append('\n')
.append(partOfFunction)
.toString();
//logger.info(script);
final String result;
try {
scope.put("pk", scope, 0);
result = Context.toString(context.evaluateString(scope, script, "<script>", 1, null));
} catch (Exception e) {
logger.warning(script);
throw new PluginImplementationException("Script 1 execution failed", e);
}
logger.info(result);
return getMethodBuilder().setReferer(fileURL).setAction(result).toGetMethod();
}
private HttpMethod findSecondUrl(final List<String> elementsOnPage, final Context context, final Scriptable scope) throws ErrorDuringDownloadingException {
Matcher matcher = getMatcherAgainstContent("(?s)<script[^<>]*?>(?:<!\\-\\-)?(.+?)</script>");
if (!matcher.find()) {
throw new PluginImplementationException("Second JavaScript not found");
}
final String rawScript = matcher.group(1);
//logger.info(rawScript);
matcher = getMatcherAgainstContent("<body[^<>]*?onload=[\"'](.+?)[\"']");
if (!matcher.find()) {
throw new PluginImplementationException("Error parsing second page");
}
final String functionToCall = matcher.group(1);
//logger.info(functionToCall);
final String script = new StringBuilder(rawScript.length() + 1 + functionToCall.length())
.append(rawScript)
.append('\n')
.append(functionToCall)
.toString();
//logger.info(script);
final JsDocument document;
try {
context.evaluateString(scope, script, "<script>", 1, null);
document = (JsDocument) scope.get("document", scope);
} catch (Exception e) {
logger.warning(script);
throw new PluginImplementationException("Script 2 execution failed", e);
}
for (final String id : elementsOnPage) {
final JsElement element = document.getElements().get(id);
if (element != null && element.isVisible()) {
return findThirdUrl(element.getText());
}
}
throw new PluginImplementationException("Download link element not found");
}
private HttpMethod findThirdUrl(final String text) throws ErrorDuringDownloadingException {
logger.info(text);
return getMethodBuilder(text).setReferer(fileURL).setActionFromAHrefWhereATagContains("").toGetMethod();
}
private void checkNameAndSize() throws Exception {
if (isList()) return;
final String content = getContentAsString();
PlugUtils.checkFileSize(httpFile, content, "sharedtabsfileinfo1-fs\" value=\"", "\">");
PlugUtils.checkName(httpFile, content, "sharedtabsfileinfo1-fn\" value=\"", "\">");
httpFile.setFileState(FileState.CHECKED_AND_EXISTING);
}
private void checkProblems() throws ErrorDuringDownloadingException {
final String content = getContentAsString();
if (content.contains("The key you provided for file download was invalid")
|| content.contains("How can MediaFire help you?")) {
throw new URLNotAvailableAnymoreException("File not found");
}
}
private void runList() throws Exception {
final Matcher matcher = getMatcherAgainstContent("src=\"(/js/myfiles.php[^\"]+?)\"");
if (!matcher.find()) throw new PluginImplementationException("URL to list not found");
final HttpMethod listMethod = getMethodBuilder().setReferer(fileURL).setAction(matcher.group(1)).toGetMethod();
if (makeRedirectedRequest(listMethod)) {
parseList();
} else {
checkProblems();
throw new ServiceConnectionProblemException();
}
}
private void parseList() {
final Matcher matcher = getMatcherAgainstContent("oe\\[[0-9]+\\]=Array\\('([^']+?)'");
final List<URI> uriList = new LinkedList<URI>();
while (matcher.find()) {
final String link = "http://www.mediafire.com/download.php?" + matcher.group(1);
try {
uriList.add(new URI(link));
} catch (URISyntaxException e) {
LogUtils.processException(logger, e);
}
}
getPluginService().getPluginContext().getQueueSupport().addLinksToQueue(httpFile, uriList);
}
private boolean isList() {
return (fileURL.contains("?sharekey="));
}
private String getPassword() throws Exception {
final String password = getDialogSupport().askForPassword("MediaFire");
if (password == null) {
throw new NotRecoverableDownloadException("This file is secured with a password");
} else {
return password;
}
}
}
| true | true | private HttpMethod findFirstUrl(final Context context, final Scriptable scope) throws ErrorDuringDownloadingException {
Matcher matcher = getMatcherAgainstContent("(?s)value=\"download\">\\s*?<script[^<>]*?>(?:<!\\-\\-)?(.+?)</script>");
if (!matcher.find()) {
throw new PluginImplementationException("First JavaScript not found");
}
final String rawScript = matcher.group(1);
//logger.info(rawScript);
final int lastFunctionIndex = rawScript.lastIndexOf("function ");
if (lastFunctionIndex < 0) {
logger.warning(rawScript);
throw new PluginImplementationException("Last function in first JavaScript not found");
}
// gysl8luzk='';oq1w66x=unescape(......; var cb=Math.random();
//(.....................................) <-- this part is what we want
matcher = PlugUtils.matcher("((?:eval\\(\")?[a-z\\d]+?\\s*?=\\s*?\\\\?'\\\\?';\\s*?[a-z\\d]+?\\s*?=\\s*?unescape\\(.+?;)[^;]+?Math\\.random\\(\\)", rawScript);
if (!matcher.find(lastFunctionIndex)) {
logger.warning(rawScript);
throw new PluginImplementationException("Error parsing last function in first JavaScript");
}
final String partOfFunction = matcher.group(1);
//logger.info(partOfFunction);
final String preparedScript = rawScript.replace("setTimeout(", "return '/dynamic/download.php?qk=' + qk + '&pk1=' + pk1 + '&r=' + pKr; setTimeout(");
final String script = new StringBuilder(preparedScript.length() + 1 + partOfFunction.length())
.append(preparedScript)
.append('\n')
.append(partOfFunction)
.toString();
//logger.info(script);
final String result;
try {
scope.put("pk", scope, 0);
result = Context.toString(context.evaluateString(scope, script, "<script>", 1, null));
} catch (Exception e) {
logger.warning(script);
throw new PluginImplementationException("Script 1 execution failed", e);
}
logger.info(result);
return getMethodBuilder().setReferer(fileURL).setAction(result).toGetMethod();
}
| private HttpMethod findFirstUrl(final Context context, final Scriptable scope) throws ErrorDuringDownloadingException {
Matcher matcher = getMatcherAgainstContent("(?s)value=\"download\">\\s*?<script[^<>]*?>(?:<!\\-\\-)?(.+?)</script>");
if (!matcher.find()) {
throw new PluginImplementationException("First JavaScript not found");
}
final String rawScript = matcher.group(1);
//logger.info(rawScript);
matcher = PlugUtils.matcher("function\\s*?[a-z\\d]+?\\(", rawScript);
int lastFunctionIndex = -1;
while (matcher.find()) {
lastFunctionIndex = matcher.start();
}
if (lastFunctionIndex < 0) {
logger.warning(rawScript);
throw new PluginImplementationException("Last function in first JavaScript not found");
}
// gysl8luzk='';oq1w66x=unescape(......; var cb=Math.random();
//(.....................................) <-- this part is what we want
matcher = PlugUtils.matcher("((?:eval\\(\")?[a-z\\d]+?\\s*?=\\s*?\\\\?'\\\\?';\\s*?[a-z\\d]+?\\s*?=\\s*?unescape\\(.+?;)[^;]+?Math\\.random\\(\\)", rawScript);
if (!matcher.find(lastFunctionIndex)) {
logger.warning(rawScript);
throw new PluginImplementationException("Error parsing last function in first JavaScript");
}
final String partOfFunction = matcher.group(1);
//logger.info(partOfFunction);
final String preparedScript = rawScript.replace("setTimeout(", "return '/dynamic/download.php?qk=' + qk + '&pk1=' + pk1 + '&r=' + pKr; setTimeout(");
final String script = new StringBuilder(preparedScript.length() + 1 + partOfFunction.length())
.append(preparedScript)
.append('\n')
.append(partOfFunction)
.toString();
//logger.info(script);
final String result;
try {
scope.put("pk", scope, 0);
result = Context.toString(context.evaluateString(scope, script, "<script>", 1, null));
} catch (Exception e) {
logger.warning(script);
throw new PluginImplementationException("Script 1 execution failed", e);
}
logger.info(result);
return getMethodBuilder().setReferer(fileURL).setAction(result).toGetMethod();
}
|
diff --git a/org.eclipse.help.webapp/src/org/eclipse/help/internal/webapp/servlet/FramesetFilter.java b/org.eclipse.help.webapp/src/org/eclipse/help/internal/webapp/servlet/FramesetFilter.java
index 831ab3cf7..b55ea9e1a 100644
--- a/org.eclipse.help.webapp/src/org/eclipse/help/internal/webapp/servlet/FramesetFilter.java
+++ b/org.eclipse.help.webapp/src/org/eclipse/help/internal/webapp/servlet/FramesetFilter.java
@@ -1,67 +1,67 @@
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.help.internal.webapp.servlet;
import java.io.*;
import javax.servlet.http.*;
import org.eclipse.help.internal.webapp.data.*;
/**
* This class inserts a script for showing the page inside the appropriate
* frameset when bookmarked.
*/
public class FramesetFilter implements IFilter {
private static final String scriptPart1 = "<script>if( self == top ){ window.location.replace( \""; //$NON-NLS-1$
private static final String scriptPart3 = "\");}</script>"; //$NON-NLS-1$
/*
* @see IFilter#filter(HttpServletRequest, OutputStream)
*/
public OutputStream filter(HttpServletRequest req, OutputStream out) {
String uri = req.getRequestURI();
if (uri == null || !uri.endsWith("html") && !uri.endsWith("htm")) { //$NON-NLS-1$ //$NON-NLS-2$
return out;
}
if ("/nftopic".equals(req.getServletPath()) || //$NON-NLS-1$
"/ntopic".equals(req.getServletPath()) || //$NON-NLS-1$
"/rtopic".equals(req.getServletPath()) || //$NON-NLS-1$
UrlUtil.isBot(req)) {
return out;
}
String noframes = req.getParameter("noframes"); //$NON-NLS-1$
if ("true".equals(noframes)) { //$NON-NLS-1$
return out;
}
String path = req.getPathInfo();
if (path == null) {
return out;
}
StringBuffer script = new StringBuffer(scriptPart1);
for (int i; 0 <= (i = path.indexOf('/')); path = path.substring(i + 1)) {
script.append("../"); //$NON-NLS-1$
}
- script.append("?topic="); //$NON-NLS-1$
+ script.append("index.jsp?topic="); //$NON-NLS-1$
script.append(req.getPathInfo());
script.append(scriptPart3);
try {
return new FilterHTMLHeadOutputStream(out, script.toString()
.getBytes("ASCII")); //$NON-NLS-1$
} catch (UnsupportedEncodingException uee) {
return out;
}
}
}
| true | true | public OutputStream filter(HttpServletRequest req, OutputStream out) {
String uri = req.getRequestURI();
if (uri == null || !uri.endsWith("html") && !uri.endsWith("htm")) { //$NON-NLS-1$ //$NON-NLS-2$
return out;
}
if ("/nftopic".equals(req.getServletPath()) || //$NON-NLS-1$
"/ntopic".equals(req.getServletPath()) || //$NON-NLS-1$
"/rtopic".equals(req.getServletPath()) || //$NON-NLS-1$
UrlUtil.isBot(req)) {
return out;
}
String noframes = req.getParameter("noframes"); //$NON-NLS-1$
if ("true".equals(noframes)) { //$NON-NLS-1$
return out;
}
String path = req.getPathInfo();
if (path == null) {
return out;
}
StringBuffer script = new StringBuffer(scriptPart1);
for (int i; 0 <= (i = path.indexOf('/')); path = path.substring(i + 1)) {
script.append("../"); //$NON-NLS-1$
}
script.append("?topic="); //$NON-NLS-1$
script.append(req.getPathInfo());
script.append(scriptPart3);
try {
return new FilterHTMLHeadOutputStream(out, script.toString()
.getBytes("ASCII")); //$NON-NLS-1$
} catch (UnsupportedEncodingException uee) {
return out;
}
}
| public OutputStream filter(HttpServletRequest req, OutputStream out) {
String uri = req.getRequestURI();
if (uri == null || !uri.endsWith("html") && !uri.endsWith("htm")) { //$NON-NLS-1$ //$NON-NLS-2$
return out;
}
if ("/nftopic".equals(req.getServletPath()) || //$NON-NLS-1$
"/ntopic".equals(req.getServletPath()) || //$NON-NLS-1$
"/rtopic".equals(req.getServletPath()) || //$NON-NLS-1$
UrlUtil.isBot(req)) {
return out;
}
String noframes = req.getParameter("noframes"); //$NON-NLS-1$
if ("true".equals(noframes)) { //$NON-NLS-1$
return out;
}
String path = req.getPathInfo();
if (path == null) {
return out;
}
StringBuffer script = new StringBuffer(scriptPart1);
for (int i; 0 <= (i = path.indexOf('/')); path = path.substring(i + 1)) {
script.append("../"); //$NON-NLS-1$
}
script.append("index.jsp?topic="); //$NON-NLS-1$
script.append(req.getPathInfo());
script.append(scriptPart3);
try {
return new FilterHTMLHeadOutputStream(out, script.toString()
.getBytes("ASCII")); //$NON-NLS-1$
} catch (UnsupportedEncodingException uee) {
return out;
}
}
|
diff --git a/src/server/Server.java b/src/server/Server.java
index 15902b8..f146e47 100644
--- a/src/server/Server.java
+++ b/src/server/Server.java
@@ -1,263 +1,263 @@
package server;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.sql.Time;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import data.Family;
import data.MemberUpdate;
import data.Rating;
import data.RatingUpdate;
import data.Update;
import data.User;
public class Server {
private final static int PORT = 4444;
private ServerSocket serverSocket;
private HashMap<String, User> userID;
private HashMap<String, Family> familyID;
private HashMap<String, Double> publicRatings;
private HashMap<String, Integer> publicCount;
/**
* Make a Server that listens for connections on port.
*
* @param port
* port number, requires 0 <= port <= 65535.
* @throws IOException
*/
public Server(int port) throws IOException {
serverSocket = new ServerSocket(port);
userID = new HashMap<String, User>();
familyID = new HashMap<String, Family>();
publicRatings = new HashMap<String, Double>();
publicCount = new HashMap<String, Integer>();
}
/**
* Run the server, listening for client connections and handling them. Never
* returns unless an exception is thrown.
*
* @throws IOException
* if the main server socket is broken (IOExceptions from
* individual clients do *not* terminate serve()).
*/
public void serve() throws IOException {
System.out.println("Listening for connectionssssss..");
while (true) {
// block until a client connects
Socket socket = serverSocket.accept();
// handle the client
(new ClientThread(socket)).start();
}
}
/**
* Handle a single client connection. Returns when client disconnects.
*
* @param socket where client is connected
* @throws IOException if connection has an error or terminates unexpectedly
*/
private void handleConnection(Socket socket) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
try {
for (String line = in.readLine(); line != null; line = in.readLine()) {
System.out.println(line);
String output = handleRequest(line);
if (output != null) {
System.out.println("SENT:"+output);
out.println(output);
}
}
} catch (SocketException e) {
System.out.println("Client disconnected");
} catch (Exception e) {
e.printStackTrace();
}
finally {
out.close();
in.close();
}
}
/**
* handler for client input
*
* @param input
* @return
*/
private String handleRequest(String input) {
/*
* Input: "GET_UPDATE userID timestamp" -> return new updates, if any
*
* Input: "NEWUSER" -> return a unique 8 digit ID
*
* Input: "GET_PUBLIC upc" -> might return null
*
* Input: "SEND_LOG " -> return nothing.
*
* Update String Representation:
*
* MemberUpdate: "MEMBER_UPDATE familyID userID boolean timestamp" -> true means add to family, false means remove
* RatingUpdate: "RATING_UPDATE upc userID rating timestamp" where rating is an enum instance
*/
String id = ".+@.+";
String upc = "([0-9]+)";
String getUpdate = "(GET_UPDATE " + id + " [0-9]+)";
String memberUpdate = "(MEMBER_UPDATE " + id + " " + id + " (true|false)) [0-9]+";
String ratingUpdate = "(RATING_UPDATE " + upc + " " + id + " (GOOD|BAD|NEUTRAL) [0-9]+)";
String getPublic = "GET_PUBLIC " + upc;
String sendLog = "SEND_LOG " + id + " .+";
String[] args = input.split(" ");
if (input.matches("NEWUSER .+@.+")) {
String newID = args[1];
if (!userID.containsKey(newID)) {
userID.put(newID, new User(newID));
}
return newID;
} else if (input.equals("NEWFAMILY "+id)) {
String newID = args[1];
familyID.put(newID, new Family(newID));
return newID;
}
else if (input.matches(getUpdate)) {
String output = "";
- int ID = Integer.parseInt(args[1]);
+ String ID = args[1];
long timeStamp = Long.parseLong(args[2]);
if (userID.containsKey(ID)) {
User user = userID.get(ID);
System.out.println(ID +" trying to get updates");
ArrayList<Update> newUpdates = user.getFutureUpdates(new Time(timeStamp));
for (Update u : newUpdates){
System.out.println("update: " + u);
output += u.toString() + "\n";
}
}
return output;
}
else if (input.matches(memberUpdate)) {
- User user = userID.get(Integer.parseInt(args[2]));
+ User user = userID.get(args[2]);
long timeStamp = Long.parseLong(args[4]);
- Family family = familyID.get(Integer.parseInt(args[1]));
+ Family family = familyID.get(args[1]);
boolean add = Boolean.parseBoolean(args[3]);
user.receiveUpdate(new MemberUpdate(family, user, add, new Date(
timeStamp)));
}
else if (input.matches(ratingUpdate)) {
- User user = userID.get(Integer.parseInt(args[2]));
+ User user = userID.get(args[2]);
Rating rating = Rating.valueOf(args[3]);
String code = args[1];
long timeStamp = Long.parseLong(args[4]);
user.receiveUpdate(new RatingUpdate(code, rating, new Date(
timeStamp), user));
Double original = (double) 0;
int count = 0;
if (publicRatings.containsKey(code)) {
count = publicCount.get(code);
original = publicRatings.get(code) * count;
}
count += 1;
original += rating.ordinal() - 2;
original /= count;
publicCount.put(code, count);
publicRatings.put(code, original);
} else if (input.matches(getPublic)) {
String code = args[1];
if (publicRatings.containsKey(code))
return publicRatings.get(code).toString() + "\n";
return "UNRATED\n";
} else if (input.matches(sendLog)){
String filename = "";
int count = 0;
int logStart = 0;
for(int i = 0; i < input.length(); i++){
if(input.charAt(i) == ' ')
count++;
logStart++;
if(count == 1)
filename += input.charAt(i);
else if(count == 2)
break;
}
String log = input.substring(logStart);
File logFile = new File(filename);
if (!logFile.exists()) {
try {
logFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
// BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile,
true));
buf.append(log);
buf.newLine();
buf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return "\n";
}
public static void main(String[] args) {
try {
Server server = new Server(PORT);
server.serve();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Thread class that takes a Socket and handles the client connection for
* that socket
*/
public class ClientThread extends Thread {
private final Socket socket;
public ClientThread(Socket socket) {
this.socket = socket;
}
public void run() {
try {
handleConnection(socket);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
| false | true | private String handleRequest(String input) {
/*
* Input: "GET_UPDATE userID timestamp" -> return new updates, if any
*
* Input: "NEWUSER" -> return a unique 8 digit ID
*
* Input: "GET_PUBLIC upc" -> might return null
*
* Input: "SEND_LOG " -> return nothing.
*
* Update String Representation:
*
* MemberUpdate: "MEMBER_UPDATE familyID userID boolean timestamp" -> true means add to family, false means remove
* RatingUpdate: "RATING_UPDATE upc userID rating timestamp" where rating is an enum instance
*/
String id = ".+@.+";
String upc = "([0-9]+)";
String getUpdate = "(GET_UPDATE " + id + " [0-9]+)";
String memberUpdate = "(MEMBER_UPDATE " + id + " " + id + " (true|false)) [0-9]+";
String ratingUpdate = "(RATING_UPDATE " + upc + " " + id + " (GOOD|BAD|NEUTRAL) [0-9]+)";
String getPublic = "GET_PUBLIC " + upc;
String sendLog = "SEND_LOG " + id + " .+";
String[] args = input.split(" ");
if (input.matches("NEWUSER .+@.+")) {
String newID = args[1];
if (!userID.containsKey(newID)) {
userID.put(newID, new User(newID));
}
return newID;
} else if (input.equals("NEWFAMILY "+id)) {
String newID = args[1];
familyID.put(newID, new Family(newID));
return newID;
}
else if (input.matches(getUpdate)) {
String output = "";
int ID = Integer.parseInt(args[1]);
long timeStamp = Long.parseLong(args[2]);
if (userID.containsKey(ID)) {
User user = userID.get(ID);
System.out.println(ID +" trying to get updates");
ArrayList<Update> newUpdates = user.getFutureUpdates(new Time(timeStamp));
for (Update u : newUpdates){
System.out.println("update: " + u);
output += u.toString() + "\n";
}
}
return output;
}
else if (input.matches(memberUpdate)) {
User user = userID.get(Integer.parseInt(args[2]));
long timeStamp = Long.parseLong(args[4]);
Family family = familyID.get(Integer.parseInt(args[1]));
boolean add = Boolean.parseBoolean(args[3]);
user.receiveUpdate(new MemberUpdate(family, user, add, new Date(
timeStamp)));
}
else if (input.matches(ratingUpdate)) {
User user = userID.get(Integer.parseInt(args[2]));
Rating rating = Rating.valueOf(args[3]);
String code = args[1];
long timeStamp = Long.parseLong(args[4]);
user.receiveUpdate(new RatingUpdate(code, rating, new Date(
timeStamp), user));
Double original = (double) 0;
int count = 0;
if (publicRatings.containsKey(code)) {
count = publicCount.get(code);
original = publicRatings.get(code) * count;
}
count += 1;
original += rating.ordinal() - 2;
original /= count;
publicCount.put(code, count);
publicRatings.put(code, original);
} else if (input.matches(getPublic)) {
String code = args[1];
if (publicRatings.containsKey(code))
return publicRatings.get(code).toString() + "\n";
return "UNRATED\n";
} else if (input.matches(sendLog)){
String filename = "";
int count = 0;
int logStart = 0;
for(int i = 0; i < input.length(); i++){
if(input.charAt(i) == ' ')
count++;
logStart++;
if(count == 1)
filename += input.charAt(i);
else if(count == 2)
break;
}
String log = input.substring(logStart);
File logFile = new File(filename);
if (!logFile.exists()) {
try {
logFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
// BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile,
true));
buf.append(log);
buf.newLine();
buf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return "\n";
}
| private String handleRequest(String input) {
/*
* Input: "GET_UPDATE userID timestamp" -> return new updates, if any
*
* Input: "NEWUSER" -> return a unique 8 digit ID
*
* Input: "GET_PUBLIC upc" -> might return null
*
* Input: "SEND_LOG " -> return nothing.
*
* Update String Representation:
*
* MemberUpdate: "MEMBER_UPDATE familyID userID boolean timestamp" -> true means add to family, false means remove
* RatingUpdate: "RATING_UPDATE upc userID rating timestamp" where rating is an enum instance
*/
String id = ".+@.+";
String upc = "([0-9]+)";
String getUpdate = "(GET_UPDATE " + id + " [0-9]+)";
String memberUpdate = "(MEMBER_UPDATE " + id + " " + id + " (true|false)) [0-9]+";
String ratingUpdate = "(RATING_UPDATE " + upc + " " + id + " (GOOD|BAD|NEUTRAL) [0-9]+)";
String getPublic = "GET_PUBLIC " + upc;
String sendLog = "SEND_LOG " + id + " .+";
String[] args = input.split(" ");
if (input.matches("NEWUSER .+@.+")) {
String newID = args[1];
if (!userID.containsKey(newID)) {
userID.put(newID, new User(newID));
}
return newID;
} else if (input.equals("NEWFAMILY "+id)) {
String newID = args[1];
familyID.put(newID, new Family(newID));
return newID;
}
else if (input.matches(getUpdate)) {
String output = "";
String ID = args[1];
long timeStamp = Long.parseLong(args[2]);
if (userID.containsKey(ID)) {
User user = userID.get(ID);
System.out.println(ID +" trying to get updates");
ArrayList<Update> newUpdates = user.getFutureUpdates(new Time(timeStamp));
for (Update u : newUpdates){
System.out.println("update: " + u);
output += u.toString() + "\n";
}
}
return output;
}
else if (input.matches(memberUpdate)) {
User user = userID.get(args[2]);
long timeStamp = Long.parseLong(args[4]);
Family family = familyID.get(args[1]);
boolean add = Boolean.parseBoolean(args[3]);
user.receiveUpdate(new MemberUpdate(family, user, add, new Date(
timeStamp)));
}
else if (input.matches(ratingUpdate)) {
User user = userID.get(args[2]);
Rating rating = Rating.valueOf(args[3]);
String code = args[1];
long timeStamp = Long.parseLong(args[4]);
user.receiveUpdate(new RatingUpdate(code, rating, new Date(
timeStamp), user));
Double original = (double) 0;
int count = 0;
if (publicRatings.containsKey(code)) {
count = publicCount.get(code);
original = publicRatings.get(code) * count;
}
count += 1;
original += rating.ordinal() - 2;
original /= count;
publicCount.put(code, count);
publicRatings.put(code, original);
} else if (input.matches(getPublic)) {
String code = args[1];
if (publicRatings.containsKey(code))
return publicRatings.get(code).toString() + "\n";
return "UNRATED\n";
} else if (input.matches(sendLog)){
String filename = "";
int count = 0;
int logStart = 0;
for(int i = 0; i < input.length(); i++){
if(input.charAt(i) == ' ')
count++;
logStart++;
if(count == 1)
filename += input.charAt(i);
else if(count == 2)
break;
}
String log = input.substring(logStart);
File logFile = new File(filename);
if (!logFile.exists()) {
try {
logFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
// BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile,
true));
buf.append(log);
buf.newLine();
buf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return "\n";
}
|
diff --git a/src/main/java/com/develogical/QueryProcessor.java b/src/main/java/com/develogical/QueryProcessor.java
index e2936b9..164c0f1 100644
--- a/src/main/java/com/develogical/QueryProcessor.java
+++ b/src/main/java/com/develogical/QueryProcessor.java
@@ -1,14 +1,14 @@
package com.develogical;
public class QueryProcessor {
public String process(String query) {
if (query.contains("SPA2012")) {
return "SPA is a conference";
}
if (query.contains("Dragos") || query.contains("Ovidiu")) {
- return "Drop flop:" + query;
+ return "I'm just a drop flop:" + query;
}
- return "I don't know this one, I'm just a drop flop!";
+ return "";
}
}
| false | true | public String process(String query) {
if (query.contains("SPA2012")) {
return "SPA is a conference";
}
if (query.contains("Dragos") || query.contains("Ovidiu")) {
return "Drop flop:" + query;
}
return "I don't know this one, I'm just a drop flop!";
}
| public String process(String query) {
if (query.contains("SPA2012")) {
return "SPA is a conference";
}
if (query.contains("Dragos") || query.contains("Ovidiu")) {
return "I'm just a drop flop:" + query;
}
return "";
}
|
diff --git a/AE-go_GameServer/src/com/aionemu/gameserver/network/aion/clientpackets/CM_DELETE_ITEM.java b/AE-go_GameServer/src/com/aionemu/gameserver/network/aion/clientpackets/CM_DELETE_ITEM.java
index 7d8a78c8..a017c1d6 100644
--- a/AE-go_GameServer/src/com/aionemu/gameserver/network/aion/clientpackets/CM_DELETE_ITEM.java
+++ b/AE-go_GameServer/src/com/aionemu/gameserver/network/aion/clientpackets/CM_DELETE_ITEM.java
@@ -1,61 +1,61 @@
/**
* This file is part of aion-unique <aion-unique.smfnew.com>.
*
* aion-unique is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* aion-unique is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with aion-unique. If not, see <http://www.gnu.org/licenses/>.
*/
package com.aionemu.gameserver.network.aion.clientpackets;
import java.util.Random;
import com.aionemu.gameserver.model.gameobjects.Item;
import com.aionemu.gameserver.model.gameobjects.Npc;
import com.aionemu.gameserver.model.gameobjects.player.Inventory;
import com.aionemu.gameserver.model.gameobjects.player.Player;
import com.aionemu.gameserver.network.aion.AionClientPacket;
import com.aionemu.gameserver.network.aion.serverpackets.SM_DELETE_ITEM;
import com.aionemu.gameserver.utils.PacketSendUtility;
import com.aionemu.gameserver.world.World;
/**
*
* @author Avol
*
*/
public class CM_DELETE_ITEM extends AionClientPacket
{
public int objId;
public CM_DELETE_ITEM(int opcode)
{
super(opcode);
}
@Override
protected void readImpl()
{
objId = readD();
}
@Override
protected void runImpl()
{
Player player = getConnection().getActivePlayer();
Inventory bag = player.getInventory();
- Item resultItem = bag.getItem(objId);
+ Item resultItem = bag.getItemByObjId(objId);
if (resultItem != null)
bag.removeFromBag(resultItem);
sendPacket(new SM_DELETE_ITEM(objId));
}
}
| true | true | protected void runImpl()
{
Player player = getConnection().getActivePlayer();
Inventory bag = player.getInventory();
Item resultItem = bag.getItem(objId);
if (resultItem != null)
bag.removeFromBag(resultItem);
sendPacket(new SM_DELETE_ITEM(objId));
}
| protected void runImpl()
{
Player player = getConnection().getActivePlayer();
Inventory bag = player.getInventory();
Item resultItem = bag.getItemByObjId(objId);
if (resultItem != null)
bag.removeFromBag(resultItem);
sendPacket(new SM_DELETE_ITEM(objId));
}
|
diff --git a/elevator/Elevator.java b/elevator/Elevator.java
index ff8e4e4..49ab23c 100755
--- a/elevator/Elevator.java
+++ b/elevator/Elevator.java
@@ -1,301 +1,301 @@
import java.util.HashMap;
import java.util.LinkedList;
import java.util.PriorityQueue;
public class Elevator implements Comparable<Elevator> {
private int floor; // The current floor of the elevator
private int startingFloor; // The floor the elevator starts on
private final int maxCap; // Maximum Capacity of the elevator
private final int maxFloor; // The maximum Floor the elevator can reach
private final int minFloor; // The minimum Floor the elevator can reach
private int distanceTrav;
private int curCap; // Current Capacity of the elevator
private int state; // -1 going down, 0 not moving, 1 going up
private PriorityQueue<Integer> goals; // The goals for the elevator
private HashMap<Integer, LinkedList<Person>> contains; // The people the
/* STATE */// elevator
private boolean dumbMode;
// contains
private FloorComparatorAscending up = new FloorComparatorAscending();
private FloorComparatorDescending down = new FloorComparatorDescending();
/* Variables to be used by the manager as well as the elevator */
public static final int DOWN = -1;
public static final int STATIC = 0;
public static final int UP = 1;
private static final char dMode = 'd';
/***
* The constructor for an elevator, with an initial starting floor and
* maximum capacity
*
* @param maxCap
* Sets the maximum capacity for the elevator (total people)
* @param start
*
* @param upperElevatorRange
*
* @param lowerElevatorRange
*
* @param mode
*
*/
public Elevator(int maxCap, int start, int upperElevatorRange, int lowerElevatorRange, String mode) {
this.maxCap = maxCap;
this.maxFloor = upperElevatorRange;
this.minFloor = lowerElevatorRange;
this.distanceTrav = 0;
this.startingFloor = start;
this.floor = this.startingFloor;
this.state = STATIC; // The elevator hasn't moved yet
goals = new PriorityQueue<Integer>();
contains = new HashMap<Integer, LinkedList<Person>>(maxCap);
extractMode(mode);
}
/***
* Sets the appropriate modes for the elevator d - for dumbMode
*
* @param mode
* A string that contains the modes with no spaces
*/
private void extractMode(String mode) {
// currently only one state
for (int i = 0; i < mode.length(); ++i) {
if (mode.charAt(i) == dMode) {
dumbMode = true;
}
}
}
/*** @returns the current capacity of the elevator */
public int getCurCap() {
return curCap;
}
/***
* Changes the current capacity of the elevator
*
* @param people
* Total number of people currently in the elevator
*/
public void setCurCap(int people) {
this.curCap = people;
}
/***
* Changes whether the elevator goes up or down
*/
public boolean changeState(int newState) {
if (newState != state) {
if (goals.isEmpty()) {
state = newState;
this.setState(newState);
return true;
}
}
return false;
}
/***
* deletes the old goals Queue and changes it to the appropriate one so that
* it priorities based on the new state of the elevator
*/
private void setState(int newState) {
if (newState > 0) {
goals = new PriorityQueue<Integer>(2 * maxCap, up);
} else {
goals = new PriorityQueue<Integer>(2 * maxCap, down);
}
this.state = newState;
}
/***
* Sets a goal for which floor the elevator will stops on
*
* @param toDo
* A floor that the elevator will go to
*/
public void setGoal(int toDo) {
goals.add(toDo);
}
public int peekGoal () {
return goals.peek();
}
/*** @Returns the total distance the elevator has traveled */
public int getDistance() {
return distanceTrav;
}
/*** @Returns the direction the elevator will move */
public int getState() {
return state;
}
/*** @returns whether the elevator is full or not */
public boolean isFull() {
return maxCap == curCap;
}
/*** Changes the current floor of the elevator */
// TODO not needed
/*
* public void setCurrentFloor(int floor) { this.floor = floor; }
*/
/***
* @Returns The floor the elevator is currently on
*/
public int getCurrentFloor() {
return this.floor;
}
/*** @Returns whether the elevator has moved in the last unit time */
public boolean isActive() {
if (state != 0) {
return true;
}
return false;
}
/*** @Returns whether the elevator is empty */
public boolean isEmpty () {
return curCap == 0;
}
/***
* Takes the input f (floor) and check if its a valid floor. Example: if f is
* somewhere below the current floor of the elevator but the elevator is
* going up it will be rejected
*/
private boolean checkValid(int f) {
if (f < floor && state == UP) {
return false;
} else if (f > floor && state == DOWN) {
return false;
}
return true;
}
// TODO Write a more specific method for enter thats takes in a certain
// person
/***
* Adds a person when appropriate inside the elevator keeping track of
* necessary information and without losing the instance of the person
*/
public boolean enter(Person p) {
if (curCap == maxCap) {
assert false; //TODO Fix this code
return false;
}
int floorWanted = p.getDestinationFloor();
if (!checkValid(floorWanted)) {
assert false; //TODO Fix this
return false;
}
goals.add(floorWanted);
LinkedList<Person> group = contains.get(floorWanted);
if (group != null) {
// group exists so we add the person to the existing group
group.add(p);
} else {
// group doesn't exist so we create a group and add its first person
LinkedList<Person> newGroup = new LinkedList<Person>();
newGroup.add(p);
contains.put(floorWanted, newGroup);
}
assert curCap >= 0; //It should never be negative
curCap++;
return true;
}
/***
* Updates the elevator's state should the elevator reach the max floor
*/
private void checkRange() {
if (floor == maxFloor && state > 0 || floor == minFloor && state < 0) {
assert (goals.isEmpty()); // If the goals are not empty this is a bug
setState(state * -1);
}
}
/***
* Moves the elevator forward one unit of time. The elevator moves up or down
* a floor depending on its state and if it has a goal. Returns either a
* group of people or null, should null be returned it means that no person
* left that floor, but people might be entering.
*/
public LinkedList<Person> update() {
// TODO Check what floors the elevator can move to
if (!goals.isEmpty()) {
move ();
int destination = goals.peek();
int localGoal = goals.peek();
// We have found a goal set
if (localGoal == floor) {
// int key = goals.remove(); //Good idea by Roger
while (localGoal == floor) {
goals.remove();
if(goals.isEmpty ()){
break;
}
localGoal = goals.peek();
}
- LinkedList<Person> peopleLeaving = contains.get(destination); // TODO
+ LinkedList<Person> peopleLeaving = contains.remove(destination); // TODO
// change
// name
// of
// destination
// to
// idk
if (peopleLeaving != null) {
this.curCap -= peopleLeaving.size();
}
checkRange();
return peopleLeaving; // Returns the group of people departing on
// this floor
}
} else if (dumbMode) {
move ();
checkRange();
} else {
state = STATIC; // we have nothing to do
}
return null;
}
public void move () {
floor += state;
distanceTrav += 1;
//checkRange();
}
/***
* Allows elevators to be comparable by priority (which is the current floor
* they are on)
*/
@Override
public int compareTo(Elevator o) {
// TODO Test this function
if (this.floor > o.floor) {
return 1;
} else if (this.floor < o.floor) {
return -1;
}
return 0;
}
public int[] getInfo () {
int[] info = {floor, startingFloor, maxCap, maxFloor, distanceTrav, curCap, state};
return info;
}
}
| true | true | public LinkedList<Person> update() {
// TODO Check what floors the elevator can move to
if (!goals.isEmpty()) {
move ();
int destination = goals.peek();
int localGoal = goals.peek();
// We have found a goal set
if (localGoal == floor) {
// int key = goals.remove(); //Good idea by Roger
while (localGoal == floor) {
goals.remove();
if(goals.isEmpty ()){
break;
}
localGoal = goals.peek();
}
LinkedList<Person> peopleLeaving = contains.get(destination); // TODO
// change
// name
// of
// destination
// to
// idk
if (peopleLeaving != null) {
this.curCap -= peopleLeaving.size();
}
checkRange();
return peopleLeaving; // Returns the group of people departing on
// this floor
}
} else if (dumbMode) {
move ();
checkRange();
} else {
state = STATIC; // we have nothing to do
}
return null;
}
| public LinkedList<Person> update() {
// TODO Check what floors the elevator can move to
if (!goals.isEmpty()) {
move ();
int destination = goals.peek();
int localGoal = goals.peek();
// We have found a goal set
if (localGoal == floor) {
// int key = goals.remove(); //Good idea by Roger
while (localGoal == floor) {
goals.remove();
if(goals.isEmpty ()){
break;
}
localGoal = goals.peek();
}
LinkedList<Person> peopleLeaving = contains.remove(destination); // TODO
// change
// name
// of
// destination
// to
// idk
if (peopleLeaving != null) {
this.curCap -= peopleLeaving.size();
}
checkRange();
return peopleLeaving; // Returns the group of people departing on
// this floor
}
} else if (dumbMode) {
move ();
checkRange();
} else {
state = STATIC; // we have nothing to do
}
return null;
}
|
diff --git a/app/controllers/Application.java b/app/controllers/Application.java
index b409689..5813287 100644
--- a/app/controllers/Application.java
+++ b/app/controllers/Application.java
@@ -1,40 +1,39 @@
package controllers;
import org.joda.time.DateTime;
import play.*;
import play.mvc.*;
import views.html.*;
import com.feth.play.module.pa.PlayAuthenticate;
public class Application extends Controller {
public static final String FLASH_MESSAGE_KEY = "message";
public static final String FLASH_ERROR_KEY = "error";
public static Result index() {
String msg = "Hello, nicocale";
String dateStr = new DateTime().toString();
return ok(index.render(msg, dateStr));
}
public static Result oAuth(final String provider) {
Http.Request req = play.mvc.Http.Context.current().request();
- System.out.println(req.queryString());
if (req.queryString().containsKey("denied")) {
return oAuthDenied(provider);
}
return com.feth.play.module.pa.controllers.Authenticate.authenticate(provider);
}
public static Result oAuthDenied(final String providerKey) {
com.feth.play.module.pa.controllers.Authenticate.noCache(response());
flash(FLASH_ERROR_KEY,
"You need to accept the OAuth connection in order to use this website!");
return redirect(routes.Application.index());
}
}
| true | true | public static Result oAuth(final String provider) {
Http.Request req = play.mvc.Http.Context.current().request();
System.out.println(req.queryString());
if (req.queryString().containsKey("denied")) {
return oAuthDenied(provider);
}
return com.feth.play.module.pa.controllers.Authenticate.authenticate(provider);
}
| public static Result oAuth(final String provider) {
Http.Request req = play.mvc.Http.Context.current().request();
if (req.queryString().containsKey("denied")) {
return oAuthDenied(provider);
}
return com.feth.play.module.pa.controllers.Authenticate.authenticate(provider);
}
|
diff --git a/content/src/org/riotfamily/pages/mapping/PageResolver.java b/content/src/org/riotfamily/pages/mapping/PageResolver.java
index a73e53cc4..d2cab2202 100644
--- a/content/src/org/riotfamily/pages/mapping/PageResolver.java
+++ b/content/src/org/riotfamily/pages/mapping/PageResolver.java
@@ -1,172 +1,172 @@
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.riotfamily.pages.mapping;
import javax.servlet.http.HttpServletRequest;
import org.riotfamily.common.util.FormatUtils;
import org.riotfamily.common.web.support.ServletUtils;
import org.riotfamily.core.security.AccessController;
import org.riotfamily.pages.config.SystemPageType;
import org.riotfamily.pages.model.ContentPage;
import org.riotfamily.pages.model.Page;
import org.riotfamily.pages.model.Site;
/**
* @author Carsten Woelk [cwoelk at neteye dot de]
* @author Felix Gnass [fgnass at neteye dot de]
* @since 7.0
*/
public final class PageResolver {
public static final String SITE_ATTRIBUTE = PageResolver.class.getName() + ".site";
public static final String PAGE_ATTRIBUTE = PageResolver.class.getName() + ".page";
private static final Object NOT_FOUND = new Object();
private PageResolver() {
}
/**
* Returns the first Site that matches the given request. The PathCompleter
* is used to strip the servlet mapping from the request URI.
* @return The first matching Site, or <code>null</code> if no match is found
*/
public static Site getSite(HttpServletRequest request) {
Object site = request.getAttribute(SITE_ATTRIBUTE);
if (site == null) {
site = resolveSite(request);
exposeSite((Site) site, request);
}
if (site == null || site == NOT_FOUND) {
return null;
}
Site result = (Site) site;
result.refreshIfDetached();
return result;
}
protected static void exposeSite(Site site, HttpServletRequest request) {
expose(site, request, SITE_ATTRIBUTE);
}
/**
* Returns the Page for the given request.
*/
public static Page getPage(HttpServletRequest request) {
Object page = request.getAttribute(PAGE_ATTRIBUTE);
if (page == null) {
page = resolvePage(request);
exposePage((Page) page, request);
}
if (page == null || page == NOT_FOUND) {
return null;
}
return (Page) page;
}
public static Page getVirtualPage(Site site, String type, Object arg) {
return site.getSchema().getVirtualPageType(type).resolve(site, arg);
}
protected static void exposePage(Page page, HttpServletRequest request) {
expose(page, request, PAGE_ATTRIBUTE);
}
/**
* Returns the previously resolved Page for the given request.
* <p>
* <strong>Note:</strong> This method does not perform any lookups itself.
* Only use this method if you are sure that
* {@link #getPage(HttpServletRequest)} has been invoked before.
*/
public static Page getResolvedPage(HttpServletRequest request) {
Object page = request.getAttribute(PAGE_ATTRIBUTE);
return page != NOT_FOUND ? (Page) page : null;
}
/**
* Returns the previously resolved Site for the given request.
* <p>
* <strong>Note:</strong> This method does not perform any lookups itself.
* Only use this method if you are sure that
* {@link #getSite(HttpServletRequest)} has been invoked before.
*/
public static Site getResolvedSite(HttpServletRequest request) {
Object site = request.getAttribute(SITE_ATTRIBUTE);
return site != NOT_FOUND ? (Site) site : null;
}
private static Site resolveSite(HttpServletRequest request) {
String hostName = request.getServerName();
return Site.loadByHostName(hostName);
}
private static Page resolvePage(HttpServletRequest request) {
Site site = getSite(request);
if (site == null) {
return null;
}
- String path = FormatUtils.stripTrailingSlash(ServletUtils.getPathWithinApplication(request));
- String lookupPath = getLookupPath(path);
+ String path = ServletUtils.getPathWithinApplication(request);
+ String lookupPath = getLookupPath(FormatUtils.stripTrailingSlash(path));
Page page = ContentPage.loadBySiteAndPath(site, lookupPath);
if (page == null) {
page = resolveVirtualChildPage(site, lookupPath);
}
if (page == null
|| !(page.isPublished() || AccessController.isAuthenticatedUser())
|| !site.getSchema().suffixMatches(page, path)) {
return null;
}
return page;
}
private static Page resolveVirtualChildPage(Site site, String lookupPath) {
for (ContentPage parent : ContentPage.findByTypesAndSite(site.getSchema().getVirtualParents(), site)) {
if (lookupPath.startsWith(parent.getPath())) {
SystemPageType parentType = (SystemPageType) site.getSchema().getPageType(parent);
String tail = lookupPath.substring(parent.getPath().length());
return parentType.getVirtualChildType().resolve(parent, tail);
}
}
return null;
}
public static String getLookupPath(HttpServletRequest request) {
return getLookupPath(ServletUtils.getPathWithinApplication(request));
}
public static String getLookupPath(String path) {
return FormatUtils.stripExtension(path);
}
private static void expose(Object object, HttpServletRequest request,
String attributeName) {
if (object == null) {
object = NOT_FOUND;
}
request.setAttribute(attributeName, object);
}
/**
* Resets all internally used attributes.
* @param request
*/
public static void resetAttributes(HttpServletRequest request) {
request.removeAttribute(SITE_ATTRIBUTE);
request.removeAttribute(PAGE_ATTRIBUTE);
}
}
| true | true | private static Page resolvePage(HttpServletRequest request) {
Site site = getSite(request);
if (site == null) {
return null;
}
String path = FormatUtils.stripTrailingSlash(ServletUtils.getPathWithinApplication(request));
String lookupPath = getLookupPath(path);
Page page = ContentPage.loadBySiteAndPath(site, lookupPath);
if (page == null) {
page = resolveVirtualChildPage(site, lookupPath);
}
if (page == null
|| !(page.isPublished() || AccessController.isAuthenticatedUser())
|| !site.getSchema().suffixMatches(page, path)) {
return null;
}
return page;
}
| private static Page resolvePage(HttpServletRequest request) {
Site site = getSite(request);
if (site == null) {
return null;
}
String path = ServletUtils.getPathWithinApplication(request);
String lookupPath = getLookupPath(FormatUtils.stripTrailingSlash(path));
Page page = ContentPage.loadBySiteAndPath(site, lookupPath);
if (page == null) {
page = resolveVirtualChildPage(site, lookupPath);
}
if (page == null
|| !(page.isPublished() || AccessController.isAuthenticatedUser())
|| !site.getSchema().suffixMatches(page, path)) {
return null;
}
return page;
}
|
diff --git a/console/src/main/java/org/apache/kalumet/console/configuration/model/KalumetConsole.java b/console/src/main/java/org/apache/kalumet/console/configuration/model/KalumetConsole.java
index 67f82c6..5cb2396 100644
--- a/console/src/main/java/org/apache/kalumet/console/configuration/model/KalumetConsole.java
+++ b/console/src/main/java/org/apache/kalumet/console/configuration/model/KalumetConsole.java
@@ -1,102 +1,104 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.kalumet.console.configuration.model;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.digester.Digester;
/**
* Represents the <code>kalumet-console</code> root tag of the
* Kalumet Console configuration.
*/
public class KalumetConsole {
private LinkedList properties;
public KalumetConsole() {
this.properties = new LinkedList();
}
/**
* Add a new property.
*
* @param property the <code>Property</code> to add.
*/
public void addProperty(Property property) throws Exception {
if(this.getProperty(property.getName()) != null) {
throw new IllegalArgumentException("The property name " + property.getName() + " already exists in the console configuration");
}
this.properties.add(property);
}
/**
* Return the property list.
*
* @return the <code>Property</code> list.
*/
public List getProperties() {
return this.properties;
}
/**
* Return the property identified by a given name.
*
* @param name the property name.
* @return the <code>Property</code> found or null if no <code>Property</code> found.
*/
public Property getProperty(String name) {
for(Iterator propertyIterator = this.getProperties().iterator(); propertyIterator.hasNext();) {
Property property = (Property) propertyIterator.next();
if(property.getName().equals(name)) {
return property;
}
}
return null;
}
/**
* Digest the Kalumet Console configuration.
*
* @param path the Kalumet Console location.
* @return the Kalumet Console configuration object.
*/
public static KalumetConsole digeste(String path) throws Exception {
KalumetConsole kalumetConsole = null;
try {
Digester digester = new Digester();
digester.setValidating(false);
digester.addObjectCreate("kalumet-console", "org.apache.kalumet.console.configuration.model.KalumetConsole");
digester.addObjectCreate("kalumet-console/property", "org.apahce.kalumet.console.configuration.model.Property");
digester.addSetProperties("kalumet-console/property");
digester.addSetNext("kalumet-console/property", "addProperty", "org.apache.kalumet.console.configuration.model.Property");
kalumetConsole = (KalumetConsole) digester.parse(path);
} catch (Exception e) {
- throw new IOException("Can't read the Apache Kalumet console configuration", e);
+ IOException ioe = new IOException("Can't read the Apache Kalumet console configuration");
+ ioe.initCause( e );
+ throw ioe;
}
return kalumetConsole;
}
}
| true | true | public static KalumetConsole digeste(String path) throws Exception {
KalumetConsole kalumetConsole = null;
try {
Digester digester = new Digester();
digester.setValidating(false);
digester.addObjectCreate("kalumet-console", "org.apache.kalumet.console.configuration.model.KalumetConsole");
digester.addObjectCreate("kalumet-console/property", "org.apahce.kalumet.console.configuration.model.Property");
digester.addSetProperties("kalumet-console/property");
digester.addSetNext("kalumet-console/property", "addProperty", "org.apache.kalumet.console.configuration.model.Property");
kalumetConsole = (KalumetConsole) digester.parse(path);
} catch (Exception e) {
throw new IOException("Can't read the Apache Kalumet console configuration", e);
}
return kalumetConsole;
}
| public static KalumetConsole digeste(String path) throws Exception {
KalumetConsole kalumetConsole = null;
try {
Digester digester = new Digester();
digester.setValidating(false);
digester.addObjectCreate("kalumet-console", "org.apache.kalumet.console.configuration.model.KalumetConsole");
digester.addObjectCreate("kalumet-console/property", "org.apahce.kalumet.console.configuration.model.Property");
digester.addSetProperties("kalumet-console/property");
digester.addSetNext("kalumet-console/property", "addProperty", "org.apache.kalumet.console.configuration.model.Property");
kalumetConsole = (KalumetConsole) digester.parse(path);
} catch (Exception e) {
IOException ioe = new IOException("Can't read the Apache Kalumet console configuration");
ioe.initCause( e );
throw ioe;
}
return kalumetConsole;
}
|
diff --git a/core/src/main/java/net/kamhon/ieagle/util/CollectionUtil.java b/core/src/main/java/net/kamhon/ieagle/util/CollectionUtil.java
index e51236f..fae7c52 100644
--- a/core/src/main/java/net/kamhon/ieagle/util/CollectionUtil.java
+++ b/core/src/main/java/net/kamhon/ieagle/util/CollectionUtil.java
@@ -1,368 +1,369 @@
/*
* Copyright 2012 Eng Kam Hon ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.kamhon.ieagle.util;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import net.kamhon.ieagle.FrameworkConst;
import net.kamhon.ieagle.exception.DataException;
import org.apache.commons.beanutils.NestedNullException;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.reflect.MethodUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import com.opensymphony.xwork2.conversion.annotations.TypeConversion;
public class CollectionUtil {
private CollectionUtil() {
}
/**
* true if collection is null or empty.
*
* @param collection
*/
public static boolean isEmpty(Collection<?> collection) {
return collection == null || collection.isEmpty();
}
/**
* true if collection is not null and not empty.
*
* @param collection
* @return
*/
public static boolean isNotEmpty(Collection<?> collection) {
return collection != null && !collection.isEmpty();
}
/**
* Remove duplicate object base on hashcode
*
* @param retList
*/
public static <T> List<T> removeDuplicateInList(List<T> retList) {
Set<T> set = new HashSet<T>(retList);
retList = new ArrayList<T>(set);
return retList;
}
/**
* Convert Arrays to HashSet
*
* @param <T>
* @param objects
* @return
*/
public static <T> Set<T> toSet(T... objects) {
List<T> list = Arrays.asList(objects);
return new HashSet<T>(list);
}
/**
* Concatenates two arrays.
*
* @param array1
* - first array
* @param array2
* - second array
* @param <T>
* - object class
* @return array contatenation
*/
public static <T> T[] concatenate2Arrays(T[] array1, T... array2) {
List<T> result = new ArrayList<T>();
result.addAll(Arrays.asList(array1));
result.addAll(Arrays.asList(array2));
return result.toArray(array1);
}
/**
* This function used to convert particular properties in Object to array.
*
* @param objects
* @param propertiesNames
* @param isSetNullToEmptyString
* @return
*/
public static Object[][] to2DArray(List<?> objects, String[] propertiesNames, boolean isSetNullToEmptyString) {
if (isEmpty(objects)) {
return new Object[0][0];
}
List<Object[]> result = new ArrayList<Object[]>();
for (Object object : objects) {
List<Object> record = new ArrayList<Object>();
for (String propertyName : propertiesNames) {
try {
Object propValue = PropertyUtils.getProperty(object, propertyName);
record.add(propValue == null ? "" : propValue);
} catch (NestedNullException ex) {
// if nested bean referenced is null
record.add("");
} catch (Exception ex) {
throw new DataException(ex);
}
}
result.add(record.toArray(new Object[0]));
}
return result.toArray(new Object[1][1]);
}
/**
* This function used to convert particular properties in Object to array. This function mainly used to response
* Client in JSON object
*
*
* @param locale
* @param objects
* @param propertiesNames
* @param isSetNullToEmptyString
* @return
*/
public static Object[][] to2DArrayForStruts(Locale locale, List<?> objects, String[] propertiesNames, boolean isSetNullToEmptyString) {
String dateTimeFormat = "";
if (isEmpty(objects)) {
return new Object[0][0];
}
List<Object[]> result = new ArrayList<Object[]>();
for (Object object : objects) {
List<Object> record = new ArrayList<Object>();
for (String propertyName : propertiesNames) {
boolean hasResult = false;
Object propValue = null;
try {
propValue = PropertyUtils.getProperty(object, propertyName);
processPropertiesForStruts(object, record, propertyName, propValue);
+ hasResult = true;
} catch (NestedNullException ex) {
// if nested bean referenced is null
record.add("");
hasResult = true;
} catch (Exception ex) {
if (locale == null)
throw new DataException(ex);
}
if (hasResult == false && propValue == null && locale != null) {
try {
String methodName = "get" + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1);
propValue = MethodUtils.invokeExactMethod(object, methodName, locale);
processPropertiesForStruts(object, record, propertyName, propValue);
} catch (Exception ex) {
throw new DataException(ex);
}
}
}
result.add(record.toArray(new Object[0]));
}
return result.toArray(new Object[1][1]);
}
private static void processPropertiesForStruts(Object object, List<Object> record, String propertyName, Object propValue) {
String dateTimeFormat;
if (propValue instanceof Date) {
SimpleDateFormat sdf = new SimpleDateFormat(FrameworkConst.DEFAULT_JSON_DATETIME_24_FORMAT);
dateTimeFormat = sdf.format(propValue);
record.add(dateTimeFormat);
} else if (propValue instanceof Number) {
record.add(processForNumber(object, propertyName, propValue));
} else {
record.add(propValue == null ? "" : propValue);
}
}
private static Object processForNumber(Object object, String propertyName, Object propValue) {
BeanWrapper wrapper = new BeanWrapperImpl(object);
PropertyDescriptor descriptor = wrapper.getPropertyDescriptor(propertyName);
Method method = descriptor.getReadMethod();
TypeConversion typeConversion = method.getAnnotation(TypeConversion.class);
if (typeConversion != null) {
String convertor = typeConversion.converter();
if (convertor.equalsIgnoreCase(FrameworkConst.STRUTS_DECIMAL_CONVERTER)) {
DecimalFormat df = new DecimalFormat(FrameworkConst.DEFAULT_DECIMAL_FORMAT);
return df.format(propValue);
} else {
return propValue;
}
} else {
if (propValue instanceof Double || propValue instanceof Float) {
DecimalFormat df = new DecimalFormat(FrameworkConst.DEFAULT_DECIMAL_FORMAT);
return df.format(propValue);
} else {
return propValue;
}
}
}
/**
* Make the log more meanings
*
* @param <K>
* @param <V>
* @param map
* @return
*/
public static <K, V> String toLog(Map<K, V> map) {
// using StringBuffer instead of String because expect there are many append operation
StringBuffer sb = new StringBuffer();
if (map == null) {
return null;
}
if (map.isEmpty()) {
return map.toString();
}
sb.append("{");
for (Iterator<K> iterator = map.keySet().iterator(); iterator.hasNext();) {
K key = iterator.next();
Object value = map.get(key);
sb.append(key).append("=");
sb.append(toString4Log(value));
if (iterator.hasNext()) {
sb.append(", ");
}
}
sb.append("}");
return sb.toString();
}
public static <E> String toLog(Collection<E> collec) {
return toLog("", collec);
}
/**
* Make the log more meanings
*
* @param <E>
* @param collec
* @return
*/
public static <E> String toLog(String separator, Collection<E> collec) {
// using StringBuffer instead of String because expect there are many append operation
StringBuffer sb = new StringBuffer();
if (collec == null) {
return null;
}
if (collec.isEmpty()) {
return collec.toString();
}
sb.append("[");
for (Iterator<E> iterator = collec.iterator(); iterator.hasNext();) {
E value = iterator.next();
sb.append(separator).append(toString4Log(value)).append(separator);
if (iterator.hasNext()) {
sb.append(", ");
}
}
sb.append("]");
return sb.toString();
}
public static <E> String toLog(E... array) {
return toLog("", array);
}
public static <E> String toLog(String separator, E... array) {
if (array != null)
return toLog(separator, Arrays.asList(array));
else
return null;
}
private static String toString4Log(Object value) {
if (value == null) {
return null;
} else if (value instanceof String) {
return (String) value;
} else if (value instanceof Short) {
return "" + ((Short) value).shortValue();
} else if (value instanceof Integer) {
return "" + ((Integer) value).intValue();
} else if (value instanceof Long) {
return "" + ((Long) value).longValue();
} else if (value instanceof Float) {
return "" + ((Float) value).floatValue();
} else if (value instanceof Double) {
return "" + ((Double) value).doubleValue();
} else if (value instanceof Object[]) {
Object[] objs = (Object[]) value;
StringBuffer sb = new StringBuffer();
sb.append("[");
for (int i = 0; i < objs.length; i++) {
sb.append(toString4Log(objs[i]));
if (i != objs.length - 1) {
sb.append(", ");
}
}
sb.append("]");
return sb.toString();
} else if (value instanceof Iterator) {
StringBuffer sb = new StringBuffer();
sb.append("[");
for (Iterator<?> i = (Iterator<?>) value; i.hasNext();) {
sb.append(toString4Log(i.next()));
if (i.hasNext()) {
sb.append(", ");
}
}
sb.append("]");
return sb.toString();
} else
return value.toString();
}
public static <T> T getFirst(Collection<T> collection) {
if (isNotEmpty(collection))
return collection.iterator().next();
else
return null;
}
}
| true | true | public static Object[][] to2DArrayForStruts(Locale locale, List<?> objects, String[] propertiesNames, boolean isSetNullToEmptyString) {
String dateTimeFormat = "";
if (isEmpty(objects)) {
return new Object[0][0];
}
List<Object[]> result = new ArrayList<Object[]>();
for (Object object : objects) {
List<Object> record = new ArrayList<Object>();
for (String propertyName : propertiesNames) {
boolean hasResult = false;
Object propValue = null;
try {
propValue = PropertyUtils.getProperty(object, propertyName);
processPropertiesForStruts(object, record, propertyName, propValue);
} catch (NestedNullException ex) {
// if nested bean referenced is null
record.add("");
hasResult = true;
} catch (Exception ex) {
if (locale == null)
throw new DataException(ex);
}
if (hasResult == false && propValue == null && locale != null) {
try {
String methodName = "get" + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1);
propValue = MethodUtils.invokeExactMethod(object, methodName, locale);
processPropertiesForStruts(object, record, propertyName, propValue);
} catch (Exception ex) {
throw new DataException(ex);
}
}
}
result.add(record.toArray(new Object[0]));
}
return result.toArray(new Object[1][1]);
}
| public static Object[][] to2DArrayForStruts(Locale locale, List<?> objects, String[] propertiesNames, boolean isSetNullToEmptyString) {
String dateTimeFormat = "";
if (isEmpty(objects)) {
return new Object[0][0];
}
List<Object[]> result = new ArrayList<Object[]>();
for (Object object : objects) {
List<Object> record = new ArrayList<Object>();
for (String propertyName : propertiesNames) {
boolean hasResult = false;
Object propValue = null;
try {
propValue = PropertyUtils.getProperty(object, propertyName);
processPropertiesForStruts(object, record, propertyName, propValue);
hasResult = true;
} catch (NestedNullException ex) {
// if nested bean referenced is null
record.add("");
hasResult = true;
} catch (Exception ex) {
if (locale == null)
throw new DataException(ex);
}
if (hasResult == false && propValue == null && locale != null) {
try {
String methodName = "get" + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1);
propValue = MethodUtils.invokeExactMethod(object, methodName, locale);
processPropertiesForStruts(object, record, propertyName, propValue);
} catch (Exception ex) {
throw new DataException(ex);
}
}
}
result.add(record.toArray(new Object[0]));
}
return result.toArray(new Object[1][1]);
}
|
diff --git a/osmosis-core/src/main/java/org/openstreetmap/osmosis/core/CorePluginLoader.java b/osmosis-core/src/main/java/org/openstreetmap/osmosis/core/CorePluginLoader.java
index 35eb37c4..22ed1970 100644
--- a/osmosis-core/src/main/java/org/openstreetmap/osmosis/core/CorePluginLoader.java
+++ b/osmosis-core/src/main/java/org/openstreetmap/osmosis/core/CorePluginLoader.java
@@ -1,116 +1,116 @@
// This software is released into the Public Domain. See copying.txt for details.
package org.openstreetmap.osmosis.core;
import java.util.HashMap;
import java.util.Map;
import org.openstreetmap.osmosis.core.bound.v0_6.BoundComputerFactory;
import org.openstreetmap.osmosis.core.bound.v0_6.BoundSetterFactory;
import org.openstreetmap.osmosis.core.buffer.v0_6.ChangeBufferFactory;
import org.openstreetmap.osmosis.core.buffer.v0_6.EntityBufferFactory;
import org.openstreetmap.osmosis.core.misc.v0_6.EmptyChangeReaderFactory;
import org.openstreetmap.osmosis.core.misc.v0_6.EmptyReaderFactory;
import org.openstreetmap.osmosis.core.misc.v0_6.NullChangeWriterFactory;
import org.openstreetmap.osmosis.core.misc.v0_6.NullWriterFactory;
import org.openstreetmap.osmosis.core.pipeline.common.TaskManagerFactory;
import org.openstreetmap.osmosis.core.plugin.PluginLoader;
import org.openstreetmap.osmosis.core.progress.v0_6.ChangeProgressLoggerFactory;
import org.openstreetmap.osmosis.core.progress.v0_6.EntityProgressLoggerFactory;
import org.openstreetmap.osmosis.core.report.v0_6.EntityReporterFactory;
import org.openstreetmap.osmosis.core.report.v0_6.IntegrityReporterFactory;
import org.openstreetmap.osmosis.core.sort.v0_6.ChangeForSeekableApplierComparator;
import org.openstreetmap.osmosis.core.sort.v0_6.ChangeForStreamableApplierComparator;
import org.openstreetmap.osmosis.core.sort.v0_6.ChangeSorterFactory;
import org.openstreetmap.osmosis.core.sort.v0_6.ChangeTagSorterFactory;
import org.openstreetmap.osmosis.core.sort.v0_6.EntityByTypeThenIdComparator;
import org.openstreetmap.osmosis.core.sort.v0_6.EntityContainerComparator;
import org.openstreetmap.osmosis.core.sort.v0_6.EntitySorterFactory;
import org.openstreetmap.osmosis.core.sort.v0_6.TagSorterFactory;
import org.openstreetmap.osmosis.core.tee.v0_6.ChangeTeeFactory;
import org.openstreetmap.osmosis.core.tee.v0_6.EntityTeeFactory;
/**
* The plugin loader for the core tasks.
*
* @author Brett Henderson
*/
public class CorePluginLoader implements PluginLoader {
/**
* {@inheritDoc}
*/
@Override
public Map<String, TaskManagerFactory> loadTaskFactories() {
Map<String, TaskManagerFactory> factoryMap;
EntitySorterFactory entitySorterFactory06;
ChangeSorterFactory changeSorterFactory06;
factoryMap = new HashMap<String, TaskManagerFactory>();
// Configure factories that require additional information.
entitySorterFactory06 = new EntitySorterFactory();
entitySorterFactory06.registerComparator("TypeThenId", new EntityContainerComparator(
new EntityByTypeThenIdComparator()), true);
changeSorterFactory06 = new ChangeSorterFactory();
changeSorterFactory06.registerComparator("streamable", new ChangeForStreamableApplierComparator(), true);
changeSorterFactory06.registerComparator("seekable", new ChangeForSeekableApplierComparator(), false);
// Register factories.
factoryMap.put("sort", entitySorterFactory06);
factoryMap.put("s", entitySorterFactory06);
factoryMap.put("sort-change", changeSorterFactory06);
factoryMap.put("sc", changeSorterFactory06);
factoryMap.put("write-null", new NullWriterFactory());
factoryMap.put("wn", new NullWriterFactory());
factoryMap.put("write-null-change", new NullChangeWriterFactory());
factoryMap.put("wnc", new NullChangeWriterFactory());
factoryMap.put("buffer", new EntityBufferFactory());
factoryMap.put("b", new EntityBufferFactory());
factoryMap.put("buffer-change", new ChangeBufferFactory());
factoryMap.put("bc", new ChangeBufferFactory());
factoryMap.put("report-entity", new EntityReporterFactory());
factoryMap.put("re", new EntityReporterFactory());
factoryMap.put("report-integrity", new IntegrityReporterFactory());
factoryMap.put("ri", new IntegrityReporterFactory());
factoryMap.put("log-progress", new EntityProgressLoggerFactory());
factoryMap.put("lp", new EntityProgressLoggerFactory());
factoryMap.put("log-progress-change", new ChangeProgressLoggerFactory());
factoryMap.put("lpc", new ChangeProgressLoggerFactory());
factoryMap.put("tee", new EntityTeeFactory());
factoryMap.put("t", new EntityTeeFactory());
factoryMap.put("tee-change", new ChangeTeeFactory());
factoryMap.put("tc", new ChangeTeeFactory());
factoryMap.put("read-empty", new EmptyReaderFactory());
- factoryMap.put("re", new EmptyReaderFactory());
+ factoryMap.put("rem", new EmptyReaderFactory());
factoryMap.put("read-empty-change", new EmptyChangeReaderFactory());
- factoryMap.put("rec", new EmptyChangeReaderFactory());
+ factoryMap.put("remc", new EmptyChangeReaderFactory());
factoryMap.put("compute-bounding-box", new BoundComputerFactory());
factoryMap.put("cbb", new BoundComputerFactory());
factoryMap.put("set-bounding-box", new BoundSetterFactory());
factoryMap.put("sbb", new BoundSetterFactory());
factoryMap.put("sort-0.6", entitySorterFactory06);
factoryMap.put("sort-change-0.6", changeSorterFactory06);
factoryMap.put("write-null-0.6", new NullWriterFactory());
factoryMap.put("write-null-change-0.6", new NullChangeWriterFactory());
factoryMap.put("buffer-0.6", new EntityBufferFactory());
factoryMap.put("buffer-change-0.6", new ChangeBufferFactory());
factoryMap.put("report-entity-0.6", new EntityReporterFactory());
factoryMap.put("report-integrity-0.6", new IntegrityReporterFactory());
factoryMap.put("log-progress-0.6", new EntityProgressLoggerFactory());
factoryMap.put("log-progress-change-0.6", new ChangeProgressLoggerFactory());
factoryMap.put("tee-0.6", new EntityTeeFactory());
factoryMap.put("tee-change-0.6", new ChangeTeeFactory());
factoryMap.put("read-empty-0.6", new EmptyReaderFactory());
factoryMap.put("read-empty-change-0.6", new EmptyChangeReaderFactory());
factoryMap.put("tag-sort-0.6", new TagSorterFactory());
factoryMap.put("tag-sort-change-0.6", new ChangeTagSorterFactory());
factoryMap.put("compute-bounding-box-0.6", new BoundComputerFactory());
factoryMap.put("set-bounding-box-0.6", new BoundSetterFactory());
return factoryMap;
}
}
| false | true | public Map<String, TaskManagerFactory> loadTaskFactories() {
Map<String, TaskManagerFactory> factoryMap;
EntitySorterFactory entitySorterFactory06;
ChangeSorterFactory changeSorterFactory06;
factoryMap = new HashMap<String, TaskManagerFactory>();
// Configure factories that require additional information.
entitySorterFactory06 = new EntitySorterFactory();
entitySorterFactory06.registerComparator("TypeThenId", new EntityContainerComparator(
new EntityByTypeThenIdComparator()), true);
changeSorterFactory06 = new ChangeSorterFactory();
changeSorterFactory06.registerComparator("streamable", new ChangeForStreamableApplierComparator(), true);
changeSorterFactory06.registerComparator("seekable", new ChangeForSeekableApplierComparator(), false);
// Register factories.
factoryMap.put("sort", entitySorterFactory06);
factoryMap.put("s", entitySorterFactory06);
factoryMap.put("sort-change", changeSorterFactory06);
factoryMap.put("sc", changeSorterFactory06);
factoryMap.put("write-null", new NullWriterFactory());
factoryMap.put("wn", new NullWriterFactory());
factoryMap.put("write-null-change", new NullChangeWriterFactory());
factoryMap.put("wnc", new NullChangeWriterFactory());
factoryMap.put("buffer", new EntityBufferFactory());
factoryMap.put("b", new EntityBufferFactory());
factoryMap.put("buffer-change", new ChangeBufferFactory());
factoryMap.put("bc", new ChangeBufferFactory());
factoryMap.put("report-entity", new EntityReporterFactory());
factoryMap.put("re", new EntityReporterFactory());
factoryMap.put("report-integrity", new IntegrityReporterFactory());
factoryMap.put("ri", new IntegrityReporterFactory());
factoryMap.put("log-progress", new EntityProgressLoggerFactory());
factoryMap.put("lp", new EntityProgressLoggerFactory());
factoryMap.put("log-progress-change", new ChangeProgressLoggerFactory());
factoryMap.put("lpc", new ChangeProgressLoggerFactory());
factoryMap.put("tee", new EntityTeeFactory());
factoryMap.put("t", new EntityTeeFactory());
factoryMap.put("tee-change", new ChangeTeeFactory());
factoryMap.put("tc", new ChangeTeeFactory());
factoryMap.put("read-empty", new EmptyReaderFactory());
factoryMap.put("re", new EmptyReaderFactory());
factoryMap.put("read-empty-change", new EmptyChangeReaderFactory());
factoryMap.put("rec", new EmptyChangeReaderFactory());
factoryMap.put("compute-bounding-box", new BoundComputerFactory());
factoryMap.put("cbb", new BoundComputerFactory());
factoryMap.put("set-bounding-box", new BoundSetterFactory());
factoryMap.put("sbb", new BoundSetterFactory());
factoryMap.put("sort-0.6", entitySorterFactory06);
factoryMap.put("sort-change-0.6", changeSorterFactory06);
factoryMap.put("write-null-0.6", new NullWriterFactory());
factoryMap.put("write-null-change-0.6", new NullChangeWriterFactory());
factoryMap.put("buffer-0.6", new EntityBufferFactory());
factoryMap.put("buffer-change-0.6", new ChangeBufferFactory());
factoryMap.put("report-entity-0.6", new EntityReporterFactory());
factoryMap.put("report-integrity-0.6", new IntegrityReporterFactory());
factoryMap.put("log-progress-0.6", new EntityProgressLoggerFactory());
factoryMap.put("log-progress-change-0.6", new ChangeProgressLoggerFactory());
factoryMap.put("tee-0.6", new EntityTeeFactory());
factoryMap.put("tee-change-0.6", new ChangeTeeFactory());
factoryMap.put("read-empty-0.6", new EmptyReaderFactory());
factoryMap.put("read-empty-change-0.6", new EmptyChangeReaderFactory());
factoryMap.put("tag-sort-0.6", new TagSorterFactory());
factoryMap.put("tag-sort-change-0.6", new ChangeTagSorterFactory());
factoryMap.put("compute-bounding-box-0.6", new BoundComputerFactory());
factoryMap.put("set-bounding-box-0.6", new BoundSetterFactory());
return factoryMap;
}
| public Map<String, TaskManagerFactory> loadTaskFactories() {
Map<String, TaskManagerFactory> factoryMap;
EntitySorterFactory entitySorterFactory06;
ChangeSorterFactory changeSorterFactory06;
factoryMap = new HashMap<String, TaskManagerFactory>();
// Configure factories that require additional information.
entitySorterFactory06 = new EntitySorterFactory();
entitySorterFactory06.registerComparator("TypeThenId", new EntityContainerComparator(
new EntityByTypeThenIdComparator()), true);
changeSorterFactory06 = new ChangeSorterFactory();
changeSorterFactory06.registerComparator("streamable", new ChangeForStreamableApplierComparator(), true);
changeSorterFactory06.registerComparator("seekable", new ChangeForSeekableApplierComparator(), false);
// Register factories.
factoryMap.put("sort", entitySorterFactory06);
factoryMap.put("s", entitySorterFactory06);
factoryMap.put("sort-change", changeSorterFactory06);
factoryMap.put("sc", changeSorterFactory06);
factoryMap.put("write-null", new NullWriterFactory());
factoryMap.put("wn", new NullWriterFactory());
factoryMap.put("write-null-change", new NullChangeWriterFactory());
factoryMap.put("wnc", new NullChangeWriterFactory());
factoryMap.put("buffer", new EntityBufferFactory());
factoryMap.put("b", new EntityBufferFactory());
factoryMap.put("buffer-change", new ChangeBufferFactory());
factoryMap.put("bc", new ChangeBufferFactory());
factoryMap.put("report-entity", new EntityReporterFactory());
factoryMap.put("re", new EntityReporterFactory());
factoryMap.put("report-integrity", new IntegrityReporterFactory());
factoryMap.put("ri", new IntegrityReporterFactory());
factoryMap.put("log-progress", new EntityProgressLoggerFactory());
factoryMap.put("lp", new EntityProgressLoggerFactory());
factoryMap.put("log-progress-change", new ChangeProgressLoggerFactory());
factoryMap.put("lpc", new ChangeProgressLoggerFactory());
factoryMap.put("tee", new EntityTeeFactory());
factoryMap.put("t", new EntityTeeFactory());
factoryMap.put("tee-change", new ChangeTeeFactory());
factoryMap.put("tc", new ChangeTeeFactory());
factoryMap.put("read-empty", new EmptyReaderFactory());
factoryMap.put("rem", new EmptyReaderFactory());
factoryMap.put("read-empty-change", new EmptyChangeReaderFactory());
factoryMap.put("remc", new EmptyChangeReaderFactory());
factoryMap.put("compute-bounding-box", new BoundComputerFactory());
factoryMap.put("cbb", new BoundComputerFactory());
factoryMap.put("set-bounding-box", new BoundSetterFactory());
factoryMap.put("sbb", new BoundSetterFactory());
factoryMap.put("sort-0.6", entitySorterFactory06);
factoryMap.put("sort-change-0.6", changeSorterFactory06);
factoryMap.put("write-null-0.6", new NullWriterFactory());
factoryMap.put("write-null-change-0.6", new NullChangeWriterFactory());
factoryMap.put("buffer-0.6", new EntityBufferFactory());
factoryMap.put("buffer-change-0.6", new ChangeBufferFactory());
factoryMap.put("report-entity-0.6", new EntityReporterFactory());
factoryMap.put("report-integrity-0.6", new IntegrityReporterFactory());
factoryMap.put("log-progress-0.6", new EntityProgressLoggerFactory());
factoryMap.put("log-progress-change-0.6", new ChangeProgressLoggerFactory());
factoryMap.put("tee-0.6", new EntityTeeFactory());
factoryMap.put("tee-change-0.6", new ChangeTeeFactory());
factoryMap.put("read-empty-0.6", new EmptyReaderFactory());
factoryMap.put("read-empty-change-0.6", new EmptyChangeReaderFactory());
factoryMap.put("tag-sort-0.6", new TagSorterFactory());
factoryMap.put("tag-sort-change-0.6", new ChangeTagSorterFactory());
factoryMap.put("compute-bounding-box-0.6", new BoundComputerFactory());
factoryMap.put("set-bounding-box-0.6", new BoundSetterFactory());
return factoryMap;
}
|
diff --git a/modules/rampart-integration/src/test/java/org/apache/rampart/RampartTest.java b/modules/rampart-integration/src/test/java/org/apache/rampart/RampartTest.java
index d0c4c1e69..8b0b84fb4 100644
--- a/modules/rampart-integration/src/test/java/org/apache/rampart/RampartTest.java
+++ b/modules/rampart-integration/src/test/java/org/apache/rampart/RampartTest.java
@@ -1,226 +1,226 @@
/*
* Copyright 2004,2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.rampart;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axiom.om.impl.builder.StAXOMBuilder;
import org.apache.axis2.Constants;
import org.apache.axis2.AxisFault;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.ConfigurationContextFactory;
import org.apache.axis2.context.ServiceContext;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.integration.UtilServer;
import org.apache.neethi.Policy;
import org.apache.neethi.PolicyEngine;
import org.apache.ws.security.handler.WSHandlerConstants;
import junit.framework.TestCase;
public class RampartTest extends TestCase {
public final static int PORT = UtilServer.TESTING_PORT;
public RampartTest(String name) {
super(name);
}
protected void setUp() throws Exception {
UtilServer.start(Constants.TESTING_PATH + "rampart_service_repo" ,null);
}
protected void tearDown() throws Exception {
UtilServer.stop();
}
public void testWithPolicy() {
try {
String repo = Constants.TESTING_PATH + "rampart_client_repo";
ConfigurationContext configContext = ConfigurationContextFactory.
createConfigurationContextFromFileSystem(repo, null);
ServiceClient serviceClient = new ServiceClient(configContext, null);
serviceClient.engageModule("addressing");
serviceClient.engageModule("rampart");
//TODO : figure this out !!
boolean basic256Supported = true;
if(basic256Supported) {
System.out.println("\nWARNING: We are using key sizes from JCE " +
"Unlimited Strength Jurisdiction Policy !!!");
}
- for (int i = 1; i <= 29; i++) { //<-The number of tests we have
+ for (int i = 1; i <= 30; i++) { //<-The number of tests we have
if(!basic256Supported && (i == 3 || i == 4 || i == 5)) {
//Skip the Basic256 tests
continue;
}
if(i == 25){
// Testcase - 25 is failing, for the moment skipping it.
continue;
}
Options options = new Options();
if( i == 13 ) {
continue; // Can't test Transport binding with Simple HTTP Server
//Username token created with user/pass from options
//options.setUserName("alice");
//options.setPassword("password");
}
System.out.println("Testing WS-Sec: custom scenario " + i);
options.setAction("urn:echo");
options.setTo(new EndpointReference("http://127.0.0.1:" +
PORT +
"/axis2/services/SecureService" + i));
ServiceContext context = serviceClient.getServiceContext();
context.setProperty(RampartMessageData.KEY_RAMPART_POLICY,
loadPolicy("/rampart/policy/" + i + ".xml"));
serviceClient.setOptions(options);
// Invoking the serive in the TestCase-28 should fail. So handling it differently..
if (i == 28) {
try {
//Blocking invocation
serviceClient.sendReceive(getOMElement());
fail("Service Should throw an error..");
} catch (AxisFault axisFault) {
assertEquals("Expected encrypted part missing", axisFault.getMessage());
}
}
else{
//Blocking invocation
serviceClient.sendReceive(getEchoElement());
}
}
System.out.println("--------------Testing negative scenarios----------------------------");
for (int i = 1; i <= 22; i++) {
if (!basic256Supported && (i == 3 || i == 4 || i == 5)) {
//Skip the Basic256 tests
continue;
}
Options options = new Options();
if (i == 13) {
continue;
}
System.out.println("Testing WS-Sec: negative scenario " + i);
options.setAction("urn:returnError");
options.setTo(new EndpointReference("http://127.0.0.1:" +
PORT +
"/axis2/services/SecureService" + i));
ServiceContext context = serviceClient.getServiceContext();
context.setProperty(RampartMessageData.KEY_RAMPART_POLICY,
loadPolicy("/rampart/policy/" + i + ".xml"));
serviceClient.setOptions(options);
try {
//Blocking invocation
serviceClient.sendReceive(getOMElement());
fail("Service Should throw an error..");
} catch (AxisFault axisFault) {
assertEquals("Testing negative scenarios with Apache Rampart. Intentional Exception", axisFault.getMessage());
}
}
for (int i = 1; i <= 3; i++) { //<-The number of tests we have
if (i == 2 || i == 3) {
continue; // Can't test Transport binding scenarios with Simple HTTP Server
}
Options options = new Options();
System.out.println("Testing WS-SecConv: custom scenario " + i);
options.setAction("urn:echo");
options.setTo(new EndpointReference("http://127.0.0.1:" + PORT + "/axis2/services/SecureServiceSC" + i));
serviceClient.getServiceContext().setProperty(RampartMessageData.KEY_RAMPART_POLICY, loadPolicy("/rampart/policy/sc-" + i + ".xml"));
serviceClient.setOptions(options);
//Blocking invocation
serviceClient.sendReceive(getEchoElement());
serviceClient.sendReceive(getEchoElement());
//Cancel the token
options.setProperty(RampartMessageData.CANCEL_REQUEST, Constants.VALUE_TRUE);
serviceClient.sendReceive(getEchoElement());
options.setProperty(RampartMessageData.CANCEL_REQUEST, Constants.VALUE_FALSE);
serviceClient.sendReceive(getEchoElement());
options.setProperty(RampartMessageData.CANCEL_REQUEST, Constants.VALUE_TRUE);
serviceClient.sendReceive(getEchoElement());
}
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
private OMElement getEchoElement() {
OMFactory fac = OMAbstractFactory.getOMFactory();
OMNamespace omNs = fac.createOMNamespace(
"http://example1.org/example1", "example1");
OMElement method = fac.createOMElement("echo", omNs);
OMElement value = fac.createOMElement("Text", omNs);
value.addChild(fac.createOMText(value, "Testing Rampart with WS-SecPolicy"));
method.addChild(value);
return method;
}
private OMElement getOMElement() {
OMFactory fac = OMAbstractFactory.getOMFactory();
OMNamespace omNs = fac.createOMNamespace(
"http://example1.org/example1", "example1");
OMElement method = fac.createOMElement("returnError", omNs);
OMElement value = fac.createOMElement("Text", omNs);
value.addChild(fac.createOMText(value, "Testing Rampart with WS-SecPolicy"));
method.addChild(value);
return method;
}
private Policy loadPolicy(String xmlPath) throws Exception {
StAXOMBuilder builder = new StAXOMBuilder(RampartTest.class.getResourceAsStream(xmlPath));
return PolicyEngine.getPolicy(builder.getDocumentElement());
}
}
| true | true | public void testWithPolicy() {
try {
String repo = Constants.TESTING_PATH + "rampart_client_repo";
ConfigurationContext configContext = ConfigurationContextFactory.
createConfigurationContextFromFileSystem(repo, null);
ServiceClient serviceClient = new ServiceClient(configContext, null);
serviceClient.engageModule("addressing");
serviceClient.engageModule("rampart");
//TODO : figure this out !!
boolean basic256Supported = true;
if(basic256Supported) {
System.out.println("\nWARNING: We are using key sizes from JCE " +
"Unlimited Strength Jurisdiction Policy !!!");
}
for (int i = 1; i <= 29; i++) { //<-The number of tests we have
if(!basic256Supported && (i == 3 || i == 4 || i == 5)) {
//Skip the Basic256 tests
continue;
}
if(i == 25){
// Testcase - 25 is failing, for the moment skipping it.
continue;
}
Options options = new Options();
if( i == 13 ) {
continue; // Can't test Transport binding with Simple HTTP Server
//Username token created with user/pass from options
//options.setUserName("alice");
//options.setPassword("password");
}
System.out.println("Testing WS-Sec: custom scenario " + i);
options.setAction("urn:echo");
options.setTo(new EndpointReference("http://127.0.0.1:" +
PORT +
"/axis2/services/SecureService" + i));
ServiceContext context = serviceClient.getServiceContext();
context.setProperty(RampartMessageData.KEY_RAMPART_POLICY,
loadPolicy("/rampart/policy/" + i + ".xml"));
serviceClient.setOptions(options);
// Invoking the serive in the TestCase-28 should fail. So handling it differently..
if (i == 28) {
try {
//Blocking invocation
serviceClient.sendReceive(getOMElement());
fail("Service Should throw an error..");
} catch (AxisFault axisFault) {
assertEquals("Expected encrypted part missing", axisFault.getMessage());
}
}
else{
//Blocking invocation
serviceClient.sendReceive(getEchoElement());
}
}
System.out.println("--------------Testing negative scenarios----------------------------");
for (int i = 1; i <= 22; i++) {
if (!basic256Supported && (i == 3 || i == 4 || i == 5)) {
//Skip the Basic256 tests
continue;
}
Options options = new Options();
if (i == 13) {
continue;
}
System.out.println("Testing WS-Sec: negative scenario " + i);
options.setAction("urn:returnError");
options.setTo(new EndpointReference("http://127.0.0.1:" +
PORT +
"/axis2/services/SecureService" + i));
ServiceContext context = serviceClient.getServiceContext();
context.setProperty(RampartMessageData.KEY_RAMPART_POLICY,
loadPolicy("/rampart/policy/" + i + ".xml"));
serviceClient.setOptions(options);
try {
//Blocking invocation
serviceClient.sendReceive(getOMElement());
fail("Service Should throw an error..");
} catch (AxisFault axisFault) {
assertEquals("Testing negative scenarios with Apache Rampart. Intentional Exception", axisFault.getMessage());
}
}
for (int i = 1; i <= 3; i++) { //<-The number of tests we have
if (i == 2 || i == 3) {
continue; // Can't test Transport binding scenarios with Simple HTTP Server
}
Options options = new Options();
System.out.println("Testing WS-SecConv: custom scenario " + i);
options.setAction("urn:echo");
options.setTo(new EndpointReference("http://127.0.0.1:" + PORT + "/axis2/services/SecureServiceSC" + i));
serviceClient.getServiceContext().setProperty(RampartMessageData.KEY_RAMPART_POLICY, loadPolicy("/rampart/policy/sc-" + i + ".xml"));
serviceClient.setOptions(options);
//Blocking invocation
serviceClient.sendReceive(getEchoElement());
serviceClient.sendReceive(getEchoElement());
//Cancel the token
options.setProperty(RampartMessageData.CANCEL_REQUEST, Constants.VALUE_TRUE);
serviceClient.sendReceive(getEchoElement());
options.setProperty(RampartMessageData.CANCEL_REQUEST, Constants.VALUE_FALSE);
serviceClient.sendReceive(getEchoElement());
options.setProperty(RampartMessageData.CANCEL_REQUEST, Constants.VALUE_TRUE);
serviceClient.sendReceive(getEchoElement());
}
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
| public void testWithPolicy() {
try {
String repo = Constants.TESTING_PATH + "rampart_client_repo";
ConfigurationContext configContext = ConfigurationContextFactory.
createConfigurationContextFromFileSystem(repo, null);
ServiceClient serviceClient = new ServiceClient(configContext, null);
serviceClient.engageModule("addressing");
serviceClient.engageModule("rampart");
//TODO : figure this out !!
boolean basic256Supported = true;
if(basic256Supported) {
System.out.println("\nWARNING: We are using key sizes from JCE " +
"Unlimited Strength Jurisdiction Policy !!!");
}
for (int i = 1; i <= 30; i++) { //<-The number of tests we have
if(!basic256Supported && (i == 3 || i == 4 || i == 5)) {
//Skip the Basic256 tests
continue;
}
if(i == 25){
// Testcase - 25 is failing, for the moment skipping it.
continue;
}
Options options = new Options();
if( i == 13 ) {
continue; // Can't test Transport binding with Simple HTTP Server
//Username token created with user/pass from options
//options.setUserName("alice");
//options.setPassword("password");
}
System.out.println("Testing WS-Sec: custom scenario " + i);
options.setAction("urn:echo");
options.setTo(new EndpointReference("http://127.0.0.1:" +
PORT +
"/axis2/services/SecureService" + i));
ServiceContext context = serviceClient.getServiceContext();
context.setProperty(RampartMessageData.KEY_RAMPART_POLICY,
loadPolicy("/rampart/policy/" + i + ".xml"));
serviceClient.setOptions(options);
// Invoking the serive in the TestCase-28 should fail. So handling it differently..
if (i == 28) {
try {
//Blocking invocation
serviceClient.sendReceive(getOMElement());
fail("Service Should throw an error..");
} catch (AxisFault axisFault) {
assertEquals("Expected encrypted part missing", axisFault.getMessage());
}
}
else{
//Blocking invocation
serviceClient.sendReceive(getEchoElement());
}
}
System.out.println("--------------Testing negative scenarios----------------------------");
for (int i = 1; i <= 22; i++) {
if (!basic256Supported && (i == 3 || i == 4 || i == 5)) {
//Skip the Basic256 tests
continue;
}
Options options = new Options();
if (i == 13) {
continue;
}
System.out.println("Testing WS-Sec: negative scenario " + i);
options.setAction("urn:returnError");
options.setTo(new EndpointReference("http://127.0.0.1:" +
PORT +
"/axis2/services/SecureService" + i));
ServiceContext context = serviceClient.getServiceContext();
context.setProperty(RampartMessageData.KEY_RAMPART_POLICY,
loadPolicy("/rampart/policy/" + i + ".xml"));
serviceClient.setOptions(options);
try {
//Blocking invocation
serviceClient.sendReceive(getOMElement());
fail("Service Should throw an error..");
} catch (AxisFault axisFault) {
assertEquals("Testing negative scenarios with Apache Rampart. Intentional Exception", axisFault.getMessage());
}
}
for (int i = 1; i <= 3; i++) { //<-The number of tests we have
if (i == 2 || i == 3) {
continue; // Can't test Transport binding scenarios with Simple HTTP Server
}
Options options = new Options();
System.out.println("Testing WS-SecConv: custom scenario " + i);
options.setAction("urn:echo");
options.setTo(new EndpointReference("http://127.0.0.1:" + PORT + "/axis2/services/SecureServiceSC" + i));
serviceClient.getServiceContext().setProperty(RampartMessageData.KEY_RAMPART_POLICY, loadPolicy("/rampart/policy/sc-" + i + ".xml"));
serviceClient.setOptions(options);
//Blocking invocation
serviceClient.sendReceive(getEchoElement());
serviceClient.sendReceive(getEchoElement());
//Cancel the token
options.setProperty(RampartMessageData.CANCEL_REQUEST, Constants.VALUE_TRUE);
serviceClient.sendReceive(getEchoElement());
options.setProperty(RampartMessageData.CANCEL_REQUEST, Constants.VALUE_FALSE);
serviceClient.sendReceive(getEchoElement());
options.setProperty(RampartMessageData.CANCEL_REQUEST, Constants.VALUE_TRUE);
serviceClient.sendReceive(getEchoElement());
}
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
|
diff --git a/htmlunit/src/test/java/com/gargoylesoftware/htmlunit/javascript/SimpleScriptableTest.java b/htmlunit/src/test/java/com/gargoylesoftware/htmlunit/javascript/SimpleScriptableTest.java
index 6f1db8c58..31cd02310 100644
--- a/htmlunit/src/test/java/com/gargoylesoftware/htmlunit/javascript/SimpleScriptableTest.java
+++ b/htmlunit/src/test/java/com/gargoylesoftware/htmlunit/javascript/SimpleScriptableTest.java
@@ -1,254 +1,255 @@
/*
* Copyright (c) 2002-2007 Gargoyle Software Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The end-user documentation included with the redistribution, if any, must
* include the following acknowledgment:
*
* "This product includes software developed by Gargoyle Software Inc.
* (http://www.GargoyleSoftware.com/)."
*
* Alternately, this acknowledgment may appear in the software itself, if
* and wherever such third-party acknowledgments normally appear.
* 4. The name "Gargoyle Software" must not be used to endorse or promote
* products derived from this software without prior written permission.
* For written permission, please contact [email protected].
* 5. Products derived from this software may not be called "HtmlUnit", nor may
* "HtmlUnit" appear in their name, without prior written permission of
* Gargoyle Software Inc.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GARGOYLE
* SOFTWARE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.gargoylesoftware.htmlunit.javascript;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Transformer;
import org.apache.commons.lang.ClassUtils;
import com.gargoylesoftware.htmlunit.CollectingAlertHandler;
import com.gargoylesoftware.htmlunit.MockWebConnection;
import com.gargoylesoftware.htmlunit.ScriptException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebTestCase;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.javascript.configuration.JavaScriptConfiguration;
/**
* Tests for {@link SimpleScriptable}.
*
* @version $Revision$
* @author <a href="mailto:[email protected]">Mike Bowler</a>
* @author <a href="mailto:[email protected]">Barnaby Court</a>
* @author David K. Taylor
* @author <a href="mailto:[email protected]">Ben Curren</a>
* @author Marc Guillemot
* @author Chris Erskine
* @author Ahmed Ashour
*/
public class SimpleScriptableTest extends WebTestCase {
/**
* Create an instance
* @param name The name of the test
*/
public SimpleScriptableTest(final String name) {
super(name);
}
/**
* @throws Exception if the test fails
*/
public void testCallInheritedFunction() throws Exception {
final WebClient client = new WebClient();
final MockWebConnection webConnection = new MockWebConnection(client);
final String content
= "<html><head><title>foo</title><script>"
+ "function doTest() {\n"
+ " document.form1.textfield1.focus();\n"
+ " alert('past focus');\n"
+ "}\n"
+ "</script></head><body onload='doTest()'>"
+ "<p>hello world</p>"
+ "<form name='form1'>"
+ " <input type='text' name='textfield1' id='textfield1' value='foo' />"
+ "</form>"
+ "</body></html>";
webConnection.setDefaultResponse(content);
client.setWebConnection(webConnection);
final List expectedAlerts = Collections.singletonList("past focus");
createTestPageForRealBrowserIfNeeded(content, expectedAlerts);
final List collectedAlerts = new ArrayList();
client.setAlertHandler(new CollectingAlertHandler(collectedAlerts));
final HtmlPage page = (HtmlPage) client.getPage(URL_GARGOYLE);
assertEquals("foo", page.getTitleText());
assertEquals("focus not changed to textfield1",
page.getFormByName("form1").getInputByName("textfield1"),
page.getElementWithFocus());
assertEquals(expectedAlerts, collectedAlerts);
}
/**
*/
public void testHtmlJavaScriptMapping_AllJavaScriptClassesArePresent() {
final Map map = JavaScriptConfiguration.getHtmlJavaScriptMapping();
final String directoryName = "../../../src/main/java/com/gargoylesoftware/htmlunit/javascript/host";
final Set names = getFileNames(directoryName.replace('/', File.separatorChar));
// Now pull out those names that we know don't have html equivalents
names.remove("ActiveXObject");
names.remove("BoxObject");
names.remove("Document");
names.remove("DOMImplementation");
names.remove("DOMParser");
names.remove("Element");
names.remove("Event");
names.remove("EventHandler");
names.remove("EventListenersContainer");
names.remove("FormField");
names.remove("History");
names.remove("JavaScriptBackgroundJob");
names.remove("Location");
names.remove("MouseEvent");
names.remove("Navigator");
names.remove("NodeImpl");
names.remove("Popup");
names.remove("Range");
names.remove("RowContainer");
names.remove("Screen");
names.remove("ScoperFunctionObject");
names.remove("Style");
names.remove("Stylesheet");
names.remove("StyleSheetList");
names.remove("TextRectangle");
names.remove("UIEvent");
names.remove("Window");
names.remove("XMLDocument");
names.remove("XMLDOMParseError");
names.remove("XMLHttpRequest");
names.remove("XMLSerializer");
names.remove("XPathNSResolver");
+ names.remove("XPathResult");
final Transformer class2ShortName = new Transformer() {
public Object transform(final Object obj) {
return ClassUtils.getShortClassName((Class) obj);
}
};
final Collection hostClassNames = new ArrayList(map.values());
CollectionUtils.transform(hostClassNames, class2ShortName);
assertEquals(new TreeSet(names), new TreeSet(hostClassNames));
}
private Set getFileNames(final String directoryName) {
File directory = new File("." + File.separatorChar + directoryName);
if (!directory.exists()) {
directory = new File("./src/main/java/".replace('/', File.separatorChar) + directoryName);
}
assertTrue("directory exists", directory.exists());
assertTrue("is a directory", directory.isDirectory());
final String fileNames[] = directory.list();
final Set collection = new HashSet();
for (int i = 0; i < fileNames.length; i++) {
final String name = fileNames[i];
if (name.endsWith(".java")) {
collection.add(name.substring(0, name.length() - 5));
}
}
return collection;
}
/**
* This test fails on IE and FF but not by HtmlUnit because according to Ecma standard,
* attempts to set read only properties should be silently ignored.
* Furthermore document.body = document.body will work on FF but not on IE
* @throws Exception if the test fails
*/
public void testSetNonWritableProperty() throws Exception {
if (notYetImplemented()) {
return;
}
final String content
= "<html><head><title>foo</title></head><body onload='document.body=123456'>"
+ "</body></html>";
try {
loadPage(content);
fail("Exception should have been thrown");
}
catch (final ScriptException e) {
// it's ok
}
}
/**
* @throws Exception if the test fails
*/
public void testArguments_toString() throws Exception {
if (notYetImplemented()) {
return;
}
final String content = "<html><head><title>foo</title><script>\n"
+ " function test() {\n"
+ " alert(arguments);\n"
+ " }\n"
+ "</script></head><body onload='test()'>\n"
+ "</body></html>";
final String[] expectedAlerts = {"[object Object]"};
final List collectedAlerts = new ArrayList();
loadPage(content, collectedAlerts);
assertEquals(expectedAlerts, collectedAlerts);
}
/**
* @throws Exception if the test fails
*/
public void testStringWithExclamationMark() throws Exception {
if (notYetImplemented()) {
return;
}
final String content = "<html><head><title>foo</title><script>\n"
+ " function test() {\n"
+ " var x = '<!>';\n"
+ " alert(x.length);\n"
+ " }\n"
+ "</script></head><body onload='test()'>\n"
+ "</body></html>";
final String[] expectedAlerts = {"3"};
final List collectedAlerts = new ArrayList();
loadPage(content, collectedAlerts);
assertEquals(expectedAlerts, collectedAlerts);
}
}
| true | true | public void testHtmlJavaScriptMapping_AllJavaScriptClassesArePresent() {
final Map map = JavaScriptConfiguration.getHtmlJavaScriptMapping();
final String directoryName = "../../../src/main/java/com/gargoylesoftware/htmlunit/javascript/host";
final Set names = getFileNames(directoryName.replace('/', File.separatorChar));
// Now pull out those names that we know don't have html equivalents
names.remove("ActiveXObject");
names.remove("BoxObject");
names.remove("Document");
names.remove("DOMImplementation");
names.remove("DOMParser");
names.remove("Element");
names.remove("Event");
names.remove("EventHandler");
names.remove("EventListenersContainer");
names.remove("FormField");
names.remove("History");
names.remove("JavaScriptBackgroundJob");
names.remove("Location");
names.remove("MouseEvent");
names.remove("Navigator");
names.remove("NodeImpl");
names.remove("Popup");
names.remove("Range");
names.remove("RowContainer");
names.remove("Screen");
names.remove("ScoperFunctionObject");
names.remove("Style");
names.remove("Stylesheet");
names.remove("StyleSheetList");
names.remove("TextRectangle");
names.remove("UIEvent");
names.remove("Window");
names.remove("XMLDocument");
names.remove("XMLDOMParseError");
names.remove("XMLHttpRequest");
names.remove("XMLSerializer");
names.remove("XPathNSResolver");
final Transformer class2ShortName = new Transformer() {
public Object transform(final Object obj) {
return ClassUtils.getShortClassName((Class) obj);
}
};
final Collection hostClassNames = new ArrayList(map.values());
CollectionUtils.transform(hostClassNames, class2ShortName);
assertEquals(new TreeSet(names), new TreeSet(hostClassNames));
}
| public void testHtmlJavaScriptMapping_AllJavaScriptClassesArePresent() {
final Map map = JavaScriptConfiguration.getHtmlJavaScriptMapping();
final String directoryName = "../../../src/main/java/com/gargoylesoftware/htmlunit/javascript/host";
final Set names = getFileNames(directoryName.replace('/', File.separatorChar));
// Now pull out those names that we know don't have html equivalents
names.remove("ActiveXObject");
names.remove("BoxObject");
names.remove("Document");
names.remove("DOMImplementation");
names.remove("DOMParser");
names.remove("Element");
names.remove("Event");
names.remove("EventHandler");
names.remove("EventListenersContainer");
names.remove("FormField");
names.remove("History");
names.remove("JavaScriptBackgroundJob");
names.remove("Location");
names.remove("MouseEvent");
names.remove("Navigator");
names.remove("NodeImpl");
names.remove("Popup");
names.remove("Range");
names.remove("RowContainer");
names.remove("Screen");
names.remove("ScoperFunctionObject");
names.remove("Style");
names.remove("Stylesheet");
names.remove("StyleSheetList");
names.remove("TextRectangle");
names.remove("UIEvent");
names.remove("Window");
names.remove("XMLDocument");
names.remove("XMLDOMParseError");
names.remove("XMLHttpRequest");
names.remove("XMLSerializer");
names.remove("XPathNSResolver");
names.remove("XPathResult");
final Transformer class2ShortName = new Transformer() {
public Object transform(final Object obj) {
return ClassUtils.getShortClassName((Class) obj);
}
};
final Collection hostClassNames = new ArrayList(map.values());
CollectionUtils.transform(hostClassNames, class2ShortName);
assertEquals(new TreeSet(names), new TreeSet(hostClassNames));
}
|
diff --git a/drools-core/src/main/java/org/drools/audit/WorkingMemoryLogger.java b/drools-core/src/main/java/org/drools/audit/WorkingMemoryLogger.java
index c274e4265..a2759b890 100644
--- a/drools-core/src/main/java/org/drools/audit/WorkingMemoryLogger.java
+++ b/drools-core/src/main/java/org/drools/audit/WorkingMemoryLogger.java
@@ -1,481 +1,481 @@
package org.drools.audit;
/*
* Copyright 2005 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.drools.WorkingMemoryEventManager;
import org.drools.FactHandle;
import org.drools.WorkingMemory;
import org.drools.audit.event.ActivationLogEvent;
import org.drools.audit.event.ILogEventFilter;
import org.drools.audit.event.LogEvent;
import org.drools.audit.event.ObjectLogEvent;
import org.drools.audit.event.RuleBaseLogEvent;
import org.drools.audit.event.RuleFlowGroupLogEvent;
import org.drools.audit.event.RuleFlowLogEvent;
import org.drools.audit.event.RuleFlowNodeLogEvent;
import org.drools.common.InternalFactHandle;
import org.drools.common.InternalWorkingMemory;
import org.drools.event.ActivationCancelledEvent;
import org.drools.event.ActivationCreatedEvent;
import org.drools.event.AfterActivationFiredEvent;
import org.drools.event.AfterFunctionRemovedEvent;
import org.drools.event.AfterPackageAddedEvent;
import org.drools.event.AfterPackageRemovedEvent;
import org.drools.event.AfterRuleAddedEvent;
import org.drools.event.AfterRuleBaseLockedEvent;
import org.drools.event.AfterRuleBaseUnlockedEvent;
import org.drools.event.AfterRuleRemovedEvent;
import org.drools.event.AgendaEventListener;
import org.drools.event.AgendaGroupPoppedEvent;
import org.drools.event.AgendaGroupPushedEvent;
import org.drools.event.BeforeActivationFiredEvent;
import org.drools.event.BeforeFunctionRemovedEvent;
import org.drools.event.BeforePackageAddedEvent;
import org.drools.event.BeforePackageRemovedEvent;
import org.drools.event.BeforeRuleAddedEvent;
import org.drools.event.BeforeRuleBaseLockedEvent;
import org.drools.event.BeforeRuleBaseUnlockedEvent;
import org.drools.event.BeforeRuleRemovedEvent;
import org.drools.event.ObjectInsertedEvent;
import org.drools.event.ObjectUpdatedEvent;
import org.drools.event.ObjectRetractedEvent;
import org.drools.event.RuleBaseEventListener;
import org.drools.event.RuleFlowCompletedEvent;
import org.drools.event.RuleFlowEventListener;
import org.drools.event.RuleFlowGroupActivatedEvent;
import org.drools.event.RuleFlowGroupDeactivatedEvent;
import org.drools.event.RuleFlowNodeTriggeredEvent;
import org.drools.event.RuleFlowStartedEvent;
import org.drools.event.WorkingMemoryEventListener;
import org.drools.rule.Declaration;
import org.drools.spi.Activation;
import org.drools.spi.Tuple;
/**
* A logger of events generated by a working memory.
* It listens to the events generated by the working memory and
* creates associated log event (containing a snapshot of the
* state of the working event at that time).
*
* Filters can be used to filter out unwanted events.
*
* Subclasses of this class should implement the logEventCreated(LogEvent)
* method and store this information, like for example log to file
* or database.
*
* @author <a href="mailto:[email protected]">Kris Verlaenen </a>
*/
public abstract class WorkingMemoryLogger
implements
WorkingMemoryEventListener,
AgendaEventListener,
RuleFlowEventListener,
RuleBaseEventListener {
private final List filters = new ArrayList();
/**
* Creates a new working memory logger for the given working memory.
*
* @param workingMemory
*/
public WorkingMemoryLogger(final WorkingMemoryEventManager workingMemoryEventManager) {
workingMemoryEventManager.addEventListener( (WorkingMemoryEventListener) this );
workingMemoryEventManager.addEventListener( (AgendaEventListener) this );
workingMemoryEventManager.addEventListener( (RuleFlowEventListener) this );
workingMemoryEventManager.addEventListener( (RuleBaseEventListener) this );
}
/**
* This method is invoked every time a new log event is created.
* Subclasses should implement this method and store the event,
* like for example log to a file or database.
*
* @param logEvent
*/
public abstract void logEventCreated(LogEvent logEvent);
/**
* This method is invoked every time a new log event is created.
* It filters out unwanted events.
*
* @param logEvent
*/
private void filterLogEvent(final LogEvent logEvent) {
final Iterator iterator = this.filters.iterator();
while ( iterator.hasNext() ) {
final ILogEventFilter filter = (ILogEventFilter) iterator.next();
// do nothing if one of the filters doesn't accept the event
if ( !filter.acceptEvent( logEvent ) ) {
return;
}
}
// if all the filters accepted the event, signal the creation
// of the event
logEventCreated( logEvent );
}
/**
* Adds the given filter to the list of filters for this event log.
* A log event must be accepted by all the filters to be entered in
* the event log.
*
* @param filter The filter that should be added.
*/
public void addFilter(final ILogEventFilter filter) {
if ( filter == null ) {
throw new NullPointerException();
}
this.filters.add( filter );
}
/**
* Removes the given filter from the list of filters for this event log.
* If the given filter was not a filter of this event log, nothing
* happens.
*
* @param filter The filter that should be removed.
*/
public void removeFilter(final ILogEventFilter filter) {
this.filters.remove( filter );
}
/**
* Clears all filters of this event log.
*/
public void clearFilters() {
this.filters.clear();
}
/**
* @see org.drools.event.WorkingMemoryEventListener
*/
public void objectInserted(final ObjectInsertedEvent event) {
filterLogEvent( new ObjectLogEvent( LogEvent.INSERTED,
((InternalFactHandle) event.getFactHandle()).getId(),
event.getObject().toString() ) );
}
/**
* @see org.drools.event.WorkingMemoryEventListener
*/
public void objectUpdated(final ObjectUpdatedEvent event) {
filterLogEvent( new ObjectLogEvent( LogEvent.UPDATED,
((InternalFactHandle) event.getFactHandle()).getId(),
event.getObject().toString() ) );
}
/**
* @see org.drools.event.WorkingMemoryEventListener
*/
public void objectRetracted(final ObjectRetractedEvent event) {
filterLogEvent( new ObjectLogEvent( LogEvent.RETRACTED,
((InternalFactHandle) event.getFactHandle()).getId(),
event.getOldObject().toString() ) );
}
/**
* @see org.drools.event.AgendaEventListener
*/
public void activationCreated(final ActivationCreatedEvent event,
final WorkingMemory workingMemory) {
filterLogEvent( new ActivationLogEvent( LogEvent.ACTIVATION_CREATED,
getActivationId( event.getActivation() ),
event.getActivation().getRule().getName(),
extractDeclarations( event.getActivation(), workingMemory ),
event.getActivation().getRule().getRuleFlowGroup() ) );
}
/**
* @see org.drools.event.AgendaEventListener
*/
public void activationCancelled(final ActivationCancelledEvent event,
final WorkingMemory workingMemory) {
filterLogEvent( new ActivationLogEvent( LogEvent.ACTIVATION_CANCELLED,
getActivationId( event.getActivation() ),
event.getActivation().getRule().getName(),
extractDeclarations( event.getActivation(), workingMemory ),
event.getActivation().getRule().getRuleFlowGroup() ) );
}
/**
* @see org.drools.event.AgendaEventListener
*/
public void beforeActivationFired(final BeforeActivationFiredEvent event,
final WorkingMemory workingMemory) {
filterLogEvent( new ActivationLogEvent( LogEvent.BEFORE_ACTIVATION_FIRE,
getActivationId( event.getActivation() ),
event.getActivation().getRule().getName(),
extractDeclarations( event.getActivation(), workingMemory ),
event.getActivation().getRule().getRuleFlowGroup() ) );
}
/**
* @see org.drools.event.AgendaEventListener
*/
public void afterActivationFired(final AfterActivationFiredEvent event,
final WorkingMemory workingMemory) {
filterLogEvent( new ActivationLogEvent( LogEvent.AFTER_ACTIVATION_FIRE,
getActivationId( event.getActivation() ),
event.getActivation().getRule().getName(),
extractDeclarations( event.getActivation(), workingMemory ),
event.getActivation().getRule().getRuleFlowGroup() ) );
}
/**
* Creates a string representation of the declarations of an activation.
* This is a list of name-value-pairs for each of the declarations in the
* tuple of the activation. The name is the identifier (=name) of the
* declaration, and the value is a toString of the value of the
* parameter, followed by the id of the fact between parentheses.
*
* @param activation The activation from which the declarations should be extracted
* @return A String represetation of the declarations of the activation.
*/
private String extractDeclarations(final Activation activation, final WorkingMemory workingMemory) {
final StringBuffer result = new StringBuffer();
final Tuple tuple = activation.getTuple();
final Map declarations = activation.getSubRule().getOuterDeclarations();
for ( Iterator it = declarations.values().iterator(); it.hasNext(); ) {
final Declaration declaration = (Declaration) it.next();
final FactHandle handle = tuple.get( declaration );
if ( handle instanceof InternalFactHandle ) {
final InternalFactHandle handleImpl = (InternalFactHandle) handle;
if ( handleImpl.getId() == -1 ) {
// This handle is now invalid, probably due to an fact retraction
continue;
}
- final Object value = declaration.getValue( (InternalWorkingMemory) workingMemory, workingMemory.getObject( handle ) );
+ final Object value = declaration.getValue( (InternalWorkingMemory) workingMemory, handleImpl.getObject() );
result.append( declaration.getIdentifier() );
result.append( "=" );
if ( value == null ) {
// this should never occur
result.append( "null" );
} else {
result.append( value );
result.append( "(" );
result.append( handleImpl.getId() );
result.append( ")" );
}
}
if ( it.hasNext() ) {
result.append( "; " );
}
}
return result.toString();
}
/**
* Returns a String that can be used as unique identifier for an
* activation. Since the activationId is the same for all assertions
* that are created during a single insert, update or retract, the
* key of the tuple of the activation is added too (which is a set
* of fact handle ids).
*
* @param activation The activation for which a unique id should be generated
* @return A unique id for the activation
*/
private static String getActivationId(final Activation activation) {
final StringBuffer result = new StringBuffer( activation.getRule().getName() );
result.append( " [" );
final Tuple tuple = activation.getTuple();
final FactHandle[] handles = tuple.getFactHandles();
for ( int i = 0; i < handles.length; i++ ) {
result.append( ((InternalFactHandle) handles[i]).getId() );
if ( i < handles.length - 1 ) {
result.append( ", " );
}
}
return result.append( "]" ).toString();
}
public void agendaGroupPopped(final AgendaGroupPoppedEvent event,
final WorkingMemory workingMemory) {
// we don't audit this yet
}
public void agendaGroupPushed(final AgendaGroupPushedEvent event,
final WorkingMemory workingMemory) {
// we don't audit this yet
}
public void beforeRuleFlowStarted(RuleFlowStartedEvent event,
WorkingMemory workingMemory) {
filterLogEvent( new RuleFlowLogEvent( LogEvent.BEFORE_RULEFLOW_CREATED,
event.getRuleFlowProcessInstance().getProcess().getId(),
event.getRuleFlowProcessInstance().getProcess().getName() ) );
}
public void afterRuleFlowStarted(RuleFlowStartedEvent event,
WorkingMemory workingMemory) {
filterLogEvent(new RuleFlowLogEvent(LogEvent.AFTER_RULEFLOW_CREATED,
event.getRuleFlowProcessInstance().getProcess().getId(),
event.getRuleFlowProcessInstance().getProcess().getName()));
}
public void beforeRuleFlowCompleted(RuleFlowCompletedEvent event,
WorkingMemory workingMemory) {
filterLogEvent( new RuleFlowLogEvent( LogEvent.BEFORE_RULEFLOW_COMPLETED,
event.getRuleFlowProcessInstance().getProcess().getId(),
event.getRuleFlowProcessInstance().getProcess().getName() ) );
}
public void afterRuleFlowCompleted(RuleFlowCompletedEvent event,
WorkingMemory workingMemory) {
filterLogEvent(new RuleFlowLogEvent(LogEvent.AFTER_RULEFLOW_COMPLETED,
event.getRuleFlowProcessInstance().getProcess().getId(),
event.getRuleFlowProcessInstance().getProcess().getName()));
}
public void beforeRuleFlowGroupActivated(
RuleFlowGroupActivatedEvent event,
WorkingMemory workingMemory) {
filterLogEvent(new RuleFlowGroupLogEvent(
LogEvent.BEFORE_RULEFLOW_GROUP_ACTIVATED, event
.getRuleFlowGroup().getName(), event.getRuleFlowGroup()
.size()));
}
public void afterRuleFlowGroupActivated(
RuleFlowGroupActivatedEvent event,
WorkingMemory workingMemory) {
filterLogEvent(new RuleFlowGroupLogEvent(
LogEvent.AFTER_RULEFLOW_GROUP_ACTIVATED,
event.getRuleFlowGroup().getName(),
event.getRuleFlowGroup().size()));
}
public void beforeRuleFlowGroupDeactivated(
RuleFlowGroupDeactivatedEvent event,
WorkingMemory workingMemory) {
filterLogEvent(new RuleFlowGroupLogEvent(
LogEvent.BEFORE_RULEFLOW_GROUP_DEACTIVATED,
event.getRuleFlowGroup().getName(),
event.getRuleFlowGroup().size()));
}
public void afterRuleFlowGroupDeactivated(
RuleFlowGroupDeactivatedEvent event,
WorkingMemory workingMemory) {
filterLogEvent(new RuleFlowGroupLogEvent(
LogEvent.AFTER_RULEFLOW_GROUP_DEACTIVATED,
event.getRuleFlowGroup().getName(),
event.getRuleFlowGroup().size()));
}
public void beforeRuleFlowNodeTriggered(RuleFlowNodeTriggeredEvent event,
WorkingMemory workingMemory) {
filterLogEvent(new RuleFlowNodeLogEvent(LogEvent.BEFORE_RULEFLOW_NODE_TRIGGERED,
event.getRuleFlowNodeInstance().getId() + "",
event.getRuleFlowNodeInstance().getNode().getName(),
event.getRuleFlowProcessInstance().getProcess().getId(), event
.getRuleFlowProcessInstance().getProcess().getName()));
}
public void afterRuleFlowNodeTriggered(RuleFlowNodeTriggeredEvent event,
WorkingMemory workingMemory) {
filterLogEvent(new RuleFlowNodeLogEvent(LogEvent.AFTER_RULEFLOW_NODE_TRIGGERED,
event.getRuleFlowNodeInstance().getId() + "",
event.getRuleFlowNodeInstance().getNode().getName(),
event.getRuleFlowProcessInstance().getProcess().getId(), event
.getRuleFlowProcessInstance().getProcess().getName()));
}
public void afterPackageAdded(AfterPackageAddedEvent event) {
filterLogEvent( new RuleBaseLogEvent( LogEvent.AFTER_PACKAGE_ADDED,
event.getPackage().getName(),
null ) );
}
public void afterPackageRemoved(AfterPackageRemovedEvent event) {
filterLogEvent( new RuleBaseLogEvent( LogEvent.AFTER_PACKAGE_REMOVED,
event.getPackage().getName(),
null ) );
}
public void afterRuleAdded(AfterRuleAddedEvent event) {
filterLogEvent( new RuleBaseLogEvent( LogEvent.AFTER_RULE_ADDED,
event.getPackage().getName(),
event.getRule().getName() ) );
}
public void afterRuleRemoved(AfterRuleRemovedEvent event) {
filterLogEvent( new RuleBaseLogEvent( LogEvent.AFTER_RULE_REMOVED,
event.getPackage().getName(),
event.getRule().getName() ) );
}
public void beforePackageAdded(BeforePackageAddedEvent event) {
filterLogEvent( new RuleBaseLogEvent( LogEvent.BEFORE_PACKAGE_ADDED,
event.getPackage().getName(),
null ) );
}
public void beforePackageRemoved(BeforePackageRemovedEvent event) {
filterLogEvent( new RuleBaseLogEvent( LogEvent.BEFORE_PACKAGE_REMOVED,
event.getPackage().getName(),
null ) );
}
public void beforeRuleAdded(BeforeRuleAddedEvent event) {
filterLogEvent( new RuleBaseLogEvent( LogEvent.BEFORE_RULE_ADDED,
event.getPackage().getName(),
event.getRule().getName() ) );
}
public void beforeRuleRemoved(BeforeRuleRemovedEvent event) {
filterLogEvent( new RuleBaseLogEvent( LogEvent.BEFORE_RULE_REMOVED,
event.getPackage().getName(),
event.getRule().getName() ) );
}
public void afterFunctionRemoved(AfterFunctionRemovedEvent event) {
// TODO Auto-generated method stub
}
public void afterRuleBaseLocked(AfterRuleBaseLockedEvent event) {
// TODO Auto-generated method stub
}
public void afterRuleBaseUnlocked(AfterRuleBaseUnlockedEvent event) {
// TODO Auto-generated method stub
}
public void beforeFunctionRemoved(BeforeFunctionRemovedEvent event) {
// TODO Auto-generated method stub
}
public void beforeRuleBaseLocked(BeforeRuleBaseLockedEvent event) {
// TODO Auto-generated method stub
}
public void beforeRuleBaseUnlocked(BeforeRuleBaseUnlockedEvent event) {
// TODO Auto-generated method stub
}
}
| true | true | private String extractDeclarations(final Activation activation, final WorkingMemory workingMemory) {
final StringBuffer result = new StringBuffer();
final Tuple tuple = activation.getTuple();
final Map declarations = activation.getSubRule().getOuterDeclarations();
for ( Iterator it = declarations.values().iterator(); it.hasNext(); ) {
final Declaration declaration = (Declaration) it.next();
final FactHandle handle = tuple.get( declaration );
if ( handle instanceof InternalFactHandle ) {
final InternalFactHandle handleImpl = (InternalFactHandle) handle;
if ( handleImpl.getId() == -1 ) {
// This handle is now invalid, probably due to an fact retraction
continue;
}
final Object value = declaration.getValue( (InternalWorkingMemory) workingMemory, workingMemory.getObject( handle ) );
result.append( declaration.getIdentifier() );
result.append( "=" );
if ( value == null ) {
// this should never occur
result.append( "null" );
} else {
result.append( value );
result.append( "(" );
result.append( handleImpl.getId() );
result.append( ")" );
}
}
if ( it.hasNext() ) {
result.append( "; " );
}
}
return result.toString();
}
| private String extractDeclarations(final Activation activation, final WorkingMemory workingMemory) {
final StringBuffer result = new StringBuffer();
final Tuple tuple = activation.getTuple();
final Map declarations = activation.getSubRule().getOuterDeclarations();
for ( Iterator it = declarations.values().iterator(); it.hasNext(); ) {
final Declaration declaration = (Declaration) it.next();
final FactHandle handle = tuple.get( declaration );
if ( handle instanceof InternalFactHandle ) {
final InternalFactHandle handleImpl = (InternalFactHandle) handle;
if ( handleImpl.getId() == -1 ) {
// This handle is now invalid, probably due to an fact retraction
continue;
}
final Object value = declaration.getValue( (InternalWorkingMemory) workingMemory, handleImpl.getObject() );
result.append( declaration.getIdentifier() );
result.append( "=" );
if ( value == null ) {
// this should never occur
result.append( "null" );
} else {
result.append( value );
result.append( "(" );
result.append( handleImpl.getId() );
result.append( ")" );
}
}
if ( it.hasNext() ) {
result.append( "; " );
}
}
return result.toString();
}
|
diff --git a/pax-url-dir/src/main/java/org/ops4j/pax/url/dir/internal/bundle/ResourceLocatorImpl.java b/pax-url-dir/src/main/java/org/ops4j/pax/url/dir/internal/bundle/ResourceLocatorImpl.java
index 9dd62723..8cb94caa 100644
--- a/pax-url-dir/src/main/java/org/ops4j/pax/url/dir/internal/bundle/ResourceLocatorImpl.java
+++ b/pax-url-dir/src/main/java/org/ops4j/pax/url/dir/internal/bundle/ResourceLocatorImpl.java
@@ -1,193 +1,195 @@
/*
* Copyright 2008 Toni Menzel.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ops4j.pax.url.dir.internal.bundle;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.ops4j.io.StreamUtils;
import org.ops4j.lang.NullArgumentException;
import org.ops4j.pax.url.dir.internal.ResourceLocator;
/**
* Finds resources of the current module under test just by given top-level parent (whatever that is)
* and name of the class under test using a narrowing approach.
*
* @author Toni Menzel (tonit)
* @since May 30, 2008
*/
public class ResourceLocatorImpl
implements ResourceLocator
{
public static final Log logger = LogFactory.getLog( ResourceLocatorImpl.class );
private File m_topLevelDir;
private String m_anchor;
private File m_root;
public ResourceLocatorImpl( File topLevelDir, String anchor )
throws IOException
{
NullArgumentException.validateNotNull( topLevelDir, "topLevelDir" );
if( !topLevelDir.exists() || !topLevelDir.canRead() || !topLevelDir.isDirectory() )
{
throw new IllegalArgumentException(
"topLevelDir " + topLevelDir.getAbsolutePath() + " is not a readable folder"
);
}
m_topLevelDir = topLevelDir;
m_anchor = anchor;
m_root = findRoot( m_topLevelDir, m_anchor );
}
public ResourceLocatorImpl( String targetClassName )
throws IOException
{
this( new File( "." ), targetClassName );
}
protected File findRoot( File dir, String targetClassName )
throws IOException
{
if( m_anchor == null )
{
return dir;
}
for( File f : dir.listFiles() )
{
if( !f.isHidden() && f.isDirectory() )
{
File r = findRoot( f, targetClassName );
if( r != null )
{
return r;
}
}
- else if( !f.isHidden() && f.getCanonicalPath().endsWith( targetClassName ) )
- {
+ else if( !f.isHidden()) {
+ String p = f.getCanonicalPath().replaceAll( "\\\\","/" );
+ if (p.endsWith( targetClassName ) ) {
return new File(
f.getCanonicalPath().substring( 0, f.getCanonicalPath().length() - targetClassName.length() )
);
}
+ }
}
// nothing found / must be wrong topevel dir
return null;
}
/**
* This locates the top level resource folders for the current component
*
* @param target to write to
*/
public void write( JarOutputStream target )
throws IOException
{
NullArgumentException.validateNotNull( target, "target" );
// determine the real base
//String anchorfile =(String) m_anchor.get(""); //m_targetClassName.replace( '.', File.separatorChar ) + ".class";
findClasspathResources( target, m_root, m_root );
if( m_root != null )
{
// convention: use mvn naming conventions to locate the other resource folders
// File pureClasses = new File( m_root.getParentFile().getCanonicalPath() + "/classes/" );
// findClasspathResources( target, pureClasses, pureClasses );
}
else
{
throw new IllegalArgumentException(
"Anchor " + m_anchor + " (which must be a file located under (" + m_topLevelDir.getAbsolutePath()
+ ") has not been found!"
);
}
}
private void findClasspathResources( JarOutputStream target, File dir, File base )
throws IOException
{
if( dir != null && dir.canRead() && dir.isDirectory() )
{
for( File f : dir.listFiles() )
{
if( f.isDirectory() )
{
findClasspathResources( target, f, base );
}
else if( !f.isHidden() )
{
writeToTarget( target, f, base );
//repo.add(f);
}
}
}
}
public File getRoot()
{
return m_root;
}
private void writeToTarget( JarOutputStream target, File f, File base )
throws IOException
{
String name =
f.getCanonicalPath().substring( base.getCanonicalPath().length() + 1 ).replace( File.separatorChar, '/' );
if( name.equals( "META-INF/MANIFEST.MF" ) )
{
throw new RuntimeException( "You have specified a " + name
+ " in your probe bundle. Please make sure that you don't have it in your project's target folder. Otherwise it would lead to false assumptions and unexpected results."
);
}
FileInputStream fis = new FileInputStream( f );
try
{
write( name, fis, target );
} finally
{
fis.close();
}
}
void write( String name, InputStream fileIn, JarOutputStream target )
throws IOException
{
target.putNextEntry( new JarEntry( name ) );
StreamUtils.copyStream( fileIn, target, false );
}
@Override
public String toString()
{
return "ResourceLocatorImpl{" +
"m_topLevelDir=" + m_topLevelDir +
", m_anchor=" + m_anchor +
'}';
}
}
| false | true | protected File findRoot( File dir, String targetClassName )
throws IOException
{
if( m_anchor == null )
{
return dir;
}
for( File f : dir.listFiles() )
{
if( !f.isHidden() && f.isDirectory() )
{
File r = findRoot( f, targetClassName );
if( r != null )
{
return r;
}
}
else if( !f.isHidden() && f.getCanonicalPath().endsWith( targetClassName ) )
{
return new File(
f.getCanonicalPath().substring( 0, f.getCanonicalPath().length() - targetClassName.length() )
);
}
}
// nothing found / must be wrong topevel dir
return null;
}
| protected File findRoot( File dir, String targetClassName )
throws IOException
{
if( m_anchor == null )
{
return dir;
}
for( File f : dir.listFiles() )
{
if( !f.isHidden() && f.isDirectory() )
{
File r = findRoot( f, targetClassName );
if( r != null )
{
return r;
}
}
else if( !f.isHidden()) {
String p = f.getCanonicalPath().replaceAll( "\\\\","/" );
if (p.endsWith( targetClassName ) ) {
return new File(
f.getCanonicalPath().substring( 0, f.getCanonicalPath().length() - targetClassName.length() )
);
}
}
}
// nothing found / must be wrong topevel dir
return null;
}
|
diff --git a/BlueMesh/src/blue/mesh/ClientThread.java b/BlueMesh/src/blue/mesh/ClientThread.java
index 3cb2c02..4c28af8 100644
--- a/BlueMesh/src/blue/mesh/ClientThread.java
+++ b/BlueMesh/src/blue/mesh/ClientThread.java
@@ -1,89 +1,92 @@
package blue.mesh;
import java.io.IOException;
import java.util.Set;
import java.util.UUID;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.util.Log;
public class ClientThread extends BluetoothConnectionThread {
private static final String TAG = "ClientThread";
private BluetoothAdapter adapter;
private RouterObject router;
private UUID uuid;
private BluetoothSocket clientSocket = null;
protected ClientThread(BluetoothAdapter mAdapter, RouterObject mRouter,
UUID a_uuid) {
uuid = a_uuid;
adapter = mAdapter;
router = mRouter;
}
// function run gets list of paired devices, and attempts to
// open and connect a socket for that device, which is then
// passed to the router object
public void run() {
while (!this.isInterrupted()) {
// get list of all paired devices
Set<BluetoothDevice> pairedDevices = adapter.getBondedDevices();
Log.d(TAG, "isInterrupted() == " + this.isInterrupted());
// Loop through paired devices and attempt to connect
for (BluetoothDevice d : pairedDevices) {
Log.d(TAG, "Trying to connect to " + d.getName());
clientSocket = null;
try {
if (router.getDeviceState(d) == Constants.STATE_CONNECTED)
continue;
clientSocket = d.createRfcommSocketToServiceRecord(uuid);
}
catch (IOException e) {
Log.e(TAG, "Socket create() failed", e);
// TODO: throw exception
return;
}
// once a socket is opened, try to connect and then pass to
// router
try {
clientSocket.connect();
Connection bluetoothConnection = new AndroidBluetoothConnection( clientSocket );
Log.d(TAG,
"Connection Created, calling router.beginConnection()");
router.beginConnection(bluetoothConnection);
}
catch (IOException e) {
Log.e(TAG, "Connection constructor failed", e);
+ if( this.isInterrupted() ){
+ return;
+ }
// TODO: throw exception
}
}
}
Log.d(TAG, "Thread interrupted");
return;
}
protected int kill() {
this.interrupt();
try {
this.clientSocket.close();
} catch (IOException e) {
Log.e(TAG, "Could not close socket", e);
}
// TODO: this thread does not get interrupted correctly
Log.d(TAG, "kill success");
return Constants.SUCCESS;
}
};
| true | true | public void run() {
while (!this.isInterrupted()) {
// get list of all paired devices
Set<BluetoothDevice> pairedDevices = adapter.getBondedDevices();
Log.d(TAG, "isInterrupted() == " + this.isInterrupted());
// Loop through paired devices and attempt to connect
for (BluetoothDevice d : pairedDevices) {
Log.d(TAG, "Trying to connect to " + d.getName());
clientSocket = null;
try {
if (router.getDeviceState(d) == Constants.STATE_CONNECTED)
continue;
clientSocket = d.createRfcommSocketToServiceRecord(uuid);
}
catch (IOException e) {
Log.e(TAG, "Socket create() failed", e);
// TODO: throw exception
return;
}
// once a socket is opened, try to connect and then pass to
// router
try {
clientSocket.connect();
Connection bluetoothConnection = new AndroidBluetoothConnection( clientSocket );
Log.d(TAG,
"Connection Created, calling router.beginConnection()");
router.beginConnection(bluetoothConnection);
}
catch (IOException e) {
Log.e(TAG, "Connection constructor failed", e);
// TODO: throw exception
}
}
}
Log.d(TAG, "Thread interrupted");
return;
}
| public void run() {
while (!this.isInterrupted()) {
// get list of all paired devices
Set<BluetoothDevice> pairedDevices = adapter.getBondedDevices();
Log.d(TAG, "isInterrupted() == " + this.isInterrupted());
// Loop through paired devices and attempt to connect
for (BluetoothDevice d : pairedDevices) {
Log.d(TAG, "Trying to connect to " + d.getName());
clientSocket = null;
try {
if (router.getDeviceState(d) == Constants.STATE_CONNECTED)
continue;
clientSocket = d.createRfcommSocketToServiceRecord(uuid);
}
catch (IOException e) {
Log.e(TAG, "Socket create() failed", e);
// TODO: throw exception
return;
}
// once a socket is opened, try to connect and then pass to
// router
try {
clientSocket.connect();
Connection bluetoothConnection = new AndroidBluetoothConnection( clientSocket );
Log.d(TAG,
"Connection Created, calling router.beginConnection()");
router.beginConnection(bluetoothConnection);
}
catch (IOException e) {
Log.e(TAG, "Connection constructor failed", e);
if( this.isInterrupted() ){
return;
}
// TODO: throw exception
}
}
}
Log.d(TAG, "Thread interrupted");
return;
}
|
diff --git a/NotePad/src/org/openintents/notepad/noteslist/NotesListCursor.java b/NotePad/src/org/openintents/notepad/noteslist/NotesListCursor.java
index 470cad4a..ad3b4833 100644
--- a/NotePad/src/org/openintents/notepad/noteslist/NotesListCursor.java
+++ b/NotePad/src/org/openintents/notepad/noteslist/NotesListCursor.java
@@ -1,308 +1,310 @@
package org.openintents.notepad.noteslist;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import org.openintents.notepad.R;
import org.openintents.notepad.NotePad.Notes;
import org.openintents.notepad.util.OpenMatrixCursor;
import android.content.Context;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
public class NotesListCursor extends OpenMatrixCursor {
private static final String TAG = "NotesListCursorUtils";
static final String TITLE_DECRYPTED = "title_decrypted";
static final String TAGS_DECRYPTED = "tags_decrypted";
/**
* The columns we are interested in from the database
*/
protected static final String[] PROJECTION_DB = new String[] {
Notes._ID, // 0
Notes.TITLE, // 1
Notes.TAGS, // 2
Notes.ENCRYPTED // 3
};
/**
* This cursors' columns
*/
protected static final String[] PROJECTION = new String[] {
Notes._ID, // 0
Notes.TITLE, // 1
Notes.TAGS, // 2
Notes.ENCRYPTED, // 3
TITLE_DECRYPTED, // 4
TAGS_DECRYPTED // 5
};
protected static final int COLUMN_INDEX_ID = 0;
/** The index of the title column */
protected static final int COLUMN_INDEX_TITLE = 1;
protected static final int COLUMN_INDEX_TAGS = 2;
protected static final int COLUMN_INDEX_ENCRYPTED = 3;
/** Contains the encrypted title if it has not been decrypted yet */
protected static final int COLUMN_INDEX_TITLE_ENCRYPTED = 4;
protected static final int COLUMN_INDEX_TAGS_ENCRYPTED = 5;
static boolean mLoggedIn = true;
Context mContext;
Intent mIntent;
//OpenMatrixCursor mCursor;
/**
* A database cursor that corresponds to the encrypted data of
* the current cursor (that contains also decrypted information).
*/
Cursor mDbCursor;
public String mCurrentFilter;
/**
* Map encrypted titles to decrypted ones.
*/
public static HashMap<String,String> mEncryptedStringHashMap = new HashMap<String,String>();
/**
* List containing all encrypted strings. These are decrypted one at a time while idle.
* The list is synchronized because background threads may add items to it.
*/
public static List<String> mEncryptedStringList = Collections.synchronizedList(new LinkedList<String>());
public NotesListCursor(Context context, Intent intent) {
super(PROJECTION);
mContext = context;
mIntent = intent;
mCurrentFilter = null;
}
// TODO: Replace new Handler() by mHandler from NotesList somehow.
ContentObserver mContentObserver = new ContentObserver(new Handler()) {
@Override
public boolean deliverSelfNotifications() {
return super.deliverSelfNotifications();
}
@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
Log.i(TAG, "NoteListCursor changed" + selfChange);
requery();
}
};
@Override
public boolean requery() {
runQuery(mCurrentFilter);
return super.requery();
}
/**
* Return a new cursor with decrypted information.
*
* @param constraint
*/
public Cursor query(CharSequence constraint) {
NotesListCursor cursor = new NotesListCursor(mContext, mIntent);
cursor.runQuery(constraint);
return cursor;
}
/**
* Return a query with decrypted information on the current cursor.
*
* @param constraint
*/
private void runQuery(CharSequence constraint) {
// We have to query all items and return a new object, because notes may be encrypted.
if (constraint != null) {
mCurrentFilter = constraint.toString();
} else {
mCurrentFilter = null;
}
if (mDbCursor != null) {
mDbCursor.unregisterContentObserver(mContentObserver);
mDbCursor.close();
mDbCursor = null;
}
mDbCursor = mContext.getContentResolver().query(mIntent.getData(), PROJECTION_DB,
null, null, Notes.DEFAULT_SORT_ORDER);
// Register content observer
mDbCursor.registerContentObserver(mContentObserver);
Log.i(TAG, "Cursor count: " + mDbCursor.getCount());
//mCursor = new OpenMatrixCursor(PROJECTION, dbcursor.getCount());
reset();
String encryptedlabel = mContext.getString(R.string.encrypted);
mDbCursor.moveToPosition(-1);
while (mDbCursor.moveToNext()) {
long id = mDbCursor.getLong(COLUMN_INDEX_ID);
String title = mDbCursor.getString(COLUMN_INDEX_TITLE);
String tags = mDbCursor.getString(COLUMN_INDEX_TAGS);
long encrypted = mDbCursor.getLong(COLUMN_INDEX_ENCRYPTED);
String titleEncrypted = null;
String tagsEncrypted = null;
// Skip encrypted notes in filter.
boolean skipEncrypted = false;
if (encrypted > 0) {
// get decrypted title:
String titleDecrypted = mEncryptedStringHashMap.get(title);
if (titleDecrypted != null) {
title = titleDecrypted;
} else {
// decrypt later
addForEncryption(title);
// Set encrypt title
titleEncrypted = title;
title = encryptedlabel;
skipEncrypted = true;
}
if (tags != null) {
String tagsDecrypted = mEncryptedStringHashMap.get(tags);
if (tagsDecrypted != null) {
tags = tagsDecrypted;
} else {
// decrypt later
addForEncryption(tags);
// Set encrypt title
tagsEncrypted = tags;
tags = "";
}
}
if (!mLoggedIn) {
// suppress all decrypted output
title = encryptedlabel;
tags = "";
}
}
boolean addrow = false;
if (TextUtils.isEmpty(mCurrentFilter)) {
// Add all rows if there is no filter.
addrow = true;
} else if (skipEncrypted) {
addrow = false;
} else {
// test the filter
// Build search string from title and tags.
String searchstring = null;
if (!TextUtils.isEmpty(mCurrentFilter)) {
StringBuilder sb = new StringBuilder();
sb.append(" ");
sb.append(title.toUpperCase());
- sb.append(" ");
- String spacetags = tags.replace(",", " ");
- sb.append(spacetags.toUpperCase());
+ if (!TextUtils.isEmpty(tags)) {
+ sb.append(" ");
+ String spacetags = tags.replace(",", " ");
+ sb.append(spacetags.toUpperCase());
+ }
searchstring = sb.toString();
}
// apply filter:
addrow = searchstring.contains(" " + mCurrentFilter.toUpperCase());
}
if (addrow) {
if (tags == null) {
tags = "";
}
Object[] row = new Object[] {id, title, tags, encrypted, titleEncrypted, tagsEncrypted};
addRow(row);
}
}
}
public static void flushDecryptedStringHashMap() {
mEncryptedStringHashMap = new HashMap<String,String>();
mLoggedIn = false;
}
public static void addForEncryption(String encryptedString) {
// Check whether it does not already exist:
if (!mEncryptedStringList.contains(encryptedString)) {
mEncryptedStringList.add(encryptedString);
}
}
public static String getNextEncryptedString() {
if (!NotesListCursor.mEncryptedStringList.isEmpty()) {
String encryptedString = NotesListCursor.mEncryptedStringList.remove(0);
return encryptedString;
} else {
return null;
}
}
@Override
public void close() {
Log.i(TAG, "Close NotesListCursor");
super.close();
}
@Override
public void deactivate() {
Log.i(TAG, "Deactivate NotesListCursor");
if (mDbCursor != null) {
mDbCursor.deactivate();
}
super.deactivate();
}
@Override
protected void finalize() {
Log.i(TAG, "Finalize NotesListCursor");
if (mDbCursor != null) {
mDbCursor.unregisterContentObserver(mContentObserver);
//mDbCursor.close();
mDbCursor.deactivate();
mDbCursor = null;
}
super.finalize();
}
}
| true | true | private void runQuery(CharSequence constraint) {
// We have to query all items and return a new object, because notes may be encrypted.
if (constraint != null) {
mCurrentFilter = constraint.toString();
} else {
mCurrentFilter = null;
}
if (mDbCursor != null) {
mDbCursor.unregisterContentObserver(mContentObserver);
mDbCursor.close();
mDbCursor = null;
}
mDbCursor = mContext.getContentResolver().query(mIntent.getData(), PROJECTION_DB,
null, null, Notes.DEFAULT_SORT_ORDER);
// Register content observer
mDbCursor.registerContentObserver(mContentObserver);
Log.i(TAG, "Cursor count: " + mDbCursor.getCount());
//mCursor = new OpenMatrixCursor(PROJECTION, dbcursor.getCount());
reset();
String encryptedlabel = mContext.getString(R.string.encrypted);
mDbCursor.moveToPosition(-1);
while (mDbCursor.moveToNext()) {
long id = mDbCursor.getLong(COLUMN_INDEX_ID);
String title = mDbCursor.getString(COLUMN_INDEX_TITLE);
String tags = mDbCursor.getString(COLUMN_INDEX_TAGS);
long encrypted = mDbCursor.getLong(COLUMN_INDEX_ENCRYPTED);
String titleEncrypted = null;
String tagsEncrypted = null;
// Skip encrypted notes in filter.
boolean skipEncrypted = false;
if (encrypted > 0) {
// get decrypted title:
String titleDecrypted = mEncryptedStringHashMap.get(title);
if (titleDecrypted != null) {
title = titleDecrypted;
} else {
// decrypt later
addForEncryption(title);
// Set encrypt title
titleEncrypted = title;
title = encryptedlabel;
skipEncrypted = true;
}
if (tags != null) {
String tagsDecrypted = mEncryptedStringHashMap.get(tags);
if (tagsDecrypted != null) {
tags = tagsDecrypted;
} else {
// decrypt later
addForEncryption(tags);
// Set encrypt title
tagsEncrypted = tags;
tags = "";
}
}
if (!mLoggedIn) {
// suppress all decrypted output
title = encryptedlabel;
tags = "";
}
}
boolean addrow = false;
if (TextUtils.isEmpty(mCurrentFilter)) {
// Add all rows if there is no filter.
addrow = true;
} else if (skipEncrypted) {
addrow = false;
} else {
// test the filter
// Build search string from title and tags.
String searchstring = null;
if (!TextUtils.isEmpty(mCurrentFilter)) {
StringBuilder sb = new StringBuilder();
sb.append(" ");
sb.append(title.toUpperCase());
sb.append(" ");
String spacetags = tags.replace(",", " ");
sb.append(spacetags.toUpperCase());
searchstring = sb.toString();
}
// apply filter:
addrow = searchstring.contains(" " + mCurrentFilter.toUpperCase());
}
if (addrow) {
if (tags == null) {
tags = "";
}
Object[] row = new Object[] {id, title, tags, encrypted, titleEncrypted, tagsEncrypted};
addRow(row);
}
}
}
| private void runQuery(CharSequence constraint) {
// We have to query all items and return a new object, because notes may be encrypted.
if (constraint != null) {
mCurrentFilter = constraint.toString();
} else {
mCurrentFilter = null;
}
if (mDbCursor != null) {
mDbCursor.unregisterContentObserver(mContentObserver);
mDbCursor.close();
mDbCursor = null;
}
mDbCursor = mContext.getContentResolver().query(mIntent.getData(), PROJECTION_DB,
null, null, Notes.DEFAULT_SORT_ORDER);
// Register content observer
mDbCursor.registerContentObserver(mContentObserver);
Log.i(TAG, "Cursor count: " + mDbCursor.getCount());
//mCursor = new OpenMatrixCursor(PROJECTION, dbcursor.getCount());
reset();
String encryptedlabel = mContext.getString(R.string.encrypted);
mDbCursor.moveToPosition(-1);
while (mDbCursor.moveToNext()) {
long id = mDbCursor.getLong(COLUMN_INDEX_ID);
String title = mDbCursor.getString(COLUMN_INDEX_TITLE);
String tags = mDbCursor.getString(COLUMN_INDEX_TAGS);
long encrypted = mDbCursor.getLong(COLUMN_INDEX_ENCRYPTED);
String titleEncrypted = null;
String tagsEncrypted = null;
// Skip encrypted notes in filter.
boolean skipEncrypted = false;
if (encrypted > 0) {
// get decrypted title:
String titleDecrypted = mEncryptedStringHashMap.get(title);
if (titleDecrypted != null) {
title = titleDecrypted;
} else {
// decrypt later
addForEncryption(title);
// Set encrypt title
titleEncrypted = title;
title = encryptedlabel;
skipEncrypted = true;
}
if (tags != null) {
String tagsDecrypted = mEncryptedStringHashMap.get(tags);
if (tagsDecrypted != null) {
tags = tagsDecrypted;
} else {
// decrypt later
addForEncryption(tags);
// Set encrypt title
tagsEncrypted = tags;
tags = "";
}
}
if (!mLoggedIn) {
// suppress all decrypted output
title = encryptedlabel;
tags = "";
}
}
boolean addrow = false;
if (TextUtils.isEmpty(mCurrentFilter)) {
// Add all rows if there is no filter.
addrow = true;
} else if (skipEncrypted) {
addrow = false;
} else {
// test the filter
// Build search string from title and tags.
String searchstring = null;
if (!TextUtils.isEmpty(mCurrentFilter)) {
StringBuilder sb = new StringBuilder();
sb.append(" ");
sb.append(title.toUpperCase());
if (!TextUtils.isEmpty(tags)) {
sb.append(" ");
String spacetags = tags.replace(",", " ");
sb.append(spacetags.toUpperCase());
}
searchstring = sb.toString();
}
// apply filter:
addrow = searchstring.contains(" " + mCurrentFilter.toUpperCase());
}
if (addrow) {
if (tags == null) {
tags = "";
}
Object[] row = new Object[] {id, title, tags, encrypted, titleEncrypted, tagsEncrypted};
addRow(row);
}
}
}
|
diff --git a/src/com/itmill/toolkit/terminal/gwt/client/ui/ICustomLayout.java b/src/com/itmill/toolkit/terminal/gwt/client/ui/ICustomLayout.java
index 0b218e796..0e4f0aaa2 100644
--- a/src/com/itmill/toolkit/terminal/gwt/client/ui/ICustomLayout.java
+++ b/src/com/itmill/toolkit/terminal/gwt/client/ui/ICustomLayout.java
@@ -1,644 +1,644 @@
/*
@ITMillApache2LicenseForJavaFiles@
*/
package com.itmill.toolkit.terminal.gwt.client.ui;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import com.google.gwt.dom.client.ImageElement;
import com.google.gwt.dom.client.NodeList;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.ComplexPanel;
import com.google.gwt.user.client.ui.Widget;
import com.itmill.toolkit.terminal.gwt.client.ApplicationConnection;
import com.itmill.toolkit.terminal.gwt.client.BrowserInfo;
import com.itmill.toolkit.terminal.gwt.client.Container;
import com.itmill.toolkit.terminal.gwt.client.ContainerResizedListener;
import com.itmill.toolkit.terminal.gwt.client.ICaption;
import com.itmill.toolkit.terminal.gwt.client.ICaptionWrapper;
import com.itmill.toolkit.terminal.gwt.client.Paintable;
import com.itmill.toolkit.terminal.gwt.client.RenderSpace;
import com.itmill.toolkit.terminal.gwt.client.UIDL;
import com.itmill.toolkit.terminal.gwt.client.Util;
import com.itmill.toolkit.terminal.gwt.client.RenderInformation.FloatSize;
/**
* Custom Layout implements complex layout defined with HTML template.
*
* @author IT Mill
*
*/
public class ICustomLayout extends ComplexPanel implements Paintable,
Container, ContainerResizedListener {
public static final String CLASSNAME = "i-customlayout";
/** Location-name to containing element in DOM map */
private final HashMap locationToElement = new HashMap();
/** Location-name to contained widget map */
private final HashMap<String, Widget> locationToWidget = new HashMap<String, Widget>();
/** Widget to captionwrapper map */
private final HashMap widgetToCaptionWrapper = new HashMap();
/** Name of the currently rendered style */
String currentTemplateName;
/** Unexecuted scripts loaded from the template */
private String scripts = "";
/** Paintable ID of this paintable */
private String pid;
private ApplicationConnection client;
/** Has the template been loaded from contents passed in UIDL **/
private boolean hasTemplateContents = false;
private Element elementWithNativeResizeFunction;
private String height = "";
private String width = "";
private HashMap<String, FloatSize> locationToExtraSize = new HashMap<String, FloatSize>();
public ICustomLayout() {
setElement(DOM.createDiv());
// Clear any unwanted styling
DOM.setStyleAttribute(getElement(), "border", "none");
DOM.setStyleAttribute(getElement(), "margin", "0");
DOM.setStyleAttribute(getElement(), "padding", "0");
if (BrowserInfo.get().isIE()) {
DOM.setStyleAttribute(getElement(), "position", "relative");
}
setStyleName(CLASSNAME);
}
/**
* Sets widget to given location.
*
* If location already contains a widget it will be removed.
*
* @param widget
* Widget to be set into location.
* @param location
* location name where widget will be added
*
* @throws IllegalArgumentException
* if no such location is found in the layout.
*/
public void setWidget(Widget widget, String location) {
if (widget == null) {
return;
}
// If no given location is found in the layout, and exception is throws
Element elem = (Element) locationToElement.get(location);
if (elem == null && hasTemplate()) {
throw new IllegalArgumentException("No location " + location
+ " found");
}
// Get previous widget
final Widget previous = locationToWidget.get(location);
// NOP if given widget already exists in this location
if (previous == widget) {
return;
}
if (previous != null) {
remove(previous);
}
// if template is missing add element in order
if (!hasTemplate()) {
elem = getElement();
}
// Add widget to location
super.add(widget, elem);
locationToWidget.put(location, widget);
}
/** Update the layout from UIDL */
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
this.client = client;
// ApplicationConnection manages generic component features
if (client.updateComponent(this, uidl, true)) {
return;
}
pid = uidl.getId();
if (!hasTemplate()) {
// Update HTML template only once
initializeHTML(uidl, client);
}
// Evaluate scripts
eval(scripts);
scripts = null;
iLayout();
// TODO Check if this is needed
client.runDescendentsLayout(this);
Set oldWidgets = new HashSet();
oldWidgets.addAll(locationToWidget.values());
// For all contained widgets
for (final Iterator i = uidl.getChildIterator(); i.hasNext();) {
final UIDL uidlForChild = (UIDL) i.next();
if (uidlForChild.getTag().equals("location")) {
final String location = uidlForChild.getStringAttribute("name");
final Paintable child = client.getPaintable(uidlForChild
.getChildUIDL(0));
try {
setWidget((Widget) child, location);
child.updateFromUIDL(uidlForChild.getChildUIDL(0), client);
} catch (final IllegalArgumentException e) {
// If no location is found, this component is not visible
}
oldWidgets.remove(child);
}
}
for (Iterator iterator = oldWidgets.iterator(); iterator.hasNext();) {
Widget oldWidget = (Widget) iterator.next();
if (oldWidget.isAttached()) {
// slot of this widget is emptied, remove it
remove(oldWidget);
}
}
iLayout();
// TODO Check if this is needed
client.runDescendentsLayout(this);
}
/** Initialize HTML-layout. */
private void initializeHTML(UIDL uidl, ApplicationConnection client) {
final String newTemplateContents = uidl
.getStringAttribute("templateContents");
final String newTemplate = uidl.getStringAttribute("template");
currentTemplateName = null;
hasTemplateContents = false;
String template = "";
if (newTemplate != null) {
// Get the HTML-template from client
template = client.getResource("layouts/" + newTemplate + ".html");
if (template == null) {
template = "<em>Layout file layouts/"
+ newTemplate
+ ".html is missing. Components will be drawn for debug purposes.</em>";
} else {
currentTemplateName = newTemplate;
}
} else {
hasTemplateContents = true;
template = newTemplateContents;
}
// Connect body of the template to DOM
template = extractBodyAndScriptsFromTemplate(template);
// TODO prefix img src:s here with a regeps, cannot work further with IE
String themeUri = client.getThemeUri();
String relImgPrefix = themeUri + "/layouts/";
// prefix all relative image elements to point to theme dir with a
// regexp search
template = template.replaceAll(
- "<((?:img)|(?:IMG)) ([^>]*)src=\"((?![a-z]+:)[^/][^\"]+)\"",
+ "<((?:img)|(?:IMG))\\s([^>]*)src=\"((?![a-z]+:)[^/][^\"]+)\"",
"<$1 $2src=\"" + relImgPrefix + "$3\"");
// also support src attributes without quotes
template = template
.replaceAll(
- "<((?:img)|(?:IMG)) ([^>]*)src=[^\"]((?![a-z]+:)[^/][^ />]+)[ />]",
+ "<((?:img)|(?:IMG))\\s([^>]*)src=[^\"]((?![a-z]+:)[^/][^ />]+)[ />]",
"<$1 $2src=\"" + relImgPrefix + "$3\"");
// also prefix relative style="...url(...)..."
template = template
.replaceAll(
"(<[^>]+style=\"[^\"]*url\\()((?![a-z]+:)[^/][^\"]+)(\\)[^>]*>)",
"$1 " + relImgPrefix + "$2 $3");
getElement().setInnerHTML(template);
// Remap locations to elements
locationToElement.clear();
scanForLocations(getElement());
initImgElements();
elementWithNativeResizeFunction = DOM.getFirstChild(getElement());
if (elementWithNativeResizeFunction == null) {
elementWithNativeResizeFunction = getElement();
}
publishResizedFunction(elementWithNativeResizeFunction);
}
private native boolean uriEndsWithSlash()
/*-{
var path = $wnd.location.pathname;
if(path.charAt(path.length - 1) == "/")
return true;
return false;
}-*/;
private boolean hasTemplate() {
if (currentTemplateName == null && !hasTemplateContents) {
return false;
} else {
return true;
}
}
/** Collect locations from template */
private void scanForLocations(Element elem) {
final String location = elem.getAttribute("location");
if (!"".equals(location)) {
locationToElement.put(location, elem);
elem.setInnerHTML("");
int x = Util.measureHorizontalPaddingAndBorder(elem, 0);
int y = Util.measureVerticalPaddingAndBorder(elem, 0);
FloatSize fs = new FloatSize(x, y);
locationToExtraSize.put(location, fs);
} else {
final int len = DOM.getChildCount(elem);
for (int i = 0; i < len; i++) {
scanForLocations(DOM.getChild(elem, i));
}
}
}
/** Evaluate given script in browser document */
private static native void eval(String script)
/*-{
try {
if (script != null)
eval("{ var document = $doc; var window = $wnd; "+ script + "}");
} catch (e) {
}
}-*/;
/**
* Img elements needs some special handling in custom layout. Img elements
* will get their onload events sunk. This way custom layout can notify
* parent about possible size change.
*/
private void initImgElements() {
NodeList<com.google.gwt.dom.client.Element> nodeList = getElement()
.getElementsByTagName("IMG");
for (int i = 0; i < nodeList.getLength(); i++) {
com.google.gwt.dom.client.ImageElement img = (ImageElement) nodeList
.getItem(i);
DOM.sinkEvents((Element) img.cast(), Event.ONLOAD);
}
}
/**
* Extract body part and script tags from raw html-template.
*
* Saves contents of all script-tags to private property: scripts. Returns
* contents of the body part for the html without script-tags. Also replaces
* all _UID_ tags with an unique id-string.
*
* @param html
* Original HTML-template received from server
* @return html that is used to create the HTMLPanel.
*/
private String extractBodyAndScriptsFromTemplate(String html) {
// Replace UID:s
html = html.replaceAll("_UID_", pid + "__");
// Exctract script-tags
scripts = "";
int endOfPrevScript = 0;
int nextPosToCheck = 0;
String lc = html.toLowerCase();
String res = "";
int scriptStart = lc.indexOf("<script", nextPosToCheck);
while (scriptStart > 0) {
res += html.substring(endOfPrevScript, scriptStart);
scriptStart = lc.indexOf(">", scriptStart);
final int j = lc.indexOf("</script>", scriptStart);
scripts += html.substring(scriptStart + 1, j) + ";";
nextPosToCheck = endOfPrevScript = j + "</script>".length();
scriptStart = lc.indexOf("<script", nextPosToCheck);
}
res += html.substring(endOfPrevScript);
// Extract body
html = res;
lc = html.toLowerCase();
int startOfBody = lc.indexOf("<body");
if (startOfBody < 0) {
res = html;
} else {
res = "";
startOfBody = lc.indexOf(">", startOfBody) + 1;
final int endOfBody = lc.indexOf("</body>", startOfBody);
if (endOfBody > startOfBody) {
res = html.substring(startOfBody, endOfBody);
} else {
res = html.substring(startOfBody);
}
}
return res;
}
/** Replace child components */
public void replaceChildComponent(Widget from, Widget to) {
final String location = getLocation(from);
if (location == null) {
throw new IllegalArgumentException();
}
setWidget(to, location);
}
/** Does this layout contain given child */
public boolean hasChildComponent(Widget component) {
return locationToWidget.containsValue(component);
}
/** Update caption for given widget */
public void updateCaption(Paintable component, UIDL uidl) {
ICaptionWrapper wrapper = (ICaptionWrapper) widgetToCaptionWrapper
.get(component);
if (ICaption.isNeeded(uidl)) {
if (wrapper == null) {
final String loc = getLocation((Widget) component);
super.remove((Widget) component);
wrapper = new ICaptionWrapper(component, client);
super.add(wrapper, (Element) locationToElement.get(loc));
widgetToCaptionWrapper.put(component, wrapper);
}
wrapper.updateCaption(uidl);
} else {
if (wrapper != null) {
final String loc = getLocation((Widget) component);
super.remove(wrapper);
super.add((Widget) wrapper.getPaintable(),
(Element) locationToElement.get(loc));
widgetToCaptionWrapper.remove(component);
}
}
}
/** Get the location of an widget */
public String getLocation(Widget w) {
for (final Iterator i = locationToWidget.keySet().iterator(); i
.hasNext();) {
final String location = (String) i.next();
if (locationToWidget.get(location) == w) {
return location;
}
}
return null;
}
/** Removes given widget from the layout */
@Override
public boolean remove(Widget w) {
client.unregisterPaintable((Paintable) w);
final String location = getLocation(w);
if (location != null) {
locationToWidget.remove(location);
}
final ICaptionWrapper cw = (ICaptionWrapper) widgetToCaptionWrapper
.get(w);
if (cw != null) {
widgetToCaptionWrapper.remove(w);
return super.remove(cw);
} else if (w != null) {
return super.remove(w);
}
return false;
}
/** Adding widget without specifying location is not supported */
@Override
public void add(Widget w) {
throw new UnsupportedOperationException();
}
/** Clear all widgets from the layout */
@Override
public void clear() {
super.clear();
locationToWidget.clear();
widgetToCaptionWrapper.clear();
}
public void iLayout() {
iLayoutJS(DOM.getFirstChild(getElement()));
}
/**
* This method is published to JS side with the same name into first DOM
* node of custom layout. This way if one implements some resizeable
* containers in custom layout he/she can notify children after resize.
*/
public void notifyChildrenOfSizeChange() {
client.runDescendentsLayout(this);
}
@Override
public void onDetach() {
super.onDetach();
detachResizedFunction(elementWithNativeResizeFunction);
}
private native void detachResizedFunction(Element element)
/*-{
element.notifyChildrenOfSizeChange = null;
}-*/;
private native void publishResizedFunction(Element element)
/*-{
var self = this;
element.notifyChildrenOfSizeChange = function() {
[email protected]::notifyChildrenOfSizeChange()();
};
}-*/;
/**
* In custom layout one may want to run layout functions made with
* JavaScript. This function tests if one exists (with name "iLayoutJS" in
* layouts first DOM node) and runs et. Return value is used to determine if
* children needs to be notified of size changes.
*
* Note! When implementing a JS layout function you most likely want to call
* notifyChildrenOfSizeChange() function on your custom layouts main
* element. That method is used to control whether child components layout
* functions are to be run.
*
* @param el
* @return true if layout function exists and was run successfully, else
* false.
*/
private native boolean iLayoutJS(Element el)
/*-{
if(el && el.iLayoutJS) {
try {
el.iLayoutJS();
return true;
} catch (e) {
return false;
}
} else {
return false;
}
}-*/;
public boolean requestLayout(Set<Paintable> child) {
updateRelativeSizedComponents(true, true);
if (width.equals("") || height.equals("")) {
/* Automatically propagated upwards if the size can change */
return false;
}
return true;
}
public RenderSpace getAllocatedSpace(Widget child) {
com.google.gwt.dom.client.Element pe = child.getElement()
.getParentElement();
FloatSize extra = locationToExtraSize.get(getLocation(child));
return new RenderSpace(pe.getOffsetWidth() - (int) extra.getWidth(), pe
.getOffsetHeight()
- (int) extra.getHeight(), Util.mayHaveScrollBars(pe));
}
@Override
public void onBrowserEvent(Event event) {
super.onBrowserEvent(event);
if (event.getTypeInt() == Event.ONLOAD) {
Util.notifyParentOfSizeChange(this, true);
event.cancelBubble(true);
}
}
@Override
public void setHeight(String height) {
if (this.height.equals(height)) {
return;
}
boolean shrinking = true;
if (isLarger(height, this.height)) {
shrinking = false;
}
this.height = height;
super.setHeight(height);
/*
* If the height shrinks we must remove all components with relative
* height from the DOM, update their height when they do not affect the
* available space and finally restore them to the original state
*/
if (shrinking) {
updateRelativeSizedComponents(false, true);
}
}
@Override
public void setWidth(String width) {
if (this.width.equals(width)) {
return;
}
boolean shrinking = true;
if (isLarger(width, this.width)) {
shrinking = false;
}
super.setWidth(width);
this.width = width;
/*
* If the width shrinks we must remove all components with relative
* width from the DOM, update their width when they do not affect the
* available space and finally restore them to the original state
*/
if (shrinking) {
updateRelativeSizedComponents(true, false);
}
}
private void updateRelativeSizedComponents(boolean relativeWidth,
boolean relativeHeight) {
Set<Widget> relativeSizeWidgets = new HashSet<Widget>();
for (Widget widget : locationToWidget.values()) {
FloatSize relativeSize = client.getRelativeSize(widget);
if (relativeSize != null) {
if ((relativeWidth && (relativeSize.getWidth() >= 0.0f))
|| (relativeHeight && (relativeSize.getHeight() >= 0.0f))) {
relativeSizeWidgets.add(widget);
widget.getElement().getStyle().setProperty("position",
"absolute");
}
}
}
for (Widget widget : relativeSizeWidgets) {
client.handleComponentRelativeSize(widget);
widget.getElement().getStyle().setProperty("position", "");
}
}
/**
* Compares newSize with currentSize and returns true if it is clear that
* newSize is larger than currentSize. Returns false if newSize is smaller
* or if it is unclear which one is smaller.
*
* @param newSize
* @param currentSize
* @return
*/
private boolean isLarger(String newSize, String currentSize) {
if (newSize.equals("") || currentSize.equals("")) {
return false;
}
if (!newSize.endsWith("px") || !currentSize.endsWith("px")) {
return false;
}
int newSizePx = Integer.parseInt(newSize.substring(0,
newSize.length() - 2));
int currentSizePx = Integer.parseInt(currentSize.substring(0,
currentSize.length() - 2));
boolean larger = newSizePx > currentSizePx;
return larger;
}
}
| false | true | private void initializeHTML(UIDL uidl, ApplicationConnection client) {
final String newTemplateContents = uidl
.getStringAttribute("templateContents");
final String newTemplate = uidl.getStringAttribute("template");
currentTemplateName = null;
hasTemplateContents = false;
String template = "";
if (newTemplate != null) {
// Get the HTML-template from client
template = client.getResource("layouts/" + newTemplate + ".html");
if (template == null) {
template = "<em>Layout file layouts/"
+ newTemplate
+ ".html is missing. Components will be drawn for debug purposes.</em>";
} else {
currentTemplateName = newTemplate;
}
} else {
hasTemplateContents = true;
template = newTemplateContents;
}
// Connect body of the template to DOM
template = extractBodyAndScriptsFromTemplate(template);
// TODO prefix img src:s here with a regeps, cannot work further with IE
String themeUri = client.getThemeUri();
String relImgPrefix = themeUri + "/layouts/";
// prefix all relative image elements to point to theme dir with a
// regexp search
template = template.replaceAll(
"<((?:img)|(?:IMG)) ([^>]*)src=\"((?![a-z]+:)[^/][^\"]+)\"",
"<$1 $2src=\"" + relImgPrefix + "$3\"");
// also support src attributes without quotes
template = template
.replaceAll(
"<((?:img)|(?:IMG)) ([^>]*)src=[^\"]((?![a-z]+:)[^/][^ />]+)[ />]",
"<$1 $2src=\"" + relImgPrefix + "$3\"");
// also prefix relative style="...url(...)..."
template = template
.replaceAll(
"(<[^>]+style=\"[^\"]*url\\()((?![a-z]+:)[^/][^\"]+)(\\)[^>]*>)",
"$1 " + relImgPrefix + "$2 $3");
getElement().setInnerHTML(template);
// Remap locations to elements
locationToElement.clear();
scanForLocations(getElement());
initImgElements();
elementWithNativeResizeFunction = DOM.getFirstChild(getElement());
if (elementWithNativeResizeFunction == null) {
elementWithNativeResizeFunction = getElement();
}
publishResizedFunction(elementWithNativeResizeFunction);
}
| private void initializeHTML(UIDL uidl, ApplicationConnection client) {
final String newTemplateContents = uidl
.getStringAttribute("templateContents");
final String newTemplate = uidl.getStringAttribute("template");
currentTemplateName = null;
hasTemplateContents = false;
String template = "";
if (newTemplate != null) {
// Get the HTML-template from client
template = client.getResource("layouts/" + newTemplate + ".html");
if (template == null) {
template = "<em>Layout file layouts/"
+ newTemplate
+ ".html is missing. Components will be drawn for debug purposes.</em>";
} else {
currentTemplateName = newTemplate;
}
} else {
hasTemplateContents = true;
template = newTemplateContents;
}
// Connect body of the template to DOM
template = extractBodyAndScriptsFromTemplate(template);
// TODO prefix img src:s here with a regeps, cannot work further with IE
String themeUri = client.getThemeUri();
String relImgPrefix = themeUri + "/layouts/";
// prefix all relative image elements to point to theme dir with a
// regexp search
template = template.replaceAll(
"<((?:img)|(?:IMG))\\s([^>]*)src=\"((?![a-z]+:)[^/][^\"]+)\"",
"<$1 $2src=\"" + relImgPrefix + "$3\"");
// also support src attributes without quotes
template = template
.replaceAll(
"<((?:img)|(?:IMG))\\s([^>]*)src=[^\"]((?![a-z]+:)[^/][^ />]+)[ />]",
"<$1 $2src=\"" + relImgPrefix + "$3\"");
// also prefix relative style="...url(...)..."
template = template
.replaceAll(
"(<[^>]+style=\"[^\"]*url\\()((?![a-z]+:)[^/][^\"]+)(\\)[^>]*>)",
"$1 " + relImgPrefix + "$2 $3");
getElement().setInnerHTML(template);
// Remap locations to elements
locationToElement.clear();
scanForLocations(getElement());
initImgElements();
elementWithNativeResizeFunction = DOM.getFirstChild(getElement());
if (elementWithNativeResizeFunction == null) {
elementWithNativeResizeFunction = getElement();
}
publishResizedFunction(elementWithNativeResizeFunction);
}
|
diff --git a/eclipse_files/src/DeviceGraphics/KitGraphics.java b/eclipse_files/src/DeviceGraphics/KitGraphics.java
index ba981f24..58c14090 100644
--- a/eclipse_files/src/DeviceGraphics/KitGraphics.java
+++ b/eclipse_files/src/DeviceGraphics/KitGraphics.java
@@ -1,83 +1,83 @@
package DeviceGraphics;
import java.util.ArrayList;
import Networking.Request;
import Networking.Server;
import Utils.Constants;
import Utils.Location;
import agent.data.PartType;
public class KitGraphics implements DeviceGraphics {
ArrayList<PartGraphics> parts = new ArrayList<PartGraphics>(); // parts currently in the kit
ArrayList<PartType> partTypes = new ArrayList<PartType>(); // part types required to make kit
Location kitLocation;
Boolean isFull; //Says whether or not the kit is full
Server server;
public KitGraphics (Server server) {
this.server = server;
isFull = false;
}
/**
* set the part types required to build kit
*
* @param kitDesign - parts required to build the kit
*/
public void setPartTypes(ArrayList<PartType> kitDesign) {
partTypes = kitDesign;
}
public void addPart (PartGraphics newPart) {
parts.add(newPart);
if ((parts.size() % 2) == 1) {
newPart.setLocation(new Location(kitLocation.getX() + 5, kitLocation.getY() + (20 * (parts.size() -1) / 2)));
}
else {
- newPart.setLocation(new Location(kitLocation.getX() + 34, kitLocation.getY() + (20 * parts.size() / 2)));
+ newPart.setLocation(new Location(kitLocation.getX() + 34, kitLocation.getY() + (20 * (parts.size()-2) / 2)));
}
if (parts.size() == 8) {
parts.clear();
}
}
public void setLocation (Location newLocation) {
kitLocation = newLocation;
}
public Location getLocation () {
return kitLocation;
}
//If true, set isFull boolean to true
public void setFull (Boolean full) {
isFull = full;
}
public Boolean getFull () {
return isFull;
}
public void receivePart(PartGraphics part) {
addPart(part);
server.sendData(new Request(Constants.KIT_UPDATE_PARTS_LIST_COMMAND, Constants.KIT_TARGET, parts));
}
@Override
public void receiveData(Request req) {
if (req.getCommand().equals("Testing")) {
addPart(new PartGraphics (PartType.A));
}
}
}
| true | true | public void addPart (PartGraphics newPart) {
parts.add(newPart);
if ((parts.size() % 2) == 1) {
newPart.setLocation(new Location(kitLocation.getX() + 5, kitLocation.getY() + (20 * (parts.size() -1) / 2)));
}
else {
newPart.setLocation(new Location(kitLocation.getX() + 34, kitLocation.getY() + (20 * parts.size() / 2)));
}
if (parts.size() == 8) {
parts.clear();
}
}
| public void addPart (PartGraphics newPart) {
parts.add(newPart);
if ((parts.size() % 2) == 1) {
newPart.setLocation(new Location(kitLocation.getX() + 5, kitLocation.getY() + (20 * (parts.size() -1) / 2)));
}
else {
newPart.setLocation(new Location(kitLocation.getX() + 34, kitLocation.getY() + (20 * (parts.size()-2) / 2)));
}
if (parts.size() == 8) {
parts.clear();
}
}
|
diff --git a/facestester/src/main/java/com/steeplesoft/jsf/facestester/context/mojarra/MojarraFacesContextBuilder.java b/facestester/src/main/java/com/steeplesoft/jsf/facestester/context/mojarra/MojarraFacesContextBuilder.java
index 548814b..55966be 100644
--- a/facestester/src/main/java/com/steeplesoft/jsf/facestester/context/mojarra/MojarraFacesContextBuilder.java
+++ b/facestester/src/main/java/com/steeplesoft/jsf/facestester/context/mojarra/MojarraFacesContextBuilder.java
@@ -1,159 +1,160 @@
package com.steeplesoft.jsf.facestester.context.mojarra;
import com.steeplesoft.jsf.facestester.context.*;
import com.steeplesoft.jsf.facestester.*;
import com.steeplesoft.jsf.facestester.servlet.impl.FacesTesterServletContext;
import com.steeplesoft.jsf.facestester.servlet.WebDeploymentDescriptor;
import com.sun.faces.config.ConfigureListener;
import com.sun.faces.config.WebConfiguration.WebContextInitParameter;
import java.util.EventListener;
import java.util.List;
import javax.faces.FacesException;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import javax.faces.FactoryFinder;
import static javax.faces.FactoryFinder.FACES_CONTEXT_FACTORY;
import javax.faces.context.FacesContext;
import javax.faces.context.FacesContextFactory;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.http.HttpSessionEvent;
import java.util.Map;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionListener;
public class MojarraFacesContextBuilder implements FacesContextBuilder {
// private static boolean initialized = false;
// private final ConfigureListener mojarraListener = new ConfigureListener();
private FacesContextFactory facesContextFactory;
private HttpSession session;
private FacesTesterServletContext servletContext;
private WebDeploymentDescriptor webDescriptor;
public MojarraFacesContextBuilder(FacesTesterServletContext servletContext, HttpSession session, WebDeploymentDescriptor webDescriptor) {
-// System.setProperty("com.sun.faces.InjectionProvider", "com.steeplesoft.jsf.facestester.injection.FacesTesterInjectionProvider");
+ // TODO: Should not have to do this :(
+ System.setProperty("com.sun.faces.InjectionProvider", "com.steeplesoft.jsf.facestester.injection.FacesTesterInjectionProvider");
try {
Class.forName("com.sun.faces.spi.AnnotationProvider");
Util.getLogger().info("This appears to be a Mojarra 2 environment. Enabling AnnotationProvider.");
// System.setProperty("com.sun.faces.spi.annotationprovider", "com.steeplesoft.jsf.facestester.context.mojarra.FacesTesterAnnotationScanner");
} catch (ClassNotFoundException ex) {
//
Util.getLogger().info("*NOT* a Mojarra 2 env.");
}
this.servletContext = servletContext;
this.session = session;
this.webDescriptor = webDescriptor;
try {
if (Util.isMojarra()) {
webDescriptor.getListeners().add(0, new ConfigureListener());
}
} catch (Exception ex) {
throw new FacesTesterException("Mojarra's ConfigureListener was found, but could not be instantiated: " + ex.getLocalizedMessage(), ex);
}
servletContext.addInitParameter(WebContextInitParameter.ExpressionFactory.getQualifiedName(),
WebContextInitParameter.ExpressionFactory.getDefaultValue());
initializeFaces(servletContext);
facesContextFactory = (FacesContextFactory) FactoryFinder.getFactory(FACES_CONTEXT_FACTORY);
}
public FacesContext createFacesContext(String method, FacesLifecycle lifecycle) {
return createFacesContext(null, method, lifecycle);
}
public FacesContext createFacesContext(String uri, String method, FacesLifecycle lifecycle) {
return buildFacesContext(mockServletRequest(uri, method), lifecycle);
}
public FacesContext createFacesContext(FacesForm form, FacesLifecycle lifecycle) {
MockHttpServletRequest request = mockServletRequest(form.getUri(), "POST");
for (Map.Entry<String, String> each : form.getParameterMap().entrySet()) {
request.addParameter(each.getKey(), each.getValue());
}
return buildFacesContext(request, lifecycle);
}
protected FacesContext buildFacesContext(MockHttpServletRequest request, FacesLifecycle lifecycle) throws FacesException {
FacesContext context = facesContextFactory.getFacesContext(servletContext, request,
new MockHttpServletResponse(), lifecycle.getUnderlyingLifecycle());
return context;
}
/*
* This is a pretty simple solution that will likely need to be replaced,
* but should get us going for now.
*/
private void addQueryParameters(MockHttpServletRequest servletRequest, String uri) {
int qmark = uri.indexOf("?");
if (qmark > -1) {
String queryString = uri.substring(qmark + 1);
String[] params = queryString.split("&");
for (String param : params) {
String[] parts = param.split("=");
if (parts.length == 1) {
servletRequest.addParameter(parts[0], "");
} else {
servletRequest.addParameter(parts[0], parts[1]);
}
}
servletRequest.setQueryString(queryString);
}
}
private void initializeFaces(ServletContext servletContext) {
ServletContextEvent sce = new ServletContextEvent(servletContext);
HttpSessionEvent hse = new HttpSessionEvent(session);
List<EventListener> listeners = webDescriptor.getListeners();
// synchronized (mojarraListener) {
// if (!initialized) {
// mojarraListener.contextInitialized(sce);
// mojarraListener.sessionCreated(hse);
// initialized = true;
// }
// }
for (EventListener listener : listeners) {
if (listener instanceof ServletContextListener) {
((ServletContextListener) listener).contextInitialized(sce);
}
}
// Do all SCLs need to be called first? Probably can't hurt...
for (EventListener listener : listeners) {
if (listener instanceof HttpSessionListener) {
((HttpSessionListener) listener).sessionCreated(hse);
}
}
}
private MockHttpServletRequest mockServletRequest(String uri, String method) {
MockHttpServletRequest servletRequest;
if (uri != null) {
servletRequest = new MockHttpServletRequest(servletContext, method,uri);
servletRequest.setServletPath(uri);
} else {
servletRequest = new MockHttpServletRequest(servletContext);
}
servletRequest.setSession(session);
// mojarraListener.requestInitialized(new ServletRequestEvent(servletContext, servletRequest));
if (uri != null) {
addQueryParameters(servletRequest, uri);
}
return servletRequest;
}
}
| true | true | public MojarraFacesContextBuilder(FacesTesterServletContext servletContext, HttpSession session, WebDeploymentDescriptor webDescriptor) {
// System.setProperty("com.sun.faces.InjectionProvider", "com.steeplesoft.jsf.facestester.injection.FacesTesterInjectionProvider");
try {
Class.forName("com.sun.faces.spi.AnnotationProvider");
Util.getLogger().info("This appears to be a Mojarra 2 environment. Enabling AnnotationProvider.");
// System.setProperty("com.sun.faces.spi.annotationprovider", "com.steeplesoft.jsf.facestester.context.mojarra.FacesTesterAnnotationScanner");
} catch (ClassNotFoundException ex) {
//
Util.getLogger().info("*NOT* a Mojarra 2 env.");
}
this.servletContext = servletContext;
this.session = session;
this.webDescriptor = webDescriptor;
try {
if (Util.isMojarra()) {
webDescriptor.getListeners().add(0, new ConfigureListener());
}
} catch (Exception ex) {
throw new FacesTesterException("Mojarra's ConfigureListener was found, but could not be instantiated: " + ex.getLocalizedMessage(), ex);
}
servletContext.addInitParameter(WebContextInitParameter.ExpressionFactory.getQualifiedName(),
WebContextInitParameter.ExpressionFactory.getDefaultValue());
initializeFaces(servletContext);
facesContextFactory = (FacesContextFactory) FactoryFinder.getFactory(FACES_CONTEXT_FACTORY);
}
| public MojarraFacesContextBuilder(FacesTesterServletContext servletContext, HttpSession session, WebDeploymentDescriptor webDescriptor) {
// TODO: Should not have to do this :(
System.setProperty("com.sun.faces.InjectionProvider", "com.steeplesoft.jsf.facestester.injection.FacesTesterInjectionProvider");
try {
Class.forName("com.sun.faces.spi.AnnotationProvider");
Util.getLogger().info("This appears to be a Mojarra 2 environment. Enabling AnnotationProvider.");
// System.setProperty("com.sun.faces.spi.annotationprovider", "com.steeplesoft.jsf.facestester.context.mojarra.FacesTesterAnnotationScanner");
} catch (ClassNotFoundException ex) {
//
Util.getLogger().info("*NOT* a Mojarra 2 env.");
}
this.servletContext = servletContext;
this.session = session;
this.webDescriptor = webDescriptor;
try {
if (Util.isMojarra()) {
webDescriptor.getListeners().add(0, new ConfigureListener());
}
} catch (Exception ex) {
throw new FacesTesterException("Mojarra's ConfigureListener was found, but could not be instantiated: " + ex.getLocalizedMessage(), ex);
}
servletContext.addInitParameter(WebContextInitParameter.ExpressionFactory.getQualifiedName(),
WebContextInitParameter.ExpressionFactory.getDefaultValue());
initializeFaces(servletContext);
facesContextFactory = (FacesContextFactory) FactoryFinder.getFactory(FACES_CONTEXT_FACTORY);
}
|
diff --git a/src/lang/psi/impl/expressions/LuaStringLiteralExpressionImpl.java b/src/lang/psi/impl/expressions/LuaStringLiteralExpressionImpl.java
index 256583b1..67bf8e4b 100644
--- a/src/lang/psi/impl/expressions/LuaStringLiteralExpressionImpl.java
+++ b/src/lang/psi/impl/expressions/LuaStringLiteralExpressionImpl.java
@@ -1,65 +1,66 @@
/*
* Copyright 2011 Jon S Akhtar (Sylvanaar)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sylvanaar.idea.Lua.lang.psi.impl.expressions;
import com.intellij.lang.ASTNode;
import com.sylvanaar.idea.Lua.lang.psi.types.LuaType;
/**
* Created by IntelliJ IDEA.
* User: Jon S Akhtar
* Date: 3/7/11
* Time: 12:18 PM
*/
public class LuaStringLiteralExpressionImpl extends LuaLiteralExpressionImpl {
public LuaStringLiteralExpressionImpl(ASTNode node) {
super(node);
}
@Override
public Object getValue() {
return getStringContent();
}
public String getStringContent() {
return stripQuotes(getText());
}
@Override
public LuaType getLuaType() {
return LuaType.STRING;
}
public static String stripQuotes(String text) {
switch (text.charAt(0)) {
case '\'':
case '\"':
- return text.substring(1, text.length()-1);
+ return text.substring(1, text.length() - 1);
case '[':
int quoteLen = text.indexOf('[', 1);
assert quoteLen > 1;
- return text.substring(quoteLen, text.length()-2*quoteLen-1);
+ int beginIndex = quoteLen + 1;
+ return text.substring(beginIndex, beginIndex + text.length() - 2 * quoteLen - 2);
}
return "ERROR";
}
}
| false | true | public static String stripQuotes(String text) {
switch (text.charAt(0)) {
case '\'':
case '\"':
return text.substring(1, text.length()-1);
case '[':
int quoteLen = text.indexOf('[', 1);
assert quoteLen > 1;
return text.substring(quoteLen, text.length()-2*quoteLen-1);
}
return "ERROR";
}
| public static String stripQuotes(String text) {
switch (text.charAt(0)) {
case '\'':
case '\"':
return text.substring(1, text.length() - 1);
case '[':
int quoteLen = text.indexOf('[', 1);
assert quoteLen > 1;
int beginIndex = quoteLen + 1;
return text.substring(beginIndex, beginIndex + text.length() - 2 * quoteLen - 2);
}
return "ERROR";
}
|
diff --git a/JavaSource/org/unitime/timetable/solver/WebSolver.java b/JavaSource/org/unitime/timetable/solver/WebSolver.java
index 5eeca51d..375632b5 100644
--- a/JavaSource/org/unitime/timetable/solver/WebSolver.java
+++ b/JavaSource/org/unitime/timetable/solver/WebSolver.java
@@ -1,822 +1,823 @@
/*
* UniTime 3.1 (University Timetabling Application)
* Copyright (C) 2008, UniTime LLC, and individual contributors
* as indicated by the @authors tag.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package org.unitime.timetable.solver;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspWriter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Transaction;
import org.unitime.commons.User;
import org.unitime.commons.web.Web;
import org.unitime.timetable.ApplicationProperties;
import org.unitime.timetable.model.Session;
import org.unitime.timetable.model.Settings;
import org.unitime.timetable.model.SolverParameter;
import org.unitime.timetable.model.SolverParameterDef;
import org.unitime.timetable.model.SolverParameterGroup;
import org.unitime.timetable.model.SolverPredefinedSetting;
import org.unitime.timetable.model.TimetableManager;
import org.unitime.timetable.model.dao.SolverPredefinedSettingDAO;
import org.unitime.timetable.solver.exam.ExamSolver;
import org.unitime.timetable.solver.exam.ExamSolverProxy;
import org.unitime.timetable.solver.exam.RemoteExamSolverProxy;
import org.unitime.timetable.solver.exam.ExamSolver.ExamSolverDisposeListener;
import org.unitime.timetable.solver.remote.BackupFileFilter;
import org.unitime.timetable.solver.remote.RemoteSolverProxy;
import org.unitime.timetable.solver.remote.RemoteSolverServerProxy;
import org.unitime.timetable.solver.remote.SolverRegisterService;
import org.unitime.timetable.tags.SolverWarnings;
import org.unitime.timetable.util.Constants;
import net.sf.cpsolver.ifs.util.DataProperties;
import net.sf.cpsolver.ifs.util.Progress;
import net.sf.cpsolver.ifs.util.ProgressListener;
/**
* @author Tomas Muller
*/
public class WebSolver extends TimetableSolver implements ProgressListener {
protected static Log sLog = LogFactory.getLog(WebSolver.class);
public static SimpleDateFormat sDF = new SimpleDateFormat("MM/dd/yy hh:mmaa");
private JspWriter iJspWriter;
private static Hashtable<String,SolverProxy> sSolvers = new Hashtable();
private static Hashtable<String,ExamSolverProxy> sExamSolvers = new Hashtable();
private static SolverPassivationThread sSolverPasivationThread = null;
private static long sMemoryLimit = Integer.parseInt(ApplicationProperties.getProperty("tmtbl.solver.mem_limit","200"))*1024*1024; //200 MB
private static boolean sBackupWhenDone = false;
public WebSolver(DataProperties properties) {
super(properties);
}
public static ExamSolverProxy getExamSolver(String puid, Long sessionId) {
try {
ExamSolverProxy solver = sExamSolvers.get(puid);
if (solver!=null) {
if (sessionId!=null && !sessionId.equals(solver.getProperties().getPropertyLong("General.SessionId",null)))
return null;
return solver;
}
Set servers = SolverRegisterService.getInstance().getServers();
synchronized (servers) {
for (Iterator i=servers.iterator();i.hasNext();) {
RemoteSolverServerProxy server = (RemoteSolverServerProxy)i.next();
if (!server.isActive()) continue;
ExamSolverProxy proxy = server.getExamSolver(puid);
if (proxy!=null) {
if (sessionId!=null && !sessionId.equals(proxy.getProperties().getPropertyLong("General.SessionId",null)))
return null;
return proxy;
}
}
}
} catch (Exception e) {
sLog.error("Unable to retrieve solver, reason:"+e.getMessage(),e);
}
return null;
}
public static ExamSolverProxy getExamSolver(javax.servlet.http.HttpSession session) {
ExamSolverProxy solver = (ExamSolverProxy)session.getAttribute("ExamSolverProxy");
if (solver!=null) {
try {
if (solver instanceof RemoteExamSolverProxy && ((RemoteExamSolverProxy)solver).exists())
return solver;
else
session.removeAttribute("ExamSolverProxy");
} catch (Exception e) {
session.removeAttribute("ExamSolverProxy");
};
}
User user = Web.getUser(session);
if (user==null) return null;
Session acadSession = null;
try {
acadSession = Session.getCurrentAcadSession(user);
} catch (Exception e) {}
if (acadSession==null) return null;
TimetableManager mgr = TimetableManager.getManager(user);
if (!mgr.canTimetableExams(acadSession, user)) return null;
String puid = (String)session.getAttribute("ManageSolver.examPuid");
if (puid!=null) {
solver = getExamSolver(puid, acadSession.getUniqueId());
if (solver!=null) {
session.setAttribute("ExamSolverProxy", solver);
return solver;
}
}
solver = getExamSolver(user.getId(), acadSession.getUniqueId());
if (solver==null) return null;
session.setAttribute("ExamSolverProxy", solver);
return solver;
}
public static ExamSolverProxy getExamSolverNoSessionCheck(javax.servlet.http.HttpSession session) {
try {
User user = Web.getUser(session);
if (user==null) return null;
String puid = (String)session.getAttribute("ManageSolver.examPuid");
if (puid!=null) {
ExamSolverProxy solver = getExamSolver(puid, null);
if (solver!=null) return solver;
}
return getExamSolver(user.getId(), null);
} catch (Exception e) {
sLog.error("Unable to retrieve solver, reason:"+e.getMessage(),e);
}
return null;
}
public static SolverProxy getSolver(String puid, Long sessionId) {
try {
SolverProxy proxy = (SolverProxy)sSolvers.get(puid);
if (proxy!=null) {
if (sessionId!=null && !sessionId.equals(proxy.getProperties().getPropertyLong("General.SessionId",null)))
return null;
return proxy;
}
Set servers = SolverRegisterService.getInstance().getServers();
synchronized (servers) {
for (Iterator i=servers.iterator();i.hasNext();) {
RemoteSolverServerProxy server = (RemoteSolverServerProxy)i.next();
if (!server.isActive()) continue;
proxy = server.getSolver(puid);
if (proxy!=null) {
if (sessionId!=null && !sessionId.equals(proxy.getProperties().getPropertyLong("General.SessionId",null)))
return null;
return proxy;
}
}
}
} catch (Exception e) {
sLog.error("Unable to retrieve solver, reason:"+e.getMessage(),e);
}
return null;
}
public static SolverProxy getSolver(javax.servlet.http.HttpSession session) {
SolverProxy solver = (SolverProxy)session.getAttribute("SolverProxy");
if (solver!=null) {
try {
if (solver instanceof RemoteSolverProxy && ((RemoteSolverProxy)solver).exists())
return solver;
else
session.removeAttribute("SolverProxy");
} catch (Exception e) {
session.removeAttribute("SolverProxy");
};
}
User user = Web.getUser(session);
if (user==null) return null;
Long sessionId = null;
try {
sessionId = Session.getCurrentAcadSession(user).getUniqueId();
} catch (Exception e) {}
String puid = (String)session.getAttribute("ManageSolver.puid");
if (puid!=null) {
solver = getSolver(puid, sessionId);
if (solver!=null) {
session.setAttribute("SolverProxy", solver);
return solver;
}
}
solver = getSolver(user.getId(), sessionId);
if (solver!=null)
session.setAttribute("SolverProxy", solver);
return solver;
}
public static SolverProxy getSolverNoSessionCheck(javax.servlet.http.HttpSession session) {
User user = Web.getUser(session);
if (user==null) return null;
String puid = (String)session.getAttribute("ManageSolver.puid");
if (puid!=null) {
SolverProxy solver = getSolver(puid, null);
if (solver!=null) return solver;
}
return getSolver(user.getId(), null);
}
public static DataProperties createProperties(Long settingsId, Hashtable extraParams, int type) {
DataProperties properties = new DataProperties();
Transaction tx = null;
try {
SolverPredefinedSettingDAO dao = new SolverPredefinedSettingDAO();
org.hibernate.Session hibSession = dao.getSession();
if (hibSession.getTransaction()==null || !hibSession.getTransaction().isActive())
tx = hibSession.beginTransaction();
List defaultParams = hibSession.createCriteria(SolverParameterDef.class).list();
for (Iterator i=defaultParams.iterator();i.hasNext();) {
SolverParameterDef def = (SolverParameterDef)i.next();
if (def.getGroup().getType()!=type) continue;
if (def.getDefault()!=null)
properties.put(def.getName(),def.getDefault());
if (extraParams!=null && extraParams.containsKey(def.getUniqueId()))
properties.put(def.getName(), (String)extraParams.get(def.getUniqueId()));
}
SolverPredefinedSetting settings = dao.get(settingsId);
for (Iterator i=settings.getParameters().iterator();i.hasNext();) {
SolverParameter param = (SolverParameter)i.next();
if (!param.getDefinition().isVisible().booleanValue()) continue;
if (param.getDefinition().getGroup().getType()!=type) continue;
properties.put(param.getDefinition().getName(),param.getValue());
if (extraParams!=null && extraParams.containsKey(param.getDefinition().getUniqueId()))
properties.put(param.getDefinition().getName(), (String)extraParams.get(param.getDefinition().getUniqueId()));
}
properties.setProperty("General.SettingsId", settings.getUniqueId().toString());
if (tx!=null) tx.commit();
} catch (Exception e) {
if (tx!=null) tx.rollback();
sLog.error(e);
}
StringBuffer ext = new StringBuffer();
if (properties.getPropertyBoolean("General.SearchIntensification",type==SolverParameterGroup.sTypeCourse)) {
if (ext.length()>0) ext.append(";");
ext.append("net.sf.cpsolver.ifs.extension.SearchIntensification");
}
if (properties.getPropertyBoolean("General.CBS",type==SolverParameterGroup.sTypeCourse)) {
if (ext.length()>0) ext.append(";");
ext.append("net.sf.cpsolver.ifs.extension.ConflictStatistics");
} else if (properties.getPropertyBoolean("ExamGeneral.CBS",type==SolverParameterGroup.sTypeExam)) {
if (ext.length()>0) ext.append(";");
ext.append("net.sf.cpsolver.ifs.extension.ConflictStatistics");
properties.setProperty("ConflictStatistics.Print","true");
}
if (type==SolverParameterGroup.sTypeCourse) {
String mode = properties.getProperty("Basic.Mode","Initial");
if ("MPP".equals(mode)) {
properties.setProperty("General.MPP","true");
if (ext.length()>0) ext.append(";");
ext.append("net.sf.cpsolver.ifs.extension.ViolatedInitials");
}
} else if (type==SolverParameterGroup.sTypeExam) {
String mode = properties.getProperty("ExamBasic.Mode","Initial");
if ("MPP".equals(mode)) {
properties.setProperty("General.MPP","true");
/*
if (ext.length()>0) ext.append(";");
ext.append("net.sf.cpsolver.ifs.extension.ViolatedInitials");
*/
}
}
properties.setProperty("Extensions.Classes",ext.toString());
if (properties.getPropertyBoolean("Basic.DisobeyHard",false)) {
properties.setProperty("General.InteractiveMode", "true");
}
if ("No Action".equals(properties.getProperty("Basic.WhenFinished")) || "No Action".equals(properties.getProperty("ExamBasic.WhenFinished"))) {
properties.setProperty("General.Save","false");
properties.setProperty("General.CreateNewSolution","false");
properties.setProperty("General.Unload","false");
} else if ("Save".equals(properties.getProperty("Basic.WhenFinished")) || "Save".equals(properties.getProperty("ExamBasic.WhenFinished"))) {
properties.setProperty("General.Save","true");
properties.setProperty("General.CreateNewSolution","false");
properties.setProperty("General.Unload","false");
} else if ("Save as New".equals(properties.getProperty("Basic.WhenFinished"))) {
properties.setProperty("General.Save","true");
properties.setProperty("General.CreateNewSolution","true");
properties.setProperty("General.Unload","false");
} else if ("Save and Unload".equals(properties.getProperty("Basic.WhenFinished")) || "Save and Unload".equals(properties.getProperty("ExamBasic.WhenFinished"))) {
properties.setProperty("General.Save","true");
properties.setProperty("General.CreateNewSolution","false");
properties.setProperty("General.Unload","true");
} else if ("Save as New and Unload".equals(properties.getProperty("Basic.WhenFinished"))) {
properties.setProperty("General.Save","true");
properties.setProperty("General.CreateNewSolution","true");
properties.setProperty("General.Unload","true");
}
properties.setProperty("Xml.ShowNames","true");
if (type==SolverParameterGroup.sTypeCourse)
properties.setProperty("Xml.ExportStudentSectioning", "true");
if (type==SolverParameterGroup.sTypeExam) {
properties.setProperty("Exam.GreatDeluge", ("Great Deluge".equals(properties.getProperty("Exam.Algorithm","Great Deluge"))?"true":"false"));
- properties.setProperty("Exam.Type", extraParams.get("Exam.Type").toString());
+ if (extraParams!=null && extraParams.get("Exam.Type")!=null)
+ properties.setProperty("Exam.Type", extraParams.get("Exam.Type").toString());
}
properties.expand();
return properties;
}
public static SolverProxy createSolver(Long sessionId, javax.servlet.http.HttpSession session, Long[] ownerId, String solutionIds, Long settingsId, Hashtable extraParams, boolean startSolver, String host) throws Exception {
try {
System.out.println("Memory limit is "+sMemoryLimit);
User user = Web.getUser(session);
if (user==null) return null;
removeSolver(session);
DataProperties properties = createProperties(settingsId, extraParams, SolverParameterGroup.sTypeCourse);
String warn = SolverWarnings.getSolverWarning(session, ownerId);
if (warn!=null)
properties.setProperty("General.SolverWarnings",warn);
else
properties.remove("General.SolverWarnings");
properties.setProperty("General.SessionId",sessionId.toString());
properties.setProperty("General.SolverGroupId",ownerId);
properties.setProperty("General.OwnerPuid", user.getId());
if (solutionIds!=null)
properties.setProperty("General.SolutionId",solutionIds);
properties.setProperty("General.StartTime", String.valueOf((new Date()).getTime()));
properties.setProperty("General.StartSolver",Boolean.toString(startSolver));
String instructorFormat = Settings.getSettingValue(user, Constants.SETTINGS_INSTRUCTOR_NAME_FORMAT);
if (instructorFormat!=null)
properties.setProperty("General.InstructorFormat",instructorFormat);
if (host!=null) {
Set servers = SolverRegisterService.getInstance().getServers();
synchronized (servers) {
for (Iterator i=servers.iterator();i.hasNext();) {
RemoteSolverServerProxy server = (RemoteSolverServerProxy)i.next();
if (!server.isActive()) continue;
if (host.equals(server.getAddress().getHostName()+":"+server.getPort())) {
SolverProxy solver = server.createSolver(user.getId(),properties);
solver.load(properties);
return solver;
}
}
}
}
if (!"local".equals(host) && !SolverRegisterService.getInstance().getServers().isEmpty()) {
RemoteSolverServerProxy bestServer = null;
Set servers = SolverRegisterService.getInstance().getServers();
synchronized (servers) {
for (Iterator i=servers.iterator();i.hasNext();) {
RemoteSolverServerProxy server = (RemoteSolverServerProxy)i.next();
if (!server.isActive()) continue;
if (server.getAvailableMemory()<sMemoryLimit) continue;
if (bestServer==null) {
bestServer = server;
} else if (bestServer.getUsage()>server.getUsage()) {
bestServer = server;
}
}
}
if (bestServer!=null) {
SolverProxy solver = bestServer.createSolver(user.getId(),properties);
solver.load(properties);
return solver;
}
}
if (getAvailableMemory()<sMemoryLimit)
throw new Exception("Not enough resources to create a solver instance, please try again later.");
WebSolver solver = new WebSolver(properties);
solver.load(properties);
Progress.getInstance(solver.currentSolution().getModel()).addProgressListener(solver);
sSolvers.put(user.getId(),solver);
return solver;
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
public static ExamSolverProxy createExamSolver(Long sessionId, javax.servlet.http.HttpSession session, Long settingsId, Hashtable extraParams, boolean startSolver, String host) throws Exception {
try {
User user = Web.getUser(session);
if (user==null) return null;
removeExamSolver(session);
DataProperties properties = createProperties(settingsId, extraParams, SolverParameterGroup.sTypeExam);
properties.setProperty("General.SessionId",sessionId.toString());
properties.setProperty("General.OwnerPuid", user.getId());
properties.setProperty("General.StartTime", String.valueOf((new Date()).getTime()));
properties.setProperty("General.StartSolver",Boolean.toString(startSolver));
String instructorFormat = Settings.getSettingValue(user, Constants.SETTINGS_INSTRUCTOR_NAME_FORMAT);
if (instructorFormat!=null)
properties.setProperty("General.InstructorFormat",instructorFormat);
if (host!=null) {
Set servers = SolverRegisterService.getInstance().getServers();
synchronized (servers) {
for (Iterator i=servers.iterator();i.hasNext();) {
RemoteSolverServerProxy server = (RemoteSolverServerProxy)i.next();
if (!server.isActive()) continue;
if (host.equals(server.getAddress().getHostName()+":"+server.getPort())) {
ExamSolverProxy solver = server.createExamSolver(user.getId(), properties);
solver.load(properties);
return solver;
}
}
}
}
if (!"local".equals(host) && !SolverRegisterService.getInstance().getServers().isEmpty()) {
RemoteSolverServerProxy bestServer = null;
Set servers = SolverRegisterService.getInstance().getServers();
synchronized (servers) {
for (Iterator i=servers.iterator();i.hasNext();) {
RemoteSolverServerProxy server = (RemoteSolverServerProxy)i.next();
if (!server.isActive()) continue;
if (server.getAvailableMemory()<sMemoryLimit) continue;
if (bestServer==null) {
bestServer = server;
} else if (bestServer.getUsage()>server.getUsage()) {
bestServer = server;
}
}
}
if (bestServer!=null) {
ExamSolverProxy solver = bestServer.createExamSolver(user.getId(), properties);
solver.load(properties);
return solver;
}
}
if (getAvailableMemory()<sMemoryLimit)
throw new Exception("Not enough resources to create a solver instance, please try again later.");
ExamSolver solver = new ExamSolver(properties, new ExamSolverOnDispose(user.getId()));
sExamSolvers.put(user.getId(), solver);
solver.load(properties);
//Progress.getInstance(sExamSolver.currentSolution().getModel()).addProgressListener(sExamSolver);
return solver;
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
public static SolverProxy reload(javax.servlet.http.HttpSession session, Long settingsId, Hashtable extraParams) throws Exception {
User user = Web.getUser(session);
if (user==null) return null;
SolverProxy solver = getSolver(session);
if (solver==null) return null;
DataProperties oldProperties = solver.getProperties();
if (settingsId==null)
settingsId = oldProperties.getPropertyLong("General.SettingsId", null);
DataProperties properties = createProperties(settingsId, extraParams, SolverParameterGroup.sTypeCourse);
String warn = SolverWarnings.getSolverWarning(session, oldProperties.getPropertyLongArry("General.SolverGroupId", null));
if (warn!=null) properties.setProperty("General.SolverWarnings",warn);
properties.setProperty("General.SessionId",oldProperties.getProperty("General.SessionId"));
properties.setProperty("General.SolverGroupId",oldProperties.getProperty("General.SolverGroupId"));
properties.setProperty("General.OwnerPuid", oldProperties.getProperty("General.OwnerPuid"));
properties.setProperty("General.StartTime", String.valueOf((new Date()).getTime()));
String instructorFormat = Settings.getSettingValue(user, Constants.SETTINGS_INSTRUCTOR_NAME_FORMAT);
if (instructorFormat!=null)
properties.setProperty("General.InstructorFormat",instructorFormat);
solver.reload(properties);
if (solver instanceof WebSolver) {
Progress p = Progress.getInstance(((WebSolver)solver).currentSolution().getModel());
p.clearProgressListeners();
p.addProgressListener((WebSolver)solver);
sSolvers.put(user.getId(),solver);
}
return solver;
}
public static ExamSolverProxy reloadExamSolver(javax.servlet.http.HttpSession session, Long settingsId, Hashtable extraParams) throws Exception {
User user = Web.getUser(session);
if (user==null) return null;
ExamSolverProxy solver = getExamSolver(session);
if (solver==null) return null;
DataProperties oldProperties = solver.getProperties();
if (settingsId==null)
settingsId = oldProperties.getPropertyLong("General.SettingsId", null);
DataProperties properties = createProperties(settingsId, extraParams, SolverParameterGroup.sTypeExam);
String warn = SolverWarnings.getSolverWarning(session, oldProperties.getPropertyLongArry("General.SolverGroupId", null));
if (warn!=null) properties.setProperty("General.SolverWarnings",warn);
properties.setProperty("General.SessionId",oldProperties.getProperty("General.SessionId"));
properties.setProperty("General.SolverGroupId",oldProperties.getProperty("General.SolverGroupId"));
properties.setProperty("General.OwnerPuid", oldProperties.getProperty("General.OwnerPuid"));
properties.setProperty("General.StartTime", String.valueOf((new Date()).getTime()));
String instructorFormat = Settings.getSettingValue(user, Constants.SETTINGS_INSTRUCTOR_NAME_FORMAT);
if (instructorFormat!=null)
properties.setProperty("General.InstructorFormat",instructorFormat);
solver.reload(properties);
return solver;
}
public void dispose() {
super.dispose();
if (iJspWriter!=null) {
try {
iJspWriter.println("<I>Solver finished.</I>");
iJspWriter.flush();
} catch (Exception e) {}
iJspWriter = null;
}
String puid = getProperties().getProperty("General.OwnerPuid");
if (puid!=null)
sSolvers.remove(puid);
}
public static void saveSolution(javax.servlet.http.HttpSession session, boolean createNewSolution, boolean commitSolution) throws Exception {
SolverProxy solver = getSolver(session);
if (solver==null) return;
solver.save(createNewSolution, commitSolution);
}
public static void removeSolver(javax.servlet.http.HttpSession session) throws Exception {
session.removeAttribute("SolverProxy");
session.removeAttribute("Suggestions.model");
session.removeAttribute("Timetable.table");
SolverProxy solver = getSolverNoSessionCheck(session);
if (solver!=null) {
if (solver.isRunning()) solver.stopSolver();
solver.dispose();
}
session.removeAttribute("ManageSolver.puid");
}
public static void removeExamSolver(javax.servlet.http.HttpSession session) throws Exception {
session.removeAttribute("ExamSolverProxy");
ExamSolverProxy solver = getExamSolverNoSessionCheck(session);
if (solver!=null) {
if (solver.isRunning()) solver.stopSolver();
solver.dispose();
}
}
public static Hashtable<String,SolverProxy> getSolvers() throws Exception {
Hashtable<String,SolverProxy> solvers = new Hashtable(sSolvers);
Set servers = SolverRegisterService.getInstance().getServers();
synchronized (servers) {
for (Iterator i=servers.iterator();i.hasNext();) {
RemoteSolverServerProxy server = (RemoteSolverServerProxy)i.next();
if (!server.isActive()) continue;
Hashtable serverSolvers = server.getSolvers();
if (serverSolvers!=null)
solvers.putAll(serverSolvers);
}
}
return solvers;
}
public static Hashtable<String,ExamSolverProxy> getExamSolvers() throws Exception {
Hashtable<String,ExamSolverProxy> solvers = new Hashtable(sExamSolvers);
Set servers = SolverRegisterService.getInstance().getServers();
synchronized (servers) {
for (Iterator i=servers.iterator();i.hasNext();) {
RemoteSolverServerProxy server = (RemoteSolverServerProxy)i.next();
if (!server.isActive()) continue;
Hashtable serverSolvers = server.getExamSolvers();
if (serverSolvers!=null)
solvers.putAll(serverSolvers);
}
}
return solvers;
}
public static Hashtable getLocalSolvers() throws Exception {
return sSolvers;
}
public static Hashtable getLocalExaminationSolvers() throws Exception {
return sExamSolvers;
}
public void setHtmlMessageWriter(JspWriter out) {
if (iJspWriter!=null && !iJspWriter.equals(out)) {
try {
iJspWriter.println("<I>Thread ended.</I>");
} catch (Exception e) {}
}
iJspWriter = out;
while (out.equals(iJspWriter)) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("STOP: "+e.getMessage());
break;
}
}
}
//Progress listener
public void statusChanged(String status) {}
public void phaseChanged(String phase) {}
public void progressChanged(long currentProgress, long maxProgress) {}
public void progressSaved() {}
public void progressRestored() {}
public void progressMessagePrinted(Progress.Message message) {
try {
if (iJspWriter!=null) {
String m = message.toHtmlString(getDebugLevel());
if (m!=null) {
iJspWriter.println(m+"<br>");
iJspWriter.flush();
}
}
} catch (IOException e) {
System.out.println("STOP: "+e.getMessage());
iJspWriter = null;
}
}
public String getHost() {
return "local";
}
public String getHostLabel() {
return getHost();
}
private void backup() {
if (!sBackupWhenDone) return;
String puid = getProperties().getProperty("General.OwnerPuid");
if (puid!=null)
backup(SolverRegisterService.sBackupDir,puid);
}
protected void onFinish() {
super.onFinish();
backup();
}
protected void onStop() {
super.onStop();
backup();
}
protected void afterLoad() {
super.afterLoad();
backup();
}
protected void afterFinalSectioning() {
super.afterFinalSectioning();
backup();
}
public void restoreBest() {
super.restoreBest();
backup();
}
public void saveBest() {
super.saveBest();
backup();
}
public static void backup(File folder) {
if (folder.exists() && !folder.isDirectory()) return;
folder.mkdirs();
File[] old = folder.listFiles(new BackupFileFilter(true,true));
for (int i=0;i<old.length;i++)
old[i].delete();
synchronized (sSolvers) {
for (Iterator i=sSolvers.entrySet().iterator();i.hasNext();) {
Map.Entry entry = (Map.Entry)i.next();
String puid = (String)entry.getKey();
WebSolver solver =(WebSolver)entry.getValue();
solver.backup(folder, puid);
}
}
synchronized (sExamSolvers) {
for (Iterator i=sExamSolvers.entrySet().iterator();i.hasNext();) {
Map.Entry entry = (Map.Entry)i.next();
String puid = (String)entry.getKey();
ExamSolver solver =(ExamSolver)entry.getValue();
solver.backup(folder, puid);
}
}
}
public static void restore(File folder, File passivateFolder) {
if (!folder.exists() || !folder.isDirectory()) return;
synchronized (sSolvers) {
for (Iterator i=sSolvers.values().iterator();i.hasNext();) {
WebSolver solver =(WebSolver)i.next();
solver.dispose();
}
sSolvers.clear();
File[] files = folder.listFiles(new BackupFileFilter(true,false));
for (int i=0;i<files.length;i++) {
File file = files[i];
String puid = file.getName().substring(0,file.getName().indexOf('.'));
if (puid.startsWith("exam_")) {
String exPuid = puid.substring("exam_".length());
ExamSolver solver = new ExamSolver(new DataProperties(), new ExamSolverOnDispose(exPuid));
if (solver.restore(folder, exPuid)) {
if (passivateFolder!=null)
solver.passivate(passivateFolder,puid);
sExamSolvers.put(exPuid, solver);
}
continue;
}
WebSolver solver = new WebSolver(new DataProperties());
if (solver.restore(folder,puid)) {
if (passivateFolder!=null)
solver.passivate(passivateFolder,puid);
sSolvers.put(puid,solver);
}
}
}
}
public static void startSolverPasivationThread(File folder) {
if (sSolverPasivationThread!=null && sSolverPasivationThread.isAlive()) return;
sSolverPasivationThread = new SolverPassivationThread(folder, sSolvers, sExamSolvers);
sSolverPasivationThread.start();
}
public static void stopSolverPasivationThread() {
if (sSolverPasivationThread!=null && sSolverPasivationThread.isAlive()) {
sSolverPasivationThread.interrupt();
}
}
public static ClassAssignmentProxy getClassAssignmentProxy(HttpSession session) {
SolverProxy solver = getSolver(session);
if (solver!=null) return new CachedClassAssignmentProxy(solver);
String solutionIdsStr = (String)session.getAttribute("Solver.selectedSolutionId");
Set solutionIds = new HashSet();
if (solutionIdsStr!=null) {
for (StringTokenizer s = new StringTokenizer(solutionIdsStr, ",");s.hasMoreTokens();) {
Long solutionId = Long.valueOf(s.nextToken());
solutionIds.add(solutionId);
}
}
SolutionClassAssignmentProxy cachedProxy = (SolutionClassAssignmentProxy)session.getAttribute("LastSolutionClassAssignmentProxy");
if (cachedProxy!=null && cachedProxy.equals(solutionIds)) {
return cachedProxy;
}
SolutionClassAssignmentProxy newProxy = new SolutionClassAssignmentProxy(solutionIds);
session.setAttribute("LastSolutionClassAssignmentProxy",newProxy);
return newProxy;
}
public static long getAvailableMemory() {
System.gc();
return Runtime.getRuntime().maxMemory() - Runtime.getRuntime().totalMemory() + Runtime.getRuntime().freeMemory();
}
public static long getUsage() {
int ret = 0;
for (Iterator i=sSolvers.entrySet().iterator();i.hasNext();) {
Map.Entry entry = (Map.Entry)i.next();
SolverProxy solver = (SolverProxy)entry.getValue();
ret++;
if (!solver.isPassivated()) ret++;
try {
if (solver.isWorking()) ret++;
} catch (Exception e) {};
}
for (Iterator i=sExamSolvers.entrySet().iterator();i.hasNext();) {
Map.Entry entry = (Map.Entry)i.next();
ExamSolverProxy solver = (ExamSolverProxy)entry.getValue();
ret++;
if (!solver.isPassivated()) ret++;
try {
if (solver.isWorking()) ret++;
} catch (Exception e) {};
}
return ret;
}
private static class ExamSolverOnDispose implements ExamSolverDisposeListener {
String iOwnerId = null;
public ExamSolverOnDispose(String ownerId) {
iOwnerId = ownerId;
}
public void onDispose() {
sExamSolvers.remove(iOwnerId);
}
}
}
| true | true | public static DataProperties createProperties(Long settingsId, Hashtable extraParams, int type) {
DataProperties properties = new DataProperties();
Transaction tx = null;
try {
SolverPredefinedSettingDAO dao = new SolverPredefinedSettingDAO();
org.hibernate.Session hibSession = dao.getSession();
if (hibSession.getTransaction()==null || !hibSession.getTransaction().isActive())
tx = hibSession.beginTransaction();
List defaultParams = hibSession.createCriteria(SolverParameterDef.class).list();
for (Iterator i=defaultParams.iterator();i.hasNext();) {
SolverParameterDef def = (SolverParameterDef)i.next();
if (def.getGroup().getType()!=type) continue;
if (def.getDefault()!=null)
properties.put(def.getName(),def.getDefault());
if (extraParams!=null && extraParams.containsKey(def.getUniqueId()))
properties.put(def.getName(), (String)extraParams.get(def.getUniqueId()));
}
SolverPredefinedSetting settings = dao.get(settingsId);
for (Iterator i=settings.getParameters().iterator();i.hasNext();) {
SolverParameter param = (SolverParameter)i.next();
if (!param.getDefinition().isVisible().booleanValue()) continue;
if (param.getDefinition().getGroup().getType()!=type) continue;
properties.put(param.getDefinition().getName(),param.getValue());
if (extraParams!=null && extraParams.containsKey(param.getDefinition().getUniqueId()))
properties.put(param.getDefinition().getName(), (String)extraParams.get(param.getDefinition().getUniqueId()));
}
properties.setProperty("General.SettingsId", settings.getUniqueId().toString());
if (tx!=null) tx.commit();
} catch (Exception e) {
if (tx!=null) tx.rollback();
sLog.error(e);
}
StringBuffer ext = new StringBuffer();
if (properties.getPropertyBoolean("General.SearchIntensification",type==SolverParameterGroup.sTypeCourse)) {
if (ext.length()>0) ext.append(";");
ext.append("net.sf.cpsolver.ifs.extension.SearchIntensification");
}
if (properties.getPropertyBoolean("General.CBS",type==SolverParameterGroup.sTypeCourse)) {
if (ext.length()>0) ext.append(";");
ext.append("net.sf.cpsolver.ifs.extension.ConflictStatistics");
} else if (properties.getPropertyBoolean("ExamGeneral.CBS",type==SolverParameterGroup.sTypeExam)) {
if (ext.length()>0) ext.append(";");
ext.append("net.sf.cpsolver.ifs.extension.ConflictStatistics");
properties.setProperty("ConflictStatistics.Print","true");
}
if (type==SolverParameterGroup.sTypeCourse) {
String mode = properties.getProperty("Basic.Mode","Initial");
if ("MPP".equals(mode)) {
properties.setProperty("General.MPP","true");
if (ext.length()>0) ext.append(";");
ext.append("net.sf.cpsolver.ifs.extension.ViolatedInitials");
}
} else if (type==SolverParameterGroup.sTypeExam) {
String mode = properties.getProperty("ExamBasic.Mode","Initial");
if ("MPP".equals(mode)) {
properties.setProperty("General.MPP","true");
/*
if (ext.length()>0) ext.append(";");
ext.append("net.sf.cpsolver.ifs.extension.ViolatedInitials");
*/
}
}
properties.setProperty("Extensions.Classes",ext.toString());
if (properties.getPropertyBoolean("Basic.DisobeyHard",false)) {
properties.setProperty("General.InteractiveMode", "true");
}
if ("No Action".equals(properties.getProperty("Basic.WhenFinished")) || "No Action".equals(properties.getProperty("ExamBasic.WhenFinished"))) {
properties.setProperty("General.Save","false");
properties.setProperty("General.CreateNewSolution","false");
properties.setProperty("General.Unload","false");
} else if ("Save".equals(properties.getProperty("Basic.WhenFinished")) || "Save".equals(properties.getProperty("ExamBasic.WhenFinished"))) {
properties.setProperty("General.Save","true");
properties.setProperty("General.CreateNewSolution","false");
properties.setProperty("General.Unload","false");
} else if ("Save as New".equals(properties.getProperty("Basic.WhenFinished"))) {
properties.setProperty("General.Save","true");
properties.setProperty("General.CreateNewSolution","true");
properties.setProperty("General.Unload","false");
} else if ("Save and Unload".equals(properties.getProperty("Basic.WhenFinished")) || "Save and Unload".equals(properties.getProperty("ExamBasic.WhenFinished"))) {
properties.setProperty("General.Save","true");
properties.setProperty("General.CreateNewSolution","false");
properties.setProperty("General.Unload","true");
} else if ("Save as New and Unload".equals(properties.getProperty("Basic.WhenFinished"))) {
properties.setProperty("General.Save","true");
properties.setProperty("General.CreateNewSolution","true");
properties.setProperty("General.Unload","true");
}
properties.setProperty("Xml.ShowNames","true");
if (type==SolverParameterGroup.sTypeCourse)
properties.setProperty("Xml.ExportStudentSectioning", "true");
if (type==SolverParameterGroup.sTypeExam) {
properties.setProperty("Exam.GreatDeluge", ("Great Deluge".equals(properties.getProperty("Exam.Algorithm","Great Deluge"))?"true":"false"));
properties.setProperty("Exam.Type", extraParams.get("Exam.Type").toString());
}
properties.expand();
return properties;
}
| public static DataProperties createProperties(Long settingsId, Hashtable extraParams, int type) {
DataProperties properties = new DataProperties();
Transaction tx = null;
try {
SolverPredefinedSettingDAO dao = new SolverPredefinedSettingDAO();
org.hibernate.Session hibSession = dao.getSession();
if (hibSession.getTransaction()==null || !hibSession.getTransaction().isActive())
tx = hibSession.beginTransaction();
List defaultParams = hibSession.createCriteria(SolverParameterDef.class).list();
for (Iterator i=defaultParams.iterator();i.hasNext();) {
SolverParameterDef def = (SolverParameterDef)i.next();
if (def.getGroup().getType()!=type) continue;
if (def.getDefault()!=null)
properties.put(def.getName(),def.getDefault());
if (extraParams!=null && extraParams.containsKey(def.getUniqueId()))
properties.put(def.getName(), (String)extraParams.get(def.getUniqueId()));
}
SolverPredefinedSetting settings = dao.get(settingsId);
for (Iterator i=settings.getParameters().iterator();i.hasNext();) {
SolverParameter param = (SolverParameter)i.next();
if (!param.getDefinition().isVisible().booleanValue()) continue;
if (param.getDefinition().getGroup().getType()!=type) continue;
properties.put(param.getDefinition().getName(),param.getValue());
if (extraParams!=null && extraParams.containsKey(param.getDefinition().getUniqueId()))
properties.put(param.getDefinition().getName(), (String)extraParams.get(param.getDefinition().getUniqueId()));
}
properties.setProperty("General.SettingsId", settings.getUniqueId().toString());
if (tx!=null) tx.commit();
} catch (Exception e) {
if (tx!=null) tx.rollback();
sLog.error(e);
}
StringBuffer ext = new StringBuffer();
if (properties.getPropertyBoolean("General.SearchIntensification",type==SolverParameterGroup.sTypeCourse)) {
if (ext.length()>0) ext.append(";");
ext.append("net.sf.cpsolver.ifs.extension.SearchIntensification");
}
if (properties.getPropertyBoolean("General.CBS",type==SolverParameterGroup.sTypeCourse)) {
if (ext.length()>0) ext.append(";");
ext.append("net.sf.cpsolver.ifs.extension.ConflictStatistics");
} else if (properties.getPropertyBoolean("ExamGeneral.CBS",type==SolverParameterGroup.sTypeExam)) {
if (ext.length()>0) ext.append(";");
ext.append("net.sf.cpsolver.ifs.extension.ConflictStatistics");
properties.setProperty("ConflictStatistics.Print","true");
}
if (type==SolverParameterGroup.sTypeCourse) {
String mode = properties.getProperty("Basic.Mode","Initial");
if ("MPP".equals(mode)) {
properties.setProperty("General.MPP","true");
if (ext.length()>0) ext.append(";");
ext.append("net.sf.cpsolver.ifs.extension.ViolatedInitials");
}
} else if (type==SolverParameterGroup.sTypeExam) {
String mode = properties.getProperty("ExamBasic.Mode","Initial");
if ("MPP".equals(mode)) {
properties.setProperty("General.MPP","true");
/*
if (ext.length()>0) ext.append(";");
ext.append("net.sf.cpsolver.ifs.extension.ViolatedInitials");
*/
}
}
properties.setProperty("Extensions.Classes",ext.toString());
if (properties.getPropertyBoolean("Basic.DisobeyHard",false)) {
properties.setProperty("General.InteractiveMode", "true");
}
if ("No Action".equals(properties.getProperty("Basic.WhenFinished")) || "No Action".equals(properties.getProperty("ExamBasic.WhenFinished"))) {
properties.setProperty("General.Save","false");
properties.setProperty("General.CreateNewSolution","false");
properties.setProperty("General.Unload","false");
} else if ("Save".equals(properties.getProperty("Basic.WhenFinished")) || "Save".equals(properties.getProperty("ExamBasic.WhenFinished"))) {
properties.setProperty("General.Save","true");
properties.setProperty("General.CreateNewSolution","false");
properties.setProperty("General.Unload","false");
} else if ("Save as New".equals(properties.getProperty("Basic.WhenFinished"))) {
properties.setProperty("General.Save","true");
properties.setProperty("General.CreateNewSolution","true");
properties.setProperty("General.Unload","false");
} else if ("Save and Unload".equals(properties.getProperty("Basic.WhenFinished")) || "Save and Unload".equals(properties.getProperty("ExamBasic.WhenFinished"))) {
properties.setProperty("General.Save","true");
properties.setProperty("General.CreateNewSolution","false");
properties.setProperty("General.Unload","true");
} else if ("Save as New and Unload".equals(properties.getProperty("Basic.WhenFinished"))) {
properties.setProperty("General.Save","true");
properties.setProperty("General.CreateNewSolution","true");
properties.setProperty("General.Unload","true");
}
properties.setProperty("Xml.ShowNames","true");
if (type==SolverParameterGroup.sTypeCourse)
properties.setProperty("Xml.ExportStudentSectioning", "true");
if (type==SolverParameterGroup.sTypeExam) {
properties.setProperty("Exam.GreatDeluge", ("Great Deluge".equals(properties.getProperty("Exam.Algorithm","Great Deluge"))?"true":"false"));
if (extraParams!=null && extraParams.get("Exam.Type")!=null)
properties.setProperty("Exam.Type", extraParams.get("Exam.Type").toString());
}
properties.expand();
return properties;
}
|
diff --git a/src/com/dotcms/solr/business/SolrQueueJob.java b/src/com/dotcms/solr/business/SolrQueueJob.java
index 95ec991..c8f4ae7 100644
--- a/src/com/dotcms/solr/business/SolrQueueJob.java
+++ b/src/com/dotcms/solr/business/SolrQueueJob.java
@@ -1,455 +1,455 @@
package com.dotcms.solr.business;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.solr.common.SolrInputDocument;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.StatefulJob;
import com.dotcms.solr.util.SolrUtil;
import com.dotmarketing.beans.Host;
import com.dotmarketing.beans.Identifier;
import com.dotmarketing.business.APILocator;
import com.dotmarketing.business.IdentifierAPI;
import com.dotmarketing.business.UserAPI;
import com.dotmarketing.exception.DotDataException;
import com.dotmarketing.plugin.business.PluginAPI;
import com.dotmarketing.portlets.categories.model.Category;
import com.dotmarketing.portlets.contentlet.business.ContentletAPI;
import com.dotmarketing.portlets.contentlet.business.HostAPI;
import com.dotmarketing.portlets.contentlet.model.Contentlet;
import com.dotmarketing.portlets.fileassets.business.IFileAsset;
import com.dotmarketing.portlets.structure.model.Field;
import com.dotmarketing.portlets.structure.model.FieldVariable;
import com.dotmarketing.portlets.structure.model.Structure;
import com.dotmarketing.util.Logger;
import com.dotmarketing.util.UtilMethods;
import com.liferay.portal.model.User;
/**
* This class read the solr_queue table and add/update or delete elements in the solr index
* @author Oswaldo
*
*/
public class SolrQueueJob implements StatefulJob {
private String pluginId = "com.dotcms.solr";
private PluginAPI pluginAPI = APILocator.getPluginAPI();
private ContentletAPI conAPI = APILocator.getContentletAPI();
private UserAPI userAPI = APILocator.getUserAPI();
private HostAPI hostAPI = APILocator.getHostAPI();
private SolrAPI solrAPI = SolrAPI.getInstance();
private IdentifierAPI identifierAPI = APILocator.getIdentifierAPI() ;
public void execute(JobExecutionContext arg0) throws JobExecutionException {
int serversNumber = 0;
int documentsPerRequest = 1;
try {
Logger.info(SolrQueueJob.class, "Running Solr Queue Job");
User user = userAPI.getSystemUser();
serversNumber = Integer.parseInt(pluginAPI.loadProperty(pluginId, "com.dotcms.solr.SOLR_SERVER_NUMBER"));
/*Number of documents to send in one request*/
documentsPerRequest = Integer.parseInt(pluginAPI.loadProperty(pluginId, "com.dotcms.solr.DOCUMENTS_PER_REQUEST"));
if(documentsPerRequest < 1){
documentsPerRequest = 1;
}
/*Get attribute to modify field varname */
String solrField = pluginAPI.loadProperty(pluginId, "com.dotcms.solr.MODIFY_FIELD_NAME_ATTRIBUTE");
/*Get the name of the attribute that indicates if a field shouldn't be include in the solr index*/
String ignoreField = pluginAPI.loadProperty(pluginId, "com.dotcms.solr.IGNORE_FIELDS_WITH_ATTRIBUTE");
String ignoreHostVariableForFileAssetsString = pluginAPI.loadProperty(pluginId, "com.dotcms.solr.IGNORE_HOST_SUBSTITUTE");
boolean isHostSubstituteRequired = "false".equalsIgnoreCase(ignoreHostVariableForFileAssetsString);
/*Metadata field to ignore*/
String dynamicIgnoreMetadaField = pluginAPI.loadProperty(pluginId, "com.dotcms.solr.IGNORE_METADATA_FIELD_ATTRIBUTES");
String ignoreMetadataFieldsString = pluginAPI.loadProperty(pluginId, "com.dotcms.solr.IGNORE_METADATA_FIELDS");
List<String> ignoreMetadataFields = new ArrayList<String>();
if(UtilMethods.isSet(ignoreMetadataFieldsString)){
for(String attr : ignoreMetadataFieldsString.split(",")){
ignoreMetadataFields.add(attr.trim());
}
}
/*the job is executed only if there are solr servers and entries in the solr_queue table to process */
if(serversNumber > 0){
List<Map<String,Object>> solrQueue = solrAPI.getSolrQueueContentletToProcess();
Logger.info(SolrQueueJob.class, "Solr Queue element(s) to process: "+solrQueue.size());
if(solrQueue.size() > 0){
Map<String,Collection<SolrInputDocument>> addDocs = new HashMap<String,Collection<SolrInputDocument>>();
Map<String,List<Map<String,Object>>> solrIdAddDocs = new HashMap<String,List<Map<String,Object>>>();
Map<String,List<String>> deleteDocs = new HashMap<String,List<String>>();
Map<String,List<Map<String,Object>>> solrIdDeleteDocs = new HashMap<String,List<Map<String,Object>>>();
Map<String,Long> languages = new HashMap<String,Long>();
for(Map<String,Object> solr : solrQueue){
try {
if(Long.parseLong(solr.get("solr_operation").toString()) == SolrAPI.ADD_OR_UPDATE_SOLR_ELEMENT){
SolrInputDocument doc = new SolrInputDocument();
String identifier =(String)solr.get("asset_identifier");
long languageId =Long.parseLong(solr.get("language_id").toString());
Contentlet con = null;
Host host=null;
try {
con = conAPI.findContentletByIdentifier(identifier, true, languageId, user, false);
}catch(Exception e){
Logger.debug(SolrQueueJob.class,e.getMessage(),e);
}
if(UtilMethods.isSet(con)){
languages.put(con.getIdentifier(), con.getLanguageId());
doc.addField("id", con.getIdentifier());
doc.addField("inode", con.getInode());
doc.addField("modUser", con.getModUser());
//String modDate = UtilMethods.dateToHTMLDate(con.getModDate(), "yyyy-MM-dd")+"T"+ UtilMethods.dateToHTMLDate(con.getModDate(), "HH:mm:ss.S")+"Z";
String modDate = SolrUtil.getGenericFormattedDateText(con.getModDate(), SolrUtil.SOLR_DEFAULT_DATE_FORMAT);
doc.addField("modDate",modDate);
doc.addField("host", con.getHost());
doc.addField("folder", con.getFolder());
Structure st = con.getStructure();
doc.addField("structureName", st.getName());
doc.addField("structureInode", st.getInode());
doc.addField("structureId", st.getVelocityVarName());
doc.addField("structureType", st.getStructureType());
if(UtilMethods.isSet(st.getDescription())){
doc.addField("structureDescription", st.getDescription());
} else {
doc.addField("structureDescription", "");
}
for(Field f : st.getFieldsBySortOrder()){
List<FieldVariable> fieldVariables = APILocator.getFieldAPI().getFieldVariablesForField(f.getInode(), user, false);
if(!SolrUtil.containsFieldVariable(fieldVariables, ignoreField)){
Object value = conAPI.getFieldValue(con, f);
String solrFieldName = SolrUtil.getSolrFieldName(fieldVariables, solrField, f.getVelocityVarName());
if(f.getFieldType().equals(Field.FieldType.DATE.toString()) || f.getFieldType().equals(Field.FieldType.DATE_TIME.toString())){
String date = "";
if(UtilMethods.isSet(value)){
//date = UtilMethods.dateToHTMLDate((Date)value, "yyyy-MM-dd")+"T"+ UtilMethods.dateToHTMLDate((Date)value, "HH:mm:ss.S")+"Z";
date = SolrUtil.getFormattedUTCDateText((Date) value, SolrUtil.SOLR_DEFAULT_DATE_FORMAT);
}
doc.addField(solrFieldName, date);
}else if(f.getFieldType().equals(Field.FieldType.FILE.toString()) || f.getFieldType().equals(Field.FieldType.IMAGE.toString())){
String path = "";
if(UtilMethods.isSet(value)){
Identifier assetIdentifier = identifierAPI.find((String)value);
host = hostAPI.find(assetIdentifier.getHostId(), user, false);
String hostName ="";
if (isHostSubstituteRequired) {
if(UtilMethods.isSet(host)){
hostName="http://"+host.getHostname();
}else{
host = hostAPI.findDefaultHost(user, false);
hostName="http://"+host.getHostname();
}
}
path = hostName+assetIdentifier.getParentPath()+assetIdentifier.getAssetName();
/**
* Add to solr index file or image field metadata
*/
if(con.getStructure().getStructureType()!=Structure.STRUCTURE_TYPE_FILEASSET){
Contentlet fileCon = conAPI.findContentletByIdentifier(assetIdentifier.getInode(), true, languageId, user, false);
IFileAsset fileA = APILocator.getFileAssetAPI().fromContentlet(fileCon);
java.io.File file = fileA.getFileAsset();
Map<String, String> keyValueMap = SolrUtil.getMetaDataMap(f, file);
for(String key : keyValueMap.keySet()){
if(!ignoreMetadataFields.contains(key) && !SolrUtil.containsFieldVariableIgnoreField(fieldVariables,dynamicIgnoreMetadaField, key)){
doc.addField(solrFieldName+"_"+key, keyValueMap.get(key));
}
}
}
}
doc.addField(solrFieldName, path );
}else if(f.getFieldType().equals(Field.FieldType.BINARY.toString())){
String path="";
if(UtilMethods.isSet(value)){
java.io.File fileValue = (java.io.File)value;
String fileName = fileValue.getName();
host = hostAPI.find(con.getHost(), user, false);
String hostName ="";
if (isHostSubstituteRequired) {
if(UtilMethods.isSet(host)){
hostName="http://"+host.getHostname();
}else{
host = hostAPI.findDefaultHost(user, false);
hostName="http://"+host.getHostname();
}
}
if(UtilMethods.isImage(fileName)){
path=hostName+"/contentAsset/image/"+con.getInode()+"/"+f.getVelocityVarName()+"/?byInode=true";
}else{
path=hostName+"/contentAsset/raw-data/"+ con.getInode() + "/" + f.getVelocityVarName() + "?byInode=true";
}
/**
* Add to solr index binary field metadata
*/
if(con.getStructure().getStructureType()!=Structure.STRUCTURE_TYPE_FILEASSET){
Map<String, String> keyValueMap = SolrUtil.getMetaDataMap(f, fileValue);
for(String key : keyValueMap.keySet()){
if(!ignoreMetadataFields.contains(key) && !SolrUtil.containsFieldVariableIgnoreField(fieldVariables,dynamicIgnoreMetadaField, key)){
doc.addField(solrFieldName+"_"+key, keyValueMap.get(key));
}
}
}
}
doc.addField(solrFieldName, path);
}else if(f.getFieldType().equals(Field.FieldType.TAG.toString())||
f.getFieldType().equals(Field.FieldType.CHECKBOX.toString()) ||
f.getFieldType().equals(Field.FieldType.MULTI_SELECT.toString()) ||
f.getFieldType().equals(Field.FieldType.CUSTOM_FIELD.toString())){
String valueString = (String)value;
if(UtilMethods.isSet(valueString)){
doc.addField(solrFieldName, valueString.split(","));
}else{
doc.addField(solrFieldName,valueString);
}
}else if(f.getFieldType().equals(Field.FieldType.KEY_VALUE.toString())){
Map<String, Object> keyValueMap = null;
String JSONValue = UtilMethods.isSet(value)? (String)value:"";
//Convert JSON to Table Display {key, value, order}
if(UtilMethods.isSet(JSONValue)){
keyValueMap = com.dotmarketing.portlets.structure.model.KeyValueFieldUtil.JSONValueToHashMap(JSONValue);
}
for(String key : keyValueMap.keySet()){
if(!ignoreMetadataFields.contains(key) && !SolrUtil.containsFieldVariableIgnoreField(fieldVariables,dynamicIgnoreMetadaField, key)){
doc.addField(solrFieldName+"_"+key, keyValueMap.get(key));
}
}
}else if(f.getFieldType().equals(Field.FieldType.CATEGORY.toString())){
@SuppressWarnings("unchecked")
HashSet<Category> categorySet = (HashSet<Category>) value;
Set<String> categoryList = new HashSet<String>();
for(Category cat : categorySet){
if(UtilMethods.isSet(cat.getKey())){
categoryList.add(cat.getKey());
}else{
categoryList.add(cat.getCategoryVelocityVarName());
}
Set<Category> parents = SolrUtil.getAllParentsCategories(cat, user);
for(Category parentCat : parents){
if(UtilMethods.isSet(parentCat.getKey())){
categoryList.add(parentCat.getKey());
}else{
categoryList.add(parentCat.getCategoryVelocityVarName());
}
}
}
for(String categoryVar : categoryList){
doc.addField(solrFieldName, categoryVar);
}
}else{
doc.addField(solrFieldName, value);
}
}
}
/*variables to send docs in groups per request in solr*/
for(String solrServerUrl : SolrUtil.getContentletSolrServers(con,user)){
if(!addDocs.containsKey(solrServerUrl)){
addDocs.put(solrServerUrl, new ArrayList<SolrInputDocument>());
}
if(!solrIdAddDocs.containsKey(solrServerUrl)){
solrIdAddDocs.put(solrServerUrl,new ArrayList<Map<String,Object>>());
}
Collection<SolrInputDocument> addDocsList = addDocs.get(solrServerUrl);
addDocsList.add(doc);
addDocs.put(solrServerUrl,addDocsList);
List<Map<String,Object>> solrIdAddDocsList = solrIdAddDocs.get(solrServerUrl);
solrIdAddDocsList.add(solr);
solrIdAddDocs.put(solrServerUrl,solrIdAddDocsList);
/* Add or update index element*/
if(addDocsList.size() == documentsPerRequest){
Logger.debug(SolrQueueJob.class,"Sending Add/Update Document(s) group request to Solr");
try {
SolrUtil.addToSolrIndex(solrServerUrl,addDocsList);
int addCounter = 0;
for(Map<String,Object> solrO : solrIdAddDocsList){
solrAPI.deleteElementFromSolrQueueTable(Long.parseLong(solrO.get("id").toString()));//delete from table
addCounter++;
}
addDocsList.clear();
addDocs.remove(solrServerUrl);
solrIdAddDocsList.clear();
solrIdAddDocs.remove(solrServerUrl);
Logger.debug(SolrQueueJob.class,"Document(s) Added/Updated: "+addCounter);
}catch(Exception e){
Logger.debug(SolrQueueJob.class,e.getMessage(),e);
Logger.debug(SolrQueueJob.class,"Document(s) not Added/Updated: "+addDocsList.size());
for(Map<String,Object> solrO : solrIdAddDocsList){
solrAPI.updateElementStatusFromSolrQueueTable(Long.parseLong(solrO.get("id").toString()),new Date(),(Integer.parseInt(solrO.get("num_of_tries").toString())+1), true, "An error occurs trying to add/update this assets in the Solr Index. ERROR: "+e);
}
addDocsList.clear();
addDocs.remove(solrServerUrl);
solrIdAddDocsList.clear();
solrIdAddDocs.remove(solrServerUrl);
break;
}
}
}
}else{
solrAPI.updateElementStatusFromSolrQueueTable(Long.parseLong(solr.get("id").toString()),new Date(),(Integer.parseInt(solr.get("num_of_tries").toString())+1), true, "This file asset content:"+(String)solr.get("asset_identifier")+" doesn't exist");
}
} else if(Long.parseLong(solr.get("solr_operation").toString()) == SolrAPI.DELETE_SOLR_ELEMENT){
/* delete element from index*/
String id = (String)solr.get("asset_identifier");
languages.put((String)solr.get("asset_identifier"), Long.parseLong(solr.get("language_id").toString()));
long languageId = languages.get(id);
- Contentlet con = conAPI.findContentletByIdentifier(id, true, languageId, user, false);
+ Contentlet con = conAPI.findContentletByIdentifier(id, false, languageId, user, false);
for(String solrServerUrl : SolrUtil.getContentletSolrServers(con,user)){
if(!deleteDocs.containsKey(solrServerUrl)){
deleteDocs.put(solrServerUrl, new ArrayList<String>());
}
if(!solrIdDeleteDocs.containsKey(solrServerUrl)){
solrIdDeleteDocs.put(solrServerUrl,new ArrayList<Map<String,Object>>());
}
List<String> deleteDocsList = deleteDocs.get(solrServerUrl);
deleteDocsList.add(id);
deleteDocs.put(solrServerUrl,deleteDocsList);
List<Map<String,Object>> solrIdDeleteDocsList = solrIdDeleteDocs.get(solrServerUrl);
solrIdDeleteDocsList.add(solr);
solrIdDeleteDocs.put(solrServerUrl,solrIdDeleteDocsList);
if(deleteDocsList.size() == documentsPerRequest){
Logger.debug(SolrQueueJob.class,"Sending Delete Document(s) group request to Solr");
try {
Logger.debug(SolrQueueJob.class,"Document(s) to Delete: "+deleteDocsList.size());
SolrUtil.deleteFromSolrIndexById(solrServerUrl,deleteDocsList);
int deleteCounter = 0;
for(Map<String,Object> solrO : solrIdDeleteDocsList){
solrAPI.deleteElementFromSolrQueueTable(Long.parseLong(solrO.get("id").toString()));//delete from table
deleteCounter++;
}
deleteDocsList.clear();
deleteDocs.remove(solrServerUrl);
solrIdDeleteDocsList.clear();
solrIdDeleteDocs.remove(solrServerUrl);
Logger.debug(SolrQueueJob.class,"Document(s) Deleted: "+deleteCounter);
}catch(Exception e){
Logger.debug(SolrQueueJob.class,e.getMessage(),e);
Logger.debug(SolrQueueJob.class,"Document(s) not Deleted: "+deleteDocsList.size());
for(Map<String,Object> solrO : solrIdDeleteDocsList){
solrAPI.updateElementStatusFromSolrQueueTable(Long.parseLong(solrO.get("id").toString()),new Date(),(Integer.parseInt(solrO.get("num_of_tries").toString())+1), true, "An error occurs trying to delete this assets in the Solr Index. ERROR: "+e);
}
deleteDocsList.clear();
deleteDocs.remove(solrServerUrl);
solrIdDeleteDocsList.clear();
solrIdDeleteDocs.remove(solrServerUrl);
break;
}
}
}
}
}catch(Exception b){
Logger.debug(SolrQueueJob.class,b.getMessage(),b);
solrAPI.updateElementStatusFromSolrQueueTable(Long.parseLong(solr.get("id").toString()),new Date(),(Integer.parseInt(solr.get("num_of_tries").toString())+1), true, "An error occurs trying to process this assets in the Solr Index. ERROR: "+b);
}
}
if(addDocs.size() > 0 ){
/* Add or update index element*/
Logger.debug(SolrQueueJob.class,"Sending Add/Update Document(s) group request to Solr");
for(String solrServerUrl : addDocs.keySet()){
Collection<SolrInputDocument> addDocsList = addDocs.get(solrServerUrl);
List<Map<String,Object>> solrIdAddDocsList = solrIdAddDocs.get(solrServerUrl);
try {
Logger.debug(SolrQueueJob.class,"Document(s) to Add/Update: "+addDocsList.size());
SolrUtil.addToSolrIndex(solrServerUrl,addDocsList);
int addCounter = 0;
for(Map<String,Object> solrO : solrIdAddDocsList){
solrAPI.deleteElementFromSolrQueueTable(Long.parseLong(solrO.get("id").toString()));//delete from table
addCounter++;
}
addDocsList.clear();
addDocs.remove(solrServerUrl);
solrIdAddDocsList.clear();
solrIdAddDocs.remove(solrServerUrl);
Logger.debug(SolrQueueJob.class,"Document(s) Added/Updated: "+addCounter);
}catch(Exception e){
Logger.debug(SolrQueueJob.class,e.getMessage(),e);
Logger.debug(SolrQueueJob.class,"Document(s) not Added/Updated: "+addDocsList.size());
for(Map<String,Object> solrO : solrIdAddDocsList){
solrAPI.updateElementStatusFromSolrQueueTable(Long.parseLong(solrO.get("id").toString()),new Date(),(Integer.parseInt(solrO.get("num_of_tries").toString())+1), true, "An error occurs trying to add/update this assets in the Solr Index. ERROR: "+e);
}
addDocsList.clear();
addDocs.remove(solrServerUrl);
solrIdAddDocsList.clear();
solrIdAddDocs.remove(solrServerUrl);
}
}
}
if(deleteDocs.size() > 0){
Logger.debug(SolrQueueJob.class,"Sending Delete Document(s) group request to Solr");
for(String solrServerUrl : deleteDocs.keySet()){
List<String> deleteDocsList = deleteDocs.get(solrServerUrl);
List<Map<String,Object>> solrIdDeleteDocsList = solrIdDeleteDocs.get(solrServerUrl);
try {
Logger.debug(SolrQueueJob.class,"Document(s) to Delete: "+deleteDocsList.size());
SolrUtil.deleteFromSolrIndexById(solrServerUrl, deleteDocsList);
int deleteCounter = 0;
for(Map<String,Object> solrO : solrIdDeleteDocsList){
solrAPI.deleteElementFromSolrQueueTable(Long.parseLong(solrO.get("id").toString()));//delete from table
deleteCounter++;
}
deleteDocsList.clear();
deleteDocs.remove(solrServerUrl);
solrIdDeleteDocsList.clear();
solrIdDeleteDocs.remove(solrServerUrl);
Logger.debug(SolrQueueJob.class,"Document(s) Deleted: "+deleteCounter);
}catch(Exception e){
Logger.debug(SolrQueueJob.class,e.getMessage(),e);
Logger.debug(SolrQueueJob.class,"Document(s) not Deleted: "+deleteDocsList.size());
for(Map<String,Object> solrO : solrIdDeleteDocsList){
solrAPI.updateElementStatusFromSolrQueueTable(Long.parseLong(solrO.get("id").toString()),new Date(),(Integer.parseInt(solrO.get("num_of_tries").toString())+1), true, "An error occurs trying to delete this assets in the Solr Index. ERROR: "+e);
}
deleteDocsList.clear();
deleteDocs.remove(solrServerUrl);
solrIdDeleteDocsList.clear();
solrIdDeleteDocs.remove(solrServerUrl);
}
}
}
}
}
Logger.info(SolrQueueJob.class, "Finished Solr Queue Job");
} catch (NumberFormatException e) {
Logger.error(SolrQueueJob.class,e.getMessage(),e);
} catch (DotDataException e) {
Logger.error(SolrQueueJob.class,e.getMessage(),e);
} catch (DotSolrException e) {
Logger.error(SolrQueueJob.class,e.getMessage(),e);
} catch (Exception e) {
Logger.error(SolrQueueJob.class,e.getMessage(),e);
}
}
}
| true | true | public void execute(JobExecutionContext arg0) throws JobExecutionException {
int serversNumber = 0;
int documentsPerRequest = 1;
try {
Logger.info(SolrQueueJob.class, "Running Solr Queue Job");
User user = userAPI.getSystemUser();
serversNumber = Integer.parseInt(pluginAPI.loadProperty(pluginId, "com.dotcms.solr.SOLR_SERVER_NUMBER"));
/*Number of documents to send in one request*/
documentsPerRequest = Integer.parseInt(pluginAPI.loadProperty(pluginId, "com.dotcms.solr.DOCUMENTS_PER_REQUEST"));
if(documentsPerRequest < 1){
documentsPerRequest = 1;
}
/*Get attribute to modify field varname */
String solrField = pluginAPI.loadProperty(pluginId, "com.dotcms.solr.MODIFY_FIELD_NAME_ATTRIBUTE");
/*Get the name of the attribute that indicates if a field shouldn't be include in the solr index*/
String ignoreField = pluginAPI.loadProperty(pluginId, "com.dotcms.solr.IGNORE_FIELDS_WITH_ATTRIBUTE");
String ignoreHostVariableForFileAssetsString = pluginAPI.loadProperty(pluginId, "com.dotcms.solr.IGNORE_HOST_SUBSTITUTE");
boolean isHostSubstituteRequired = "false".equalsIgnoreCase(ignoreHostVariableForFileAssetsString);
/*Metadata field to ignore*/
String dynamicIgnoreMetadaField = pluginAPI.loadProperty(pluginId, "com.dotcms.solr.IGNORE_METADATA_FIELD_ATTRIBUTES");
String ignoreMetadataFieldsString = pluginAPI.loadProperty(pluginId, "com.dotcms.solr.IGNORE_METADATA_FIELDS");
List<String> ignoreMetadataFields = new ArrayList<String>();
if(UtilMethods.isSet(ignoreMetadataFieldsString)){
for(String attr : ignoreMetadataFieldsString.split(",")){
ignoreMetadataFields.add(attr.trim());
}
}
/*the job is executed only if there are solr servers and entries in the solr_queue table to process */
if(serversNumber > 0){
List<Map<String,Object>> solrQueue = solrAPI.getSolrQueueContentletToProcess();
Logger.info(SolrQueueJob.class, "Solr Queue element(s) to process: "+solrQueue.size());
if(solrQueue.size() > 0){
Map<String,Collection<SolrInputDocument>> addDocs = new HashMap<String,Collection<SolrInputDocument>>();
Map<String,List<Map<String,Object>>> solrIdAddDocs = new HashMap<String,List<Map<String,Object>>>();
Map<String,List<String>> deleteDocs = new HashMap<String,List<String>>();
Map<String,List<Map<String,Object>>> solrIdDeleteDocs = new HashMap<String,List<Map<String,Object>>>();
Map<String,Long> languages = new HashMap<String,Long>();
for(Map<String,Object> solr : solrQueue){
try {
if(Long.parseLong(solr.get("solr_operation").toString()) == SolrAPI.ADD_OR_UPDATE_SOLR_ELEMENT){
SolrInputDocument doc = new SolrInputDocument();
String identifier =(String)solr.get("asset_identifier");
long languageId =Long.parseLong(solr.get("language_id").toString());
Contentlet con = null;
Host host=null;
try {
con = conAPI.findContentletByIdentifier(identifier, true, languageId, user, false);
}catch(Exception e){
Logger.debug(SolrQueueJob.class,e.getMessage(),e);
}
if(UtilMethods.isSet(con)){
languages.put(con.getIdentifier(), con.getLanguageId());
doc.addField("id", con.getIdentifier());
doc.addField("inode", con.getInode());
doc.addField("modUser", con.getModUser());
//String modDate = UtilMethods.dateToHTMLDate(con.getModDate(), "yyyy-MM-dd")+"T"+ UtilMethods.dateToHTMLDate(con.getModDate(), "HH:mm:ss.S")+"Z";
String modDate = SolrUtil.getGenericFormattedDateText(con.getModDate(), SolrUtil.SOLR_DEFAULT_DATE_FORMAT);
doc.addField("modDate",modDate);
doc.addField("host", con.getHost());
doc.addField("folder", con.getFolder());
Structure st = con.getStructure();
doc.addField("structureName", st.getName());
doc.addField("structureInode", st.getInode());
doc.addField("structureId", st.getVelocityVarName());
doc.addField("structureType", st.getStructureType());
if(UtilMethods.isSet(st.getDescription())){
doc.addField("structureDescription", st.getDescription());
} else {
doc.addField("structureDescription", "");
}
for(Field f : st.getFieldsBySortOrder()){
List<FieldVariable> fieldVariables = APILocator.getFieldAPI().getFieldVariablesForField(f.getInode(), user, false);
if(!SolrUtil.containsFieldVariable(fieldVariables, ignoreField)){
Object value = conAPI.getFieldValue(con, f);
String solrFieldName = SolrUtil.getSolrFieldName(fieldVariables, solrField, f.getVelocityVarName());
if(f.getFieldType().equals(Field.FieldType.DATE.toString()) || f.getFieldType().equals(Field.FieldType.DATE_TIME.toString())){
String date = "";
if(UtilMethods.isSet(value)){
//date = UtilMethods.dateToHTMLDate((Date)value, "yyyy-MM-dd")+"T"+ UtilMethods.dateToHTMLDate((Date)value, "HH:mm:ss.S")+"Z";
date = SolrUtil.getFormattedUTCDateText((Date) value, SolrUtil.SOLR_DEFAULT_DATE_FORMAT);
}
doc.addField(solrFieldName, date);
}else if(f.getFieldType().equals(Field.FieldType.FILE.toString()) || f.getFieldType().equals(Field.FieldType.IMAGE.toString())){
String path = "";
if(UtilMethods.isSet(value)){
Identifier assetIdentifier = identifierAPI.find((String)value);
host = hostAPI.find(assetIdentifier.getHostId(), user, false);
String hostName ="";
if (isHostSubstituteRequired) {
if(UtilMethods.isSet(host)){
hostName="http://"+host.getHostname();
}else{
host = hostAPI.findDefaultHost(user, false);
hostName="http://"+host.getHostname();
}
}
path = hostName+assetIdentifier.getParentPath()+assetIdentifier.getAssetName();
/**
* Add to solr index file or image field metadata
*/
if(con.getStructure().getStructureType()!=Structure.STRUCTURE_TYPE_FILEASSET){
Contentlet fileCon = conAPI.findContentletByIdentifier(assetIdentifier.getInode(), true, languageId, user, false);
IFileAsset fileA = APILocator.getFileAssetAPI().fromContentlet(fileCon);
java.io.File file = fileA.getFileAsset();
Map<String, String> keyValueMap = SolrUtil.getMetaDataMap(f, file);
for(String key : keyValueMap.keySet()){
if(!ignoreMetadataFields.contains(key) && !SolrUtil.containsFieldVariableIgnoreField(fieldVariables,dynamicIgnoreMetadaField, key)){
doc.addField(solrFieldName+"_"+key, keyValueMap.get(key));
}
}
}
}
doc.addField(solrFieldName, path );
}else if(f.getFieldType().equals(Field.FieldType.BINARY.toString())){
String path="";
if(UtilMethods.isSet(value)){
java.io.File fileValue = (java.io.File)value;
String fileName = fileValue.getName();
host = hostAPI.find(con.getHost(), user, false);
String hostName ="";
if (isHostSubstituteRequired) {
if(UtilMethods.isSet(host)){
hostName="http://"+host.getHostname();
}else{
host = hostAPI.findDefaultHost(user, false);
hostName="http://"+host.getHostname();
}
}
if(UtilMethods.isImage(fileName)){
path=hostName+"/contentAsset/image/"+con.getInode()+"/"+f.getVelocityVarName()+"/?byInode=true";
}else{
path=hostName+"/contentAsset/raw-data/"+ con.getInode() + "/" + f.getVelocityVarName() + "?byInode=true";
}
/**
* Add to solr index binary field metadata
*/
if(con.getStructure().getStructureType()!=Structure.STRUCTURE_TYPE_FILEASSET){
Map<String, String> keyValueMap = SolrUtil.getMetaDataMap(f, fileValue);
for(String key : keyValueMap.keySet()){
if(!ignoreMetadataFields.contains(key) && !SolrUtil.containsFieldVariableIgnoreField(fieldVariables,dynamicIgnoreMetadaField, key)){
doc.addField(solrFieldName+"_"+key, keyValueMap.get(key));
}
}
}
}
doc.addField(solrFieldName, path);
}else if(f.getFieldType().equals(Field.FieldType.TAG.toString())||
f.getFieldType().equals(Field.FieldType.CHECKBOX.toString()) ||
f.getFieldType().equals(Field.FieldType.MULTI_SELECT.toString()) ||
f.getFieldType().equals(Field.FieldType.CUSTOM_FIELD.toString())){
String valueString = (String)value;
if(UtilMethods.isSet(valueString)){
doc.addField(solrFieldName, valueString.split(","));
}else{
doc.addField(solrFieldName,valueString);
}
}else if(f.getFieldType().equals(Field.FieldType.KEY_VALUE.toString())){
Map<String, Object> keyValueMap = null;
String JSONValue = UtilMethods.isSet(value)? (String)value:"";
//Convert JSON to Table Display {key, value, order}
if(UtilMethods.isSet(JSONValue)){
keyValueMap = com.dotmarketing.portlets.structure.model.KeyValueFieldUtil.JSONValueToHashMap(JSONValue);
}
for(String key : keyValueMap.keySet()){
if(!ignoreMetadataFields.contains(key) && !SolrUtil.containsFieldVariableIgnoreField(fieldVariables,dynamicIgnoreMetadaField, key)){
doc.addField(solrFieldName+"_"+key, keyValueMap.get(key));
}
}
}else if(f.getFieldType().equals(Field.FieldType.CATEGORY.toString())){
@SuppressWarnings("unchecked")
HashSet<Category> categorySet = (HashSet<Category>) value;
Set<String> categoryList = new HashSet<String>();
for(Category cat : categorySet){
if(UtilMethods.isSet(cat.getKey())){
categoryList.add(cat.getKey());
}else{
categoryList.add(cat.getCategoryVelocityVarName());
}
Set<Category> parents = SolrUtil.getAllParentsCategories(cat, user);
for(Category parentCat : parents){
if(UtilMethods.isSet(parentCat.getKey())){
categoryList.add(parentCat.getKey());
}else{
categoryList.add(parentCat.getCategoryVelocityVarName());
}
}
}
for(String categoryVar : categoryList){
doc.addField(solrFieldName, categoryVar);
}
}else{
doc.addField(solrFieldName, value);
}
}
}
/*variables to send docs in groups per request in solr*/
for(String solrServerUrl : SolrUtil.getContentletSolrServers(con,user)){
if(!addDocs.containsKey(solrServerUrl)){
addDocs.put(solrServerUrl, new ArrayList<SolrInputDocument>());
}
if(!solrIdAddDocs.containsKey(solrServerUrl)){
solrIdAddDocs.put(solrServerUrl,new ArrayList<Map<String,Object>>());
}
Collection<SolrInputDocument> addDocsList = addDocs.get(solrServerUrl);
addDocsList.add(doc);
addDocs.put(solrServerUrl,addDocsList);
List<Map<String,Object>> solrIdAddDocsList = solrIdAddDocs.get(solrServerUrl);
solrIdAddDocsList.add(solr);
solrIdAddDocs.put(solrServerUrl,solrIdAddDocsList);
/* Add or update index element*/
if(addDocsList.size() == documentsPerRequest){
Logger.debug(SolrQueueJob.class,"Sending Add/Update Document(s) group request to Solr");
try {
SolrUtil.addToSolrIndex(solrServerUrl,addDocsList);
int addCounter = 0;
for(Map<String,Object> solrO : solrIdAddDocsList){
solrAPI.deleteElementFromSolrQueueTable(Long.parseLong(solrO.get("id").toString()));//delete from table
addCounter++;
}
addDocsList.clear();
addDocs.remove(solrServerUrl);
solrIdAddDocsList.clear();
solrIdAddDocs.remove(solrServerUrl);
Logger.debug(SolrQueueJob.class,"Document(s) Added/Updated: "+addCounter);
}catch(Exception e){
Logger.debug(SolrQueueJob.class,e.getMessage(),e);
Logger.debug(SolrQueueJob.class,"Document(s) not Added/Updated: "+addDocsList.size());
for(Map<String,Object> solrO : solrIdAddDocsList){
solrAPI.updateElementStatusFromSolrQueueTable(Long.parseLong(solrO.get("id").toString()),new Date(),(Integer.parseInt(solrO.get("num_of_tries").toString())+1), true, "An error occurs trying to add/update this assets in the Solr Index. ERROR: "+e);
}
addDocsList.clear();
addDocs.remove(solrServerUrl);
solrIdAddDocsList.clear();
solrIdAddDocs.remove(solrServerUrl);
break;
}
}
}
}else{
solrAPI.updateElementStatusFromSolrQueueTable(Long.parseLong(solr.get("id").toString()),new Date(),(Integer.parseInt(solr.get("num_of_tries").toString())+1), true, "This file asset content:"+(String)solr.get("asset_identifier")+" doesn't exist");
}
} else if(Long.parseLong(solr.get("solr_operation").toString()) == SolrAPI.DELETE_SOLR_ELEMENT){
/* delete element from index*/
String id = (String)solr.get("asset_identifier");
languages.put((String)solr.get("asset_identifier"), Long.parseLong(solr.get("language_id").toString()));
long languageId = languages.get(id);
Contentlet con = conAPI.findContentletByIdentifier(id, true, languageId, user, false);
for(String solrServerUrl : SolrUtil.getContentletSolrServers(con,user)){
if(!deleteDocs.containsKey(solrServerUrl)){
deleteDocs.put(solrServerUrl, new ArrayList<String>());
}
if(!solrIdDeleteDocs.containsKey(solrServerUrl)){
solrIdDeleteDocs.put(solrServerUrl,new ArrayList<Map<String,Object>>());
}
List<String> deleteDocsList = deleteDocs.get(solrServerUrl);
deleteDocsList.add(id);
deleteDocs.put(solrServerUrl,deleteDocsList);
List<Map<String,Object>> solrIdDeleteDocsList = solrIdDeleteDocs.get(solrServerUrl);
solrIdDeleteDocsList.add(solr);
solrIdDeleteDocs.put(solrServerUrl,solrIdDeleteDocsList);
if(deleteDocsList.size() == documentsPerRequest){
Logger.debug(SolrQueueJob.class,"Sending Delete Document(s) group request to Solr");
try {
Logger.debug(SolrQueueJob.class,"Document(s) to Delete: "+deleteDocsList.size());
SolrUtil.deleteFromSolrIndexById(solrServerUrl,deleteDocsList);
int deleteCounter = 0;
for(Map<String,Object> solrO : solrIdDeleteDocsList){
solrAPI.deleteElementFromSolrQueueTable(Long.parseLong(solrO.get("id").toString()));//delete from table
deleteCounter++;
}
deleteDocsList.clear();
deleteDocs.remove(solrServerUrl);
solrIdDeleteDocsList.clear();
solrIdDeleteDocs.remove(solrServerUrl);
Logger.debug(SolrQueueJob.class,"Document(s) Deleted: "+deleteCounter);
}catch(Exception e){
Logger.debug(SolrQueueJob.class,e.getMessage(),e);
Logger.debug(SolrQueueJob.class,"Document(s) not Deleted: "+deleteDocsList.size());
for(Map<String,Object> solrO : solrIdDeleteDocsList){
solrAPI.updateElementStatusFromSolrQueueTable(Long.parseLong(solrO.get("id").toString()),new Date(),(Integer.parseInt(solrO.get("num_of_tries").toString())+1), true, "An error occurs trying to delete this assets in the Solr Index. ERROR: "+e);
}
deleteDocsList.clear();
deleteDocs.remove(solrServerUrl);
solrIdDeleteDocsList.clear();
solrIdDeleteDocs.remove(solrServerUrl);
break;
}
}
}
}
}catch(Exception b){
Logger.debug(SolrQueueJob.class,b.getMessage(),b);
solrAPI.updateElementStatusFromSolrQueueTable(Long.parseLong(solr.get("id").toString()),new Date(),(Integer.parseInt(solr.get("num_of_tries").toString())+1), true, "An error occurs trying to process this assets in the Solr Index. ERROR: "+b);
}
}
if(addDocs.size() > 0 ){
/* Add or update index element*/
Logger.debug(SolrQueueJob.class,"Sending Add/Update Document(s) group request to Solr");
for(String solrServerUrl : addDocs.keySet()){
Collection<SolrInputDocument> addDocsList = addDocs.get(solrServerUrl);
List<Map<String,Object>> solrIdAddDocsList = solrIdAddDocs.get(solrServerUrl);
try {
Logger.debug(SolrQueueJob.class,"Document(s) to Add/Update: "+addDocsList.size());
SolrUtil.addToSolrIndex(solrServerUrl,addDocsList);
int addCounter = 0;
for(Map<String,Object> solrO : solrIdAddDocsList){
solrAPI.deleteElementFromSolrQueueTable(Long.parseLong(solrO.get("id").toString()));//delete from table
addCounter++;
}
addDocsList.clear();
addDocs.remove(solrServerUrl);
solrIdAddDocsList.clear();
solrIdAddDocs.remove(solrServerUrl);
Logger.debug(SolrQueueJob.class,"Document(s) Added/Updated: "+addCounter);
}catch(Exception e){
Logger.debug(SolrQueueJob.class,e.getMessage(),e);
Logger.debug(SolrQueueJob.class,"Document(s) not Added/Updated: "+addDocsList.size());
for(Map<String,Object> solrO : solrIdAddDocsList){
solrAPI.updateElementStatusFromSolrQueueTable(Long.parseLong(solrO.get("id").toString()),new Date(),(Integer.parseInt(solrO.get("num_of_tries").toString())+1), true, "An error occurs trying to add/update this assets in the Solr Index. ERROR: "+e);
}
addDocsList.clear();
addDocs.remove(solrServerUrl);
solrIdAddDocsList.clear();
solrIdAddDocs.remove(solrServerUrl);
}
}
}
if(deleteDocs.size() > 0){
Logger.debug(SolrQueueJob.class,"Sending Delete Document(s) group request to Solr");
for(String solrServerUrl : deleteDocs.keySet()){
List<String> deleteDocsList = deleteDocs.get(solrServerUrl);
List<Map<String,Object>> solrIdDeleteDocsList = solrIdDeleteDocs.get(solrServerUrl);
try {
Logger.debug(SolrQueueJob.class,"Document(s) to Delete: "+deleteDocsList.size());
SolrUtil.deleteFromSolrIndexById(solrServerUrl, deleteDocsList);
int deleteCounter = 0;
for(Map<String,Object> solrO : solrIdDeleteDocsList){
solrAPI.deleteElementFromSolrQueueTable(Long.parseLong(solrO.get("id").toString()));//delete from table
deleteCounter++;
}
deleteDocsList.clear();
deleteDocs.remove(solrServerUrl);
solrIdDeleteDocsList.clear();
solrIdDeleteDocs.remove(solrServerUrl);
Logger.debug(SolrQueueJob.class,"Document(s) Deleted: "+deleteCounter);
}catch(Exception e){
Logger.debug(SolrQueueJob.class,e.getMessage(),e);
Logger.debug(SolrQueueJob.class,"Document(s) not Deleted: "+deleteDocsList.size());
for(Map<String,Object> solrO : solrIdDeleteDocsList){
solrAPI.updateElementStatusFromSolrQueueTable(Long.parseLong(solrO.get("id").toString()),new Date(),(Integer.parseInt(solrO.get("num_of_tries").toString())+1), true, "An error occurs trying to delete this assets in the Solr Index. ERROR: "+e);
}
deleteDocsList.clear();
deleteDocs.remove(solrServerUrl);
solrIdDeleteDocsList.clear();
solrIdDeleteDocs.remove(solrServerUrl);
}
}
}
}
}
Logger.info(SolrQueueJob.class, "Finished Solr Queue Job");
} catch (NumberFormatException e) {
Logger.error(SolrQueueJob.class,e.getMessage(),e);
} catch (DotDataException e) {
Logger.error(SolrQueueJob.class,e.getMessage(),e);
} catch (DotSolrException e) {
Logger.error(SolrQueueJob.class,e.getMessage(),e);
} catch (Exception e) {
Logger.error(SolrQueueJob.class,e.getMessage(),e);
}
}
| public void execute(JobExecutionContext arg0) throws JobExecutionException {
int serversNumber = 0;
int documentsPerRequest = 1;
try {
Logger.info(SolrQueueJob.class, "Running Solr Queue Job");
User user = userAPI.getSystemUser();
serversNumber = Integer.parseInt(pluginAPI.loadProperty(pluginId, "com.dotcms.solr.SOLR_SERVER_NUMBER"));
/*Number of documents to send in one request*/
documentsPerRequest = Integer.parseInt(pluginAPI.loadProperty(pluginId, "com.dotcms.solr.DOCUMENTS_PER_REQUEST"));
if(documentsPerRequest < 1){
documentsPerRequest = 1;
}
/*Get attribute to modify field varname */
String solrField = pluginAPI.loadProperty(pluginId, "com.dotcms.solr.MODIFY_FIELD_NAME_ATTRIBUTE");
/*Get the name of the attribute that indicates if a field shouldn't be include in the solr index*/
String ignoreField = pluginAPI.loadProperty(pluginId, "com.dotcms.solr.IGNORE_FIELDS_WITH_ATTRIBUTE");
String ignoreHostVariableForFileAssetsString = pluginAPI.loadProperty(pluginId, "com.dotcms.solr.IGNORE_HOST_SUBSTITUTE");
boolean isHostSubstituteRequired = "false".equalsIgnoreCase(ignoreHostVariableForFileAssetsString);
/*Metadata field to ignore*/
String dynamicIgnoreMetadaField = pluginAPI.loadProperty(pluginId, "com.dotcms.solr.IGNORE_METADATA_FIELD_ATTRIBUTES");
String ignoreMetadataFieldsString = pluginAPI.loadProperty(pluginId, "com.dotcms.solr.IGNORE_METADATA_FIELDS");
List<String> ignoreMetadataFields = new ArrayList<String>();
if(UtilMethods.isSet(ignoreMetadataFieldsString)){
for(String attr : ignoreMetadataFieldsString.split(",")){
ignoreMetadataFields.add(attr.trim());
}
}
/*the job is executed only if there are solr servers and entries in the solr_queue table to process */
if(serversNumber > 0){
List<Map<String,Object>> solrQueue = solrAPI.getSolrQueueContentletToProcess();
Logger.info(SolrQueueJob.class, "Solr Queue element(s) to process: "+solrQueue.size());
if(solrQueue.size() > 0){
Map<String,Collection<SolrInputDocument>> addDocs = new HashMap<String,Collection<SolrInputDocument>>();
Map<String,List<Map<String,Object>>> solrIdAddDocs = new HashMap<String,List<Map<String,Object>>>();
Map<String,List<String>> deleteDocs = new HashMap<String,List<String>>();
Map<String,List<Map<String,Object>>> solrIdDeleteDocs = new HashMap<String,List<Map<String,Object>>>();
Map<String,Long> languages = new HashMap<String,Long>();
for(Map<String,Object> solr : solrQueue){
try {
if(Long.parseLong(solr.get("solr_operation").toString()) == SolrAPI.ADD_OR_UPDATE_SOLR_ELEMENT){
SolrInputDocument doc = new SolrInputDocument();
String identifier =(String)solr.get("asset_identifier");
long languageId =Long.parseLong(solr.get("language_id").toString());
Contentlet con = null;
Host host=null;
try {
con = conAPI.findContentletByIdentifier(identifier, true, languageId, user, false);
}catch(Exception e){
Logger.debug(SolrQueueJob.class,e.getMessage(),e);
}
if(UtilMethods.isSet(con)){
languages.put(con.getIdentifier(), con.getLanguageId());
doc.addField("id", con.getIdentifier());
doc.addField("inode", con.getInode());
doc.addField("modUser", con.getModUser());
//String modDate = UtilMethods.dateToHTMLDate(con.getModDate(), "yyyy-MM-dd")+"T"+ UtilMethods.dateToHTMLDate(con.getModDate(), "HH:mm:ss.S")+"Z";
String modDate = SolrUtil.getGenericFormattedDateText(con.getModDate(), SolrUtil.SOLR_DEFAULT_DATE_FORMAT);
doc.addField("modDate",modDate);
doc.addField("host", con.getHost());
doc.addField("folder", con.getFolder());
Structure st = con.getStructure();
doc.addField("structureName", st.getName());
doc.addField("structureInode", st.getInode());
doc.addField("structureId", st.getVelocityVarName());
doc.addField("structureType", st.getStructureType());
if(UtilMethods.isSet(st.getDescription())){
doc.addField("structureDescription", st.getDescription());
} else {
doc.addField("structureDescription", "");
}
for(Field f : st.getFieldsBySortOrder()){
List<FieldVariable> fieldVariables = APILocator.getFieldAPI().getFieldVariablesForField(f.getInode(), user, false);
if(!SolrUtil.containsFieldVariable(fieldVariables, ignoreField)){
Object value = conAPI.getFieldValue(con, f);
String solrFieldName = SolrUtil.getSolrFieldName(fieldVariables, solrField, f.getVelocityVarName());
if(f.getFieldType().equals(Field.FieldType.DATE.toString()) || f.getFieldType().equals(Field.FieldType.DATE_TIME.toString())){
String date = "";
if(UtilMethods.isSet(value)){
//date = UtilMethods.dateToHTMLDate((Date)value, "yyyy-MM-dd")+"T"+ UtilMethods.dateToHTMLDate((Date)value, "HH:mm:ss.S")+"Z";
date = SolrUtil.getFormattedUTCDateText((Date) value, SolrUtil.SOLR_DEFAULT_DATE_FORMAT);
}
doc.addField(solrFieldName, date);
}else if(f.getFieldType().equals(Field.FieldType.FILE.toString()) || f.getFieldType().equals(Field.FieldType.IMAGE.toString())){
String path = "";
if(UtilMethods.isSet(value)){
Identifier assetIdentifier = identifierAPI.find((String)value);
host = hostAPI.find(assetIdentifier.getHostId(), user, false);
String hostName ="";
if (isHostSubstituteRequired) {
if(UtilMethods.isSet(host)){
hostName="http://"+host.getHostname();
}else{
host = hostAPI.findDefaultHost(user, false);
hostName="http://"+host.getHostname();
}
}
path = hostName+assetIdentifier.getParentPath()+assetIdentifier.getAssetName();
/**
* Add to solr index file or image field metadata
*/
if(con.getStructure().getStructureType()!=Structure.STRUCTURE_TYPE_FILEASSET){
Contentlet fileCon = conAPI.findContentletByIdentifier(assetIdentifier.getInode(), true, languageId, user, false);
IFileAsset fileA = APILocator.getFileAssetAPI().fromContentlet(fileCon);
java.io.File file = fileA.getFileAsset();
Map<String, String> keyValueMap = SolrUtil.getMetaDataMap(f, file);
for(String key : keyValueMap.keySet()){
if(!ignoreMetadataFields.contains(key) && !SolrUtil.containsFieldVariableIgnoreField(fieldVariables,dynamicIgnoreMetadaField, key)){
doc.addField(solrFieldName+"_"+key, keyValueMap.get(key));
}
}
}
}
doc.addField(solrFieldName, path );
}else if(f.getFieldType().equals(Field.FieldType.BINARY.toString())){
String path="";
if(UtilMethods.isSet(value)){
java.io.File fileValue = (java.io.File)value;
String fileName = fileValue.getName();
host = hostAPI.find(con.getHost(), user, false);
String hostName ="";
if (isHostSubstituteRequired) {
if(UtilMethods.isSet(host)){
hostName="http://"+host.getHostname();
}else{
host = hostAPI.findDefaultHost(user, false);
hostName="http://"+host.getHostname();
}
}
if(UtilMethods.isImage(fileName)){
path=hostName+"/contentAsset/image/"+con.getInode()+"/"+f.getVelocityVarName()+"/?byInode=true";
}else{
path=hostName+"/contentAsset/raw-data/"+ con.getInode() + "/" + f.getVelocityVarName() + "?byInode=true";
}
/**
* Add to solr index binary field metadata
*/
if(con.getStructure().getStructureType()!=Structure.STRUCTURE_TYPE_FILEASSET){
Map<String, String> keyValueMap = SolrUtil.getMetaDataMap(f, fileValue);
for(String key : keyValueMap.keySet()){
if(!ignoreMetadataFields.contains(key) && !SolrUtil.containsFieldVariableIgnoreField(fieldVariables,dynamicIgnoreMetadaField, key)){
doc.addField(solrFieldName+"_"+key, keyValueMap.get(key));
}
}
}
}
doc.addField(solrFieldName, path);
}else if(f.getFieldType().equals(Field.FieldType.TAG.toString())||
f.getFieldType().equals(Field.FieldType.CHECKBOX.toString()) ||
f.getFieldType().equals(Field.FieldType.MULTI_SELECT.toString()) ||
f.getFieldType().equals(Field.FieldType.CUSTOM_FIELD.toString())){
String valueString = (String)value;
if(UtilMethods.isSet(valueString)){
doc.addField(solrFieldName, valueString.split(","));
}else{
doc.addField(solrFieldName,valueString);
}
}else if(f.getFieldType().equals(Field.FieldType.KEY_VALUE.toString())){
Map<String, Object> keyValueMap = null;
String JSONValue = UtilMethods.isSet(value)? (String)value:"";
//Convert JSON to Table Display {key, value, order}
if(UtilMethods.isSet(JSONValue)){
keyValueMap = com.dotmarketing.portlets.structure.model.KeyValueFieldUtil.JSONValueToHashMap(JSONValue);
}
for(String key : keyValueMap.keySet()){
if(!ignoreMetadataFields.contains(key) && !SolrUtil.containsFieldVariableIgnoreField(fieldVariables,dynamicIgnoreMetadaField, key)){
doc.addField(solrFieldName+"_"+key, keyValueMap.get(key));
}
}
}else if(f.getFieldType().equals(Field.FieldType.CATEGORY.toString())){
@SuppressWarnings("unchecked")
HashSet<Category> categorySet = (HashSet<Category>) value;
Set<String> categoryList = new HashSet<String>();
for(Category cat : categorySet){
if(UtilMethods.isSet(cat.getKey())){
categoryList.add(cat.getKey());
}else{
categoryList.add(cat.getCategoryVelocityVarName());
}
Set<Category> parents = SolrUtil.getAllParentsCategories(cat, user);
for(Category parentCat : parents){
if(UtilMethods.isSet(parentCat.getKey())){
categoryList.add(parentCat.getKey());
}else{
categoryList.add(parentCat.getCategoryVelocityVarName());
}
}
}
for(String categoryVar : categoryList){
doc.addField(solrFieldName, categoryVar);
}
}else{
doc.addField(solrFieldName, value);
}
}
}
/*variables to send docs in groups per request in solr*/
for(String solrServerUrl : SolrUtil.getContentletSolrServers(con,user)){
if(!addDocs.containsKey(solrServerUrl)){
addDocs.put(solrServerUrl, new ArrayList<SolrInputDocument>());
}
if(!solrIdAddDocs.containsKey(solrServerUrl)){
solrIdAddDocs.put(solrServerUrl,new ArrayList<Map<String,Object>>());
}
Collection<SolrInputDocument> addDocsList = addDocs.get(solrServerUrl);
addDocsList.add(doc);
addDocs.put(solrServerUrl,addDocsList);
List<Map<String,Object>> solrIdAddDocsList = solrIdAddDocs.get(solrServerUrl);
solrIdAddDocsList.add(solr);
solrIdAddDocs.put(solrServerUrl,solrIdAddDocsList);
/* Add or update index element*/
if(addDocsList.size() == documentsPerRequest){
Logger.debug(SolrQueueJob.class,"Sending Add/Update Document(s) group request to Solr");
try {
SolrUtil.addToSolrIndex(solrServerUrl,addDocsList);
int addCounter = 0;
for(Map<String,Object> solrO : solrIdAddDocsList){
solrAPI.deleteElementFromSolrQueueTable(Long.parseLong(solrO.get("id").toString()));//delete from table
addCounter++;
}
addDocsList.clear();
addDocs.remove(solrServerUrl);
solrIdAddDocsList.clear();
solrIdAddDocs.remove(solrServerUrl);
Logger.debug(SolrQueueJob.class,"Document(s) Added/Updated: "+addCounter);
}catch(Exception e){
Logger.debug(SolrQueueJob.class,e.getMessage(),e);
Logger.debug(SolrQueueJob.class,"Document(s) not Added/Updated: "+addDocsList.size());
for(Map<String,Object> solrO : solrIdAddDocsList){
solrAPI.updateElementStatusFromSolrQueueTable(Long.parseLong(solrO.get("id").toString()),new Date(),(Integer.parseInt(solrO.get("num_of_tries").toString())+1), true, "An error occurs trying to add/update this assets in the Solr Index. ERROR: "+e);
}
addDocsList.clear();
addDocs.remove(solrServerUrl);
solrIdAddDocsList.clear();
solrIdAddDocs.remove(solrServerUrl);
break;
}
}
}
}else{
solrAPI.updateElementStatusFromSolrQueueTable(Long.parseLong(solr.get("id").toString()),new Date(),(Integer.parseInt(solr.get("num_of_tries").toString())+1), true, "This file asset content:"+(String)solr.get("asset_identifier")+" doesn't exist");
}
} else if(Long.parseLong(solr.get("solr_operation").toString()) == SolrAPI.DELETE_SOLR_ELEMENT){
/* delete element from index*/
String id = (String)solr.get("asset_identifier");
languages.put((String)solr.get("asset_identifier"), Long.parseLong(solr.get("language_id").toString()));
long languageId = languages.get(id);
Contentlet con = conAPI.findContentletByIdentifier(id, false, languageId, user, false);
for(String solrServerUrl : SolrUtil.getContentletSolrServers(con,user)){
if(!deleteDocs.containsKey(solrServerUrl)){
deleteDocs.put(solrServerUrl, new ArrayList<String>());
}
if(!solrIdDeleteDocs.containsKey(solrServerUrl)){
solrIdDeleteDocs.put(solrServerUrl,new ArrayList<Map<String,Object>>());
}
List<String> deleteDocsList = deleteDocs.get(solrServerUrl);
deleteDocsList.add(id);
deleteDocs.put(solrServerUrl,deleteDocsList);
List<Map<String,Object>> solrIdDeleteDocsList = solrIdDeleteDocs.get(solrServerUrl);
solrIdDeleteDocsList.add(solr);
solrIdDeleteDocs.put(solrServerUrl,solrIdDeleteDocsList);
if(deleteDocsList.size() == documentsPerRequest){
Logger.debug(SolrQueueJob.class,"Sending Delete Document(s) group request to Solr");
try {
Logger.debug(SolrQueueJob.class,"Document(s) to Delete: "+deleteDocsList.size());
SolrUtil.deleteFromSolrIndexById(solrServerUrl,deleteDocsList);
int deleteCounter = 0;
for(Map<String,Object> solrO : solrIdDeleteDocsList){
solrAPI.deleteElementFromSolrQueueTable(Long.parseLong(solrO.get("id").toString()));//delete from table
deleteCounter++;
}
deleteDocsList.clear();
deleteDocs.remove(solrServerUrl);
solrIdDeleteDocsList.clear();
solrIdDeleteDocs.remove(solrServerUrl);
Logger.debug(SolrQueueJob.class,"Document(s) Deleted: "+deleteCounter);
}catch(Exception e){
Logger.debug(SolrQueueJob.class,e.getMessage(),e);
Logger.debug(SolrQueueJob.class,"Document(s) not Deleted: "+deleteDocsList.size());
for(Map<String,Object> solrO : solrIdDeleteDocsList){
solrAPI.updateElementStatusFromSolrQueueTable(Long.parseLong(solrO.get("id").toString()),new Date(),(Integer.parseInt(solrO.get("num_of_tries").toString())+1), true, "An error occurs trying to delete this assets in the Solr Index. ERROR: "+e);
}
deleteDocsList.clear();
deleteDocs.remove(solrServerUrl);
solrIdDeleteDocsList.clear();
solrIdDeleteDocs.remove(solrServerUrl);
break;
}
}
}
}
}catch(Exception b){
Logger.debug(SolrQueueJob.class,b.getMessage(),b);
solrAPI.updateElementStatusFromSolrQueueTable(Long.parseLong(solr.get("id").toString()),new Date(),(Integer.parseInt(solr.get("num_of_tries").toString())+1), true, "An error occurs trying to process this assets in the Solr Index. ERROR: "+b);
}
}
if(addDocs.size() > 0 ){
/* Add or update index element*/
Logger.debug(SolrQueueJob.class,"Sending Add/Update Document(s) group request to Solr");
for(String solrServerUrl : addDocs.keySet()){
Collection<SolrInputDocument> addDocsList = addDocs.get(solrServerUrl);
List<Map<String,Object>> solrIdAddDocsList = solrIdAddDocs.get(solrServerUrl);
try {
Logger.debug(SolrQueueJob.class,"Document(s) to Add/Update: "+addDocsList.size());
SolrUtil.addToSolrIndex(solrServerUrl,addDocsList);
int addCounter = 0;
for(Map<String,Object> solrO : solrIdAddDocsList){
solrAPI.deleteElementFromSolrQueueTable(Long.parseLong(solrO.get("id").toString()));//delete from table
addCounter++;
}
addDocsList.clear();
addDocs.remove(solrServerUrl);
solrIdAddDocsList.clear();
solrIdAddDocs.remove(solrServerUrl);
Logger.debug(SolrQueueJob.class,"Document(s) Added/Updated: "+addCounter);
}catch(Exception e){
Logger.debug(SolrQueueJob.class,e.getMessage(),e);
Logger.debug(SolrQueueJob.class,"Document(s) not Added/Updated: "+addDocsList.size());
for(Map<String,Object> solrO : solrIdAddDocsList){
solrAPI.updateElementStatusFromSolrQueueTable(Long.parseLong(solrO.get("id").toString()),new Date(),(Integer.parseInt(solrO.get("num_of_tries").toString())+1), true, "An error occurs trying to add/update this assets in the Solr Index. ERROR: "+e);
}
addDocsList.clear();
addDocs.remove(solrServerUrl);
solrIdAddDocsList.clear();
solrIdAddDocs.remove(solrServerUrl);
}
}
}
if(deleteDocs.size() > 0){
Logger.debug(SolrQueueJob.class,"Sending Delete Document(s) group request to Solr");
for(String solrServerUrl : deleteDocs.keySet()){
List<String> deleteDocsList = deleteDocs.get(solrServerUrl);
List<Map<String,Object>> solrIdDeleteDocsList = solrIdDeleteDocs.get(solrServerUrl);
try {
Logger.debug(SolrQueueJob.class,"Document(s) to Delete: "+deleteDocsList.size());
SolrUtil.deleteFromSolrIndexById(solrServerUrl, deleteDocsList);
int deleteCounter = 0;
for(Map<String,Object> solrO : solrIdDeleteDocsList){
solrAPI.deleteElementFromSolrQueueTable(Long.parseLong(solrO.get("id").toString()));//delete from table
deleteCounter++;
}
deleteDocsList.clear();
deleteDocs.remove(solrServerUrl);
solrIdDeleteDocsList.clear();
solrIdDeleteDocs.remove(solrServerUrl);
Logger.debug(SolrQueueJob.class,"Document(s) Deleted: "+deleteCounter);
}catch(Exception e){
Logger.debug(SolrQueueJob.class,e.getMessage(),e);
Logger.debug(SolrQueueJob.class,"Document(s) not Deleted: "+deleteDocsList.size());
for(Map<String,Object> solrO : solrIdDeleteDocsList){
solrAPI.updateElementStatusFromSolrQueueTable(Long.parseLong(solrO.get("id").toString()),new Date(),(Integer.parseInt(solrO.get("num_of_tries").toString())+1), true, "An error occurs trying to delete this assets in the Solr Index. ERROR: "+e);
}
deleteDocsList.clear();
deleteDocs.remove(solrServerUrl);
solrIdDeleteDocsList.clear();
solrIdDeleteDocs.remove(solrServerUrl);
}
}
}
}
}
Logger.info(SolrQueueJob.class, "Finished Solr Queue Job");
} catch (NumberFormatException e) {
Logger.error(SolrQueueJob.class,e.getMessage(),e);
} catch (DotDataException e) {
Logger.error(SolrQueueJob.class,e.getMessage(),e);
} catch (DotSolrException e) {
Logger.error(SolrQueueJob.class,e.getMessage(),e);
} catch (Exception e) {
Logger.error(SolrQueueJob.class,e.getMessage(),e);
}
}
|
diff --git a/src/com/stromberglabs/jopensurf/IntegralImage.java b/src/com/stromberglabs/jopensurf/IntegralImage.java
index ae936c6..98ae9a7 100644
--- a/src/com/stromberglabs/jopensurf/IntegralImage.java
+++ b/src/com/stromberglabs/jopensurf/IntegralImage.java
@@ -1,117 +1,117 @@
/*
This work was derived from Chris Evan's opensurf project and re-licensed as the
3 clause BSD license with permission of the original author. Thank you Chris!
Copyright (c) 2010, Andrew Stromberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither Andrew Stromberg nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Andrew Stromberg BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.stromberglabs.jopensurf;
import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;
import java.io.Serializable;
/**
* ABOUT generateIntegralImage
*
* When OpenSURF stores it's version of the integral image, some slight rounding actually
* occurs, it doesn't maintain the same values from when it calculates the integral image
* to when it calls BoxIntegral on the same data
* @author astromberg
*
* Example from C++ OpenSURF - THIS DOESN'T HAPPEN IN THE JAVA VERSION
*
* IntegralImage Values at Calculation Time:
* integralImage[11][9] = 33.69019699
* integralImage[16][9] = 47.90196228
* integralImage[11][18] = 65.84313202
* integralImage[16][18] = 93.58038330
*
*
* integralImage[11][18] = 65.84313202
* que? integralImage[18][11] = 64.56079102
*
* IntegralImage Values at BoxIntegral Time:
* img[11][9] = 33.83921814
* img[11][18] = 64.56079102
* img[16][9] = 48.76078796
* img[16][18] = 93.03530884
*
*/
public class IntegralImage implements Serializable {
private static final long serialVersionUID = 1L;
private float[][] mIntImage;
private int mWidth = -1;
private int mHeight = -1;
public float[][] getValues(){
return mIntImage;
}
public int getWidth(){
return mWidth;
}
public int getHeight(){
return mHeight;
}
public float getValue(int column, int row){
return mIntImage[column][row];
}
public IntegralImage(BufferedImage input){
mIntImage = new float[input.getWidth()][input.getHeight()];
mWidth = mIntImage.length;
mHeight = mIntImage[0].length;
int width = input.getWidth();
int height = input.getHeight();
WritableRaster raster = input.getRaster();
- int[] pixel = new int[3];
+ int[] pixel = new int[4];
float sum;
for ( int y = 0; y < height; y++ ){
sum = 0F;
for ( int x = 0; x < width; x++ ){
raster.getPixel(x,y,pixel);
/**
* TODO: FIX LOSS IN PRECISION HERE, DON'T ROUND BEFORE THE DIVISION (OR AFTER, OR AT ALL)
* This was done to match the C++ version, can be removed after confident that it's working
* correctly.
*/
float intensity = Math.round((0.299D*pixel[0] + 0.587D*pixel[1] + 0.114D*pixel[2]))/255F;
sum += intensity;
if ( y == 0 ){
mIntImage[x][y] = sum;
} else {
mIntImage[x][y] = sum + mIntImage[x][y-1];
}
}
}
}
}
| true | true | public IntegralImage(BufferedImage input){
mIntImage = new float[input.getWidth()][input.getHeight()];
mWidth = mIntImage.length;
mHeight = mIntImage[0].length;
int width = input.getWidth();
int height = input.getHeight();
WritableRaster raster = input.getRaster();
int[] pixel = new int[3];
float sum;
for ( int y = 0; y < height; y++ ){
sum = 0F;
for ( int x = 0; x < width; x++ ){
raster.getPixel(x,y,pixel);
/**
* TODO: FIX LOSS IN PRECISION HERE, DON'T ROUND BEFORE THE DIVISION (OR AFTER, OR AT ALL)
* This was done to match the C++ version, can be removed after confident that it's working
* correctly.
*/
float intensity = Math.round((0.299D*pixel[0] + 0.587D*pixel[1] + 0.114D*pixel[2]))/255F;
sum += intensity;
if ( y == 0 ){
mIntImage[x][y] = sum;
} else {
mIntImage[x][y] = sum + mIntImage[x][y-1];
}
}
}
}
| public IntegralImage(BufferedImage input){
mIntImage = new float[input.getWidth()][input.getHeight()];
mWidth = mIntImage.length;
mHeight = mIntImage[0].length;
int width = input.getWidth();
int height = input.getHeight();
WritableRaster raster = input.getRaster();
int[] pixel = new int[4];
float sum;
for ( int y = 0; y < height; y++ ){
sum = 0F;
for ( int x = 0; x < width; x++ ){
raster.getPixel(x,y,pixel);
/**
* TODO: FIX LOSS IN PRECISION HERE, DON'T ROUND BEFORE THE DIVISION (OR AFTER, OR AT ALL)
* This was done to match the C++ version, can be removed after confident that it's working
* correctly.
*/
float intensity = Math.round((0.299D*pixel[0] + 0.587D*pixel[1] + 0.114D*pixel[2]))/255F;
sum += intensity;
if ( y == 0 ){
mIntImage[x][y] = sum;
} else {
mIntImage[x][y] = sum + mIntImage[x][y-1];
}
}
}
}
|
diff --git a/parser/org/eclipse/cdt/internal/core/pdom/dom/cpp/PDOMCPPTypeList.java b/parser/org/eclipse/cdt/internal/core/pdom/dom/cpp/PDOMCPPTypeList.java
index c29a426af..460dcf6dd 100644
--- a/parser/org/eclipse/cdt/internal/core/pdom/dom/cpp/PDOMCPPTypeList.java
+++ b/parser/org/eclipse/cdt/internal/core/pdom/dom/cpp/PDOMCPPTypeList.java
@@ -1,95 +1,97 @@
/*******************************************************************************
* Copyright (c) 2008, 2009 Wind River Systems, Inc. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Markus Schorn - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.pdom.dom.cpp;
import org.eclipse.cdt.core.dom.ast.IType;
import org.eclipse.cdt.internal.core.pdom.db.Database;
import org.eclipse.cdt.internal.core.pdom.dom.PDOMLinkage;
import org.eclipse.cdt.internal.core.pdom.dom.PDOMNode;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
/**
* Stores a list of types
*/
class PDOMCPPTypeList {
protected static final int NODE_SIZE = 4;
/**
* Stores the given types in the database.
* @return the record by which the types can be referenced.
*/
public static int putTypes(PDOMNode parent, IType[] types) throws CoreException {
if (types == null)
return 0;
final PDOMLinkage linkage= parent.getLinkage();
final Database db= linkage.getDB();
final short len = (short)Math.min(types.length, (Database.MAX_MALLOC_SIZE-2)/NODE_SIZE);
final int block = db.malloc(2+ NODE_SIZE*len);
int p = block;
db.putShort(p, len); p+=2;
for (int i=0; i<len; i++, p+=NODE_SIZE) {
final IType type = types[i];
+ int rec= 0;
if (type != null) {
final PDOMNode pdomType = linkage.addType(parent, type);
- db.putInt(p, pdomType.getRecord());
- } else {
- db.putInt(p, 0);
+ if (pdomType != null) {
+ rec= pdomType.getRecord();
+ }
}
+ db.putInt(p, rec);
}
return block;
}
public static IType[] getTypes(PDOMNode parent, int rec) throws CoreException {
if (rec == 0)
return null;
final PDOMLinkage linkage= parent.getLinkage();
final Database db= linkage.getDB();
final short len = db.getShort(rec);
if (len == 0)
return IType.EMPTY_TYPE_ARRAY;
Assert.isTrue(len >= 0 && len <= (Database.MAX_MALLOC_SIZE-2)/NODE_SIZE);
rec+=2;
IType[] result= new IType[len];
for (int i=0; i<len; i++, rec+=NODE_SIZE) {
final int typeRec= db.getInt(rec);
if (typeRec != 0)
result[i]= (IType)linkage.getNode(typeRec);
}
return result;
}
/**
* Restores an array of template arguments from the database.
*/
public static void clearTypes(PDOMNode parent, final int record) throws CoreException {
if (record == 0)
return;
final PDOMLinkage linkage= parent.getLinkage();
final Database db= linkage.getDB();
final short len= db.getShort(record);
Assert.isTrue(len >= 0 && len <= (Database.MAX_MALLOC_SIZE-2)/NODE_SIZE);
int p= record+2;
for (int i=0; i<len; i++, p+=NODE_SIZE) {
final int typeRec= db.getInt(p);
final IType t= (IType) linkage.getNode(typeRec);
linkage.deleteType(t, parent.getRecord());
}
db.free(record);
}
}
| false | true | public static int putTypes(PDOMNode parent, IType[] types) throws CoreException {
if (types == null)
return 0;
final PDOMLinkage linkage= parent.getLinkage();
final Database db= linkage.getDB();
final short len = (short)Math.min(types.length, (Database.MAX_MALLOC_SIZE-2)/NODE_SIZE);
final int block = db.malloc(2+ NODE_SIZE*len);
int p = block;
db.putShort(p, len); p+=2;
for (int i=0; i<len; i++, p+=NODE_SIZE) {
final IType type = types[i];
if (type != null) {
final PDOMNode pdomType = linkage.addType(parent, type);
db.putInt(p, pdomType.getRecord());
} else {
db.putInt(p, 0);
}
}
return block;
}
| public static int putTypes(PDOMNode parent, IType[] types) throws CoreException {
if (types == null)
return 0;
final PDOMLinkage linkage= parent.getLinkage();
final Database db= linkage.getDB();
final short len = (short)Math.min(types.length, (Database.MAX_MALLOC_SIZE-2)/NODE_SIZE);
final int block = db.malloc(2+ NODE_SIZE*len);
int p = block;
db.putShort(p, len); p+=2;
for (int i=0; i<len; i++, p+=NODE_SIZE) {
final IType type = types[i];
int rec= 0;
if (type != null) {
final PDOMNode pdomType = linkage.addType(parent, type);
if (pdomType != null) {
rec= pdomType.getRecord();
}
}
db.putInt(p, rec);
}
return block;
}
|
diff --git a/LunchList/src/edu/mines/csci498/ybakos/lunchlist/HelpActivity.java b/LunchList/src/edu/mines/csci498/ybakos/lunchlist/HelpActivity.java
index 957d306..0a0a678 100644
--- a/LunchList/src/edu/mines/csci498/ybakos/lunchlist/HelpActivity.java
+++ b/LunchList/src/edu/mines/csci498/ybakos/lunchlist/HelpActivity.java
@@ -1,20 +1,20 @@
package edu.mines.csci498.ybakos.lunchlist;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.webkit.WebView;
public class HelpActivity extends Activity {
private WebView browser;
@Override
public void onCreate(Bundle state) {
super.onCreate(state);
setContentView(R.layout.help);
browser = (WebView) findViewById(R.id.webkit);
- browser.loadUrl("file://android_asset/help.html");
+ browser.loadUrl("file:///android_asset/help.html");
}
}
| true | true | public void onCreate(Bundle state) {
super.onCreate(state);
setContentView(R.layout.help);
browser = (WebView) findViewById(R.id.webkit);
browser.loadUrl("file://android_asset/help.html");
}
| public void onCreate(Bundle state) {
super.onCreate(state);
setContentView(R.layout.help);
browser = (WebView) findViewById(R.id.webkit);
browser.loadUrl("file:///android_asset/help.html");
}
|
diff --git a/src/org/mozilla/javascript/DefaultErrorReporter.java b/src/org/mozilla/javascript/DefaultErrorReporter.java
index 17ad79ac..c7d93d48 100644
--- a/src/org/mozilla/javascript/DefaultErrorReporter.java
+++ b/src/org/mozilla/javascript/DefaultErrorReporter.java
@@ -1,102 +1,113 @@
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1997-1999
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Norris Boyd
*
* Alternatively, the contents of this file may be used under the terms of
* the GNU General Public License Version 2 or later (the "GPL"), in which
* case the provisions of the GPL are applicable instead of those above. If
* you wish to allow use of your version of this file only under the terms of
* the GPL and not to allow others to use your version of this file under the
* MPL, indicate your decision by deleting the provisions above and replacing
* them with the notice and other provisions required by the GPL. If you do
* not delete the provisions above, a recipient may use your version of this
* file under either the MPL or the GPL.
*
* ***** END LICENSE BLOCK ***** */
package org.mozilla.javascript;
/**
* This is the default error reporter for JavaScript.
*
* @author Norris Boyd
*/
class DefaultErrorReporter implements ErrorReporter
{
static final DefaultErrorReporter instance = new DefaultErrorReporter();
private boolean forEval;
private ErrorReporter chainedReporter;
private DefaultErrorReporter() { }
static ErrorReporter forEval(ErrorReporter reporter)
{
DefaultErrorReporter r = new DefaultErrorReporter();
r.forEval = true;
r.chainedReporter = reporter;
return r;
}
public void warning(String message, String sourceURI, int line,
String lineText, int lineOffset)
{
if (chainedReporter != null) {
chainedReporter.warning(
message, sourceURI, line, lineText, lineOffset);
} else {
// Do nothing
}
}
public void error(String message, String sourceURI, int line,
String lineText, int lineOffset)
{
if (forEval) {
- throw ScriptRuntime.constructError(
- "SyntaxError", message, sourceURI, line, lineText, lineOffset);
+ // Assume error message strings that start with "TypeError: "
+ // should become TypeError exceptions. A bit of a hack, but we
+ // don't want to change the ErrorReporter interface.
+ String error = "SyntaxError";
+ final String TYPE_ERROR_NAME = "TypeError";
+ final String DELIMETER = ": ";
+ final String prefix = TYPE_ERROR_NAME + DELIMETER;
+ if (message.startsWith(prefix)) {
+ error = TYPE_ERROR_NAME;
+ message = message.substring(prefix.length());
+ }
+ throw ScriptRuntime.constructError(error, message, sourceURI,
+ line, lineText, lineOffset);
}
if (chainedReporter != null) {
chainedReporter.error(
message, sourceURI, line, lineText, lineOffset);
} else {
throw runtimeError(
message, sourceURI, line, lineText, lineOffset);
}
}
public EvaluatorException runtimeError(String message, String sourceURI,
int line, String lineText,
int lineOffset)
{
if (chainedReporter != null) {
return chainedReporter.runtimeError(
message, sourceURI, line, lineText, lineOffset);
} else {
return new EvaluatorException(
message, sourceURI, line, lineText, lineOffset);
}
}
}
| true | true | public void error(String message, String sourceURI, int line,
String lineText, int lineOffset)
{
if (forEval) {
throw ScriptRuntime.constructError(
"SyntaxError", message, sourceURI, line, lineText, lineOffset);
}
if (chainedReporter != null) {
chainedReporter.error(
message, sourceURI, line, lineText, lineOffset);
} else {
throw runtimeError(
message, sourceURI, line, lineText, lineOffset);
}
}
| public void error(String message, String sourceURI, int line,
String lineText, int lineOffset)
{
if (forEval) {
// Assume error message strings that start with "TypeError: "
// should become TypeError exceptions. A bit of a hack, but we
// don't want to change the ErrorReporter interface.
String error = "SyntaxError";
final String TYPE_ERROR_NAME = "TypeError";
final String DELIMETER = ": ";
final String prefix = TYPE_ERROR_NAME + DELIMETER;
if (message.startsWith(prefix)) {
error = TYPE_ERROR_NAME;
message = message.substring(prefix.length());
}
throw ScriptRuntime.constructError(error, message, sourceURI,
line, lineText, lineOffset);
}
if (chainedReporter != null) {
chainedReporter.error(
message, sourceURI, line, lineText, lineOffset);
} else {
throw runtimeError(
message, sourceURI, line, lineText, lineOffset);
}
}
|
diff --git a/opentripplanner-api-thrift/src/test/java/org/opentripplanner/api/thrift/impl/OTPServiceImplTest.java b/opentripplanner-api-thrift/src/test/java/org/opentripplanner/api/thrift/impl/OTPServiceImplTest.java
index 28b790234..807c52f65 100644
--- a/opentripplanner-api-thrift/src/test/java/org/opentripplanner/api/thrift/impl/OTPServiceImplTest.java
+++ b/opentripplanner-api-thrift/src/test/java/org/opentripplanner/api/thrift/impl/OTPServiceImplTest.java
@@ -1,316 +1,316 @@
/* This program is free software: you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public License
as published by the Free Software Foundation, either version 3 of
the License, or (props, at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
package org.opentripplanner.api.thrift.impl;
import static org.junit.Assert.*;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import org.apache.thrift.TException;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.opentripplanner.api.thrift.definition.BulkPathsRequest;
import org.opentripplanner.api.thrift.definition.BulkPathsResponse;
import org.opentripplanner.api.thrift.definition.FindNearestVertexRequest;
import org.opentripplanner.api.thrift.definition.FindNearestVertexResponse;
import org.opentripplanner.api.thrift.definition.FindPathsRequest;
import org.opentripplanner.api.thrift.definition.FindPathsResponse;
import org.opentripplanner.api.thrift.definition.GraphEdge;
import org.opentripplanner.api.thrift.definition.GraphEdgesRequest;
import org.opentripplanner.api.thrift.definition.GraphEdgesResponse;
import org.opentripplanner.api.thrift.definition.GraphVertex;
import org.opentripplanner.api.thrift.definition.GraphVerticesRequest;
import org.opentripplanner.api.thrift.definition.GraphVerticesResponse;
import org.opentripplanner.api.thrift.definition.LatLng;
import org.opentripplanner.api.thrift.definition.Location;
import org.opentripplanner.api.thrift.definition.Path;
import org.opentripplanner.api.thrift.definition.PathOptions;
import org.opentripplanner.api.thrift.definition.TravelMode;
import org.opentripplanner.api.thrift.definition.TravelState;
import org.opentripplanner.api.thrift.definition.TripParameters;
import org.opentripplanner.api.thrift.definition.TripPaths;
import org.opentripplanner.api.thrift.definition.VertexQuery;
import org.opentripplanner.common.model.P2;
import org.opentripplanner.graph_builder.impl.osm.DefaultWayPropertySetSource;
import org.opentripplanner.graph_builder.impl.osm.OpenStreetMapGraphBuilderImpl;
import org.opentripplanner.openstreetmap.impl.FileBasedOpenStreetMapProviderImpl;
import org.opentripplanner.routing.algorithm.GenericAStar;
import org.opentripplanner.routing.core.RoutingRequest;
import org.opentripplanner.routing.graph.Edge;
import org.opentripplanner.routing.graph.Graph;
import org.opentripplanner.routing.graph.Vertex;
import org.opentripplanner.routing.impl.DefaultStreetVertexIndexFactory;
import org.opentripplanner.routing.impl.GraphServiceImpl;
import org.opentripplanner.routing.impl.SimplifiedPathServiceImpl;
import com.vividsolutions.jts.geom.Coordinate;
public class OTPServiceImplTest {
private static HashMap<Class<?>, Object> extra;
private static Graph graph;
private Random rand;
private OTPServiceImpl serviceImpl;
@BeforeClass
public static void beforeClass() {
extra = new HashMap<Class<?>, Object>();
graph = new Graph();
OpenStreetMapGraphBuilderImpl loader = new OpenStreetMapGraphBuilderImpl();
loader.setDefaultWayPropertySetSource(new DefaultWayPropertySetSource());
FileBasedOpenStreetMapProviderImpl provider = new FileBasedOpenStreetMapProviderImpl();
File file = new File(OTPServiceImplTest.class.getResource("NYC_small.osm.gz").getFile());
provider.setPath(file);
loader.setProvider(provider);
loader.buildGraph(graph, extra);
// Need to set up the index because buildGraph doesn't do it.
graph.rebuildVertexAndEdgeIndices();
graph.streetIndex = (new DefaultStreetVertexIndexFactory()).newIndex(graph);
}
@Before
public void before() {
rand = new Random(1234);
GraphServiceImpl graphService = new GraphServiceImpl();
graphService.registerGraph("", graph);
SimplifiedPathServiceImpl pathService = new SimplifiedPathServiceImpl();
pathService.setGraphService(graphService);
pathService.setSptService(new GenericAStar());
RoutingRequest prototype = new RoutingRequest();
prototype.setTurnReluctance(1.0);
prototype.setWalkReluctance(1.0);
prototype.setStairsReluctance(1.0);
serviceImpl = new OTPServiceImpl();
serviceImpl.setPrototypeRoutingRequest(prototype);
serviceImpl.setGraphService(graphService);
serviceImpl.setPathService(pathService);
}
@Test
public void testGetGraphEdges() throws TException {
GraphEdgesRequest req = new GraphEdgesRequest();
req.validate();
req.setStreet_edges_only(true);
GraphEdgesResponse res = serviceImpl.GetEdges(req);
Set<Integer> expectedEdgeIds = new HashSet<Integer>();
for (Edge e : graph.getStreetEdges()) {
expectedEdgeIds.add(e.getId());
}
Set<Integer> actualEdgeIds = new HashSet<Integer>(res.getEdgesSize());
for (GraphEdge ge : res.getEdges()) {
actualEdgeIds.add(ge.getId());
}
assertTrue(expectedEdgeIds.equals(actualEdgeIds));
}
@Test
public void testGetGraphVertices() throws TException {
GraphVerticesRequest req = new GraphVerticesRequest();
req.validate();
GraphVerticesResponse res = serviceImpl.GetVertices(req);
Set<Integer> expectedVertexIds = new HashSet<Integer>();
for (Vertex v : graph.getVertices()) {
expectedVertexIds.add(v.getIndex());
}
Set<Integer> actualVertexIds = new HashSet<Integer>(res.getVerticesSize());
for (GraphVertex gv : res.getVertices()) {
actualVertexIds.add(gv.getId());
}
assertTrue(expectedVertexIds.equals(actualVertexIds));
}
private Location getLocationForVertex(Vertex v) {
Location loc = new Location();
Coordinate c = v.getCoordinate();
loc.setLat_lng(new LatLng(c.y, c.x));
return loc;
}
private Location getLocationForTravelState(TravelState ts) {
Location loc = new Location();
loc.setLat_lng(ts.getVertex().getLat_lng());
return loc;
}
private P2<Location> pickOriginAndDest() {
List<Vertex> vList = new ArrayList<Vertex>(graph.getVertices());
Collections.shuffle(vList, rand);
P2<Location> pair = new P2<Location>(getLocationForVertex(vList.get(0)),
getLocationForVertex(vList.get(1)));
return pair;
}
private void checkPath(Path p) {
int duration = p.getDuration();
int nStates = p.getStatesSize();
long startTime = p.getStates().get(0).getArrival_time();
long endTime = p.getStates().get(nStates - 1).getArrival_time();
int computedDuration = (int) (endTime - startTime);
assertEquals(duration, computedDuration);
}
@Test
public void testFindPaths() throws TException {
PathOptions opts = new PathOptions();
opts.setNum_paths(1);
opts.setReturn_detailed_path(true);
TripParameters trip = new TripParameters();
trip.addToAllowed_modes(TravelMode.CAR);
P2<Location> pair = pickOriginAndDest();
trip.setOrigin(pair.getFirst());
trip.setDestination(pair.getSecond());
FindPathsRequest req = new FindPathsRequest();
req.setOptions(opts);
req.setTrip(trip);
req.validate();
FindPathsResponse res = serviceImpl.FindPaths(req);
TripPaths paths = res.getPaths();
- while (paths.getPaths().isEmpty()) {
+ while (paths == null || paths.getPaths().isEmpty()) {
// Pick another if we got no result.
pair = pickOriginAndDest();
trip.setOrigin(pair.getFirst());
trip.setDestination(pair.getSecond());
res = serviceImpl.FindPaths(req);
paths = res.getPaths();
}
assertEquals(1, paths.getPathsSize());
Path p = paths.getPaths().get(0);
checkPath(p);
// Check what happens when we decompose this path into subpaths.
int expectedTotalDuration = p.getDuration();
int subPathDurations = 0;
for (int i = 1; i < p.getStatesSize(); ++i) {
TravelState firstState = p.getStates().get(i - 1);
TravelState secondState = p.getStates().get(i);
Location startLoc = getLocationForTravelState(firstState);
Location endLoc = getLocationForTravelState(secondState);
trip.setOrigin(startLoc);
trip.setDestination(endLoc);
req = new FindPathsRequest();
req.setOptions(opts);
req.setTrip(trip);
req.validate();
res = serviceImpl.FindPaths(req);
paths = res.getPaths();
assertEquals(1, paths.getPathsSize());
Path subPath = paths.getPaths().get(0);
checkPath(subPath);
subPathDurations += subPath.getDuration();
}
// Subpaths may take less time because they need not start on the
// the same edges as the original path.
assertTrue(subPathDurations <= expectedTotalDuration);
}
@Test
public void testBulkFindPaths() throws TException {
PathOptions opts = new PathOptions();
opts.setNum_paths(1);
opts.setReturn_detailed_path(true);
BulkPathsRequest req = new BulkPathsRequest();
req.setOptions(opts);
for (int i = 0; i < 4; ++i) {
TripParameters trip = new TripParameters();
trip.addToAllowed_modes(TravelMode.CAR);
P2<Location> pair = pickOriginAndDest();
trip.setOrigin(pair.getFirst());
trip.setDestination(pair.getSecond());
req.addToTrips(trip);
}
req.validate();
BulkPathsResponse res = serviceImpl.BulkFindPaths(req);
for (TripPaths paths : res.getPaths()) {
int expectedPathsSize = paths.isNo_paths_found() ? 0 : 1;
assertEquals(expectedPathsSize, paths.getPathsSize());
if (!paths.isSetNo_paths_found()) {
Path p = paths.getPaths().get(0);
checkPath(p);
}
}
}
@Test
public void testFindNearestVertex() throws TException {
for (Vertex v : graph.getVertices()) {
FindNearestVertexRequest req = new FindNearestVertexRequest();
VertexQuery q = new VertexQuery();
q.setLocation(getLocationForVertex(v));
req.setQuery(q);
FindNearestVertexResponse res = serviceImpl.FindNearestVertex(req);
GraphVertex gv = res.getResult().getNearest_vertex();
int expectedId = v.getIndex();
int actualId = gv.getId();
if (expectedId != actualId) {
// If not equal, then the distance should be approaching 0.
LatLng ll = gv.getLat_lng();
Coordinate outCoord = new Coordinate(ll.getLng(), ll.getLat());
assertTrue(v.getCoordinate().distance(outCoord) < 0.00001);
}
}
}
}
| true | true | public void testFindPaths() throws TException {
PathOptions opts = new PathOptions();
opts.setNum_paths(1);
opts.setReturn_detailed_path(true);
TripParameters trip = new TripParameters();
trip.addToAllowed_modes(TravelMode.CAR);
P2<Location> pair = pickOriginAndDest();
trip.setOrigin(pair.getFirst());
trip.setDestination(pair.getSecond());
FindPathsRequest req = new FindPathsRequest();
req.setOptions(opts);
req.setTrip(trip);
req.validate();
FindPathsResponse res = serviceImpl.FindPaths(req);
TripPaths paths = res.getPaths();
while (paths.getPaths().isEmpty()) {
// Pick another if we got no result.
pair = pickOriginAndDest();
trip.setOrigin(pair.getFirst());
trip.setDestination(pair.getSecond());
res = serviceImpl.FindPaths(req);
paths = res.getPaths();
}
assertEquals(1, paths.getPathsSize());
Path p = paths.getPaths().get(0);
checkPath(p);
// Check what happens when we decompose this path into subpaths.
int expectedTotalDuration = p.getDuration();
int subPathDurations = 0;
for (int i = 1; i < p.getStatesSize(); ++i) {
TravelState firstState = p.getStates().get(i - 1);
TravelState secondState = p.getStates().get(i);
Location startLoc = getLocationForTravelState(firstState);
Location endLoc = getLocationForTravelState(secondState);
trip.setOrigin(startLoc);
trip.setDestination(endLoc);
req = new FindPathsRequest();
req.setOptions(opts);
req.setTrip(trip);
req.validate();
res = serviceImpl.FindPaths(req);
paths = res.getPaths();
assertEquals(1, paths.getPathsSize());
Path subPath = paths.getPaths().get(0);
checkPath(subPath);
subPathDurations += subPath.getDuration();
}
// Subpaths may take less time because they need not start on the
// the same edges as the original path.
assertTrue(subPathDurations <= expectedTotalDuration);
}
| public void testFindPaths() throws TException {
PathOptions opts = new PathOptions();
opts.setNum_paths(1);
opts.setReturn_detailed_path(true);
TripParameters trip = new TripParameters();
trip.addToAllowed_modes(TravelMode.CAR);
P2<Location> pair = pickOriginAndDest();
trip.setOrigin(pair.getFirst());
trip.setDestination(pair.getSecond());
FindPathsRequest req = new FindPathsRequest();
req.setOptions(opts);
req.setTrip(trip);
req.validate();
FindPathsResponse res = serviceImpl.FindPaths(req);
TripPaths paths = res.getPaths();
while (paths == null || paths.getPaths().isEmpty()) {
// Pick another if we got no result.
pair = pickOriginAndDest();
trip.setOrigin(pair.getFirst());
trip.setDestination(pair.getSecond());
res = serviceImpl.FindPaths(req);
paths = res.getPaths();
}
assertEquals(1, paths.getPathsSize());
Path p = paths.getPaths().get(0);
checkPath(p);
// Check what happens when we decompose this path into subpaths.
int expectedTotalDuration = p.getDuration();
int subPathDurations = 0;
for (int i = 1; i < p.getStatesSize(); ++i) {
TravelState firstState = p.getStates().get(i - 1);
TravelState secondState = p.getStates().get(i);
Location startLoc = getLocationForTravelState(firstState);
Location endLoc = getLocationForTravelState(secondState);
trip.setOrigin(startLoc);
trip.setDestination(endLoc);
req = new FindPathsRequest();
req.setOptions(opts);
req.setTrip(trip);
req.validate();
res = serviceImpl.FindPaths(req);
paths = res.getPaths();
assertEquals(1, paths.getPathsSize());
Path subPath = paths.getPaths().get(0);
checkPath(subPath);
subPathDurations += subPath.getDuration();
}
// Subpaths may take less time because they need not start on the
// the same edges as the original path.
assertTrue(subPathDurations <= expectedTotalDuration);
}
|
diff --git a/common/plugins/org.jboss.tools.common.model/src/org/jboss/tools/common/model/util/PositionSearcher.java b/common/plugins/org.jboss.tools.common.model/src/org/jboss/tools/common/model/util/PositionSearcher.java
index 1d2030447..99a7a7958 100644
--- a/common/plugins/org.jboss.tools.common.model/src/org/jboss/tools/common/model/util/PositionSearcher.java
+++ b/common/plugins/org.jboss.tools.common.model/src/org/jboss/tools/common/model/util/PositionSearcher.java
@@ -1,313 +1,316 @@
/*******************************************************************************
* Copyright (c) 2007 Exadel, Inc. and Red Hat, Inc.
* Distributed under license by Red Hat, Inc. All rights reserved.
* This program is made available under the terms of the
* Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Exadel, Inc. and Red Hat, Inc. - initial API and implementation
******************************************************************************/
package org.jboss.tools.common.model.util;
import java.util.StringTokenizer;
import org.jboss.tools.common.meta.XAttribute;
import org.jboss.tools.common.model.XModelObject;
import org.jboss.tools.common.model.loaders.XObjectLoader;
import org.jboss.tools.common.model.loaders.impl.PropertiesLoader;
import org.jboss.tools.common.model.loaders.impl.SimpleWebFileLoader;
/**
* Searches for position of start tag corresponding to model object.
* If, optionally, attribute name is provided, searches for position
* of its value.
* This feature is necessary because model object does not keep its
* position in XML text, being loaded using standard XML parser
* that does not provide location in text.
* The algorithm used here is not 100% safe, and should not be
* used for context changes, rather it can be used for
* synchronizing text selection to tree or diagram selection.
*
*
* @author glory
*/
public class PositionSearcher {
String text;
XModelObject object;
String attribute;
int startPosition;
int endPosition;
boolean selectAttributeName = false;
XModelObjectLoaderUtil util;
PropertiesLoader propertiesLoader = null;
public PositionSearcher() {}
public void init(String text, XModelObject object, String attribute) {
if(attribute != null && attribute.startsWith("&")) { //$NON-NLS-1$
selectAttributeName = true;
attribute = attribute.substring(1);
}
this.text = text;
this.object = object;
this.attribute = attribute;
XModelObject f = object;
while(f != null && f.getFileType() != XModelObject.FILE) f = f.getParent();
if(f != null) {
XObjectLoader loader = XModelObjectLoaderUtil.getObjectLoader(f);
if(loader instanceof SimpleWebFileLoader) {
//TODO have more common case, this does not include WebProcessLoader
SimpleWebFileLoader fileLoader = (SimpleWebFileLoader)loader;
fileLoader.createRootElement(f); // initializes namespaces if available.
util = fileLoader.getUtil();
} else if(loader instanceof PropertiesLoader) {
propertiesLoader = (PropertiesLoader)loader;
}
}
}
public void execute() {
startPosition = -1;
endPosition = -1;
if(text == null || object == null) return;
if(propertiesLoader != null) {
String name = object.getAttributeValue("name"); //$NON-NLS-1$
String dname = object.getAttributeValue("dirtyname"); //$NON-NLS-1$
String nvs = object.getAttributeValue("name-value-separator"); //$NON-NLS-1$
int i = text.indexOf(dname + nvs);
if(i >= 0) {
i = text.indexOf(name, i);
startPosition = i;
endPosition = i + name.length();
}
} else {
TagIterator it = new TagIterator();
it.selectObject(object);
if(it.startPos < 0 || it.endPos < it.startPos) return;
startPosition = it.startPos;
endPosition = it.endPos;
/// findTagEnd();
selectAttribute();
}
}
private void selectAttribute() {
if(attribute == null || attribute.length() == 0) return;
XAttribute a = object.getModelEntity().getAttribute(attribute);
if(isESB(a)) {
findESBAttrPosition(a);
}
String xml = (a == null) ? null : a.getXMLName();
if(xml == null || xml.length() == 0) return;
if(xml.indexOf(".") < 0) { //$NON-NLS-1$
String s = text.substring(startPosition, endPosition);
int i1 = findAttrPosition(s, xml);
if(selectAttributeName) {
if(i1 < 0) return;
startPosition = startPosition + i1;
endPosition = startPosition + xml.length();
return;
}
int i2 = (i1 < 0) ? -1 : s.indexOf('"', i1 + 1);
int i3 = (i2 < 0) ? -1 : s.indexOf('"', i2 + 1);
if(i3 > 0) {
endPosition = startPosition + i3;
startPosition = startPosition + i2 + 1;
}
} else {
- xml = xml.substring(0, xml.indexOf('.'));
+ xml = xml.substring(0, xml.lastIndexOf('.')); //remove .#text
+ if(xml.indexOf('.') >= 0) {
+ xml = xml.substring(xml.lastIndexOf('.') + 1); // simplify - look for the last name only
+ }
int e1 = text.indexOf("</" + getTagXMLName(object) + ">", startPosition); //$NON-NLS-1$ //$NON-NLS-2$
String s = e1 < 0 ? "" : text.substring(startPosition, e1); //$NON-NLS-1$
if(xml.length() == 0) {
int i1 = s.indexOf(">"); //$NON-NLS-1$
endPosition = startPosition + i1 + 1;
startPosition = startPosition + e1;
} else if(s.length() > 0) {
int i1a = s.indexOf("<" + xml + ">"); //$NON-NLS-1$ //$NON-NLS-2$
int i1b = s.indexOf("<" + xml + "/>"); //$NON-NLS-1$ //$NON-NLS-2$
int i2 = (i1a < 0) ? -1 : s.indexOf("</", i1a); //$NON-NLS-1$
if(i1a >= 0 && i2 >= 0) {
endPosition = startPosition + i2;
startPosition = startPosition + i1a + 2 + xml.length();
} else if(i1b >= 0) {
endPosition = startPosition + i1b + 3 + xml.length();
startPosition = startPosition + i1b;
}
}
}
}
private String getTagXMLName(XModelObject object) {
String TAG_ATTR = "tag";//$NON-NLS-1$
String result = null;
if(object.getModelEntity().getAttribute(TAG_ATTR) != null) {
result = object.getAttributeValue(TAG_ATTR);
} else {
result = object.getModelEntity().getXMLSubPath();
if(result != null && util != null) {
result = util.applyNamespaceToTag(result);
}
}
return result;
}
private int findAttrPosition(String s, String name) {
int i = s.indexOf(name);
if(i < 0) {
return -1;
}
StringTokenizer st = new StringTokenizer(s, "\"", true); //$NON-NLS-1$
int pos = 0;
boolean inValue = false;
while(st.hasMoreTokens()) {
String t = st.nextToken();
if(t.equals("\"")) { //$NON-NLS-1$
inValue = !inValue;
} else {
if(!inValue) {
int k = t.indexOf(name);
if(k >= 0) {
boolean ok = true;
if(k > 0) {
char c = t.charAt(k - 1);
if(Character.isJavaIdentifierPart(c) || c == '-') ok = false;
}
if(ok) return pos + k;
}
}
}
pos += t.length();
}
return -1;
}
public int getStartPosition() {
return startPosition;
}
public int getEndPosition() {
return endPosition;
}
void findTagEnd() {
if(startPosition < 0) return;
if(attribute != null && attribute.length() > 0) return;
String tagname = getTagXMLName(object);
if(tagname == null || tagname.length() == 0) return;
String start = "<" + tagname; //$NON-NLS-1$
if(text.indexOf(start, startPosition) != startPosition) return;
String finish = "</" + tagname + ">"; //$NON-NLS-1$ //$NON-NLS-2$
int i = text.indexOf(finish, startPosition);
if(i >= 0) endPosition = i + finish.length();
}
class TagIterator {
int startPos;
int endPos;
TagIterator() {
startPos = -1;
endPos = 0;
}
public void selectObject(XModelObject object) {
if(object == null) return;
String xml = getTagXMLName(object);
String token = "<" + xml; //$NON-NLS-1$
if(object.getFileType() == XModelObject.FILE) {
startPos = nextStartPos(token, startPos + 1);
if(startPos >= 0) {
endPos = text.indexOf(">", startPos + 1); //$NON-NLS-1$
if(endPos < 0) endPos = text.indexOf("<", startPos + 1); //$NON-NLS-1$
if(endPos < 0) endPos = text.length(); else endPos++;
}
} else if(token.equals("<")) { //$NON-NLS-1$
selectObject(object.getParent());
} else {
XModelObject parent = object.getParent();
selectObject(parent);
if(startPos < 0) return;
// String entity = object.getModelEntity().getName();
XModelObject[] os = parent.getChildren();
for (int i = 0; i < os.length; i++) {
String xml_i = getTagXMLName(os[i]);
if(!xml.equals(xml_i)) continue;
boolean ok = false;
while(!ok) {
startPos = nextStartPos(token, startPos + 1);
if(startPos < 0) return;
if(startPos + token.length() == text.length()) {
ok = true;
} else {
char ch = text.charAt(startPos + token.length());
ok = Character.isWhitespace(ch) || ch == '/' || ch == '>';
}
}
if(os[i] == object) {
endPos = text.indexOf(">", startPos + 1); //$NON-NLS-1$
if(endPos < 0) endPos = text.indexOf("<", startPos + 1); //$NON-NLS-1$
if(endPos < 0) endPos = text.length(); else endPos++;
return;
}
}
}
}
int nextStartPos(String token, int b) {
int s = text.indexOf(token, b);
if(s < 0) return s;
int cb = text.indexOf("<!--", b); //$NON-NLS-1$
if(cb < 0 || cb > s) return s;
int ce = text.indexOf("-->", cb); //$NON-NLS-1$
if(ce < 0) return -1;
return nextStartPos(token, ce + 3);
}
}
/**
* Temporal solution; should be refactored to a framework.
*
*/
boolean isESB(XAttribute a) {
return a != null && "true".equals(a.getProperty("pre"));
}
void findESBAttrPosition(XAttribute a) {
int ep = text.indexOf("</action>", startPosition);
if(ep < 0) return;
String dt = text.substring(startPosition, ep);
String name = "name=\"" + a.getXMLName() + "\"";
int name_i = dt.indexOf(name);
if(name_i < 0) return;
int ps = dt.lastIndexOf("<property", name_i);
if(ps < 0) return;
int pe = dt.indexOf("/>", ps);
if(pe < 0) return;
String dt2 = dt.substring(ps, pe + 2);
int value_i = dt2.indexOf("value=");
if(value_i >= 0) {
int i2 = dt2.indexOf('"', value_i);
int i3 = (i2 < 0) ? -1 : dt2.indexOf('"', i2 + 1);
if(i3 > i2 + 1) {
startPosition = startPosition + ps + i2 + 1;
endPosition = startPosition + i3 - i2 - 1;
return;
} else if(i3 == i2 + 1) {
startPosition = startPosition + ps + i2;
endPosition = startPosition + 2;
return;
}
}
startPosition = startPosition + ps;
endPosition = startPosition + pe + 2 - ps;
}
}
| true | true | private void selectAttribute() {
if(attribute == null || attribute.length() == 0) return;
XAttribute a = object.getModelEntity().getAttribute(attribute);
if(isESB(a)) {
findESBAttrPosition(a);
}
String xml = (a == null) ? null : a.getXMLName();
if(xml == null || xml.length() == 0) return;
if(xml.indexOf(".") < 0) { //$NON-NLS-1$
String s = text.substring(startPosition, endPosition);
int i1 = findAttrPosition(s, xml);
if(selectAttributeName) {
if(i1 < 0) return;
startPosition = startPosition + i1;
endPosition = startPosition + xml.length();
return;
}
int i2 = (i1 < 0) ? -1 : s.indexOf('"', i1 + 1);
int i3 = (i2 < 0) ? -1 : s.indexOf('"', i2 + 1);
if(i3 > 0) {
endPosition = startPosition + i3;
startPosition = startPosition + i2 + 1;
}
} else {
xml = xml.substring(0, xml.indexOf('.'));
int e1 = text.indexOf("</" + getTagXMLName(object) + ">", startPosition); //$NON-NLS-1$ //$NON-NLS-2$
String s = e1 < 0 ? "" : text.substring(startPosition, e1); //$NON-NLS-1$
if(xml.length() == 0) {
int i1 = s.indexOf(">"); //$NON-NLS-1$
endPosition = startPosition + i1 + 1;
startPosition = startPosition + e1;
} else if(s.length() > 0) {
int i1a = s.indexOf("<" + xml + ">"); //$NON-NLS-1$ //$NON-NLS-2$
int i1b = s.indexOf("<" + xml + "/>"); //$NON-NLS-1$ //$NON-NLS-2$
int i2 = (i1a < 0) ? -1 : s.indexOf("</", i1a); //$NON-NLS-1$
if(i1a >= 0 && i2 >= 0) {
endPosition = startPosition + i2;
startPosition = startPosition + i1a + 2 + xml.length();
} else if(i1b >= 0) {
endPosition = startPosition + i1b + 3 + xml.length();
startPosition = startPosition + i1b;
}
}
}
}
| private void selectAttribute() {
if(attribute == null || attribute.length() == 0) return;
XAttribute a = object.getModelEntity().getAttribute(attribute);
if(isESB(a)) {
findESBAttrPosition(a);
}
String xml = (a == null) ? null : a.getXMLName();
if(xml == null || xml.length() == 0) return;
if(xml.indexOf(".") < 0) { //$NON-NLS-1$
String s = text.substring(startPosition, endPosition);
int i1 = findAttrPosition(s, xml);
if(selectAttributeName) {
if(i1 < 0) return;
startPosition = startPosition + i1;
endPosition = startPosition + xml.length();
return;
}
int i2 = (i1 < 0) ? -1 : s.indexOf('"', i1 + 1);
int i3 = (i2 < 0) ? -1 : s.indexOf('"', i2 + 1);
if(i3 > 0) {
endPosition = startPosition + i3;
startPosition = startPosition + i2 + 1;
}
} else {
xml = xml.substring(0, xml.lastIndexOf('.')); //remove .#text
if(xml.indexOf('.') >= 0) {
xml = xml.substring(xml.lastIndexOf('.') + 1); // simplify - look for the last name only
}
int e1 = text.indexOf("</" + getTagXMLName(object) + ">", startPosition); //$NON-NLS-1$ //$NON-NLS-2$
String s = e1 < 0 ? "" : text.substring(startPosition, e1); //$NON-NLS-1$
if(xml.length() == 0) {
int i1 = s.indexOf(">"); //$NON-NLS-1$
endPosition = startPosition + i1 + 1;
startPosition = startPosition + e1;
} else if(s.length() > 0) {
int i1a = s.indexOf("<" + xml + ">"); //$NON-NLS-1$ //$NON-NLS-2$
int i1b = s.indexOf("<" + xml + "/>"); //$NON-NLS-1$ //$NON-NLS-2$
int i2 = (i1a < 0) ? -1 : s.indexOf("</", i1a); //$NON-NLS-1$
if(i1a >= 0 && i2 >= 0) {
endPosition = startPosition + i2;
startPosition = startPosition + i1a + 2 + xml.length();
} else if(i1b >= 0) {
endPosition = startPosition + i1b + 3 + xml.length();
startPosition = startPosition + i1b;
}
}
}
}
|
diff --git a/org.emftext.sdk.ant/src/org/emftext/sdk/ant/GenerateTextResourceTask.java b/org.emftext.sdk.ant/src/org/emftext/sdk/ant/GenerateTextResourceTask.java
index fe7795d93..ea8123346 100644
--- a/org.emftext.sdk.ant/src/org/emftext/sdk/ant/GenerateTextResourceTask.java
+++ b/org.emftext.sdk.ant/src/org/emftext/sdk/ant/GenerateTextResourceTask.java
@@ -1,218 +1,218 @@
/*******************************************************************************
* Copyright (c) 2006-2009
* Software Technology Group, Dresden University of Technology
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option) any
* later version. This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* See the GNU Lesser General Public License for more details. You should have
* received a copy of the GNU Lesser General Public License along with this
* program; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
* Suite 330, Boston, MA 02111-1307 USA
*
* Contributors:
* Software Technology Group - TU Dresden, Germany
* - initial API and implementation
******************************************************************************/
package org.emftext.sdk.ant;
import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.plugin.EcorePlugin;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.URIConverter;
import org.emftext.runtime.resource.ITextResource;
import org.emftext.runtime.resource.impl.TextResourceHelper;
import org.emftext.sdk.SDKOptionProvider;
import org.emftext.sdk.codegen.generators.ResourcePluginGenerator.Result;
import org.emftext.sdk.concretesyntax.ConcreteSyntax;
/**
* A custom task for the ANT build tool that generates
* a resource plug-in for a given syntax specification.
*/
public class GenerateTextResourceTask extends Task {
private final static TextResourceHelper resourceHelper = new TextResourceHelper();
private File rootFolder;
private File syntaxFile;
private String syntaxProjectName;
private List<GenModelElement> genModels = new ArrayList<GenModelElement>();
private List<GenPackageElement> genPackages = new ArrayList<GenPackageElement>();
private static Resource.Factory alternativeEcoreEcoreFactory = null;
@Override
public void execute() throws BuildException {
checkParameters();
registerResourceFactories();
try {
log("loading syntax file...");
ITextResource csResource = resourceHelper.getResource(syntaxFile, new SDKOptionProvider().getOptions());
ConcreteSyntax syntax = (ConcreteSyntax) csResource.getContents().get(0);
EPackage ePackage = syntax.getPackage().getEcorePackage();
if (ePackage == null || ePackage.eIsProxy()) {
log("loading with alternative ecore format....");
syntax = tryAlternativeEcoreResourceFactory(syntax);
}
Result result = new AntResourcePluginGenerator().run(
syntax,
new AntGenerationContext(syntax, rootFolder, syntaxProjectName, new AntProblemCollector(this)),
new AntLogMarker(this),
new AntDelegateProgressMonitor(this)
);
if (result != Result.SUCCESS) {
if (result == Result.ERROR_FOUND_UNRESOLVED_PROXIES) {
for (EObject unresolvedProxy : result.getUnresolvedProxies()) {
log("Found unresolved proxy \"" + ((InternalEObject) unresolvedProxy).eProxyURI() + "\" in " + unresolvedProxy.eResource());
}
throw new BuildException("Generation failed " + result);
} else {
throw new BuildException("Generation failed " + result);
}
}
} catch (Exception e) {
e.printStackTrace();
throw new BuildException(e);
}
}
private ConcreteSyntax tryAlternativeEcoreResourceFactory(ConcreteSyntax syntax) throws BuildException {
try {
if (alternativeEcoreEcoreFactory == null) {
String alternativeEcoreResourceFactoryName = "org.emftext.language.ecore.resource.ecore.EcoreResourceFactory";
alternativeEcoreEcoreFactory = (Resource.Factory) Class.forName(alternativeEcoreResourceFactoryName).newInstance();
}
registerFactory("ecore", alternativeEcoreEcoreFactory);
ITextResource alternativeCsResource = resourceHelper.getResource(syntaxFile, new SDKOptionProvider().getOptions());
ConcreteSyntax alternativeSyntax = (ConcreteSyntax) alternativeCsResource.getContents().get(0);
EPackage alternativeEPackage = alternativeSyntax.getPackage().getEcorePackage();
if (alternativeEPackage != null && !alternativeEPackage.eIsProxy()) {
//ecore file is loaded; we can reset the resource factory
registerFactory("ecore", new org.eclipse.emf.ecore.xmi.impl.EcoreResourceFactoryImpl());
return alternativeSyntax;
}
else {
return syntax;
}
} catch (Exception e) {
e.printStackTrace();
throw new BuildException(e);
}
}
private void checkParameters() {
if (syntaxFile == null) {
throw new BuildException("Parameter \"syntax\" is missing.");
}
if (rootFolder == null) {
throw new BuildException("Parameter \"rootFolder\" is missing.");
}
if (syntaxProjectName == null) {
throw new BuildException("Parameter \"syntaxProjectName\" is missing.");
}
}
public void setSyntax(File syntaxFile) {
this.syntaxFile = syntaxFile;
}
public void setRootFolder(File rootFolder) {
this.rootFolder = rootFolder;
}
public void setSyntaxProjectName(String syntaxProjectName) {
this.syntaxProjectName = syntaxProjectName;
}
public void addGenModel(GenModelElement factory) {
genModels.add(factory);
}
public void addGenPackage(GenPackageElement factory) {
genPackages.add(factory);
}
public void registerResourceFactories() {
registerFactory("ecore", new org.eclipse.emf.ecore.xmi.impl.EcoreResourceFactoryImpl());
registerFactory("genmodel", new org.eclipse.emf.ecore.xmi.impl.EcoreResourceFactoryImpl());
registerFactory("cs", new org.emftext.sdk.concretesyntax.resource.cs.CsResourceFactory());
for (GenModelElement genModelElement : genModels) {
String namespaceURI = genModelElement.getNamespaceURI();
String genModelURI = genModelElement.getGenModelURI();
try {
log("registering genmodel " + namespaceURI + " at " + genModelURI);
EcorePlugin.getEPackageNsURIToGenModelLocationMap().put(
namespaceURI,
URI.createURI(genModelURI)
);
- //register a mapping using for the usual "plugin:" URIs in case one genmodel imports
- //one this genmodel itself using this URI
+ //register a mapping for "resource:/plugin/..." URIs in case
+ //one genmodel imports another genmodel using this URI
String filesSystemURI = genModelURI;
int startIdx = filesSystemURI.indexOf("/plugins");
int versionStartIdx = filesSystemURI.indexOf("_",startIdx);
int filePathStartIdx = filesSystemURI.lastIndexOf("!/") + 1;
if(startIdx > -1 && versionStartIdx > startIdx && filePathStartIdx > versionStartIdx) {
String platformPluginURI = "platform:" + filesSystemURI.substring(startIdx, versionStartIdx);
platformPluginURI = platformPluginURI + filesSystemURI.substring(filePathStartIdx);
platformPluginURI = platformPluginURI.replace("/plugins/", "/plugin/");
//gen model
log("adding mapping from " + platformPluginURI + " to " + filesSystemURI);
URIConverter.URI_MAP.put(
URI.createURI(platformPluginURI),
URI.createURI(filesSystemURI));
//ecore model (this code assumes that both files are named equally)
filesSystemURI = filesSystemURI.replace(".genmodel", ".ecore");
platformPluginURI = platformPluginURI.replace(".genmodel", ".ecore");
log("adding mapping from " + platformPluginURI + " to " + filesSystemURI);
URIConverter.URI_MAP.put(
URI.createURI(platformPluginURI),
URI.createURI(filesSystemURI));
}
} catch (Exception e) {
throw new BuildException("Error while registering genmodel " + namespaceURI, e);
}
}
for (GenPackageElement genPackage : genPackages) {
String namespaceURI = genPackage.getNamespaceURI();
String ePackageClassName = genPackage.getEPackageClassName();
try {
log("registering ePackage " + namespaceURI + " at " + ePackageClassName);
Field factoryInstance = Class.forName(ePackageClassName).getField("eINSTANCE");
Object ePackageObject = factoryInstance.get(null);
EPackage.Registry.INSTANCE.put(namespaceURI, ePackageObject);
} catch (Exception e) {
e.printStackTrace();
throw new BuildException("Error while registering EPackage " + namespaceURI, e);
}
}
}
private void registerFactory(String extension, Object factory) {
Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put(
extension,
factory);
}
}
| true | true | public void registerResourceFactories() {
registerFactory("ecore", new org.eclipse.emf.ecore.xmi.impl.EcoreResourceFactoryImpl());
registerFactory("genmodel", new org.eclipse.emf.ecore.xmi.impl.EcoreResourceFactoryImpl());
registerFactory("cs", new org.emftext.sdk.concretesyntax.resource.cs.CsResourceFactory());
for (GenModelElement genModelElement : genModels) {
String namespaceURI = genModelElement.getNamespaceURI();
String genModelURI = genModelElement.getGenModelURI();
try {
log("registering genmodel " + namespaceURI + " at " + genModelURI);
EcorePlugin.getEPackageNsURIToGenModelLocationMap().put(
namespaceURI,
URI.createURI(genModelURI)
);
//register a mapping using for the usual "plugin:" URIs in case one genmodel imports
//one this genmodel itself using this URI
String filesSystemURI = genModelURI;
int startIdx = filesSystemURI.indexOf("/plugins");
int versionStartIdx = filesSystemURI.indexOf("_",startIdx);
int filePathStartIdx = filesSystemURI.lastIndexOf("!/") + 1;
if(startIdx > -1 && versionStartIdx > startIdx && filePathStartIdx > versionStartIdx) {
String platformPluginURI = "platform:" + filesSystemURI.substring(startIdx, versionStartIdx);
platformPluginURI = platformPluginURI + filesSystemURI.substring(filePathStartIdx);
platformPluginURI = platformPluginURI.replace("/plugins/", "/plugin/");
//gen model
log("adding mapping from " + platformPluginURI + " to " + filesSystemURI);
URIConverter.URI_MAP.put(
URI.createURI(platformPluginURI),
URI.createURI(filesSystemURI));
//ecore model (this code assumes that both files are named equally)
filesSystemURI = filesSystemURI.replace(".genmodel", ".ecore");
platformPluginURI = platformPluginURI.replace(".genmodel", ".ecore");
log("adding mapping from " + platformPluginURI + " to " + filesSystemURI);
URIConverter.URI_MAP.put(
URI.createURI(platformPluginURI),
URI.createURI(filesSystemURI));
}
} catch (Exception e) {
throw new BuildException("Error while registering genmodel " + namespaceURI, e);
}
}
for (GenPackageElement genPackage : genPackages) {
String namespaceURI = genPackage.getNamespaceURI();
String ePackageClassName = genPackage.getEPackageClassName();
try {
log("registering ePackage " + namespaceURI + " at " + ePackageClassName);
Field factoryInstance = Class.forName(ePackageClassName).getField("eINSTANCE");
Object ePackageObject = factoryInstance.get(null);
EPackage.Registry.INSTANCE.put(namespaceURI, ePackageObject);
} catch (Exception e) {
e.printStackTrace();
throw new BuildException("Error while registering EPackage " + namespaceURI, e);
}
}
}
| public void registerResourceFactories() {
registerFactory("ecore", new org.eclipse.emf.ecore.xmi.impl.EcoreResourceFactoryImpl());
registerFactory("genmodel", new org.eclipse.emf.ecore.xmi.impl.EcoreResourceFactoryImpl());
registerFactory("cs", new org.emftext.sdk.concretesyntax.resource.cs.CsResourceFactory());
for (GenModelElement genModelElement : genModels) {
String namespaceURI = genModelElement.getNamespaceURI();
String genModelURI = genModelElement.getGenModelURI();
try {
log("registering genmodel " + namespaceURI + " at " + genModelURI);
EcorePlugin.getEPackageNsURIToGenModelLocationMap().put(
namespaceURI,
URI.createURI(genModelURI)
);
//register a mapping for "resource:/plugin/..." URIs in case
//one genmodel imports another genmodel using this URI
String filesSystemURI = genModelURI;
int startIdx = filesSystemURI.indexOf("/plugins");
int versionStartIdx = filesSystemURI.indexOf("_",startIdx);
int filePathStartIdx = filesSystemURI.lastIndexOf("!/") + 1;
if(startIdx > -1 && versionStartIdx > startIdx && filePathStartIdx > versionStartIdx) {
String platformPluginURI = "platform:" + filesSystemURI.substring(startIdx, versionStartIdx);
platformPluginURI = platformPluginURI + filesSystemURI.substring(filePathStartIdx);
platformPluginURI = platformPluginURI.replace("/plugins/", "/plugin/");
//gen model
log("adding mapping from " + platformPluginURI + " to " + filesSystemURI);
URIConverter.URI_MAP.put(
URI.createURI(platformPluginURI),
URI.createURI(filesSystemURI));
//ecore model (this code assumes that both files are named equally)
filesSystemURI = filesSystemURI.replace(".genmodel", ".ecore");
platformPluginURI = platformPluginURI.replace(".genmodel", ".ecore");
log("adding mapping from " + platformPluginURI + " to " + filesSystemURI);
URIConverter.URI_MAP.put(
URI.createURI(platformPluginURI),
URI.createURI(filesSystemURI));
}
} catch (Exception e) {
throw new BuildException("Error while registering genmodel " + namespaceURI, e);
}
}
for (GenPackageElement genPackage : genPackages) {
String namespaceURI = genPackage.getNamespaceURI();
String ePackageClassName = genPackage.getEPackageClassName();
try {
log("registering ePackage " + namespaceURI + " at " + ePackageClassName);
Field factoryInstance = Class.forName(ePackageClassName).getField("eINSTANCE");
Object ePackageObject = factoryInstance.get(null);
EPackage.Registry.INSTANCE.put(namespaceURI, ePackageObject);
} catch (Exception e) {
e.printStackTrace();
throw new BuildException("Error while registering EPackage " + namespaceURI, e);
}
}
}
|
diff --git a/src/com/bingo/eatime/EaTimeServlet.java b/src/com/bingo/eatime/EaTimeServlet.java
index 616a8fa..229de47 100644
--- a/src/com/bingo/eatime/EaTimeServlet.java
+++ b/src/com/bingo/eatime/EaTimeServlet.java
@@ -1,31 +1,31 @@
package com.bingo.eatime;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class EaTimeServlet extends HttpServlet {
private static final long serialVersionUID = -7796866550957261709L;
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
String isLogin=(String) req.getSession().getAttribute("loginStatus");
if(isLogin==null)
- resp.sendRedirect("login");
- if(isLogin.equals("false"))
- resp.sendRedirect("login");
+ resp.sendRedirect("login.jsp");
+ else if(isLogin.equals("false"))
+ resp.sendRedirect("login.jsp");
RequestDispatcher rd = req.getRequestDispatcher("/main.jsp");
try {
rd.forward(req, resp);
} catch (ServletException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| true | true | public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
String isLogin=(String) req.getSession().getAttribute("loginStatus");
if(isLogin==null)
resp.sendRedirect("login");
if(isLogin.equals("false"))
resp.sendRedirect("login");
RequestDispatcher rd = req.getRequestDispatcher("/main.jsp");
try {
rd.forward(req, resp);
} catch (ServletException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
| public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
String isLogin=(String) req.getSession().getAttribute("loginStatus");
if(isLogin==null)
resp.sendRedirect("login.jsp");
else if(isLogin.equals("false"))
resp.sendRedirect("login.jsp");
RequestDispatcher rd = req.getRequestDispatcher("/main.jsp");
try {
rd.forward(req, resp);
} catch (ServletException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
|
diff --git a/src/main/java/com/brotherlogic/booser/servlets/APIEndpoint.java b/src/main/java/com/brotherlogic/booser/servlets/APIEndpoint.java
index 9ca31df..a064633 100644
--- a/src/main/java/com/brotherlogic/booser/servlets/APIEndpoint.java
+++ b/src/main/java/com/brotherlogic/booser/servlets/APIEndpoint.java
@@ -1,368 +1,368 @@
package com.brotherlogic.booser.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DateFormat;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.brotherlogic.booser.Config;
import com.brotherlogic.booser.atom.Atom;
import com.brotherlogic.booser.atom.Beer;
import com.brotherlogic.booser.atom.Drink;
import com.brotherlogic.booser.atom.FoursquareVenue;
import com.brotherlogic.booser.atom.User;
import com.brotherlogic.booser.atom.Venue;
import com.brotherlogic.booser.storage.AssetManager;
import com.brotherlogic.booser.storage.db.Database;
import com.brotherlogic.booser.storage.db.DatabaseFactory;
import com.brotherlogic.booser.storage.web.Downloader;
import com.brotherlogic.booser.storage.web.WebLayer;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
public class APIEndpoint extends UntappdBaseServlet
{
private static final String baseURL = "http://localhost:8080/";
private static final int COOKIE_AGE = 60 * 60 * 24 * 365;
private static final String COOKIE_NAME = "untappdpicker_cookie";
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException
{
if (req.getParameter("action") != null && req.getParameter("action").equals("version"))
{
write(resp, "0.4");
return;
}
String token = null;
if (req.getParameter("notoken") == null)
{
token = req.getParameter("access_token");
if (token == null)
token = getUserToken(req, resp);
}
// If we're not logged in, server will redirect
if (token != "not_logged_in")
{
AssetManager manager = AssetManager.getManager(token);
String action = req.getParameter("action");
if (action == null)
{
resp.sendRedirect("/");
return;
}
if (action.equals("getVenue"))
{
double lat = Double.parseDouble(req.getParameter("lat"));
double lon = Double.parseDouble(req.getParameter("lon"));
List<Atom> venues = getFoursquareVenues(manager, lat, lon);
processJson(resp, venues);
}
else if (action.equals("venueDetails"))
{
Database db = DatabaseFactory.getInstance().getDatabase();
db.reset();
- User me = manager.pullUser("BrotherLogic");
+ User me = manager.getUser("BrotherLogic");
System.out.println("GOT USER = " + me);
Venue v = manager.getVenue(req.getParameter("vid"));
List<JsonObject> retList = new LinkedList<JsonObject>();
for (Entry<Beer, Integer> count : v.getBeerCounts().entrySet())
{
JsonObject nObj = new JsonObject();
nObj.add("beer_name", new JsonPrimitive(count.getKey().getBeerName()));
nObj.add("beer_style", new JsonPrimitive(count.getKey().getBeerStyle()));
nObj.add("brewery_name", new JsonPrimitive(count.getKey().getBrewery()
.getBreweryName()));
nObj.add("count", new JsonPrimitive(count.getValue()));
nObj.add("beer_score", new JsonPrimitive(count.getKey().resolveScore(token)));
boolean had = false;
for (Drink d : me.getDrinks())
if (d.getBeer() != null && d.getBeer().getId().equals(count.getKey().getId()))
{
had = true;
break;
}
if (had)
nObj.add("had", new JsonPrimitive(true));
else
nObj.add("had", new JsonPrimitive(false));
retList.add(nObj);
}
// Simple sorting for now
Collections.sort(retList, new Comparator<JsonObject>()
{
@Override
public int compare(JsonObject arg0, JsonObject arg1)
{
double diff = (arg1.get("beer_score").getAsDouble() - arg0.get("beer_score")
.getAsDouble()) * 1000;
System.out.println("DIFF = " + ((int) diff) + " from " + diff);
return (int) diff;
}
});
System.out.println("TOP = " + retList.get(0).get("beer_score").getAsDouble());
JsonArray retArr = new JsonArray();
for (JsonObject obj : retList)
retArr.add(obj);
write(resp, retArr);
}
else if (action.equals("getNumberOfDrinks"))
{
Database db = DatabaseFactory.getInstance().getDatabase();
db.reset();
User u = manager.getUser();
List<Drink> beers = u.getDrinks();
JsonObject obj = new JsonObject();
obj.add("drinks", new JsonPrimitive(beers.size()));
obj.add("username", new JsonPrimitive(u.getId()));
write(resp, obj);
}
else if (action.equals("getDrinks"))
{
Database db = DatabaseFactory.getInstance().getDatabase();
db.reset();
User u = manager.getUser();
List<Drink> drinks = u.getDrinks();
Map<Beer, Integer> counts = new TreeMap<Beer, Integer>();
Map<Beer, Double> beers = new TreeMap<Beer, Double>();
for (Drink d : drinks)
{
if (!counts.containsKey(d.getBeer()))
counts.put(d.getBeer(), 1);
else
counts.put(d.getBeer(), counts.get(d.getBeer()) + 1);
beers.put(d.getBeer(), d.getRating_score());
}
Gson gson = new Gson();
JsonArray arr = new JsonArray();
for (Beer b : beers.keySet())
{
JsonObject obj = gson.toJsonTree(b).getAsJsonObject();
obj.add("rating", new JsonPrimitive(beers.get(b)));
obj.add("drunkcount", new JsonPrimitive(counts.get(b)));
arr.add(obj);
}
write(resp, arr);
}
else if (action.equals("getStyle"))
{
String style = req.getParameter("style");
if (style.equals("null"))
style = "";
Database db = DatabaseFactory.getInstance().getDatabase();
db.reset();
User u = manager.getUser();
List<Drink> drinks = u.getDrinks();
Map<Beer, Integer> counts = new TreeMap<Beer, Integer>();
Map<Beer, Double> rating = new TreeMap<Beer, Double>();
for (Drink d : drinks)
if (style.length() == 0 || d.getBeer().getBeerStyle().equals(style))
{
if (!counts.containsKey(d.getBeer()))
counts.put(d.getBeer(), 1);
else
counts.put(d.getBeer(), counts.get(d.getBeer()) + 1);
rating.put(d.getBeer(), d.getRating_score());
}
Gson gson = new Gson();
JsonArray arr = new JsonArray();
for (Beer b : counts.keySet())
{
JsonObject obj = gson.toJsonTree(b).getAsJsonObject();
obj.add("drunkcount", new JsonPrimitive(counts.get(b)));
obj.add("rating", new JsonPrimitive(rating.get(b)));
arr.add(obj);
}
write(resp, arr);
}
else if (action.equals("getBeer"))
{
String beerId = req.getParameter("beer");
DateFormat df = DateFormat.getInstance();
Database db = DatabaseFactory.getInstance().getDatabase();
db.reset();
User u = manager.getUser();
List<Drink> drinks = u.getDrinks();
List<Drink> show = new LinkedList<Drink>();
for (Drink d : drinks)
if (d.getBeer().getId().equals(beerId))
show.add(d);
Gson gson = new Gson();
JsonArray arr = new JsonArray();
for (Drink d : show)
{
JsonObject obj = gson.toJsonTree(d.getBeer()).getAsJsonObject();
obj.add("date", new JsonPrimitive(df.format(d.getCreated_at().getTime())));
if (d.getPhoto_url() != null)
obj.add("photo", new JsonPrimitive(d.getPhoto_url()));
obj.add("rating", new JsonPrimitive(d.getRating_score()));
arr.add(obj);
}
write(resp, arr);
}
else if (action.equals("users"))
{
Database db = DatabaseFactory.getInstance().getDatabase();
db.reset();
List<Atom> users = manager.getUsers();
JsonArray arr = new JsonArray();
for (Atom user : users)
arr.add(new JsonPrimitive(user.getId()));
write(resp, arr);
}
}
}
public List<Atom> getFoursquareVenues(AssetManager manager, double lat, double lon)
{
try
{
WebLayer layer = new WebLayer(manager);
List<Atom> atoms = layer.getLocal(FoursquareVenue.class,
new URL("https://api.foursquare.com/v2/venues/search?ll=" + lat + "," + lon
+ "&client_id=" + Config.getFoursquareClientId() + "&" + "client_secret="
+ Config.getFoursquareSecret() + "&v=20130118"), false);
return atoms;
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
return new LinkedList<Atom>();
}
public String getUserDetails(String userToken) throws IOException
{
User u = AssetManager.getManager(userToken).getUser();
return u.getJson().toString();
}
/**
* Gets the user token from the request
*
* @param req
* The servlet request object
* @return The User Token
*/
private String getUserToken(final HttpServletRequest req, final HttpServletResponse resp)
{
if (req.getCookies() != null)
for (Cookie cookie : req.getCookies())
if (cookie.getName().equals(COOKIE_NAME))
return cookie.getValue();
// Forward the thingy on to the login point
try
{
// Check we're not in the login process
if (req.getParameter("code") != null)
{
String response = Downloader.getInstance().download(
new URL("https://untappd.com/oauth/authorize/?client_id="
+ Config.getUntappdClient() + "&client_secret=" + Config.getUntappdSecret()
+ "&response_type=code&redirect_url=" + baseURL + "API&code="
+ req.getParameter("code")));
// Get the access token
JsonParser parser = new JsonParser();
String nToken = parser.parse(response).getAsJsonObject().get("response")
.getAsJsonObject().get("access_token").getAsString();
// Set the cookie
Cookie cookie = new Cookie(COOKIE_NAME, nToken);
cookie.setMaxAge(COOKIE_AGE);
cookie.setPath("/");
resp.addCookie(cookie);
return nToken;
}
else
resp.sendRedirect("http://untappd.com/oauth/authenticate/?client_id="
+ Config.getUntappdClient() + "&client_secret=" + Config.getUntappdSecret()
+ "&response_type=code&redirect_url=" + baseURL + "API");
}
catch (IOException e)
{
e.printStackTrace();
}
return "not_logged_in";
}
private void processJson(HttpServletResponse resp, List<Atom> atoms) throws IOException
{
JsonArray arr = new JsonArray();
for (Atom atom : atoms)
arr.add(atom.getJson());
write(resp, arr.toString());
}
private void write(HttpServletResponse resp, JsonElement obj) throws IOException
{
write(resp, obj.toString());
}
private void write(HttpServletResponse resp, String jsonString) throws IOException
{
resp.setContentType("application/json");
PrintWriter out = resp.getWriter();
String convString = new String(jsonString.getBytes("UTF-8"), "US-ASCII");
out.print(convString);
out.close();
}
}
| true | true | protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException
{
if (req.getParameter("action") != null && req.getParameter("action").equals("version"))
{
write(resp, "0.4");
return;
}
String token = null;
if (req.getParameter("notoken") == null)
{
token = req.getParameter("access_token");
if (token == null)
token = getUserToken(req, resp);
}
// If we're not logged in, server will redirect
if (token != "not_logged_in")
{
AssetManager manager = AssetManager.getManager(token);
String action = req.getParameter("action");
if (action == null)
{
resp.sendRedirect("/");
return;
}
if (action.equals("getVenue"))
{
double lat = Double.parseDouble(req.getParameter("lat"));
double lon = Double.parseDouble(req.getParameter("lon"));
List<Atom> venues = getFoursquareVenues(manager, lat, lon);
processJson(resp, venues);
}
else if (action.equals("venueDetails"))
{
Database db = DatabaseFactory.getInstance().getDatabase();
db.reset();
User me = manager.pullUser("BrotherLogic");
System.out.println("GOT USER = " + me);
Venue v = manager.getVenue(req.getParameter("vid"));
List<JsonObject> retList = new LinkedList<JsonObject>();
for (Entry<Beer, Integer> count : v.getBeerCounts().entrySet())
{
JsonObject nObj = new JsonObject();
nObj.add("beer_name", new JsonPrimitive(count.getKey().getBeerName()));
nObj.add("beer_style", new JsonPrimitive(count.getKey().getBeerStyle()));
nObj.add("brewery_name", new JsonPrimitive(count.getKey().getBrewery()
.getBreweryName()));
nObj.add("count", new JsonPrimitive(count.getValue()));
nObj.add("beer_score", new JsonPrimitive(count.getKey().resolveScore(token)));
boolean had = false;
for (Drink d : me.getDrinks())
if (d.getBeer() != null && d.getBeer().getId().equals(count.getKey().getId()))
{
had = true;
break;
}
if (had)
nObj.add("had", new JsonPrimitive(true));
else
nObj.add("had", new JsonPrimitive(false));
retList.add(nObj);
}
// Simple sorting for now
Collections.sort(retList, new Comparator<JsonObject>()
{
@Override
public int compare(JsonObject arg0, JsonObject arg1)
{
double diff = (arg1.get("beer_score").getAsDouble() - arg0.get("beer_score")
.getAsDouble()) * 1000;
System.out.println("DIFF = " + ((int) diff) + " from " + diff);
return (int) diff;
}
});
System.out.println("TOP = " + retList.get(0).get("beer_score").getAsDouble());
JsonArray retArr = new JsonArray();
for (JsonObject obj : retList)
retArr.add(obj);
write(resp, retArr);
}
else if (action.equals("getNumberOfDrinks"))
{
Database db = DatabaseFactory.getInstance().getDatabase();
db.reset();
User u = manager.getUser();
List<Drink> beers = u.getDrinks();
JsonObject obj = new JsonObject();
obj.add("drinks", new JsonPrimitive(beers.size()));
obj.add("username", new JsonPrimitive(u.getId()));
write(resp, obj);
}
else if (action.equals("getDrinks"))
{
Database db = DatabaseFactory.getInstance().getDatabase();
db.reset();
User u = manager.getUser();
List<Drink> drinks = u.getDrinks();
Map<Beer, Integer> counts = new TreeMap<Beer, Integer>();
Map<Beer, Double> beers = new TreeMap<Beer, Double>();
for (Drink d : drinks)
{
if (!counts.containsKey(d.getBeer()))
counts.put(d.getBeer(), 1);
else
counts.put(d.getBeer(), counts.get(d.getBeer()) + 1);
beers.put(d.getBeer(), d.getRating_score());
}
Gson gson = new Gson();
JsonArray arr = new JsonArray();
for (Beer b : beers.keySet())
{
JsonObject obj = gson.toJsonTree(b).getAsJsonObject();
obj.add("rating", new JsonPrimitive(beers.get(b)));
obj.add("drunkcount", new JsonPrimitive(counts.get(b)));
arr.add(obj);
}
write(resp, arr);
}
else if (action.equals("getStyle"))
{
String style = req.getParameter("style");
if (style.equals("null"))
style = "";
Database db = DatabaseFactory.getInstance().getDatabase();
db.reset();
User u = manager.getUser();
List<Drink> drinks = u.getDrinks();
Map<Beer, Integer> counts = new TreeMap<Beer, Integer>();
Map<Beer, Double> rating = new TreeMap<Beer, Double>();
for (Drink d : drinks)
if (style.length() == 0 || d.getBeer().getBeerStyle().equals(style))
{
if (!counts.containsKey(d.getBeer()))
counts.put(d.getBeer(), 1);
else
counts.put(d.getBeer(), counts.get(d.getBeer()) + 1);
rating.put(d.getBeer(), d.getRating_score());
}
Gson gson = new Gson();
JsonArray arr = new JsonArray();
for (Beer b : counts.keySet())
{
JsonObject obj = gson.toJsonTree(b).getAsJsonObject();
obj.add("drunkcount", new JsonPrimitive(counts.get(b)));
obj.add("rating", new JsonPrimitive(rating.get(b)));
arr.add(obj);
}
write(resp, arr);
}
else if (action.equals("getBeer"))
{
String beerId = req.getParameter("beer");
DateFormat df = DateFormat.getInstance();
Database db = DatabaseFactory.getInstance().getDatabase();
db.reset();
User u = manager.getUser();
List<Drink> drinks = u.getDrinks();
List<Drink> show = new LinkedList<Drink>();
for (Drink d : drinks)
if (d.getBeer().getId().equals(beerId))
show.add(d);
Gson gson = new Gson();
JsonArray arr = new JsonArray();
for (Drink d : show)
{
JsonObject obj = gson.toJsonTree(d.getBeer()).getAsJsonObject();
obj.add("date", new JsonPrimitive(df.format(d.getCreated_at().getTime())));
if (d.getPhoto_url() != null)
obj.add("photo", new JsonPrimitive(d.getPhoto_url()));
obj.add("rating", new JsonPrimitive(d.getRating_score()));
arr.add(obj);
}
write(resp, arr);
}
else if (action.equals("users"))
{
Database db = DatabaseFactory.getInstance().getDatabase();
db.reset();
List<Atom> users = manager.getUsers();
JsonArray arr = new JsonArray();
for (Atom user : users)
arr.add(new JsonPrimitive(user.getId()));
write(resp, arr);
}
}
}
| protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException
{
if (req.getParameter("action") != null && req.getParameter("action").equals("version"))
{
write(resp, "0.4");
return;
}
String token = null;
if (req.getParameter("notoken") == null)
{
token = req.getParameter("access_token");
if (token == null)
token = getUserToken(req, resp);
}
// If we're not logged in, server will redirect
if (token != "not_logged_in")
{
AssetManager manager = AssetManager.getManager(token);
String action = req.getParameter("action");
if (action == null)
{
resp.sendRedirect("/");
return;
}
if (action.equals("getVenue"))
{
double lat = Double.parseDouble(req.getParameter("lat"));
double lon = Double.parseDouble(req.getParameter("lon"));
List<Atom> venues = getFoursquareVenues(manager, lat, lon);
processJson(resp, venues);
}
else if (action.equals("venueDetails"))
{
Database db = DatabaseFactory.getInstance().getDatabase();
db.reset();
User me = manager.getUser("BrotherLogic");
System.out.println("GOT USER = " + me);
Venue v = manager.getVenue(req.getParameter("vid"));
List<JsonObject> retList = new LinkedList<JsonObject>();
for (Entry<Beer, Integer> count : v.getBeerCounts().entrySet())
{
JsonObject nObj = new JsonObject();
nObj.add("beer_name", new JsonPrimitive(count.getKey().getBeerName()));
nObj.add("beer_style", new JsonPrimitive(count.getKey().getBeerStyle()));
nObj.add("brewery_name", new JsonPrimitive(count.getKey().getBrewery()
.getBreweryName()));
nObj.add("count", new JsonPrimitive(count.getValue()));
nObj.add("beer_score", new JsonPrimitive(count.getKey().resolveScore(token)));
boolean had = false;
for (Drink d : me.getDrinks())
if (d.getBeer() != null && d.getBeer().getId().equals(count.getKey().getId()))
{
had = true;
break;
}
if (had)
nObj.add("had", new JsonPrimitive(true));
else
nObj.add("had", new JsonPrimitive(false));
retList.add(nObj);
}
// Simple sorting for now
Collections.sort(retList, new Comparator<JsonObject>()
{
@Override
public int compare(JsonObject arg0, JsonObject arg1)
{
double diff = (arg1.get("beer_score").getAsDouble() - arg0.get("beer_score")
.getAsDouble()) * 1000;
System.out.println("DIFF = " + ((int) diff) + " from " + diff);
return (int) diff;
}
});
System.out.println("TOP = " + retList.get(0).get("beer_score").getAsDouble());
JsonArray retArr = new JsonArray();
for (JsonObject obj : retList)
retArr.add(obj);
write(resp, retArr);
}
else if (action.equals("getNumberOfDrinks"))
{
Database db = DatabaseFactory.getInstance().getDatabase();
db.reset();
User u = manager.getUser();
List<Drink> beers = u.getDrinks();
JsonObject obj = new JsonObject();
obj.add("drinks", new JsonPrimitive(beers.size()));
obj.add("username", new JsonPrimitive(u.getId()));
write(resp, obj);
}
else if (action.equals("getDrinks"))
{
Database db = DatabaseFactory.getInstance().getDatabase();
db.reset();
User u = manager.getUser();
List<Drink> drinks = u.getDrinks();
Map<Beer, Integer> counts = new TreeMap<Beer, Integer>();
Map<Beer, Double> beers = new TreeMap<Beer, Double>();
for (Drink d : drinks)
{
if (!counts.containsKey(d.getBeer()))
counts.put(d.getBeer(), 1);
else
counts.put(d.getBeer(), counts.get(d.getBeer()) + 1);
beers.put(d.getBeer(), d.getRating_score());
}
Gson gson = new Gson();
JsonArray arr = new JsonArray();
for (Beer b : beers.keySet())
{
JsonObject obj = gson.toJsonTree(b).getAsJsonObject();
obj.add("rating", new JsonPrimitive(beers.get(b)));
obj.add("drunkcount", new JsonPrimitive(counts.get(b)));
arr.add(obj);
}
write(resp, arr);
}
else if (action.equals("getStyle"))
{
String style = req.getParameter("style");
if (style.equals("null"))
style = "";
Database db = DatabaseFactory.getInstance().getDatabase();
db.reset();
User u = manager.getUser();
List<Drink> drinks = u.getDrinks();
Map<Beer, Integer> counts = new TreeMap<Beer, Integer>();
Map<Beer, Double> rating = new TreeMap<Beer, Double>();
for (Drink d : drinks)
if (style.length() == 0 || d.getBeer().getBeerStyle().equals(style))
{
if (!counts.containsKey(d.getBeer()))
counts.put(d.getBeer(), 1);
else
counts.put(d.getBeer(), counts.get(d.getBeer()) + 1);
rating.put(d.getBeer(), d.getRating_score());
}
Gson gson = new Gson();
JsonArray arr = new JsonArray();
for (Beer b : counts.keySet())
{
JsonObject obj = gson.toJsonTree(b).getAsJsonObject();
obj.add("drunkcount", new JsonPrimitive(counts.get(b)));
obj.add("rating", new JsonPrimitive(rating.get(b)));
arr.add(obj);
}
write(resp, arr);
}
else if (action.equals("getBeer"))
{
String beerId = req.getParameter("beer");
DateFormat df = DateFormat.getInstance();
Database db = DatabaseFactory.getInstance().getDatabase();
db.reset();
User u = manager.getUser();
List<Drink> drinks = u.getDrinks();
List<Drink> show = new LinkedList<Drink>();
for (Drink d : drinks)
if (d.getBeer().getId().equals(beerId))
show.add(d);
Gson gson = new Gson();
JsonArray arr = new JsonArray();
for (Drink d : show)
{
JsonObject obj = gson.toJsonTree(d.getBeer()).getAsJsonObject();
obj.add("date", new JsonPrimitive(df.format(d.getCreated_at().getTime())));
if (d.getPhoto_url() != null)
obj.add("photo", new JsonPrimitive(d.getPhoto_url()));
obj.add("rating", new JsonPrimitive(d.getRating_score()));
arr.add(obj);
}
write(resp, arr);
}
else if (action.equals("users"))
{
Database db = DatabaseFactory.getInstance().getDatabase();
db.reset();
List<Atom> users = manager.getUsers();
JsonArray arr = new JsonArray();
for (Atom user : users)
arr.add(new JsonPrimitive(user.getId()));
write(resp, arr);
}
}
}
|
diff --git a/api/src/java/com/robonobo/mina/external/node/EonEndPoint.java b/api/src/java/com/robonobo/mina/external/node/EonEndPoint.java
index ed43c8b..34d8410 100755
--- a/api/src/java/com/robonobo/mina/external/node/EonEndPoint.java
+++ b/api/src/java/com/robonobo/mina/external/node/EonEndPoint.java
@@ -1,87 +1,89 @@
package com.robonobo.mina.external.node;
import java.net.InetAddress;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.robonobo.common.util.TextUtil;
import com.robonobo.core.api.proto.CoreApi.EndPoint;
public abstract class EonEndPoint {
static final Pattern EP_PATTERN = Pattern.compile("^(\\w+?):(.*):(\\d+):(\\d+);(.*)$");
protected int udpPort;
protected int eonPort;
protected InetAddress address;
protected String url;
/** Does only a quick check against the protocol, doesn't check the url components */
public static boolean isEonUrl(String url) {
int colPos = url.indexOf(":");
if (colPos < 0)
return false;
String protocol = url.substring(0, colPos);
return (protocol.equals("seon") || protocol.equals("deon"));
}
public static EonEndPoint parse(String url) {
Matcher m = EP_PATTERN.matcher(url);
if (!m.matches())
throw new RuntimeException("Error in url " + url);
String protocol = m.group(1);
try {
InetAddress addr = InetAddress.getByName(m.group(2));
int udpPort = Integer.parseInt(m.group(3));
int eonPort = Integer.parseInt(m.group(4));
String[] opts = m.group(5).split(",");
if (protocol.equals("seon")) {
for (String opt : opts) {
+ if(opt.length() == 0)
+ continue;
if(opt.equals("nt"))
return new SeonNatTraversalEndPoint(addr, udpPort, eonPort);
throw new RuntimeException("Unknown eon option "+opt);
}
return new SeonEndPoint(addr, udpPort, eonPort);
} else if (protocol.equals("deon"))
return new DeonEndPoint(addr, udpPort, eonPort);
} catch (Exception ignore) {
}
throw new RuntimeException("Invalid eon url " + url);
}
EonEndPoint() {
}
public boolean equals(Object obj) {
if (obj instanceof EonEndPoint)
return hashCode() == obj.hashCode();
return false;
}
public int hashCode() {
return getClass().getName().hashCode() ^ url.hashCode();
}
public int getEonPort() {
return eonPort;
}
public int getUdpPort() {
return udpPort;
}
public InetAddress getAddress() {
return address;
}
public String getUrl() {
return url;
}
@Override
public String toString() {
return url;
}
public EndPoint toMsg() {
return EndPoint.newBuilder().setUrl(url).build();
}
}
| true | true | public static EonEndPoint parse(String url) {
Matcher m = EP_PATTERN.matcher(url);
if (!m.matches())
throw new RuntimeException("Error in url " + url);
String protocol = m.group(1);
try {
InetAddress addr = InetAddress.getByName(m.group(2));
int udpPort = Integer.parseInt(m.group(3));
int eonPort = Integer.parseInt(m.group(4));
String[] opts = m.group(5).split(",");
if (protocol.equals("seon")) {
for (String opt : opts) {
if(opt.equals("nt"))
return new SeonNatTraversalEndPoint(addr, udpPort, eonPort);
throw new RuntimeException("Unknown eon option "+opt);
}
return new SeonEndPoint(addr, udpPort, eonPort);
} else if (protocol.equals("deon"))
return new DeonEndPoint(addr, udpPort, eonPort);
} catch (Exception ignore) {
}
throw new RuntimeException("Invalid eon url " + url);
}
| public static EonEndPoint parse(String url) {
Matcher m = EP_PATTERN.matcher(url);
if (!m.matches())
throw new RuntimeException("Error in url " + url);
String protocol = m.group(1);
try {
InetAddress addr = InetAddress.getByName(m.group(2));
int udpPort = Integer.parseInt(m.group(3));
int eonPort = Integer.parseInt(m.group(4));
String[] opts = m.group(5).split(",");
if (protocol.equals("seon")) {
for (String opt : opts) {
if(opt.length() == 0)
continue;
if(opt.equals("nt"))
return new SeonNatTraversalEndPoint(addr, udpPort, eonPort);
throw new RuntimeException("Unknown eon option "+opt);
}
return new SeonEndPoint(addr, udpPort, eonPort);
} else if (protocol.equals("deon"))
return new DeonEndPoint(addr, udpPort, eonPort);
} catch (Exception ignore) {
}
throw new RuntimeException("Invalid eon url " + url);
}
|
diff --git a/src/com/norcode/bukkit/enhancedfishing/LootTable.java b/src/com/norcode/bukkit/enhancedfishing/LootTable.java
index 548f709..9e96782 100644
--- a/src/com/norcode/bukkit/enhancedfishing/LootTable.java
+++ b/src/com/norcode/bukkit/enhancedfishing/LootTable.java
@@ -1,94 +1,94 @@
package com.norcode.bukkit.enhancedfishing;
import java.util.NavigableMap;
import java.util.Random;
import java.util.TreeMap;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.inventory.ItemStack;
public class LootTable {
public static class Loot {
String name;
ItemStack stack;
double weight;
public Loot(String name, ItemStack stack, double weight) {
this.name = name;
this.stack = stack;
this.weight = weight;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ItemStack getStack() {
return stack;
}
public void setStack(ItemStack stack) {
this.stack = stack;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
}
private ConfigAccessor configAccessor;
private final NavigableMap<Double, Loot> map = new TreeMap<Double, Loot>();
private final Random random;
private double total = 0;
private String world;
public LootTable(EnhancedFishing plugin, String world) {
this.world = world.toLowerCase();
this.random = new Random();
this.configAccessor = plugin.getTreasureConfig();
this.configAccessor.getConfig();
this.configAccessor.saveDefaultConfig();
}
public void clear() {
this.map.clear();
this.total = 0;
}
public void add(String name, ItemStack stack, double weight) {
if (weight <= 0) return;
total += weight;
map.put(total, new Loot(name, stack, weight));
}
public Loot get(int lootingLevel) {
double max = 0;
double score = 0;
- for (int i=0;i<random.nextInt(lootingLevel/2)+1;i++) {
+ for (int i=0;i<random.nextInt((lootingLevel/2)+1);i++) {
score = random.nextDouble() * total;
if (score > max) max = score;
}
if (max >= total) {
max = total-1;
}
return map.ceilingEntry(max).getValue();
}
public void reload() {
configAccessor.reloadConfig();
this.clear();
ConfigurationSection cfg = null;
for (String key: getLootConfig().getKeys(false)) {
cfg = getLootConfig().getConfigurationSection(key);
if (!cfg.contains("worlds") || cfg.getStringList("worlds").contains(world)) {
add(key, cfg.getItemStack("item"), cfg.getDouble("weight"));
}
}
}
private ConfigurationSection getLootConfig() {
return configAccessor.getConfig();
}
}
| true | true | public Loot get(int lootingLevel) {
double max = 0;
double score = 0;
for (int i=0;i<random.nextInt(lootingLevel/2)+1;i++) {
score = random.nextDouble() * total;
if (score > max) max = score;
}
if (max >= total) {
max = total-1;
}
return map.ceilingEntry(max).getValue();
}
| public Loot get(int lootingLevel) {
double max = 0;
double score = 0;
for (int i=0;i<random.nextInt((lootingLevel/2)+1);i++) {
score = random.nextDouble() * total;
if (score > max) max = score;
}
if (max >= total) {
max = total-1;
}
return map.ceilingEntry(max).getValue();
}
|
diff --git a/plugins/org.obeonetwork.dsl.uml2.design/src/org/obeonetwork/dsl/uml2/design/services/SequenceServices.java b/plugins/org.obeonetwork.dsl.uml2.design/src/org/obeonetwork/dsl/uml2/design/services/SequenceServices.java
index 7fc91bbc..7eba49e4 100644
--- a/plugins/org.obeonetwork.dsl.uml2.design/src/org/obeonetwork/dsl/uml2/design/services/SequenceServices.java
+++ b/plugins/org.obeonetwork.dsl.uml2.design/src/org/obeonetwork/dsl/uml2/design/services/SequenceServices.java
@@ -1,1213 +1,1214 @@
/*******************************************************************************
* Copyright (c) 2009, 2011 Obeo.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Obeo - initial API and implementation
*******************************************************************************/
package org.obeonetwork.dsl.uml2.design.services;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.gef.EditPart;
import org.eclipse.gmf.runtime.diagram.ui.parts.IDiagramWorkbenchPart;
import org.eclipse.ui.IEditorPart;
import org.eclipse.uml2.uml.BehaviorExecutionSpecification;
import org.eclipse.uml2.uml.Element;
import org.eclipse.uml2.uml.Event;
import org.eclipse.uml2.uml.ExecutionEvent;
import org.eclipse.uml2.uml.ExecutionOccurrenceSpecification;
import org.eclipse.uml2.uml.ExecutionSpecification;
import org.eclipse.uml2.uml.Interaction;
import org.eclipse.uml2.uml.InteractionFragment;
import org.eclipse.uml2.uml.InterfaceRealization;
import org.eclipse.uml2.uml.Lifeline;
import org.eclipse.uml2.uml.Message;
import org.eclipse.uml2.uml.MessageOccurrenceSpecification;
import org.eclipse.uml2.uml.MessageSort;
import org.eclipse.uml2.uml.NamedElement;
import org.eclipse.uml2.uml.OccurrenceSpecification;
import org.eclipse.uml2.uml.OpaqueBehavior;
import org.eclipse.uml2.uml.Operation;
import org.eclipse.uml2.uml.Package;
import org.eclipse.uml2.uml.ReceiveOperationEvent;
import org.eclipse.uml2.uml.ReceiveSignalEvent;
import org.eclipse.uml2.uml.SendOperationEvent;
import org.eclipse.uml2.uml.SendSignalEvent;
import org.eclipse.uml2.uml.Signal;
import org.eclipse.uml2.uml.UMLFactory;
import org.obeonetwork.dsl.uml2.design.services.internal.NamedElementServices;
import fr.obeo.dsl.common.ui.tools.api.util.EclipseUIUtil;
import fr.obeo.dsl.viewpoint.DDiagram;
import fr.obeo.dsl.viewpoint.DDiagramElement;
import fr.obeo.dsl.viewpoint.DEdge;
import fr.obeo.dsl.viewpoint.DNode;
import fr.obeo.dsl.viewpoint.diagram.sequence.business.internal.elements.ISequenceEvent;
import fr.obeo.dsl.viewpoint.diagram.sequence.business.internal.elements.SequenceDiagram;
import fr.obeo.dsl.viewpoint.diagram.sequence.business.internal.operation.RefreshGraphicalOrderingOperation;
import fr.obeo.dsl.viewpoint.diagram.sequence.business.internal.operation.RefreshSemanticOrderingOperation;
import fr.obeo.dsl.viewpoint.diagram.sequence.ui.tool.internal.edit.operation.SynchronizeGraphicalOrderingOperation;
import fr.obeo.dsl.viewpoint.diagram.sequence.ui.tool.internal.edit.part.ISequenceEventEditPart;
import fr.obeo.dsl.viewpoint.diagram.sequence.ui.tool.internal.edit.part.SequenceDiagramEditPart;
import fr.obeo.dsl.viewpoint.diagram.tools.api.editor.DDiagramEditor;
/**
* Utility services to manage sequence diagrams.
*
* @author Gonzague Reydet <a href="mailto:[email protected]">[email protected]</a>
* @author M�lanie Bats <a href="mailto:[email protected]">[email protected]</a>
*/
public class SequenceServices {
private static final String SIGNAL_SUFFIX = "_signal";
private static final String EVENT_MESSAGE_SUFFIX = "_event";
private static final String SENDER_MESSAGE_SUFFIX = "_sender";
private static final String RECEIVER_MESSAGE_SUFFIX = "_receiver";
/**
* Retrieves the context element ({@link Lifeline} or {@link ExecutionSpecification}) of the given
* {@link OccurrenceSpecification}.
*
* @param occurrenceSpecification
* the {@link OccurrenceSpecification} for which to find the context
* @return the {@link ExecutionSpecification} on which the given {@link OccurrenceSpecification} is
* attached or otherwise, the {@link Lifeline}otherwise it is attached to.
*/
public NamedElement findOccurrenceSpecificationContext(OccurrenceSpecification occurrenceSpecification) {
final Lifeline lifeline = occurrenceSpecification.getCovereds().get(0);
Stack<NamedElement> context = new Stack<NamedElement>();
context.add(lifeline);
List<InteractionFragment> allFragments = occurrenceSpecification.getEnclosingInteraction()
.getFragments();
List<InteractionFragment> fragments = new ArrayList<InteractionFragment>();
for (InteractionFragment fragment : allFragments) {
if (fragment.getCovered(lifeline.getName()) != null)
fragments.add(fragment);
}
for (int i = 0; i < fragments.size(); i++) {
InteractionFragment e = fragments.get(i);
InteractionFragment en;
if (i + 1 < fragments.size())
en = fragments.get(i + 1);
else
en = null;
if (e instanceof MessageOccurrenceSpecification && en != null
&& en instanceof ExecutionSpecification)
context.add(en);
if (e instanceof ExecutionOccurrenceSpecification) {
if (en == null || !(en instanceof ExecutionSpecification))
context.pop();
}
// Found our element
if (e == occurrenceSpecification) {
return context.peek();
}
if (e instanceof ExecutionOccurrenceSpecification) {
if (en != null && en instanceof ExecutionSpecification)
context.add(fragments.get(i + 1));
}
if (e instanceof MessageOccurrenceSpecification && isEnd(e, fragments)) {
context.pop();
}
}
return lifeline;
}
private boolean isEnd(InteractionFragment endCandidate, List<InteractionFragment> fragments) {
List<InteractionFragment> executionFinishes = new ArrayList<InteractionFragment>();
for (InteractionFragment fragment : fragments) {
if (fragment instanceof BehaviorExecutionSpecification) {
// Get start
BehaviorExecutionSpecification behavior = (BehaviorExecutionSpecification)fragment;
// Get finish
executionFinishes.add(behavior.getFinish());
}
}
return executionFinishes.contains(endCandidate);
}
private BehaviorExecutionSpecification getExecution(InteractionFragment occurence) {
if (occurence == null)
return null;
Map<InteractionFragment, BehaviorExecutionSpecification> behaviors = new HashMap<InteractionFragment, BehaviorExecutionSpecification>();
for (InteractionFragment fragment : occurence.getEnclosingInteraction().getFragments()) {
if (fragment instanceof BehaviorExecutionSpecification) {
BehaviorExecutionSpecification behavior = (BehaviorExecutionSpecification)fragment;
// Get start
behaviors.put(behavior.getStart(), behavior);
// Get finish
behaviors.put(behavior.getFinish(), behavior);
}
}
return behaviors.get(occurence);
}
/**
* Finds the first level of {@link ExecutionSpecification} in the context of the given {@link Lifeline}.
*
* @param lifeline
* the context.
* @return the {@link ExecutionSpecification} semantic candidates.
*/
public List<ExecutionSpecification> executionSemanticCandidates(Lifeline lifeline) {
return getFirstLevelExecutions(lifeline, lifeline.getInteraction().getFragments());
}
/**
* Finds the first level of {@link ExecutionSpecification} in the context of the given
* {@link ExecutionSpecification}.
*
* @param execution
* the context.
* @return the {@link ExecutionSpecification} semantic candidates.
*/
public List<ExecutionSpecification> executionSemanticCandidates(ExecutionSpecification execution) {
final List<InteractionFragment> fragments = execution.getEnclosingInteraction().getFragments();
final int startIndex = fragments.indexOf(execution.getStart());
final int finishIndex = fragments.indexOf(execution.getFinish());
final List<InteractionFragment> candidateFragments = new ArrayList<InteractionFragment>(
fragments.subList(startIndex + 2, finishIndex));
return getFirstLevelExecutions(execution.getCovereds().get(0), candidateFragments);
}
/**
* Finds the first level of {@link ExecutionSpecification} in the context of the given
* {@link ExecutionSpecification}.
*
* @param execution
* the context.
* @return the {@link ExecutionSpecification} semantic candidates.
*/
public List<OccurrenceSpecification> executionSemanticCandidateOccurences(ExecutionSpecification execution) {
List<ExecutionSpecification> executions = executionSemanticCandidates(execution);
List<OccurrenceSpecification> occurrences = new ArrayList<OccurrenceSpecification>();
occurrences.add(execution.getStart());
occurrences.add(execution.getFinish());
for (ExecutionSpecification subExecution : executions) {
occurrences.add(subExecution.getStart());
occurrences.add(subExecution.getFinish());
}
return occurrences;
}
/**
* Finds the first level of {@link ExecutionSpecification} in the context of the given
* {@link ExecutionSpecification}.
*
* @param execution
* the context.
* @return the {@link ExecutionSpecification} semantic candidates.
*/
public List<OccurrenceSpecification> executionSemanticCandidateOccurences(Lifeline lifeline) {
List<ExecutionSpecification> executions = executionSemanticCandidates(lifeline);
List<OccurrenceSpecification> occurrences = new ArrayList<OccurrenceSpecification>();
for (ExecutionSpecification subExecution : executions) {
occurrences.add(subExecution.getStart());
occurrences.add(subExecution.getFinish());
}
return occurrences;
}
/**
* Find the first level of {@link ExecutionSpecification} in the given {@link InteractionFragment} list.
*
* @param lifeline
* the {@link Lifeline} which is covered by the searched {@link ExecutionSpecification}
* @param candidateFragments
* a sub-list of {@link InteractionFragment} to inspect for the first
* {@link ExecutionSpecification} level.
* @return {@link List} of the {@link ExecutionSpecification}
*/
private List<ExecutionSpecification> getFirstLevelExecutions(Lifeline lifeline,
final List<InteractionFragment> candidateFragments) {
List<ExecutionSpecification> executions = new ArrayList<ExecutionSpecification>();
ExecutionSpecification subExec = null;
for (InteractionFragment fragment : candidateFragments) {
if (fragment instanceof ExecutionSpecification && fragment.getCovereds().contains(lifeline)) {
// Element on the same lifeline
if (subExec == null) {
subExec = (ExecutionSpecification)fragment;
}
} else if (fragment instanceof OccurrenceSpecification && subExec != null
&& fragment.equals(subExec.getFinish())) {
executions.add(subExec);
subExec = null;
}
}
return executions;
}
/**
* Delete the all the semantic elements attached to the given node. This will find the semantic elements
* of the current node and those coming recursively from sub-bordered nodes and linked edges.
*
* @param node
* the root node to delete.
* @return the parent diagram.
*/
public DDiagram fullDelete(DNode node) {
final Collection<EObject> elementsToDelete = getSemanticElementsToDelete(node);
for (EObject eObject : elementsToDelete) {
EcoreUtil.remove(eObject);
}
return node.getParentDiagram();
}
/**
* Retrieves all the semantic elements of the current node, those of the incoming and outgoing edges and
* recursively along the sub-bordered node tree.
*
* @param node
* the root {@link DNode}
* @return the list of attached semantic elements
*/
private static Collection<EObject> getSemanticElementsToDelete(DNode node) {
final Collection<EObject> elementsToDelete = new LinkedHashSet<EObject>();
elementsToDelete.addAll(node.getSemanticElements());
for (DEdge incomingEdge : node.getIncomingEdges()) {
elementsToDelete.addAll(incomingEdge.getSemanticElements());
}
for (DEdge outgoingEdges : node.getOutgoingEdges()) {
elementsToDelete.addAll(outgoingEdges.getSemanticElements());
}
for (DNode borderedNode : node.getOwnedBorderedNodes()) {
elementsToDelete.addAll(getSemanticElementsToDelete(borderedNode));
}
return elementsToDelete;
}
/**
* Create a typed execution. Execution could be created on lifeline or other parent execution.
*
* @param interaction
* Interaction
* @param fragment
* Lifeline or parent execution
* @param operation
* Operation associated to execution
* @param startingEndPredecessor
* Starting end predecessor
*/
public void createExecution(Interaction interaction, NamedElement fragment, Operation operation,
NamedElement startingEndPredecessor) {
Lifeline lifeline = getLifeline(fragment);
UMLFactory factory = UMLFactory.eINSTANCE;
StringBuffer executionName;
if (operation == null) {
List<BehaviorExecutionSpecification> behaviors = new ArrayList<BehaviorExecutionSpecification>();
for (InteractionFragment behavior : interaction.getFragments()) {
if (behavior instanceof BehaviorExecutionSpecification)
behaviors.add((BehaviorExecutionSpecification)behavior);
}
executionName = new StringBuffer("BehaviorExecution_").append(behaviors.size());
} else {
executionName = new StringBuffer(operation.getName());
}
// Create execution start
ExecutionOccurrenceSpecification startExec = factory.createExecutionOccurrenceSpecification();
StringBuffer startExecName = new StringBuffer(executionName).append("_start");
startExec.setName(startExecName.toString());
startExec.getCovereds().add(lifeline);
// Create start event
ExecutionEvent startEvent = factory.createExecutionEvent();
startEvent.setName(startExecName.append(EVENT_MESSAGE_SUFFIX).toString());
startExec.setEvent(startEvent);
// Create behavior
OpaqueBehavior behavior = factory.createOpaqueBehavior();
behavior.setName(executionName.toString());
behavior.setSpecification(operation);
interaction.getOwnedBehaviors().add(behavior);
BehaviorExecutionSpecification execution = factory.createBehaviorExecutionSpecification();
execution.setName(executionName.toString());
execution.getCovereds().add(lifeline);
execution.setBehavior(behavior);
execution.setStart(startExec);
startExec.setExecution(execution);
// Create execution end
ExecutionOccurrenceSpecification endExec = factory.createExecutionOccurrenceSpecification();
StringBuffer endExecName = new StringBuffer(executionName).append("_finish");
endExec.setName(endExecName.toString());
endExec.getCovereds().add(lifeline);
endExec.setExecution(execution);
execution.setFinish(endExec);
// Create end event
ExecutionEvent endEvent = factory.createExecutionEvent();
endEvent.setName(endExecName.append(EVENT_MESSAGE_SUFFIX).toString());
endExec.setEvent(endEvent);
// Add and order fragments under the interaction
EList<InteractionFragment> fragments = interaction.getFragments();
// Ordered fragments
fragments.add(startExec);
startExec.getNearestPackage().getPackagedElements().add(startEvent);
// If execution starts from an execution, add the new execution start after the execution
// specification
if (startingEndPredecessor instanceof OccurrenceSpecification
&& getExecution((OccurrenceSpecification)startingEndPredecessor) != null
&& startingEndPredecessor
.equals(getExecution((OccurrenceSpecification)startingEndPredecessor).getStart()))
fragments.move(fragments.indexOf(startingEndPredecessor) + 2, startExec);
else
// Message starts from a lifeline, add the message start after the last starting predecessor
// (message)
fragments.move(fragments.indexOf(startingEndPredecessor) + 1, startExec);
fragments.add(execution);
fragments.move(fragments.indexOf(startExec) + 1, execution);
fragments.add(endExec);
endExec.getNearestPackage().getPackagedElements().add(endEvent);
fragments.move(fragments.indexOf(execution) + 1, endExec);
}
/**
* Create a typed execution. Execution could be created on lifeline or other parent execution.
*
* @param interaction
* Interaction
* @param fragment
* Lifeline or parent execution
* @param startingEndPredecessor
* Starting end predecessor
*/
public void createExecution(Interaction interaction, NamedElement fragment,
NamedElement startingEndPredecessor) {
createExecution(interaction, fragment, null, startingEndPredecessor);
}
/**
* Create asynchronous typed message.
*
* @param interaction
* Interaction
* @param sourceFragment
* Source
* @param targetFragment
* Target
* @param operation
* Operation associated to message
* @param startingEndPredecessor
* Starting end predecessor
* @param finishingEndPredecessor
* Finishing end predecessor
*/
public void createAsynchronousMessage(Interaction interaction, NamedElement sourceFragment,
NamedElement targetFragment, Operation operation, NamedElement startingEndPredecessor,
NamedElement finishingEndPredecessor) {
Lifeline source = getLifeline(sourceFragment);
Lifeline target = getLifeline(targetFragment);
BehaviorExecutionSpecification predecessorExecution = getExecution((InteractionFragment)startingEndPredecessor);
UMLFactory factory = UMLFactory.eINSTANCE;
EList<InteractionFragment> fragments = interaction.getFragments();
// Create message
Message message = factory.createMessage();
StringBuffer operationName;
if (operation == null)
operationName = new StringBuffer("Message_").append(interaction.getMessages().size());
else
operationName = new StringBuffer(operation.getName());
message.setName(operationName.toString());
message.setMessageSort(MessageSort.ASYNCH_CALL_LITERAL);
interaction.getMessages().add(message);
// Create message send event
MessageOccurrenceSpecification senderEventMessage = factory.createMessageOccurrenceSpecification();
StringBuffer senderEventName = new StringBuffer(operationName).append(SENDER_MESSAGE_SUFFIX);
senderEventMessage.setName(senderEventName.toString());
senderEventMessage.getCovereds().add(source);
senderEventMessage.setMessage(message);
// Create message receive event
MessageOccurrenceSpecification receiverEventMessage = factory.createMessageOccurrenceSpecification();
StringBuffer receiverEventName = new StringBuffer(operationName).append(RECEIVER_MESSAGE_SUFFIX);
receiverEventMessage.setName(receiverEventName.toString());
receiverEventMessage.getCovereds().add(target);
receiverEventMessage.setMessage(message);
message.setSendEvent(senderEventMessage);
message.setReceiveEvent(receiverEventMessage);
// Create behavior
BehaviorExecutionSpecification execution = null;
if (operation != null) {
OpaqueBehavior behavior = factory.createOpaqueBehavior();
behavior.setName(operationName.toString());
if (targetFragment instanceof ExecutionSpecification)
behavior.setSpecification(operation);
interaction.getOwnedBehaviors().add(behavior);
execution = factory.createBehaviorExecutionSpecification();
execution.setName(operationName.toString());
execution.getCovereds().add(target);
execution.setBehavior(behavior);
// Create send event
SendOperationEvent sendEvent = factory.createSendOperationEvent();
sendEvent.setName(senderEventName.append(EVENT_MESSAGE_SUFFIX).toString());
senderEventMessage.setEvent(sendEvent);
sendEvent.setOperation(operation);
// Create receive event
ReceiveOperationEvent receiveEvent = factory.createReceiveOperationEvent();
receiveEvent.setName(receiverEventName.append(EVENT_MESSAGE_SUFFIX).toString());
receiverEventMessage.setEvent(receiveEvent);
receiveEvent.setOperation(operation);
message.getNearestPackage().getPackagedElements().add(sendEvent);
message.getNearestPackage().getPackagedElements().add(receiveEvent);
} else {
// Create send event
SendSignalEvent sendEvent = factory.createSendSignalEvent();
sendEvent.setName(senderEventName.append(EVENT_MESSAGE_SUFFIX).toString());
senderEventMessage.setEvent(sendEvent);
// Create receive event
ReceiveSignalEvent receiveEvent = factory.createReceiveSignalEvent();
receiveEvent.setName(receiverEventName.append(EVENT_MESSAGE_SUFFIX).toString());
receiverEventMessage.setEvent(receiveEvent);
// Create signal
Signal signal = factory.createSignal();
signal.setName(operationName.append(SIGNAL_SUFFIX).toString());
sendEvent.setSignal(signal);
receiveEvent.setSignal(signal);
message.getNearestPackage().getPackagedElements().add(signal);
message.getNearestPackage().getPackagedElements().add(sendEvent);
message.getNearestPackage().getPackagedElements().add(receiveEvent);
}
ExecutionOccurrenceSpecification endExec = null;
if (execution != null) {
execution.setStart(receiverEventMessage);
// Create end execution
endExec = factory.createExecutionOccurrenceSpecification();
StringBuffer executionEndName = new StringBuffer(execution.getName()).append("_finish");
endExec.setName(executionEndName.toString());
endExec.getCovereds().add(target);
endExec.setExecution(execution);
execution.setFinish(endExec);
// Create end event
ExecutionEvent endEvent = factory.createExecutionEvent();
endEvent.setName(executionEndName.append(EVENT_MESSAGE_SUFFIX).toString());
endExec.setEvent(endEvent);
}
// Add and order fragments under the interaction
// Add message after starting end predecessor
fragments.add(senderEventMessage);
// If predecessor is the beginning of an execution add message after the execution
if (startingEndPredecessor != null && startingEndPredecessor instanceof OccurrenceSpecification
&& predecessorExecution != null
&& startingEndPredecessor.equals(predecessorExecution.getStart()))
fragments.move(fragments.indexOf(predecessorExecution) + 1, senderEventMessage);
// Else set it directly after the predecessor
else
fragments.move(fragments.indexOf(startingEndPredecessor) + 1, senderEventMessage);
fragments.add(receiverEventMessage);
fragments.move(fragments.indexOf(senderEventMessage) + 1, receiverEventMessage);
if (execution != null) {
fragments.add(execution);
fragments.add(endExec);
fragments.move(fragments.indexOf(receiverEventMessage) + 1, execution);
fragments.move(fragments.indexOf(execution) + 1, endExec);
}
}
/**
* Create asynchronous message.
*
* @param interaction
* Interaction
* @param sourceFragment
* Source
* @param targetFragment
* Target
* @param startingEndPredecessor
* Starting end predecessor
* @param finishingEndPredecessor
* Finishing end predecessor
*/
public void createAsynchronousMessage(Interaction interaction, NamedElement sourceFragment,
NamedElement targetFragment, NamedElement startingEndPredecessor,
NamedElement finishingEndPredecessor) {
createAsynchronousMessage(interaction, sourceFragment, targetFragment, null, startingEndPredecessor,
finishingEndPredecessor);
}
/**
* Create synchronous typed message.
*
* @param interaction
* Interaction
* @param sourceFragment
* Source
* @param targetFragment
* Target
* @param operation
* Operation associated to message
* @param startingEndPredecessor
* Starting end predecessor
* @param finishingEndPredecessor
* Finishing end predecessor
*/
public void createSynchronousMessage(Interaction interaction, NamedElement sourceFragment,
NamedElement targetFragment, Operation operation, NamedElement startingEndPredecessor,
NamedElement finishingEndPredecessor) {
Lifeline source = getLifeline(sourceFragment);
Lifeline target = getLifeline(targetFragment);
BehaviorExecutionSpecification predecessorExecution = getExecution((InteractionFragment)startingEndPredecessor);
UMLFactory factory = UMLFactory.eINSTANCE;
EList<InteractionFragment> fragments = interaction.getFragments();
// Create message
Message message = factory.createMessage();
StringBuffer operationName;
if (operation == null)
operationName = new StringBuffer("Message_").append(interaction.getMessages().size());
else
operationName = new StringBuffer(operation.getName());
message.setName(operationName.toString());
message.setMessageSort(MessageSort.SYNCH_CALL_LITERAL);
interaction.getMessages().add(message);
// Create message send event
MessageOccurrenceSpecification senderEventMessage = factory.createMessageOccurrenceSpecification();
StringBuffer senderEventName = new StringBuffer(operationName).append(SENDER_MESSAGE_SUFFIX);
senderEventMessage.setName(senderEventName.toString());
senderEventMessage.getCovereds().add(source);
senderEventMessage.setMessage(message);
// Create message receive event
MessageOccurrenceSpecification receiverEventMessage = factory.createMessageOccurrenceSpecification();
StringBuffer receiverEventName = new StringBuffer(operationName).append(RECEIVER_MESSAGE_SUFFIX);
receiverEventMessage.setName(receiverEventName.toString());
receiverEventMessage.getCovereds().add(target);
receiverEventMessage.setMessage(message);
message.setSendEvent(senderEventMessage);
message.setReceiveEvent(receiverEventMessage);
// Create behavior
BehaviorExecutionSpecification execution = null;
if (operation != null) {
OpaqueBehavior behavior = factory.createOpaqueBehavior();
behavior.setName(operationName.toString());
if (operation != null || targetFragment instanceof ExecutionSpecification)
behavior.setSpecification(operation);
interaction.getOwnedBehaviors().add(behavior);
execution = factory.createBehaviorExecutionSpecification();
execution.setName(operationName.toString());
execution.getCovereds().add(target);
execution.setBehavior(behavior);
// Create send event
SendOperationEvent sendEvent = factory.createSendOperationEvent();
sendEvent.setName(senderEventName.append(EVENT_MESSAGE_SUFFIX).toString());
senderEventMessage.setEvent(sendEvent);
sendEvent.setOperation(operation);
// Create receive event
ReceiveOperationEvent receiveEvent = factory.createReceiveOperationEvent();
receiveEvent.setName(receiverEventName.append(EVENT_MESSAGE_SUFFIX).toString());
receiverEventMessage.setEvent(receiveEvent);
receiveEvent.setOperation(operation);
message.getNearestPackage().getPackagedElements().add(sendEvent);
message.getNearestPackage().getPackagedElements().add(receiveEvent);
} else {
// Create send event
SendSignalEvent sendEvent = factory.createSendSignalEvent();
sendEvent.setName(senderEventName.append(EVENT_MESSAGE_SUFFIX).toString());
senderEventMessage.setEvent(sendEvent);
// Create receive event
ReceiveSignalEvent receiveEvent = factory.createReceiveSignalEvent();
receiveEvent.setName(receiverEventName.append(EVENT_MESSAGE_SUFFIX).toString());
receiverEventMessage.setEvent(receiveEvent);
// Create signal
Signal signal = factory.createSignal();
- signal.setName(operationName.append(SIGNAL_SUFFIX).toString());
+ StringBuffer signalName = new StringBuffer(operationName).append(SIGNAL_SUFFIX);
+ signal.setName(signalName.toString());
sendEvent.setSignal(signal);
receiveEvent.setSignal(signal);
message.getNearestPackage().getPackagedElements().add(signal);
message.getNearestPackage().getPackagedElements().add(sendEvent);
message.getNearestPackage().getPackagedElements().add(receiveEvent);
}
if (execution != null)
execution.setStart(receiverEventMessage);
// Create reply message
Message replyMessage = factory.createMessage();
StringBuffer replyName = new StringBuffer(operationName).append("_reply");
replyMessage.setName(replyName.toString());
replyMessage.setMessageSort(MessageSort.REPLY_LITERAL);
interaction.getMessages().add(replyMessage);
// Create reply message send event
MessageOccurrenceSpecification senderEventReplyMessage = factory
.createMessageOccurrenceSpecification();
StringBuffer senderReplyEventName = new StringBuffer(replyName).append(SENDER_MESSAGE_SUFFIX);
senderEventReplyMessage.setName(senderReplyEventName.toString());
senderEventReplyMessage.getCovereds().add(target);
senderEventReplyMessage.setMessage(replyMessage);
// Create reply message receive event
MessageOccurrenceSpecification receiverEventReplyMessage = factory
.createMessageOccurrenceSpecification();
StringBuffer receiverReplyEventName = new StringBuffer(replyName).append(RECEIVER_MESSAGE_SUFFIX);
receiverEventReplyMessage.setName(receiverReplyEventName.toString());
receiverEventReplyMessage.getCovereds().add(source);
receiverEventReplyMessage.setMessage(replyMessage);
replyMessage.setSendEvent(senderEventReplyMessage);
replyMessage.setReceiveEvent(receiverEventReplyMessage);
if (execution != null)
execution.setFinish(senderEventReplyMessage);
if (operation != null) {
// Create send event
SendOperationEvent sendReplyEvent = factory.createSendOperationEvent();
sendReplyEvent.setName(senderEventName.append(EVENT_MESSAGE_SUFFIX).toString());
senderEventReplyMessage.setEvent(sendReplyEvent);
sendReplyEvent.setOperation(operation);
// Create receive event
ReceiveOperationEvent receiveReplyEvent = factory.createReceiveOperationEvent();
receiveReplyEvent.setName(receiverEventName.append(EVENT_MESSAGE_SUFFIX).toString());
receiverEventReplyMessage.setEvent(receiveReplyEvent);
receiveReplyEvent.setOperation(operation);
message.getNearestPackage().getPackagedElements().add(sendReplyEvent);
message.getNearestPackage().getPackagedElements().add(receiveReplyEvent);
} else {
// Create send reply event
SendSignalEvent sendReplyEvent = factory.createSendSignalEvent();
sendReplyEvent.setName(senderReplyEventName.append(EVENT_MESSAGE_SUFFIX).toString());
sendReplyEvent.setSignal(((SendSignalEvent)senderEventMessage.getEvent()).getSignal());
senderEventReplyMessage.setEvent(sendReplyEvent);
// Create receive reply event
ReceiveSignalEvent receiveReplyEvent = factory.createReceiveSignalEvent();
receiveReplyEvent.setName(receiverReplyEventName.append(EVENT_MESSAGE_SUFFIX).toString());
receiveReplyEvent.setSignal(((ReceiveSignalEvent)receiverEventMessage.getEvent()).getSignal());
receiverEventReplyMessage.setEvent(receiveReplyEvent);
message.getNearestPackage().getPackagedElements().add(sendReplyEvent);
message.getNearestPackage().getPackagedElements().add(receiveReplyEvent);
}
// Add and order fragments under the interaction
// Add message after starting end predecessor
fragments.add(senderEventMessage);
// If predecessor is the beginning of an execution add message after the execution
if (startingEndPredecessor != null && startingEndPredecessor instanceof OccurrenceSpecification
&& predecessorExecution != null
&& startingEndPredecessor.equals(predecessorExecution.getStart()))
fragments.move(fragments.indexOf(predecessorExecution) + 1, senderEventMessage);
// Else set it directly after the predecessor
else
fragments.move(fragments.indexOf(startingEndPredecessor) + 1, senderEventMessage);
fragments.add(receiverEventMessage);
fragments.move(fragments.indexOf(senderEventMessage) + 1, receiverEventMessage);
fragments.add(senderEventReplyMessage);
if (execution != null) {
fragments.add(execution);
fragments.move(fragments.indexOf(receiverEventMessage) + 1, execution);
fragments.move(fragments.indexOf(execution) + 1, senderEventReplyMessage);
} else
fragments.move(fragments.indexOf(receiverEventMessage) + 1, senderEventReplyMessage);
fragments.add(receiverEventReplyMessage);
fragments.move(fragments.indexOf(senderEventReplyMessage) + 1, receiverEventReplyMessage);
}
/**
* Create synchronous typed message.
*
* @param interaction
* Interaction
* @param sourceFragment
* Source
* @param targetFragment
* Target
* @param operation
* Operation associated to message
* @param startingEndPredecessor
* Starting end predecessor
* @param finishingEndPredecessor
* Finishing end predecessor
*/
public void createSynchronousMessage(Interaction interaction, NamedElement sourceFragment,
NamedElement targetFragment, NamedElement startingEndPredecessor,
NamedElement finishingEndPredecessor) {
createSynchronousMessage(interaction, sourceFragment, targetFragment, null, startingEndPredecessor,
finishingEndPredecessor);
}
/**
* Delete execution.
*
* @param execution
* Execution to delete
*/
public void delete(BehaviorExecutionSpecification execution) {
// Get fragments
Interaction interaction = (Interaction)execution.eContainer();
// Delete opaque behavior
interaction.getOwnedBehaviors().remove(execution.getBehavior());
// Delete start and finish behavior
List<InteractionFragment> fragments = interaction.getFragments();
if (execution.getStart() instanceof ExecutionOccurrenceSpecification) {
// Delete event
execution.getStart().getEvent().destroy();
fragments.remove(execution.getStart());
}
if (execution.getFinish() instanceof ExecutionOccurrenceSpecification) {
// Delete event
execution.getFinish().getEvent().destroy();
fragments.remove(execution.getFinish());
}
// Delete execution
fragments.remove(execution);
}
/**
* Delete message.
*
* @param message
* Message to delete
*/
public void delete(Message message) {
// Get fragments
Interaction interaction = (Interaction)message.eContainer();
List<InteractionFragment> fragments = interaction.getFragments();
// Delete start and finish message and if an execution is associated to the message remove also the
// execution
MessageOccurrenceSpecification receiveMessage = (MessageOccurrenceSpecification)message
.getReceiveEvent();
// If message is a synchronous message delete also the reply message
if (MessageSort.SYNCH_CALL_LITERAL.equals(message.getMessageSort())) {
delete(getReplyMessage(message));
}
if (getExecution(receiveMessage) != null)
delete(getExecution(receiveMessage));
Event receiveEvent = receiveMessage.getEvent();
// Delete signal
if (receiveEvent instanceof ReceiveSignalEvent
&& ((ReceiveSignalEvent)receiveEvent).getSignal() != null) {
((ReceiveSignalEvent)receiveEvent).getSignal().destroy();
}
receiveEvent.destroy();
fragments.remove(receiveMessage);
MessageOccurrenceSpecification sendMessage = (MessageOccurrenceSpecification)message.getSendEvent();
if (getExecution(sendMessage) != null)
delete(getExecution(sendMessage));
Event sendEvent = sendMessage.getEvent();
// Delete signal
if (sendEvent instanceof SendSignalEvent && ((SendSignalEvent)sendEvent).getSignal() != null) {
((SendSignalEvent)sendEvent).getSignal().destroy();
}
sendEvent.destroy();
fragments.remove(message.getSendEvent());
// Delete message
interaction.getMessages().remove(message);
}
private Lifeline getLifeline(Element fragment) {
if (fragment instanceof Lifeline) {
return (Lifeline)fragment;
} else if (fragment instanceof ExecutionSpecification) {
List<Lifeline> lifelines = ((ExecutionSpecification)fragment).getCovereds();
if (lifelines != null && !lifelines.isEmpty()) {
return lifelines.get(0);
}
}
return null;
}
/**
* Get operations associated to a lifeline or an execution. To get all the available operations, we should
* get the one defined directly under the class and those defined in realized interface.
*
* @param target
* Lifeline or execution
* @return All operations available for the lifeline or execution
*/
public List<Operation> getOperations(EObject target) {
List<Element> elements = null;
if (target instanceof Lifeline) {
elements = ((Lifeline)target).getRepresents().getType().getOwnedElements();
} else if (target instanceof ExecutionSpecification) {
elements = ((ExecutionSpecification)target).getOwnedElements();
}
if (elements == null)
return null;
List<Operation> operations = new ArrayList<Operation>();
// represents.type.ownedOperation + represents.type.interfaceRealization.contract.ownedOperation
for (Element element : elements) {
// represents.type.ownedOperation
if (element instanceof Operation) {
operations.add((Operation)element);
}
// represents.type.interfaceRealization.contract.ownedOperation
else if (element instanceof InterfaceRealization
&& ((InterfaceRealization)element).getContract() != null) {
operations.addAll(((InterfaceRealization)element).getContract().getAllOperations());
}
}
return operations;
}
/**
* Create interaction a new interaction in package.
*
* @param pkg
* Package containing new interaction.
*/
public void createInteraction(EObject pkg) {
UMLFactory factory = UMLFactory.eINSTANCE;
Interaction interaction = factory.createInteraction();
interaction.setName(NamedElementServices.getNewInteractionName((Package)pkg));
((Package)pkg).getPackagedElements().add(interaction);
}
/**
* Reorder execution.
*
* @param execution
* Moved execution
* @param startingEndPredecessorAfter
* Fragment preceding moved execution start before the beginning of reorder operation
* @param finishingEndPredecessorAfter
* Fragment preceding moved execution finish before the beginning of reorder operation
*/
public void reorder(ExecutionSpecification execution, InteractionFragment startingEndPredecessorAfter,
InteractionFragment finishingEndPredecessorAfter) {
// Get current interaction
Interaction interaction = execution.getEnclosingInteraction();
// Re-order fragments under the interaction
EList<InteractionFragment> fragments = interaction.getFragments();
// Move execution start after startEndPredecessorAfter
int startIndex = 0;
if (startingEndPredecessorAfter != null) {
// If predecessor is the start of an execution, keep execution just after execution start
if (getExecution(startingEndPredecessorAfter) != null
&& startingEndPredecessorAfter == (getExecution(startingEndPredecessorAfter).getStart()))
startIndex = fragments.indexOf(getExecution(startingEndPredecessorAfter)) + 1;
else {
// Predecessor is the last fragment, the move operation will update the list
if (fragments.indexOf(startingEndPredecessorAfter) == fragments.size() - 1)
startIndex = fragments.indexOf(startingEndPredecessorAfter);
else
startIndex = fragments.indexOf(startingEndPredecessorAfter) + 1;
}
}
List<InteractionFragment> subFragments = new ArrayList<InteractionFragment>();
subFragments.addAll(fragments.subList(fragments.indexOf(execution.getStart()) + 1,
fragments.indexOf(execution.getFinish()) + 1));
// If execution start is a message move the message start and receive
if (execution.getStart() instanceof MessageOccurrenceSpecification)
reorder(((MessageOccurrenceSpecification)execution.getStart()).getMessage(),
startingEndPredecessorAfter, null);
else
fragments.move(startIndex, fragments.indexOf(execution.getStart()));
// Move all the elements attached to the moved execution
for (InteractionFragment fragment : subFragments) {
// If execution end is a message move the message start and receive
if (fragment.equals(execution.getFinish())
&& execution.getFinish() instanceof MessageOccurrenceSpecification)
reorder(((MessageOccurrenceSpecification)execution.getFinish()).getMessage(), execution, null);
else {
int newIndex = startIndex + subFragments.indexOf(fragment) + 1;
// Predecessor is the last fragment
if (startIndex == fragments.size() - 1)
newIndex = startIndex;
fragments.move(newIndex, fragments.indexOf(fragment));
}
}
}
/**
* Reorder message.
*
* @param message
* Moved message
* @param startingEndPredecessorAfter
* Fragment preceding moved execution start before the beginning of reorder operation
* @param finishingEndPredecessorAfter
* Fragment preceding moved execution finish before the beginning of reorder operation
*/
public void reorder(Message message, InteractionFragment startingEndPredecessorAfter,
InteractionFragment finishingEndPredecessorAfter) {
// Get current interaction
Interaction interaction = message.getInteraction();
// Re-order fragments under the interaction
EList<InteractionFragment> fragments = interaction.getFragments();
// Move message start after startEndPredecessorAfter
int sendMsgIndex = 0;
if (startingEndPredecessorAfter != null) {
// If predecessor is the start of an execution, keep execution just after execution start
if (getExecution(startingEndPredecessorAfter) != null
&& startingEndPredecessorAfter == (getExecution(startingEndPredecessorAfter).getStart()))
sendMsgIndex = fragments.indexOf(getExecution(startingEndPredecessorAfter)) + 1;
else {
// Predecessor is the last fragment, the move operation will update the list
if (fragments.indexOf(startingEndPredecessorAfter) == fragments.size() - 1)
sendMsgIndex = fragments.indexOf(startingEndPredecessorAfter);
else
sendMsgIndex = fragments.indexOf(startingEndPredecessorAfter) + 1;
}
}
fragments.move(sendMsgIndex, fragments.indexOf(message.getSendEvent()));
int receiveMsgIndex = fragments.indexOf(message.getSendEvent()) + 1;
// Predecessor is the last fragment
if (sendMsgIndex == fragments.size() - 1)
receiveMsgIndex = sendMsgIndex;
fragments.move(receiveMsgIndex, fragments.indexOf(message.getReceiveEvent()));
}
/**
* Create an operation from a lifeline. Create the operation in the class and the execution on the
* lifeline.
*
* @param lifeline
* Lifeline
* @param startingEndPredecessor
* Predecessor
*/
public void createOperation(Lifeline lifeline, NamedElement startingEndPredecessor) {
// Get associated class
org.eclipse.uml2.uml.Class type = (org.eclipse.uml2.uml.Class)lifeline.getRepresents().getType();
Operation operation = OperationServices.createOperation(type);
// Create execution
createExecution(lifeline.getInteraction(), lifeline, operation, startingEndPredecessor);
}
/**
* Create an operation from an execution. Create the operation in the class and the execution on the
* execution.
*
* @param execution
* Execution
* @param startingEndPredecessor
* Predecessor
*/
public void createOperation(ExecutionSpecification execution, NamedElement startingEndPredecessor) {
// Get associated class
org.eclipse.uml2.uml.Class type = (org.eclipse.uml2.uml.Class)execution.getCovereds().get(0)
.getRepresents().getType();
Operation operation = OperationServices.createOperation(type);
// Create execution
createExecution(execution.getEnclosingInteraction(), execution, operation, startingEndPredecessor);
}
/**
* Create an operation from a lifeline. Create the operation in the class and the asynchronous message in
* the interaction.
*
* @param lifeline
* Lifeline
* @param startingEndPredecessor
* Predecessor
*/
public void createOperationAndAsynchMessage(NamedElement target, NamedElement source,
NamedElement startingEndPredecessor, NamedElement finishingEndPredecessor) {
// Get associated class and interaction
org.eclipse.uml2.uml.Class type;
Interaction interaction;
if (target instanceof Lifeline) {
type = (org.eclipse.uml2.uml.Class)((Lifeline)target).getRepresents().getType();
interaction = ((Lifeline)target).getInteraction();
} else {
type = (org.eclipse.uml2.uml.Class)(((ExecutionSpecification)target).getCovereds().get(0))
.getRepresents().getType();
interaction = ((ExecutionSpecification)target).getEnclosingInteraction();
}
Operation operation = OperationServices.createOperation(type);
// Create message
createAsynchronousMessage(interaction, source, target, operation, startingEndPredecessor,
finishingEndPredecessor);
}
/**
* Create an operation from a lifeline or an execution. Create the operation in the class and the
* execution on the source element.
*
* @param target
* Target message element, it could be a lifeline or an execution
* @param source
* Source messgae element, it could be a lifeline or an execution
* @param startingEndPredecessor
* Start predecessor
* @param finishingEndPredecessor
* Finish predecessor
*/
public void createOperationAndSynchMessage(NamedElement target, NamedElement source,
NamedElement startingEndPredecessor, NamedElement finishingEndPredecessor) {
// Get associated class and interaction
org.eclipse.uml2.uml.Class type;
Interaction interaction;
if (target instanceof Lifeline) {
type = (org.eclipse.uml2.uml.Class)((Lifeline)target).getRepresents().getType();
interaction = ((Lifeline)target).getInteraction();
} else {
type = (org.eclipse.uml2.uml.Class)(((ExecutionSpecification)target).getCovereds().get(0))
.getRepresents().getType();
interaction = ((ExecutionSpecification)target).getEnclosingInteraction();
}
Operation operation = OperationServices.createOperation(type);
// Create message
createSynchronousMessage(interaction, source, target, operation, startingEndPredecessor,
finishingEndPredecessor);
}
public boolean hasStartMessage(Message message) {
MessageOccurrenceSpecification msgReceive = (MessageOccurrenceSpecification)message.getReceiveEvent();
ExecutionSpecification execution = (ExecutionSpecification)findOccurrenceSpecificationContext(msgReceive);
if (execution.getStart() instanceof MessageOccurrenceSpecification
|| msgReceive.equals(execution.getStart()))
return true;
return false;
}
/**
* Link an existing end message as execution target start.
*
* @param message
* Message
*/
public void linkToExecutionAsStart(Message message, DDiagramElement containerView) {
// Get associated execution
MessageOccurrenceSpecification msgReceive = (MessageOccurrenceSpecification)message.getReceiveEvent();
ExecutionSpecification execution = (ExecutionSpecification)findOccurrenceSpecificationContext(msgReceive);
// Get current execution start
ExecutionOccurrenceSpecification executionStart = (ExecutionOccurrenceSpecification)execution
.getStart();
// Set end message as execution start
execution.setStart(msgReceive);
// Move execution and all sub level elements after message receiver
EList<InteractionFragment> fragments = message.getInteraction().getFragments();
fragments.move(fragments.indexOf(msgReceive), execution);
// Remove associated event
executionStart.getEvent().destroy();
// Remove execution start
fragments.remove(executionStart);
executionStart.destroy();
// If message is a synchronous message, move and rename reply
if (MessageSort.SYNCH_CALL_LITERAL.equals(message.getMessageSort())) {
// Get message reply
Message msgReply = getReplyMessage(message);
// Get current execution finish
OccurrenceSpecification executionFinish = (OccurrenceSpecification)execution.getFinish();
MessageOccurrenceSpecification msgReplySend = (MessageOccurrenceSpecification)msgReply
.getSendEvent();
// Move message reply after execution
reorder(msgReply, execution.getFinish(), execution.getFinish());
// Set end message as execution finish
execution.setFinish(msgReplySend);
// Remove associated event
executionFinish.getEvent().destroy();
// Remove execution finish
fragments.remove(executionFinish);
executionFinish.destroy();
// Rename message, message sender and message receiver
msgReply.setName(execution.getName());
msgReply.getReceiveEvent().setName(execution.getName() + RECEIVER_MESSAGE_SUFFIX);
msgReplySend.setName(execution.getName() + SENDER_MESSAGE_SUFFIX);
}
// Rename message, message sender and message receiver
message.setName(execution.getName());
message.getSendEvent().setName(execution.getName() + SENDER_MESSAGE_SUFFIX);
msgReceive.setName(execution.getName() + RECEIVER_MESSAGE_SUFFIX);
// Refresh layout
refreshLayout(containerView);
}
private Message getReplyMessage(Message message) {
for (Message messageReply : message.getInteraction().getMessages()) {
if (MessageSort.REPLY_LITERAL.equals(messageReply.getMessageSort())
&& messageReply.getName().startsWith(message.getName())) {
return messageReply;
}
}
return null;
}
private void refreshLayout(DDiagramElement containerView) {
IEditorPart ed = EclipseUIUtil.getActiveEditor();
if (ed instanceof DDiagramEditor && ed instanceof IDiagramWorkbenchPart) {
Map editPartRegistry = ((IDiagramWorkbenchPart)ed).getDiagramGraphicalViewer()
.getEditPartRegistry();
EditPart targetEditPart = (EditPart)editPartRegistry.get(containerView);
if (targetEditPart instanceof ISequenceEventEditPart) {
ISequenceEvent ise = ((ISequenceEventEditPart)targetEditPart).getISequenceEvent();
if (ise != null) {
SequenceDiagram diagram = ise.getDiagram();
SequenceDiagramEditPart sdep = (SequenceDiagramEditPart)editPartRegistry.get(diagram
.getNotationDiagram());
new RefreshGraphicalOrderingOperation(diagram).execute();
new RefreshSemanticOrderingOperation(diagram.getSequenceDDiagram()).execute();
new SynchronizeGraphicalOrderingOperation(sdep, false).execute();
}
}
}
}
}
| true | true | public void createSynchronousMessage(Interaction interaction, NamedElement sourceFragment,
NamedElement targetFragment, Operation operation, NamedElement startingEndPredecessor,
NamedElement finishingEndPredecessor) {
Lifeline source = getLifeline(sourceFragment);
Lifeline target = getLifeline(targetFragment);
BehaviorExecutionSpecification predecessorExecution = getExecution((InteractionFragment)startingEndPredecessor);
UMLFactory factory = UMLFactory.eINSTANCE;
EList<InteractionFragment> fragments = interaction.getFragments();
// Create message
Message message = factory.createMessage();
StringBuffer operationName;
if (operation == null)
operationName = new StringBuffer("Message_").append(interaction.getMessages().size());
else
operationName = new StringBuffer(operation.getName());
message.setName(operationName.toString());
message.setMessageSort(MessageSort.SYNCH_CALL_LITERAL);
interaction.getMessages().add(message);
// Create message send event
MessageOccurrenceSpecification senderEventMessage = factory.createMessageOccurrenceSpecification();
StringBuffer senderEventName = new StringBuffer(operationName).append(SENDER_MESSAGE_SUFFIX);
senderEventMessage.setName(senderEventName.toString());
senderEventMessage.getCovereds().add(source);
senderEventMessage.setMessage(message);
// Create message receive event
MessageOccurrenceSpecification receiverEventMessage = factory.createMessageOccurrenceSpecification();
StringBuffer receiverEventName = new StringBuffer(operationName).append(RECEIVER_MESSAGE_SUFFIX);
receiverEventMessage.setName(receiverEventName.toString());
receiverEventMessage.getCovereds().add(target);
receiverEventMessage.setMessage(message);
message.setSendEvent(senderEventMessage);
message.setReceiveEvent(receiverEventMessage);
// Create behavior
BehaviorExecutionSpecification execution = null;
if (operation != null) {
OpaqueBehavior behavior = factory.createOpaqueBehavior();
behavior.setName(operationName.toString());
if (operation != null || targetFragment instanceof ExecutionSpecification)
behavior.setSpecification(operation);
interaction.getOwnedBehaviors().add(behavior);
execution = factory.createBehaviorExecutionSpecification();
execution.setName(operationName.toString());
execution.getCovereds().add(target);
execution.setBehavior(behavior);
// Create send event
SendOperationEvent sendEvent = factory.createSendOperationEvent();
sendEvent.setName(senderEventName.append(EVENT_MESSAGE_SUFFIX).toString());
senderEventMessage.setEvent(sendEvent);
sendEvent.setOperation(operation);
// Create receive event
ReceiveOperationEvent receiveEvent = factory.createReceiveOperationEvent();
receiveEvent.setName(receiverEventName.append(EVENT_MESSAGE_SUFFIX).toString());
receiverEventMessage.setEvent(receiveEvent);
receiveEvent.setOperation(operation);
message.getNearestPackage().getPackagedElements().add(sendEvent);
message.getNearestPackage().getPackagedElements().add(receiveEvent);
} else {
// Create send event
SendSignalEvent sendEvent = factory.createSendSignalEvent();
sendEvent.setName(senderEventName.append(EVENT_MESSAGE_SUFFIX).toString());
senderEventMessage.setEvent(sendEvent);
// Create receive event
ReceiveSignalEvent receiveEvent = factory.createReceiveSignalEvent();
receiveEvent.setName(receiverEventName.append(EVENT_MESSAGE_SUFFIX).toString());
receiverEventMessage.setEvent(receiveEvent);
// Create signal
Signal signal = factory.createSignal();
signal.setName(operationName.append(SIGNAL_SUFFIX).toString());
sendEvent.setSignal(signal);
receiveEvent.setSignal(signal);
message.getNearestPackage().getPackagedElements().add(signal);
message.getNearestPackage().getPackagedElements().add(sendEvent);
message.getNearestPackage().getPackagedElements().add(receiveEvent);
}
if (execution != null)
execution.setStart(receiverEventMessage);
// Create reply message
Message replyMessage = factory.createMessage();
StringBuffer replyName = new StringBuffer(operationName).append("_reply");
replyMessage.setName(replyName.toString());
replyMessage.setMessageSort(MessageSort.REPLY_LITERAL);
interaction.getMessages().add(replyMessage);
// Create reply message send event
MessageOccurrenceSpecification senderEventReplyMessage = factory
.createMessageOccurrenceSpecification();
StringBuffer senderReplyEventName = new StringBuffer(replyName).append(SENDER_MESSAGE_SUFFIX);
senderEventReplyMessage.setName(senderReplyEventName.toString());
senderEventReplyMessage.getCovereds().add(target);
senderEventReplyMessage.setMessage(replyMessage);
// Create reply message receive event
MessageOccurrenceSpecification receiverEventReplyMessage = factory
.createMessageOccurrenceSpecification();
StringBuffer receiverReplyEventName = new StringBuffer(replyName).append(RECEIVER_MESSAGE_SUFFIX);
receiverEventReplyMessage.setName(receiverReplyEventName.toString());
receiverEventReplyMessage.getCovereds().add(source);
receiverEventReplyMessage.setMessage(replyMessage);
replyMessage.setSendEvent(senderEventReplyMessage);
replyMessage.setReceiveEvent(receiverEventReplyMessage);
if (execution != null)
execution.setFinish(senderEventReplyMessage);
if (operation != null) {
// Create send event
SendOperationEvent sendReplyEvent = factory.createSendOperationEvent();
sendReplyEvent.setName(senderEventName.append(EVENT_MESSAGE_SUFFIX).toString());
senderEventReplyMessage.setEvent(sendReplyEvent);
sendReplyEvent.setOperation(operation);
// Create receive event
ReceiveOperationEvent receiveReplyEvent = factory.createReceiveOperationEvent();
receiveReplyEvent.setName(receiverEventName.append(EVENT_MESSAGE_SUFFIX).toString());
receiverEventReplyMessage.setEvent(receiveReplyEvent);
receiveReplyEvent.setOperation(operation);
message.getNearestPackage().getPackagedElements().add(sendReplyEvent);
message.getNearestPackage().getPackagedElements().add(receiveReplyEvent);
} else {
// Create send reply event
SendSignalEvent sendReplyEvent = factory.createSendSignalEvent();
sendReplyEvent.setName(senderReplyEventName.append(EVENT_MESSAGE_SUFFIX).toString());
sendReplyEvent.setSignal(((SendSignalEvent)senderEventMessage.getEvent()).getSignal());
senderEventReplyMessage.setEvent(sendReplyEvent);
// Create receive reply event
ReceiveSignalEvent receiveReplyEvent = factory.createReceiveSignalEvent();
receiveReplyEvent.setName(receiverReplyEventName.append(EVENT_MESSAGE_SUFFIX).toString());
receiveReplyEvent.setSignal(((ReceiveSignalEvent)receiverEventMessage.getEvent()).getSignal());
receiverEventReplyMessage.setEvent(receiveReplyEvent);
message.getNearestPackage().getPackagedElements().add(sendReplyEvent);
message.getNearestPackage().getPackagedElements().add(receiveReplyEvent);
}
// Add and order fragments under the interaction
// Add message after starting end predecessor
fragments.add(senderEventMessage);
// If predecessor is the beginning of an execution add message after the execution
if (startingEndPredecessor != null && startingEndPredecessor instanceof OccurrenceSpecification
&& predecessorExecution != null
&& startingEndPredecessor.equals(predecessorExecution.getStart()))
fragments.move(fragments.indexOf(predecessorExecution) + 1, senderEventMessage);
// Else set it directly after the predecessor
else
fragments.move(fragments.indexOf(startingEndPredecessor) + 1, senderEventMessage);
fragments.add(receiverEventMessage);
fragments.move(fragments.indexOf(senderEventMessage) + 1, receiverEventMessage);
fragments.add(senderEventReplyMessage);
if (execution != null) {
fragments.add(execution);
fragments.move(fragments.indexOf(receiverEventMessage) + 1, execution);
fragments.move(fragments.indexOf(execution) + 1, senderEventReplyMessage);
} else
fragments.move(fragments.indexOf(receiverEventMessage) + 1, senderEventReplyMessage);
fragments.add(receiverEventReplyMessage);
fragments.move(fragments.indexOf(senderEventReplyMessage) + 1, receiverEventReplyMessage);
}
| public void createSynchronousMessage(Interaction interaction, NamedElement sourceFragment,
NamedElement targetFragment, Operation operation, NamedElement startingEndPredecessor,
NamedElement finishingEndPredecessor) {
Lifeline source = getLifeline(sourceFragment);
Lifeline target = getLifeline(targetFragment);
BehaviorExecutionSpecification predecessorExecution = getExecution((InteractionFragment)startingEndPredecessor);
UMLFactory factory = UMLFactory.eINSTANCE;
EList<InteractionFragment> fragments = interaction.getFragments();
// Create message
Message message = factory.createMessage();
StringBuffer operationName;
if (operation == null)
operationName = new StringBuffer("Message_").append(interaction.getMessages().size());
else
operationName = new StringBuffer(operation.getName());
message.setName(operationName.toString());
message.setMessageSort(MessageSort.SYNCH_CALL_LITERAL);
interaction.getMessages().add(message);
// Create message send event
MessageOccurrenceSpecification senderEventMessage = factory.createMessageOccurrenceSpecification();
StringBuffer senderEventName = new StringBuffer(operationName).append(SENDER_MESSAGE_SUFFIX);
senderEventMessage.setName(senderEventName.toString());
senderEventMessage.getCovereds().add(source);
senderEventMessage.setMessage(message);
// Create message receive event
MessageOccurrenceSpecification receiverEventMessage = factory.createMessageOccurrenceSpecification();
StringBuffer receiverEventName = new StringBuffer(operationName).append(RECEIVER_MESSAGE_SUFFIX);
receiverEventMessage.setName(receiverEventName.toString());
receiverEventMessage.getCovereds().add(target);
receiverEventMessage.setMessage(message);
message.setSendEvent(senderEventMessage);
message.setReceiveEvent(receiverEventMessage);
// Create behavior
BehaviorExecutionSpecification execution = null;
if (operation != null) {
OpaqueBehavior behavior = factory.createOpaqueBehavior();
behavior.setName(operationName.toString());
if (operation != null || targetFragment instanceof ExecutionSpecification)
behavior.setSpecification(operation);
interaction.getOwnedBehaviors().add(behavior);
execution = factory.createBehaviorExecutionSpecification();
execution.setName(operationName.toString());
execution.getCovereds().add(target);
execution.setBehavior(behavior);
// Create send event
SendOperationEvent sendEvent = factory.createSendOperationEvent();
sendEvent.setName(senderEventName.append(EVENT_MESSAGE_SUFFIX).toString());
senderEventMessage.setEvent(sendEvent);
sendEvent.setOperation(operation);
// Create receive event
ReceiveOperationEvent receiveEvent = factory.createReceiveOperationEvent();
receiveEvent.setName(receiverEventName.append(EVENT_MESSAGE_SUFFIX).toString());
receiverEventMessage.setEvent(receiveEvent);
receiveEvent.setOperation(operation);
message.getNearestPackage().getPackagedElements().add(sendEvent);
message.getNearestPackage().getPackagedElements().add(receiveEvent);
} else {
// Create send event
SendSignalEvent sendEvent = factory.createSendSignalEvent();
sendEvent.setName(senderEventName.append(EVENT_MESSAGE_SUFFIX).toString());
senderEventMessage.setEvent(sendEvent);
// Create receive event
ReceiveSignalEvent receiveEvent = factory.createReceiveSignalEvent();
receiveEvent.setName(receiverEventName.append(EVENT_MESSAGE_SUFFIX).toString());
receiverEventMessage.setEvent(receiveEvent);
// Create signal
Signal signal = factory.createSignal();
StringBuffer signalName = new StringBuffer(operationName).append(SIGNAL_SUFFIX);
signal.setName(signalName.toString());
sendEvent.setSignal(signal);
receiveEvent.setSignal(signal);
message.getNearestPackage().getPackagedElements().add(signal);
message.getNearestPackage().getPackagedElements().add(sendEvent);
message.getNearestPackage().getPackagedElements().add(receiveEvent);
}
if (execution != null)
execution.setStart(receiverEventMessage);
// Create reply message
Message replyMessage = factory.createMessage();
StringBuffer replyName = new StringBuffer(operationName).append("_reply");
replyMessage.setName(replyName.toString());
replyMessage.setMessageSort(MessageSort.REPLY_LITERAL);
interaction.getMessages().add(replyMessage);
// Create reply message send event
MessageOccurrenceSpecification senderEventReplyMessage = factory
.createMessageOccurrenceSpecification();
StringBuffer senderReplyEventName = new StringBuffer(replyName).append(SENDER_MESSAGE_SUFFIX);
senderEventReplyMessage.setName(senderReplyEventName.toString());
senderEventReplyMessage.getCovereds().add(target);
senderEventReplyMessage.setMessage(replyMessage);
// Create reply message receive event
MessageOccurrenceSpecification receiverEventReplyMessage = factory
.createMessageOccurrenceSpecification();
StringBuffer receiverReplyEventName = new StringBuffer(replyName).append(RECEIVER_MESSAGE_SUFFIX);
receiverEventReplyMessage.setName(receiverReplyEventName.toString());
receiverEventReplyMessage.getCovereds().add(source);
receiverEventReplyMessage.setMessage(replyMessage);
replyMessage.setSendEvent(senderEventReplyMessage);
replyMessage.setReceiveEvent(receiverEventReplyMessage);
if (execution != null)
execution.setFinish(senderEventReplyMessage);
if (operation != null) {
// Create send event
SendOperationEvent sendReplyEvent = factory.createSendOperationEvent();
sendReplyEvent.setName(senderEventName.append(EVENT_MESSAGE_SUFFIX).toString());
senderEventReplyMessage.setEvent(sendReplyEvent);
sendReplyEvent.setOperation(operation);
// Create receive event
ReceiveOperationEvent receiveReplyEvent = factory.createReceiveOperationEvent();
receiveReplyEvent.setName(receiverEventName.append(EVENT_MESSAGE_SUFFIX).toString());
receiverEventReplyMessage.setEvent(receiveReplyEvent);
receiveReplyEvent.setOperation(operation);
message.getNearestPackage().getPackagedElements().add(sendReplyEvent);
message.getNearestPackage().getPackagedElements().add(receiveReplyEvent);
} else {
// Create send reply event
SendSignalEvent sendReplyEvent = factory.createSendSignalEvent();
sendReplyEvent.setName(senderReplyEventName.append(EVENT_MESSAGE_SUFFIX).toString());
sendReplyEvent.setSignal(((SendSignalEvent)senderEventMessage.getEvent()).getSignal());
senderEventReplyMessage.setEvent(sendReplyEvent);
// Create receive reply event
ReceiveSignalEvent receiveReplyEvent = factory.createReceiveSignalEvent();
receiveReplyEvent.setName(receiverReplyEventName.append(EVENT_MESSAGE_SUFFIX).toString());
receiveReplyEvent.setSignal(((ReceiveSignalEvent)receiverEventMessage.getEvent()).getSignal());
receiverEventReplyMessage.setEvent(receiveReplyEvent);
message.getNearestPackage().getPackagedElements().add(sendReplyEvent);
message.getNearestPackage().getPackagedElements().add(receiveReplyEvent);
}
// Add and order fragments under the interaction
// Add message after starting end predecessor
fragments.add(senderEventMessage);
// If predecessor is the beginning of an execution add message after the execution
if (startingEndPredecessor != null && startingEndPredecessor instanceof OccurrenceSpecification
&& predecessorExecution != null
&& startingEndPredecessor.equals(predecessorExecution.getStart()))
fragments.move(fragments.indexOf(predecessorExecution) + 1, senderEventMessage);
// Else set it directly after the predecessor
else
fragments.move(fragments.indexOf(startingEndPredecessor) + 1, senderEventMessage);
fragments.add(receiverEventMessage);
fragments.move(fragments.indexOf(senderEventMessage) + 1, receiverEventMessage);
fragments.add(senderEventReplyMessage);
if (execution != null) {
fragments.add(execution);
fragments.move(fragments.indexOf(receiverEventMessage) + 1, execution);
fragments.move(fragments.indexOf(execution) + 1, senderEventReplyMessage);
} else
fragments.move(fragments.indexOf(receiverEventMessage) + 1, senderEventReplyMessage);
fragments.add(receiverEventReplyMessage);
fragments.move(fragments.indexOf(senderEventReplyMessage) + 1, receiverEventReplyMessage);
}
|
diff --git a/src/com/redhat/ceylon/compiler/loader/model/LazyPackage.java b/src/com/redhat/ceylon/compiler/loader/model/LazyPackage.java
index 6fb3b7bea..d072ed5f5 100644
--- a/src/com/redhat/ceylon/compiler/loader/model/LazyPackage.java
+++ b/src/com/redhat/ceylon/compiler/loader/model/LazyPackage.java
@@ -1,180 +1,180 @@
/*
* Copyright Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the authors tag. All rights reserved.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License version 2.
*
* This particular file is subject to the "Classpath" exception as provided in the
* LICENSE file that accompanied this code.
*
* This program is distributed in the hope that it will be useful, but WITHOUT A
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License,
* along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package com.redhat.ceylon.compiler.loader.model;
import static com.redhat.ceylon.compiler.typechecker.model.Util.lookupMember;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import com.redhat.ceylon.compiler.java.util.Util;
import com.redhat.ceylon.compiler.loader.AbstractModelLoader;
import com.redhat.ceylon.compiler.loader.ModelLoader.DeclarationType;
import com.redhat.ceylon.compiler.loader.mirror.ClassMirror;
import com.redhat.ceylon.compiler.typechecker.model.Class;
import com.redhat.ceylon.compiler.typechecker.model.Declaration;
import com.redhat.ceylon.compiler.typechecker.model.Package;
import com.redhat.ceylon.compiler.typechecker.model.ProducedType;
import com.redhat.ceylon.compiler.typechecker.model.Unit;
/**
* Represents a lazy Package declaration.
*
* @author Stéphane Épardaud <[email protected]>
*/
public class LazyPackage extends Package {
private AbstractModelLoader modelLoader;
private List<Declaration> compiledDeclarations = new LinkedList<Declaration>();
private Set<Unit> lazyUnits = new HashSet<Unit>();
public LazyPackage(AbstractModelLoader modelLoader){
this.modelLoader = modelLoader;
}
@Override
public Declaration getMember(String name, List<ProducedType> signature, boolean ellipsis) {
// FIXME: what use is this method in the type checker?
return getDirectMember(name, signature, ellipsis);
}
@Override
public Declaration getDirectMemberOrParameter(String name, List<ProducedType> signature, boolean ellipsis) {
// FIXME: what's the difference?
return getDirectMember(name, signature, ellipsis);
}
// FIXME: redo this method better: https://github.com/ceylon/ceylon-spec/issues/90
@Override
public Declaration getDirectMember(String name, List<ProducedType> signature, boolean ellipsis) {
synchronized(modelLoader){
String pkgName = getQualifiedNameString();
// we need its package ready first
modelLoader.loadPackage(pkgName, false);
// make sure we iterate over a copy of compiledDeclarations, to avoid lazy loading to modify it and
// cause a ConcurrentModificationException: https://github.com/ceylon/ceylon-compiler/issues/399
- Declaration d = lookupMember(copy(compiledDeclarations), name, signature, ellipsis, false);
+ Declaration d = lookupMember(copy(compiledDeclarations), name, signature, ellipsis);
if (d != null) {
return d;
}
String className = getQualifiedName(pkgName, name);
ClassMirror classSymbol = modelLoader.lookupClassMirror(className);
// only get it from the classpath if we're not compiling it, unless
// it happens to be a java source
if(classSymbol != null && (!classSymbol.isLoadedFromSource() || classSymbol.isJavaSource())) {
d = modelLoader.convertToDeclaration(className, DeclarationType.VALUE);
if (d instanceof Class) {
if ( ((Class) d).isAbstraction()) {
// make sure we iterate over a copy of compiledDeclarations, to avoid lazy loading to modify it and
// cause a ConcurrentModificationException: https://github.com/ceylon/ceylon-compiler/issues/399
- return lookupMember(copy(compiledDeclarations), name, signature, ellipsis, false);
+ return lookupMember(copy(compiledDeclarations), name, signature, ellipsis);
}
}
return d;
}
return getDirectMemberFromSource(name);
}
}
private List<Declaration> copy(List<Declaration> list) {
List<Declaration> ret = new ArrayList<Declaration>(list.size());
ret.addAll(list);
return ret;
}
private Declaration getDirectMemberFromSource(String name) {
for (Declaration d: super.getMembers()) {
if (com.redhat.ceylon.compiler.typechecker.model.Util.isResolvable(d) /* && d.isShared() */
&& com.redhat.ceylon.compiler.typechecker.model.Util.isNamed(name, d)) {
return d;
}
}
return null;
}
private String getQualifiedName(final String pkgName, String name) {
// FIXME: some refactoring needed
String className = pkgName.isEmpty() ? name : Util.quoteJavaKeywords(pkgName) + "." + name;
return className;
}
// FIXME: This is only here for wildcard imports, and we should be able to make it lazy like the rest
// with a bit of work in the typechecker
// FIXME: redo this method better: https://github.com/ceylon/ceylon-spec/issues/90
@Override
public List<Declaration> getMembers() {
synchronized(modelLoader){
// make sure the package is loaded
modelLoader.loadPackage(getQualifiedNameString(), true);
List<Declaration> sourceDeclarations = super.getMembers();
LinkedList<Declaration> ret = new LinkedList<Declaration>();
ret.addAll(sourceDeclarations);
ret.addAll(compiledDeclarations);
return ret;
}
}
public void addMember(Declaration d) {
synchronized(modelLoader){
compiledDeclarations.add(d);
if (d instanceof LazyClass && d.getUnit().getFilename() != null) {
lazyUnits.add(d.getUnit());
}
}
}
@Override
public Iterable<Unit> getUnits() {
synchronized(modelLoader){
Iterable<Unit> sourceUnits = super.getUnits();
LinkedList<Unit> ret = new LinkedList<Unit>();
for (Unit unit : sourceUnits) {
ret.add(unit);
}
ret.addAll(lazyUnits);
return ret;
}
}
@Override
public void removeUnit(Unit unit) {
synchronized(modelLoader){
if (lazyUnits.remove(unit)) {
for (Declaration d : unit.getDeclarations()) {
compiledDeclarations.remove(d);
// TODO : remove the declaration from the declaration map in AbstractModelLoader
}
modelLoader.removeDeclarations(unit.getDeclarations());
} else {
super.removeUnit(unit);
}
}
}
}
| false | true | public Declaration getDirectMember(String name, List<ProducedType> signature, boolean ellipsis) {
synchronized(modelLoader){
String pkgName = getQualifiedNameString();
// we need its package ready first
modelLoader.loadPackage(pkgName, false);
// make sure we iterate over a copy of compiledDeclarations, to avoid lazy loading to modify it and
// cause a ConcurrentModificationException: https://github.com/ceylon/ceylon-compiler/issues/399
Declaration d = lookupMember(copy(compiledDeclarations), name, signature, ellipsis, false);
if (d != null) {
return d;
}
String className = getQualifiedName(pkgName, name);
ClassMirror classSymbol = modelLoader.lookupClassMirror(className);
// only get it from the classpath if we're not compiling it, unless
// it happens to be a java source
if(classSymbol != null && (!classSymbol.isLoadedFromSource() || classSymbol.isJavaSource())) {
d = modelLoader.convertToDeclaration(className, DeclarationType.VALUE);
if (d instanceof Class) {
if ( ((Class) d).isAbstraction()) {
// make sure we iterate over a copy of compiledDeclarations, to avoid lazy loading to modify it and
// cause a ConcurrentModificationException: https://github.com/ceylon/ceylon-compiler/issues/399
return lookupMember(copy(compiledDeclarations), name, signature, ellipsis, false);
}
}
return d;
}
return getDirectMemberFromSource(name);
}
}
| public Declaration getDirectMember(String name, List<ProducedType> signature, boolean ellipsis) {
synchronized(modelLoader){
String pkgName = getQualifiedNameString();
// we need its package ready first
modelLoader.loadPackage(pkgName, false);
// make sure we iterate over a copy of compiledDeclarations, to avoid lazy loading to modify it and
// cause a ConcurrentModificationException: https://github.com/ceylon/ceylon-compiler/issues/399
Declaration d = lookupMember(copy(compiledDeclarations), name, signature, ellipsis);
if (d != null) {
return d;
}
String className = getQualifiedName(pkgName, name);
ClassMirror classSymbol = modelLoader.lookupClassMirror(className);
// only get it from the classpath if we're not compiling it, unless
// it happens to be a java source
if(classSymbol != null && (!classSymbol.isLoadedFromSource() || classSymbol.isJavaSource())) {
d = modelLoader.convertToDeclaration(className, DeclarationType.VALUE);
if (d instanceof Class) {
if ( ((Class) d).isAbstraction()) {
// make sure we iterate over a copy of compiledDeclarations, to avoid lazy loading to modify it and
// cause a ConcurrentModificationException: https://github.com/ceylon/ceylon-compiler/issues/399
return lookupMember(copy(compiledDeclarations), name, signature, ellipsis);
}
}
return d;
}
return getDirectMemberFromSource(name);
}
}
|
diff --git a/src/RDFaAnnotator/main/TemplateGenerater.java b/src/RDFaAnnotator/main/TemplateGenerater.java
index f794e48..65555a8 100644
--- a/src/RDFaAnnotator/main/TemplateGenerater.java
+++ b/src/RDFaAnnotator/main/TemplateGenerater.java
@@ -1,240 +1,240 @@
package RDFaAnnotator.main;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import baxtree.btr.LabelFinder;
import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Resource;
public class TemplateGenerater {
private String template_str = "";
private String topic_uri;
private Model model;
private String img_formats = ".avi|.bmp|.emf|.gif|.jpg|.jpeg|.mov|.mpg|.mpeg|.png|.wmf|.xbm";
private String page_formats = ".html|.htm|.shtml|.asp|.jsp|.cgi|.php";
public TemplateGenerater(Model model, String topic_uri){
this.model = model;
this.topic_uri = topic_uri;
}
public TemplateGenerater(String rdf_url, String topic_uri){
this.model = ModelFactory.createDefaultModel();
this.model = RDFModelLoader.loadTriplesFromURL(rdf_url);
this.topic_uri = topic_uri;
}
public String createTemplate(String template_name){
- String topic_local_name = this.model.getResource(this.topic_uri).getLocalName();
- if(topic_local_name != null && !topic_local_name.equals(""))
- template_str += "<div about=\"${topic.topicuri}\">about: <a href=\"${topic.topicuri}\">"+topic_local_name+"</a><br/>\r\n\r\n";
- else
+// String topic_local_name = this.model.getResource(this.topic_uri).getLocalName();
+// if(topic_local_name != null && !topic_local_name.equals(""))
+// template_str += "<div about=\"${topic.topicuri}\">about: <a href=\"${topic.topicuri}\">"+topic_local_name+"</a><br/>\r\n\r\n";
+// else
template_str += "<div about=\"${topic.topicuri}\">about: <a href=\"${topic.topicuri}\">${topic.topicuri}</a><br/>\r\n\r\n";
//topic ?p ?o
String preprouri = "";
String querystr =
" SELECT ?p ?o" +
" {" +
" <"+this.topic_uri+"> ?p ?o." +
" }" +
" ORDER BY ?p";
Query query = QueryFactory.create(querystr);
QueryExecution qe = QueryExecutionFactory.create(query, model);
ResultSet results = qe.execSelect();
qe.close();
for(;results.hasNext();){
QuerySolution qs = results.nextSolution();
Resource property = (Resource) qs.get("p");
if(property.getURI().equalsIgnoreCase(preprouri)){
continue;
}
else{
preprouri = property.getURI();
RDFNode object = qs.get("o");
String pro_local_name = property.getLocalName();
String pro_node_name = (model.getNsURIPrefix(property.getNameSpace())+"_"+pro_local_name + "rel").replace("-", "$dash$");;
String pro_curie_name = model.getNsURIPrefix(property.getNameSpace())+":"+pro_local_name;
if(object.isLiteral()){
template_str += "<#if topic."+ pro_node_name +"??>\r\n" +
" <#list topic."+pro_node_name+"?keys as key>\r\n" +
" <#if topic."+ pro_node_name +"[key].val??>\r\n" +
getLiteralStyle(pro_local_name, preprouri)+
" <span property=\""+ pro_curie_name +"\"<#if topic."+ pro_node_name +"[key].dat??> datatype=\"${topic."+ pro_node_name +"[key].dat}\"</#if><#if topic."+ pro_node_name +"[key].lan??> xml:lang=\"${topic."+ pro_node_name +"[key].lan}\"</#if>>${topic."+ pro_node_name +"[key].val}</span><br/>\r\n" +
" </#if>\r\n" +
" </#list>\r\n" +
"</#if>\r\n\r\n";
}
else if(object.isResource()){
String web_resource_tags = "";
Resource resource = (Resource)object;
if(object.isURIResource()){
String object_uri = resource.getURI();
String object_local_name = resource.getLocalName();
int index = 0;
if(object_uri.indexOf(".") != -1)
index = object_uri.lastIndexOf(".");
String expension_name = object_uri.substring(index);
if(img_formats.indexOf(expension_name) != -1){
web_resource_tags = "<img rev=\""+ pro_curie_name +"\" src=\"${topic."+ pro_node_name +"[key].uri}\" alt=\"\"></img><br/>\r\n";
}
else if(page_formats.indexOf(expension_name) != -1){
web_resource_tags = "<a rel=\""+ pro_curie_name +"\" href=\"${topic."+ pro_node_name +"[key].uri}\">${topic."+ pro_node_name +"[key].uri}</a><br/>\r\n";
}
else if(pro_curie_name.indexOf("license") != -1 || pro_curie_name.indexOf("License") != -1 || pro_curie_name.indexOf("LICENSE") != -1){
web_resource_tags = "<a rel=\""+ pro_curie_name +"\" href=\"${topic."+ pro_node_name +"[key].uri}\">${topic."+ pro_node_name +"[key].uri}</a><br/>\r\n";
}
else{
web_resource_tags = "<a rel=\""+ pro_curie_name +"\" href=\"${topic."+ pro_node_name +"[key].uri}\">${topic."+ pro_node_name +"[key].uri}</a><br/>\r\n";
}
}
/*@TODO need test
else if(object.isAnon()){
web_resource_tags = "<a rel=\""+ pro_curie_name +"\">" +
" <#if topic."+ pro_node_name +"[key].bnojbpro??>" +
" <#if topic."+ pro_node_name +"[key].bnuri??>" +
" <a rel=\"${topic."+ pro_node_name +"[key].bnojbpro}\" resource=\"${topic."+ pro_node_name +"[key].bnuri}\">${topic."+ pro_node_name +"[key].bnuri}</a><br/>\r\n" +
" </#if>" +
" </#if>" +
" <#if topic."+ pro_node_name +"[key].bndatpro??>" +
" <#if topic."+ pro_node_name +"[key].bnlex??>" +
" <a property=\"${topic."+ pro_node_name +"[key].bndatpro}\"<#if topic."+ pro_node_name +"[key].bndat??> datatype=\"${topic."+ pro_node_name +"[key].bndat}\"</#if><#if topic."+ pro_node_name +"[key].bnlan??> xml:lang=\"${topic."+ pro_node_name +"[key].bnlan}\"</#if>></a><br/>\r\n" +
" </#if>" +
" </#if>";
}
*/
else{
web_resource_tags = "<a rel=\""+ pro_curie_name +"\" href=\"${topic."+ pro_node_name +"[key].uri}\">${topic."+ pro_node_name +"[key].uri}</a><br/>\r\n";
}
template_str += "<#if topic."+ pro_node_name +"??>\r\n" +
" <#list topic."+pro_node_name+"?keys as key>\r\n" +
" <#if topic."+ pro_node_name +"[key].uri??>\r\n" +
getResourceStyle(pro_local_name, preprouri, true) +
web_resource_tags +
" </#if>\r\n" +
" </#list>\r\n" +
"</#if>\r\n\r\n";
}
}
}
preprouri = "";
//?s ?p topic copied and pasted codes here and it needs refactoring
String querystr2 =
" SELECT ?s ?p" +
" {" +
" ?s ?p <"+this.topic_uri+">." +
" }" +
" ORDER BY ?p";
Query query2 = QueryFactory.create(querystr2);
QueryExecution qe2 = QueryExecutionFactory.create(query2, model);
ResultSet results2 = qe2.execSelect();
qe2.close();
for(;results2.hasNext();){
QuerySolution qs = results2.nextSolution();
Resource property = (Resource) qs.get("p");
if(property.getURI().equalsIgnoreCase(preprouri)){
continue;
}
else{
preprouri = property.getURI();
Resource subject = (Resource) qs.get("s");
String pro_local_name = property.getLocalName();
String pro_node_name = (model.getNsURIPrefix(property.getNameSpace())+"_"+pro_local_name + "rev").replace("-", "$dash$");
String pro_curie_name = model.getNsURIPrefix(property.getNameSpace())+":"+pro_local_name;
if(subject.isResource()){
Resource resource = subject;
String web_resource_tags = "";
if(subject.isURIResource()){
String object_uri = resource.getURI();
String object_local_name = resource.getLocalName();
int index = 0;
if(object_uri.indexOf(".") != -1)
index = object_uri.lastIndexOf(".");
String expension_name = object_uri.substring(index);
if(img_formats.indexOf(expension_name) != -1){
web_resource_tags = "<img rel=\""+ pro_curie_name +"\" src=\"${topic."+ pro_node_name +"[key].uri}\" alt=\"\"></img><br/>\r\n";
}
else if(page_formats.indexOf(expension_name) != -1){
web_resource_tags = "<a rev=\""+ pro_curie_name +"\" href=\"${topic."+ pro_node_name +"[key].uri}\">${topic."+ pro_node_name +"[key].uri}</a><br/>\r\n";
}
else if(pro_curie_name.indexOf("license") != -1 || pro_curie_name.indexOf("License") != -1 || pro_curie_name.indexOf("LICENSE") != -1){
web_resource_tags = "<a rev=\""+ pro_curie_name +"\" href=\"${topic."+ pro_node_name +"[key].uri}\">${topic."+ pro_node_name +"[key].uri}</a><br/>\r\n";
}
else{
web_resource_tags = "<a rev=\""+ pro_curie_name +"\" href=\"${topic."+ pro_node_name +"[key].uri}\">${topic."+ pro_node_name +"[key].uri}</a><br/>\r\n";
}
}
else{
web_resource_tags = "<a rev=\""+ pro_curie_name +"\" href=\"${topic."+ pro_node_name +"[key].uri}\">${topic."+ pro_node_name +"[key].uri}</a><br/>\r\n";
}
template_str += "<#if topic."+ pro_node_name +"??>\r\n" +
" <#list topic."+pro_node_name+"?keys as key>\r\n" +
" <#if topic."+ pro_node_name +"[key].uri??>\r\n" +
getResourceStyle(pro_local_name, preprouri, false) +
web_resource_tags +
" </#if>\r\n" +
" </#list>\r\n" +
"</#if>\r\n\r\n";
}
}
}
// System.out.println(template_str);
template_str += "</div>\r\n\r\n";
return template_str;
}
public String getLiteralStyle(String property_name, String property_uri){
// property_name = "[[<span style=\"color:blue\">"+property_name+"</span>]]";
property_name = "[<a href=\""+property_uri+"\">" + property_name +"</a> >>] ";
return property_name;
}
public String getResourceStyle(String property_name, String property_uri, boolean rel_flag){
// property_name = "{{<span style=\"color:green\">"+property_name+"</span>}}";
if(rel_flag)
property_name = "[<a href=\""+property_uri+"\">" + property_name +"</a> >>] ";
else
property_name = "[<a href=\""+property_uri+"\">" + property_name +"</a> <<] ";
return property_name;
}
public static void main(String [] args){
Model model = ModelFactory.createDefaultModel();
String rdf_url = "http://richard.cyganiak.de/foaf.rdf";
String topic_uri = "http://richard.cyganiak.de/foaf.rdf#cygri";
try{
URL url = new URL(rdf_url);
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setRequestProperty("Accept", "application/rdf+xml");
InputStream is = con.getInputStream();
InputStreamReader isr = new InputStreamReader(is, "UTF-8");
model.read(isr, rdf_url, null);
}
catch (MalformedURLException murle){
murle.printStackTrace();
}
catch(FileNotFoundException fnfe){
fnfe.printStackTrace();
}
catch(IOException ioe){
ioe.printStackTrace();
}
TemplateGenerater itg = new TemplateGenerater(model, topic_uri);
itg.createTemplate("foaftemplate");
}
}
| true | true | public String createTemplate(String template_name){
String topic_local_name = this.model.getResource(this.topic_uri).getLocalName();
if(topic_local_name != null && !topic_local_name.equals(""))
template_str += "<div about=\"${topic.topicuri}\">about: <a href=\"${topic.topicuri}\">"+topic_local_name+"</a><br/>\r\n\r\n";
else
template_str += "<div about=\"${topic.topicuri}\">about: <a href=\"${topic.topicuri}\">${topic.topicuri}</a><br/>\r\n\r\n";
//topic ?p ?o
String preprouri = "";
String querystr =
" SELECT ?p ?o" +
" {" +
" <"+this.topic_uri+"> ?p ?o." +
" }" +
" ORDER BY ?p";
Query query = QueryFactory.create(querystr);
QueryExecution qe = QueryExecutionFactory.create(query, model);
ResultSet results = qe.execSelect();
qe.close();
for(;results.hasNext();){
QuerySolution qs = results.nextSolution();
Resource property = (Resource) qs.get("p");
if(property.getURI().equalsIgnoreCase(preprouri)){
continue;
}
else{
preprouri = property.getURI();
RDFNode object = qs.get("o");
String pro_local_name = property.getLocalName();
String pro_node_name = (model.getNsURIPrefix(property.getNameSpace())+"_"+pro_local_name + "rel").replace("-", "$dash$");;
String pro_curie_name = model.getNsURIPrefix(property.getNameSpace())+":"+pro_local_name;
if(object.isLiteral()){
template_str += "<#if topic."+ pro_node_name +"??>\r\n" +
" <#list topic."+pro_node_name+"?keys as key>\r\n" +
" <#if topic."+ pro_node_name +"[key].val??>\r\n" +
getLiteralStyle(pro_local_name, preprouri)+
" <span property=\""+ pro_curie_name +"\"<#if topic."+ pro_node_name +"[key].dat??> datatype=\"${topic."+ pro_node_name +"[key].dat}\"</#if><#if topic."+ pro_node_name +"[key].lan??> xml:lang=\"${topic."+ pro_node_name +"[key].lan}\"</#if>>${topic."+ pro_node_name +"[key].val}</span><br/>\r\n" +
" </#if>\r\n" +
" </#list>\r\n" +
"</#if>\r\n\r\n";
}
else if(object.isResource()){
String web_resource_tags = "";
Resource resource = (Resource)object;
if(object.isURIResource()){
String object_uri = resource.getURI();
String object_local_name = resource.getLocalName();
int index = 0;
if(object_uri.indexOf(".") != -1)
index = object_uri.lastIndexOf(".");
String expension_name = object_uri.substring(index);
if(img_formats.indexOf(expension_name) != -1){
web_resource_tags = "<img rev=\""+ pro_curie_name +"\" src=\"${topic."+ pro_node_name +"[key].uri}\" alt=\"\"></img><br/>\r\n";
}
else if(page_formats.indexOf(expension_name) != -1){
web_resource_tags = "<a rel=\""+ pro_curie_name +"\" href=\"${topic."+ pro_node_name +"[key].uri}\">${topic."+ pro_node_name +"[key].uri}</a><br/>\r\n";
}
else if(pro_curie_name.indexOf("license") != -1 || pro_curie_name.indexOf("License") != -1 || pro_curie_name.indexOf("LICENSE") != -1){
web_resource_tags = "<a rel=\""+ pro_curie_name +"\" href=\"${topic."+ pro_node_name +"[key].uri}\">${topic."+ pro_node_name +"[key].uri}</a><br/>\r\n";
}
else{
web_resource_tags = "<a rel=\""+ pro_curie_name +"\" href=\"${topic."+ pro_node_name +"[key].uri}\">${topic."+ pro_node_name +"[key].uri}</a><br/>\r\n";
}
}
/*@TODO need test
else if(object.isAnon()){
web_resource_tags = "<a rel=\""+ pro_curie_name +"\">" +
" <#if topic."+ pro_node_name +"[key].bnojbpro??>" +
" <#if topic."+ pro_node_name +"[key].bnuri??>" +
" <a rel=\"${topic."+ pro_node_name +"[key].bnojbpro}\" resource=\"${topic."+ pro_node_name +"[key].bnuri}\">${topic."+ pro_node_name +"[key].bnuri}</a><br/>\r\n" +
" </#if>" +
" </#if>" +
" <#if topic."+ pro_node_name +"[key].bndatpro??>" +
" <#if topic."+ pro_node_name +"[key].bnlex??>" +
" <a property=\"${topic."+ pro_node_name +"[key].bndatpro}\"<#if topic."+ pro_node_name +"[key].bndat??> datatype=\"${topic."+ pro_node_name +"[key].bndat}\"</#if><#if topic."+ pro_node_name +"[key].bnlan??> xml:lang=\"${topic."+ pro_node_name +"[key].bnlan}\"</#if>></a><br/>\r\n" +
" </#if>" +
" </#if>";
}
*/
else{
web_resource_tags = "<a rel=\""+ pro_curie_name +"\" href=\"${topic."+ pro_node_name +"[key].uri}\">${topic."+ pro_node_name +"[key].uri}</a><br/>\r\n";
}
template_str += "<#if topic."+ pro_node_name +"??>\r\n" +
" <#list topic."+pro_node_name+"?keys as key>\r\n" +
" <#if topic."+ pro_node_name +"[key].uri??>\r\n" +
getResourceStyle(pro_local_name, preprouri, true) +
web_resource_tags +
" </#if>\r\n" +
" </#list>\r\n" +
"</#if>\r\n\r\n";
}
}
}
preprouri = "";
//?s ?p topic copied and pasted codes here and it needs refactoring
String querystr2 =
" SELECT ?s ?p" +
" {" +
" ?s ?p <"+this.topic_uri+">." +
" }" +
" ORDER BY ?p";
Query query2 = QueryFactory.create(querystr2);
QueryExecution qe2 = QueryExecutionFactory.create(query2, model);
ResultSet results2 = qe2.execSelect();
qe2.close();
for(;results2.hasNext();){
QuerySolution qs = results2.nextSolution();
Resource property = (Resource) qs.get("p");
if(property.getURI().equalsIgnoreCase(preprouri)){
continue;
}
else{
preprouri = property.getURI();
Resource subject = (Resource) qs.get("s");
String pro_local_name = property.getLocalName();
String pro_node_name = (model.getNsURIPrefix(property.getNameSpace())+"_"+pro_local_name + "rev").replace("-", "$dash$");
String pro_curie_name = model.getNsURIPrefix(property.getNameSpace())+":"+pro_local_name;
if(subject.isResource()){
Resource resource = subject;
String web_resource_tags = "";
if(subject.isURIResource()){
String object_uri = resource.getURI();
String object_local_name = resource.getLocalName();
int index = 0;
if(object_uri.indexOf(".") != -1)
index = object_uri.lastIndexOf(".");
String expension_name = object_uri.substring(index);
if(img_formats.indexOf(expension_name) != -1){
web_resource_tags = "<img rel=\""+ pro_curie_name +"\" src=\"${topic."+ pro_node_name +"[key].uri}\" alt=\"\"></img><br/>\r\n";
}
else if(page_formats.indexOf(expension_name) != -1){
web_resource_tags = "<a rev=\""+ pro_curie_name +"\" href=\"${topic."+ pro_node_name +"[key].uri}\">${topic."+ pro_node_name +"[key].uri}</a><br/>\r\n";
}
else if(pro_curie_name.indexOf("license") != -1 || pro_curie_name.indexOf("License") != -1 || pro_curie_name.indexOf("LICENSE") != -1){
web_resource_tags = "<a rev=\""+ pro_curie_name +"\" href=\"${topic."+ pro_node_name +"[key].uri}\">${topic."+ pro_node_name +"[key].uri}</a><br/>\r\n";
}
else{
web_resource_tags = "<a rev=\""+ pro_curie_name +"\" href=\"${topic."+ pro_node_name +"[key].uri}\">${topic."+ pro_node_name +"[key].uri}</a><br/>\r\n";
}
}
else{
web_resource_tags = "<a rev=\""+ pro_curie_name +"\" href=\"${topic."+ pro_node_name +"[key].uri}\">${topic."+ pro_node_name +"[key].uri}</a><br/>\r\n";
}
template_str += "<#if topic."+ pro_node_name +"??>\r\n" +
" <#list topic."+pro_node_name+"?keys as key>\r\n" +
" <#if topic."+ pro_node_name +"[key].uri??>\r\n" +
getResourceStyle(pro_local_name, preprouri, false) +
web_resource_tags +
" </#if>\r\n" +
" </#list>\r\n" +
"</#if>\r\n\r\n";
}
}
}
// System.out.println(template_str);
template_str += "</div>\r\n\r\n";
return template_str;
}
| public String createTemplate(String template_name){
// String topic_local_name = this.model.getResource(this.topic_uri).getLocalName();
// if(topic_local_name != null && !topic_local_name.equals(""))
// template_str += "<div about=\"${topic.topicuri}\">about: <a href=\"${topic.topicuri}\">"+topic_local_name+"</a><br/>\r\n\r\n";
// else
template_str += "<div about=\"${topic.topicuri}\">about: <a href=\"${topic.topicuri}\">${topic.topicuri}</a><br/>\r\n\r\n";
//topic ?p ?o
String preprouri = "";
String querystr =
" SELECT ?p ?o" +
" {" +
" <"+this.topic_uri+"> ?p ?o." +
" }" +
" ORDER BY ?p";
Query query = QueryFactory.create(querystr);
QueryExecution qe = QueryExecutionFactory.create(query, model);
ResultSet results = qe.execSelect();
qe.close();
for(;results.hasNext();){
QuerySolution qs = results.nextSolution();
Resource property = (Resource) qs.get("p");
if(property.getURI().equalsIgnoreCase(preprouri)){
continue;
}
else{
preprouri = property.getURI();
RDFNode object = qs.get("o");
String pro_local_name = property.getLocalName();
String pro_node_name = (model.getNsURIPrefix(property.getNameSpace())+"_"+pro_local_name + "rel").replace("-", "$dash$");;
String pro_curie_name = model.getNsURIPrefix(property.getNameSpace())+":"+pro_local_name;
if(object.isLiteral()){
template_str += "<#if topic."+ pro_node_name +"??>\r\n" +
" <#list topic."+pro_node_name+"?keys as key>\r\n" +
" <#if topic."+ pro_node_name +"[key].val??>\r\n" +
getLiteralStyle(pro_local_name, preprouri)+
" <span property=\""+ pro_curie_name +"\"<#if topic."+ pro_node_name +"[key].dat??> datatype=\"${topic."+ pro_node_name +"[key].dat}\"</#if><#if topic."+ pro_node_name +"[key].lan??> xml:lang=\"${topic."+ pro_node_name +"[key].lan}\"</#if>>${topic."+ pro_node_name +"[key].val}</span><br/>\r\n" +
" </#if>\r\n" +
" </#list>\r\n" +
"</#if>\r\n\r\n";
}
else if(object.isResource()){
String web_resource_tags = "";
Resource resource = (Resource)object;
if(object.isURIResource()){
String object_uri = resource.getURI();
String object_local_name = resource.getLocalName();
int index = 0;
if(object_uri.indexOf(".") != -1)
index = object_uri.lastIndexOf(".");
String expension_name = object_uri.substring(index);
if(img_formats.indexOf(expension_name) != -1){
web_resource_tags = "<img rev=\""+ pro_curie_name +"\" src=\"${topic."+ pro_node_name +"[key].uri}\" alt=\"\"></img><br/>\r\n";
}
else if(page_formats.indexOf(expension_name) != -1){
web_resource_tags = "<a rel=\""+ pro_curie_name +"\" href=\"${topic."+ pro_node_name +"[key].uri}\">${topic."+ pro_node_name +"[key].uri}</a><br/>\r\n";
}
else if(pro_curie_name.indexOf("license") != -1 || pro_curie_name.indexOf("License") != -1 || pro_curie_name.indexOf("LICENSE") != -1){
web_resource_tags = "<a rel=\""+ pro_curie_name +"\" href=\"${topic."+ pro_node_name +"[key].uri}\">${topic."+ pro_node_name +"[key].uri}</a><br/>\r\n";
}
else{
web_resource_tags = "<a rel=\""+ pro_curie_name +"\" href=\"${topic."+ pro_node_name +"[key].uri}\">${topic."+ pro_node_name +"[key].uri}</a><br/>\r\n";
}
}
/*@TODO need test
else if(object.isAnon()){
web_resource_tags = "<a rel=\""+ pro_curie_name +"\">" +
" <#if topic."+ pro_node_name +"[key].bnojbpro??>" +
" <#if topic."+ pro_node_name +"[key].bnuri??>" +
" <a rel=\"${topic."+ pro_node_name +"[key].bnojbpro}\" resource=\"${topic."+ pro_node_name +"[key].bnuri}\">${topic."+ pro_node_name +"[key].bnuri}</a><br/>\r\n" +
" </#if>" +
" </#if>" +
" <#if topic."+ pro_node_name +"[key].bndatpro??>" +
" <#if topic."+ pro_node_name +"[key].bnlex??>" +
" <a property=\"${topic."+ pro_node_name +"[key].bndatpro}\"<#if topic."+ pro_node_name +"[key].bndat??> datatype=\"${topic."+ pro_node_name +"[key].bndat}\"</#if><#if topic."+ pro_node_name +"[key].bnlan??> xml:lang=\"${topic."+ pro_node_name +"[key].bnlan}\"</#if>></a><br/>\r\n" +
" </#if>" +
" </#if>";
}
*/
else{
web_resource_tags = "<a rel=\""+ pro_curie_name +"\" href=\"${topic."+ pro_node_name +"[key].uri}\">${topic."+ pro_node_name +"[key].uri}</a><br/>\r\n";
}
template_str += "<#if topic."+ pro_node_name +"??>\r\n" +
" <#list topic."+pro_node_name+"?keys as key>\r\n" +
" <#if topic."+ pro_node_name +"[key].uri??>\r\n" +
getResourceStyle(pro_local_name, preprouri, true) +
web_resource_tags +
" </#if>\r\n" +
" </#list>\r\n" +
"</#if>\r\n\r\n";
}
}
}
preprouri = "";
//?s ?p topic copied and pasted codes here and it needs refactoring
String querystr2 =
" SELECT ?s ?p" +
" {" +
" ?s ?p <"+this.topic_uri+">." +
" }" +
" ORDER BY ?p";
Query query2 = QueryFactory.create(querystr2);
QueryExecution qe2 = QueryExecutionFactory.create(query2, model);
ResultSet results2 = qe2.execSelect();
qe2.close();
for(;results2.hasNext();){
QuerySolution qs = results2.nextSolution();
Resource property = (Resource) qs.get("p");
if(property.getURI().equalsIgnoreCase(preprouri)){
continue;
}
else{
preprouri = property.getURI();
Resource subject = (Resource) qs.get("s");
String pro_local_name = property.getLocalName();
String pro_node_name = (model.getNsURIPrefix(property.getNameSpace())+"_"+pro_local_name + "rev").replace("-", "$dash$");
String pro_curie_name = model.getNsURIPrefix(property.getNameSpace())+":"+pro_local_name;
if(subject.isResource()){
Resource resource = subject;
String web_resource_tags = "";
if(subject.isURIResource()){
String object_uri = resource.getURI();
String object_local_name = resource.getLocalName();
int index = 0;
if(object_uri.indexOf(".") != -1)
index = object_uri.lastIndexOf(".");
String expension_name = object_uri.substring(index);
if(img_formats.indexOf(expension_name) != -1){
web_resource_tags = "<img rel=\""+ pro_curie_name +"\" src=\"${topic."+ pro_node_name +"[key].uri}\" alt=\"\"></img><br/>\r\n";
}
else if(page_formats.indexOf(expension_name) != -1){
web_resource_tags = "<a rev=\""+ pro_curie_name +"\" href=\"${topic."+ pro_node_name +"[key].uri}\">${topic."+ pro_node_name +"[key].uri}</a><br/>\r\n";
}
else if(pro_curie_name.indexOf("license") != -1 || pro_curie_name.indexOf("License") != -1 || pro_curie_name.indexOf("LICENSE") != -1){
web_resource_tags = "<a rev=\""+ pro_curie_name +"\" href=\"${topic."+ pro_node_name +"[key].uri}\">${topic."+ pro_node_name +"[key].uri}</a><br/>\r\n";
}
else{
web_resource_tags = "<a rev=\""+ pro_curie_name +"\" href=\"${topic."+ pro_node_name +"[key].uri}\">${topic."+ pro_node_name +"[key].uri}</a><br/>\r\n";
}
}
else{
web_resource_tags = "<a rev=\""+ pro_curie_name +"\" href=\"${topic."+ pro_node_name +"[key].uri}\">${topic."+ pro_node_name +"[key].uri}</a><br/>\r\n";
}
template_str += "<#if topic."+ pro_node_name +"??>\r\n" +
" <#list topic."+pro_node_name+"?keys as key>\r\n" +
" <#if topic."+ pro_node_name +"[key].uri??>\r\n" +
getResourceStyle(pro_local_name, preprouri, false) +
web_resource_tags +
" </#if>\r\n" +
" </#list>\r\n" +
"</#if>\r\n\r\n";
}
}
}
// System.out.println(template_str);
template_str += "</div>\r\n\r\n";
return template_str;
}
|
diff --git a/tests/org.bonitasoft.studio.engine.test/src/org/bonitasoft/studio/engine/test/bar/BarExporterTest.java b/tests/org.bonitasoft.studio.engine.test/src/org/bonitasoft/studio/engine/test/bar/BarExporterTest.java
index 957ab07ec0..d3b6931458 100644
--- a/tests/org.bonitasoft.studio.engine.test/src/org/bonitasoft/studio/engine/test/bar/BarExporterTest.java
+++ b/tests/org.bonitasoft.studio.engine.test/src/org/bonitasoft/studio/engine/test/bar/BarExporterTest.java
@@ -1,194 +1,194 @@
/**
* Copyright (C) 2012 BonitaSoft S.A.
* BonitaSoft, 31 rue Gustave Eiffel - 38000 Grenoble
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2.0 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.bonitasoft.studio.engine.test.bar;
import java.io.File;
import java.util.Vector;
import junit.framework.Assert;
import org.bonitasoft.studio.common.ProjectUtil;
import org.bonitasoft.studio.common.jface.FileActionDialog;
import org.bonitasoft.studio.engine.i18n.Messages;
import org.bonitasoft.studio.test.swtbot.util.SWTBotTestUtil;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.swtbot.eclipse.finder.waits.Conditions;
import org.eclipse.swtbot.eclipse.finder.widgets.SWTBotEditor;
import org.eclipse.swtbot.eclipse.gef.finder.SWTBotGefTestCase;
import org.eclipse.swtbot.eclipse.gef.finder.widgets.SWTBotGefEditor;
import org.eclipse.swtbot.swt.finder.junit.SWTBotJunit4ClassRunner;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotShell;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotTree;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotTreeItem;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* @author Florine Boudin
*
*/
@RunWith(SWTBotJunit4ClassRunner.class)
public class BarExporterTest extends SWTBotGefTestCase {
private static boolean disablePopup;
final public static String EditorTitleRegex = "(.*)\\s\\((.*)\\)";
@BeforeClass
public static void setUpBeforeClass() {
disablePopup = FileActionDialog.getDisablePopup();
FileActionDialog.setDisablePopup(true);
}
@AfterClass
public static void tearDownAfterClass() {
FileActionDialog.setDisablePopup(disablePopup);
}
@Test
public void testServerBuild() {
SWTBotTestUtil.createNewDiagram(bot);
SWTBotEditor activeEditor = bot.activeEditor();
String editorTitle = activeEditor.getTitle();
//System.out.println("editorTitle1 = "+editorTitle1);
Assert.assertFalse("Error: first diagram name is empty.", editorTitle.isEmpty());
// get the GEF editor to activate tools
final SWTBotGefEditor gmfEditor = bot.gefEditor(editorTitle);
// Create 2 Pools
gmfEditor.activateTool("Pool");
gmfEditor.click(200, 500);
gmfEditor.activateTool("Pool");
gmfEditor.click(200, 800);
// Save Diagram
bot.menu("Diagram").menu("Save").click();
//System.out.println(editorTitle);
- bot.waitUntil(Conditions.widgetIsEnabled(bot.menu("Runtime")));
+ bot.waitUntil(Conditions.widgetIsEnabled(bot.menu("Server")));
// Menu Server > Build...
- bot.menu("Runtime").menu("Build...").click();
+ bot.menu("Server").menu("Build...").click();
// shell 'Build'
final SWTBotShell shell = bot.shell(Messages.buildTitle);
bot.waitUntil(Conditions.shellIsActive(Messages.buildTitle));
// select and check created Diagram in the Tree
SWTBotTree tree = bot.treeWithLabel("Select processes to export");
SWTBotTreeItem diagramTreeItem = tree.getTreeItem(editorTitle);
// check the diagram to export
diagramTreeItem.select().check();
diagramTreeItem.expand();
// Number of pool in the diagram
int poolListSize = diagramTreeItem.getItems().length ;
//System.out.println("Diagram contains "+ poolListSize + " items");
Assert.assertEquals("Error: Diagram must contain 3 Pools.",3,poolListSize );
// unselect the first pool of the list
diagramTreeItem.getNode(0).select();
diagramTreeItem.getNode(0).uncheck();
Vector<String> poolTitleList = new Vector<String>(3);
int poolTitleListSize = poolTitleList.size();
// check the selected pools
for(int i=1; i<poolTitleListSize;i++){
SWTBotTreeItem poolTreeItem = diagramTreeItem.getNode(i);
poolTitleList.set(i, poolTreeItem.getText());
String poolName = getItemName(poolTitleList.get(i));
// test the good pool is checked
Assert.assertFalse("Error: Pool "+i+" should be checked.", !poolTreeItem.isChecked());
Assert.assertFalse("Error: Pool selected is not the good one.",!poolName.equals("Pool"+i));
}
// create tmp directory to write diagrams
File tmpBarFolder = new File(ProjectUtil.getBonitaStudioWorkFolder(),"testExportBar");
tmpBarFolder.mkdirs();
//set the path where files are saved
final String tmpBarFolderPath = tmpBarFolder.getAbsolutePath();
bot.comboBoxWithLabel(Messages.destinationPath+" *").setText(tmpBarFolderPath);
// String tmpBarFolderPath = bot.comboBoxWithLabel(Messages.destinationPath+" *").getText();
// System.out.println("tmpBarFolder = "+tmpBarFolderPath);
// click 'Finish' button to close 'Build' shell
bot.waitUntil(Conditions.widgetIsEnabled(bot.button(IDialogConstants.FINISH_LABEL)));
bot.button(IDialogConstants.FINISH_LABEL).click();
// click 'OK' button to close 'Export' shell
bot.waitUntil(Conditions.shellIsActive(Messages.exportSuccessTitle));
bot.button(IDialogConstants.OK_LABEL).click();
// wait the shell to close before checking creation of files
bot.waitUntil(Conditions.shellCloses(shell));
// check directory exists
String diagramDir1 = getItemName(editorTitle) + "--"+getItemVersion(editorTitle);
//System.out.println("diagramDir1 = "+diagramDir1);
// check pools files exist
for(int i=1; i<poolTitleListSize;i++){
String tmpPoolTitle = poolTitleList.get(i);
String poolFileName = getItemName(tmpPoolTitle)+"--"+getItemVersion(tmpPoolTitle)+".bar";
final File poolFile = new File(tmpBarFolderPath, poolFileName);
assertTrue( "Error: The Pool export must exist", poolFile.exists());
assertTrue( "Error: The Pool export must be a file", poolFile.isFile());
}
}
/**Return the name of a Diagram from the Title of the Editor
*
* @param s title of the editor
* @return the name of the diagram
* <p>
* <b>Example:</b>
* <p>
* entry : "MyDiagram (1.0)"<br>
* return : "MyDiagram"
*/
public String getItemName(String s){
return s.replaceFirst(EditorTitleRegex, "$1");
}
/**Return the version of a Diagram from the Title of the Editor
*
* @param s title of the editor
* @return the name of the diagram
* <p>
* <b>Example:</b>
* <p>
* entry : "MyDiagram (1.0)"<br>
* return : "1.0"
*/
public String getItemVersion(String s){
return s.replaceFirst(EditorTitleRegex, "$2");
}
}
| false | true | public void testServerBuild() {
SWTBotTestUtil.createNewDiagram(bot);
SWTBotEditor activeEditor = bot.activeEditor();
String editorTitle = activeEditor.getTitle();
//System.out.println("editorTitle1 = "+editorTitle1);
Assert.assertFalse("Error: first diagram name is empty.", editorTitle.isEmpty());
// get the GEF editor to activate tools
final SWTBotGefEditor gmfEditor = bot.gefEditor(editorTitle);
// Create 2 Pools
gmfEditor.activateTool("Pool");
gmfEditor.click(200, 500);
gmfEditor.activateTool("Pool");
gmfEditor.click(200, 800);
// Save Diagram
bot.menu("Diagram").menu("Save").click();
//System.out.println(editorTitle);
bot.waitUntil(Conditions.widgetIsEnabled(bot.menu("Runtime")));
// Menu Server > Build...
bot.menu("Runtime").menu("Build...").click();
// shell 'Build'
final SWTBotShell shell = bot.shell(Messages.buildTitle);
bot.waitUntil(Conditions.shellIsActive(Messages.buildTitle));
// select and check created Diagram in the Tree
SWTBotTree tree = bot.treeWithLabel("Select processes to export");
SWTBotTreeItem diagramTreeItem = tree.getTreeItem(editorTitle);
// check the diagram to export
diagramTreeItem.select().check();
diagramTreeItem.expand();
// Number of pool in the diagram
int poolListSize = diagramTreeItem.getItems().length ;
//System.out.println("Diagram contains "+ poolListSize + " items");
Assert.assertEquals("Error: Diagram must contain 3 Pools.",3,poolListSize );
// unselect the first pool of the list
diagramTreeItem.getNode(0).select();
diagramTreeItem.getNode(0).uncheck();
Vector<String> poolTitleList = new Vector<String>(3);
int poolTitleListSize = poolTitleList.size();
// check the selected pools
for(int i=1; i<poolTitleListSize;i++){
SWTBotTreeItem poolTreeItem = diagramTreeItem.getNode(i);
poolTitleList.set(i, poolTreeItem.getText());
String poolName = getItemName(poolTitleList.get(i));
// test the good pool is checked
Assert.assertFalse("Error: Pool "+i+" should be checked.", !poolTreeItem.isChecked());
Assert.assertFalse("Error: Pool selected is not the good one.",!poolName.equals("Pool"+i));
}
// create tmp directory to write diagrams
File tmpBarFolder = new File(ProjectUtil.getBonitaStudioWorkFolder(),"testExportBar");
tmpBarFolder.mkdirs();
//set the path where files are saved
final String tmpBarFolderPath = tmpBarFolder.getAbsolutePath();
bot.comboBoxWithLabel(Messages.destinationPath+" *").setText(tmpBarFolderPath);
// String tmpBarFolderPath = bot.comboBoxWithLabel(Messages.destinationPath+" *").getText();
// System.out.println("tmpBarFolder = "+tmpBarFolderPath);
// click 'Finish' button to close 'Build' shell
bot.waitUntil(Conditions.widgetIsEnabled(bot.button(IDialogConstants.FINISH_LABEL)));
bot.button(IDialogConstants.FINISH_LABEL).click();
// click 'OK' button to close 'Export' shell
bot.waitUntil(Conditions.shellIsActive(Messages.exportSuccessTitle));
bot.button(IDialogConstants.OK_LABEL).click();
// wait the shell to close before checking creation of files
bot.waitUntil(Conditions.shellCloses(shell));
// check directory exists
String diagramDir1 = getItemName(editorTitle) + "--"+getItemVersion(editorTitle);
//System.out.println("diagramDir1 = "+diagramDir1);
// check pools files exist
for(int i=1; i<poolTitleListSize;i++){
String tmpPoolTitle = poolTitleList.get(i);
String poolFileName = getItemName(tmpPoolTitle)+"--"+getItemVersion(tmpPoolTitle)+".bar";
final File poolFile = new File(tmpBarFolderPath, poolFileName);
assertTrue( "Error: The Pool export must exist", poolFile.exists());
assertTrue( "Error: The Pool export must be a file", poolFile.isFile());
}
}
| public void testServerBuild() {
SWTBotTestUtil.createNewDiagram(bot);
SWTBotEditor activeEditor = bot.activeEditor();
String editorTitle = activeEditor.getTitle();
//System.out.println("editorTitle1 = "+editorTitle1);
Assert.assertFalse("Error: first diagram name is empty.", editorTitle.isEmpty());
// get the GEF editor to activate tools
final SWTBotGefEditor gmfEditor = bot.gefEditor(editorTitle);
// Create 2 Pools
gmfEditor.activateTool("Pool");
gmfEditor.click(200, 500);
gmfEditor.activateTool("Pool");
gmfEditor.click(200, 800);
// Save Diagram
bot.menu("Diagram").menu("Save").click();
//System.out.println(editorTitle);
bot.waitUntil(Conditions.widgetIsEnabled(bot.menu("Server")));
// Menu Server > Build...
bot.menu("Server").menu("Build...").click();
// shell 'Build'
final SWTBotShell shell = bot.shell(Messages.buildTitle);
bot.waitUntil(Conditions.shellIsActive(Messages.buildTitle));
// select and check created Diagram in the Tree
SWTBotTree tree = bot.treeWithLabel("Select processes to export");
SWTBotTreeItem diagramTreeItem = tree.getTreeItem(editorTitle);
// check the diagram to export
diagramTreeItem.select().check();
diagramTreeItem.expand();
// Number of pool in the diagram
int poolListSize = diagramTreeItem.getItems().length ;
//System.out.println("Diagram contains "+ poolListSize + " items");
Assert.assertEquals("Error: Diagram must contain 3 Pools.",3,poolListSize );
// unselect the first pool of the list
diagramTreeItem.getNode(0).select();
diagramTreeItem.getNode(0).uncheck();
Vector<String> poolTitleList = new Vector<String>(3);
int poolTitleListSize = poolTitleList.size();
// check the selected pools
for(int i=1; i<poolTitleListSize;i++){
SWTBotTreeItem poolTreeItem = diagramTreeItem.getNode(i);
poolTitleList.set(i, poolTreeItem.getText());
String poolName = getItemName(poolTitleList.get(i));
// test the good pool is checked
Assert.assertFalse("Error: Pool "+i+" should be checked.", !poolTreeItem.isChecked());
Assert.assertFalse("Error: Pool selected is not the good one.",!poolName.equals("Pool"+i));
}
// create tmp directory to write diagrams
File tmpBarFolder = new File(ProjectUtil.getBonitaStudioWorkFolder(),"testExportBar");
tmpBarFolder.mkdirs();
//set the path where files are saved
final String tmpBarFolderPath = tmpBarFolder.getAbsolutePath();
bot.comboBoxWithLabel(Messages.destinationPath+" *").setText(tmpBarFolderPath);
// String tmpBarFolderPath = bot.comboBoxWithLabel(Messages.destinationPath+" *").getText();
// System.out.println("tmpBarFolder = "+tmpBarFolderPath);
// click 'Finish' button to close 'Build' shell
bot.waitUntil(Conditions.widgetIsEnabled(bot.button(IDialogConstants.FINISH_LABEL)));
bot.button(IDialogConstants.FINISH_LABEL).click();
// click 'OK' button to close 'Export' shell
bot.waitUntil(Conditions.shellIsActive(Messages.exportSuccessTitle));
bot.button(IDialogConstants.OK_LABEL).click();
// wait the shell to close before checking creation of files
bot.waitUntil(Conditions.shellCloses(shell));
// check directory exists
String diagramDir1 = getItemName(editorTitle) + "--"+getItemVersion(editorTitle);
//System.out.println("diagramDir1 = "+diagramDir1);
// check pools files exist
for(int i=1; i<poolTitleListSize;i++){
String tmpPoolTitle = poolTitleList.get(i);
String poolFileName = getItemName(tmpPoolTitle)+"--"+getItemVersion(tmpPoolTitle)+".bar";
final File poolFile = new File(tmpBarFolderPath, poolFileName);
assertTrue( "Error: The Pool export must exist", poolFile.exists());
assertTrue( "Error: The Pool export must be a file", poolFile.isFile());
}
}
|
diff --git a/src/edu/upenn/cis/cis350/algorithmvisualization/BinPackingProblemFactory.java b/src/edu/upenn/cis/cis350/algorithmvisualization/BinPackingProblemFactory.java
index 22856d3..755bdcb 100644
--- a/src/edu/upenn/cis/cis350/algorithmvisualization/BinPackingProblemFactory.java
+++ b/src/edu/upenn/cis/cis350/algorithmvisualization/BinPackingProblemFactory.java
@@ -1,120 +1,118 @@
package edu.upenn.cis.cis350.algorithmvisualization;
import java.util.ArrayList;
import java.util.Collection;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.content.Context;
import android.content.res.XmlResourceParser;
/**
* Generates the Bins and BinObjects for each Bin Packing problem difficulty,
* as specified in res/xml/problems.xml. Also calculates optimal solutions.
*/
public class BinPackingProblemFactory {
private Collection<BinObject> easyObjects, mediumObjects, hardObjects;
private Collection<Bin> easyBins, mediumBins, hardBins;
private double easyOptSol, mediumOptSol, hardOptSol;
/**
* @param difficulty The difficulty of the problem as specified in problems.xml.
* @return a Collection of all BinObjects for the specified difficulty, or null if the
* difficulty is unspecified in problems.xml.
*/
public Collection<BinObject> getBinObjects(String difficulty) {
if ("easy".equalsIgnoreCase(difficulty)) return easyObjects;
else if ("medium".equalsIgnoreCase(difficulty)) return mediumObjects;
else if ("hard".equalsIgnoreCase(difficulty)) return hardObjects;
return null;
}
/**
* @param difficulty The difficulty of the problem as specified in problems.xml.
* @return a Collection of all Bins for the specified difficulty, or null if the
* difficulty is unspecified in problems.xml.
*/
public Collection<Bin> getBins(String difficulty) {
if ("easy".equalsIgnoreCase(difficulty)) return easyBins;
else if ("medium".equalsIgnoreCase(difficulty)) return mediumBins;
else if ("hard".equalsIgnoreCase(difficulty)) return hardBins;
return null;
}
/**
* @param difficulty The difficulty of the problem as specified in problems.xml.
* @return the value of the optimal solution for the specified difficulty, or -1 if the
* difficulty is unspecified in problems.xml.
*/
public double getOptimalSolution(String difficulty) {
if ("easy".equalsIgnoreCase(difficulty)) return easyOptSol;
else if ("medium".equalsIgnoreCase(difficulty)) return mediumOptSol;
else if ("hard".equalsIgnoreCase(difficulty)) return hardOptSol;
return -1;
}
/**
* For each difficulty: reads in the app config specified in res/xml/problems.xml,
* generates the corresponding Bin and BinObject collections, and calculates
* the value of the optimal solution.
*/
public BinPackingProblemFactory(Context context) {
//Initialize instance variables
easyBins = new ArrayList<Bin>();
mediumBins = new ArrayList<Bin>();
hardBins = new ArrayList<Bin>();
easyObjects = new ArrayList<BinObject>();
mediumObjects = new ArrayList<BinObject>();
hardObjects = new ArrayList<BinObject>();
easyOptSol = -1;
mediumOptSol = -1;
hardOptSol = -1;
//Parse problems.xml
XmlResourceParser parser = context.getResources().getXml(R.id.bin_packing);
try {
int event = parser.next();
- while (!"item".equals(parser.getName()) &&
- !"bin_packing".equals(parser.getAttributeValue("","name"))) event = parser.next();
- while (event != XmlPullParser.END_DOCUMENT) {
+ while (!(event == XmlPullParser.END_TAG && parser.getName().equalsIgnoreCase("item"))) {
String difficulty = "";
if (event == XmlPullParser.START_TAG) {
String element = parser.getName();
if ("problem".equals(element)) { //Parse problem difficulty
difficulty = parser.getAttributeValue("", "difficulty");
if (!"easy".equalsIgnoreCase(difficulty) && !"medium".equalsIgnoreCase(difficulty)
&& !"hard".equalsIgnoreCase(difficulty))
throw new XmlPullParserException("Invalidly formatted file");
} else if ("bin".equals(element)) { //Parse Bin element
double capacity = new Double(parser.getAttributeValue("","capacity"));
Bin bin = new Bin(capacity);
if ("easy".equalsIgnoreCase(difficulty)) easyBins.add(bin);
else if ("medium".equalsIgnoreCase(difficulty)) mediumBins.add(bin);
else if ("hard".equalsIgnoreCase(difficulty)) hardBins.add(bin);
else throw new XmlPullParserException("Invalidly formatted file");
} else if ("object".equals(element)) { //Parse BinObject element
double weight = new Double(parser.getAttributeValue("","weight"));
double value = new Double(parser.getAttributeValue("","value"));
String type = parser.getAttributeValue("","type");
BinObject obj = new BinObject(weight, value, type);
if ("easy".equalsIgnoreCase(difficulty)) easyObjects.add(obj);
else if ("medium".equalsIgnoreCase(difficulty)) mediumObjects.add(obj);
else if ("hard".equalsIgnoreCase(difficulty)) hardObjects.add(obj);
else throw new XmlPullParserException("Invalidly formatted file");
- } else if ("item".equals(element)) break;
+ }
}
event = parser.next();
}
} catch (Exception e) { //Invalidly formatted XML file
System.err.println("Problem parsing res/values/problems.xml - please check file format");
System.exit(-1);
} finally {
parser.close();
}
//TODO Calculate optimal solutions
}
}
| false | true | public BinPackingProblemFactory(Context context) {
//Initialize instance variables
easyBins = new ArrayList<Bin>();
mediumBins = new ArrayList<Bin>();
hardBins = new ArrayList<Bin>();
easyObjects = new ArrayList<BinObject>();
mediumObjects = new ArrayList<BinObject>();
hardObjects = new ArrayList<BinObject>();
easyOptSol = -1;
mediumOptSol = -1;
hardOptSol = -1;
//Parse problems.xml
XmlResourceParser parser = context.getResources().getXml(R.id.bin_packing);
try {
int event = parser.next();
while (!"item".equals(parser.getName()) &&
!"bin_packing".equals(parser.getAttributeValue("","name"))) event = parser.next();
while (event != XmlPullParser.END_DOCUMENT) {
String difficulty = "";
if (event == XmlPullParser.START_TAG) {
String element = parser.getName();
if ("problem".equals(element)) { //Parse problem difficulty
difficulty = parser.getAttributeValue("", "difficulty");
if (!"easy".equalsIgnoreCase(difficulty) && !"medium".equalsIgnoreCase(difficulty)
&& !"hard".equalsIgnoreCase(difficulty))
throw new XmlPullParserException("Invalidly formatted file");
} else if ("bin".equals(element)) { //Parse Bin element
double capacity = new Double(parser.getAttributeValue("","capacity"));
Bin bin = new Bin(capacity);
if ("easy".equalsIgnoreCase(difficulty)) easyBins.add(bin);
else if ("medium".equalsIgnoreCase(difficulty)) mediumBins.add(bin);
else if ("hard".equalsIgnoreCase(difficulty)) hardBins.add(bin);
else throw new XmlPullParserException("Invalidly formatted file");
} else if ("object".equals(element)) { //Parse BinObject element
double weight = new Double(parser.getAttributeValue("","weight"));
double value = new Double(parser.getAttributeValue("","value"));
String type = parser.getAttributeValue("","type");
BinObject obj = new BinObject(weight, value, type);
if ("easy".equalsIgnoreCase(difficulty)) easyObjects.add(obj);
else if ("medium".equalsIgnoreCase(difficulty)) mediumObjects.add(obj);
else if ("hard".equalsIgnoreCase(difficulty)) hardObjects.add(obj);
else throw new XmlPullParserException("Invalidly formatted file");
} else if ("item".equals(element)) break;
}
event = parser.next();
}
} catch (Exception e) { //Invalidly formatted XML file
System.err.println("Problem parsing res/values/problems.xml - please check file format");
System.exit(-1);
} finally {
parser.close();
}
//TODO Calculate optimal solutions
}
| public BinPackingProblemFactory(Context context) {
//Initialize instance variables
easyBins = new ArrayList<Bin>();
mediumBins = new ArrayList<Bin>();
hardBins = new ArrayList<Bin>();
easyObjects = new ArrayList<BinObject>();
mediumObjects = new ArrayList<BinObject>();
hardObjects = new ArrayList<BinObject>();
easyOptSol = -1;
mediumOptSol = -1;
hardOptSol = -1;
//Parse problems.xml
XmlResourceParser parser = context.getResources().getXml(R.id.bin_packing);
try {
int event = parser.next();
while (!(event == XmlPullParser.END_TAG && parser.getName().equalsIgnoreCase("item"))) {
String difficulty = "";
if (event == XmlPullParser.START_TAG) {
String element = parser.getName();
if ("problem".equals(element)) { //Parse problem difficulty
difficulty = parser.getAttributeValue("", "difficulty");
if (!"easy".equalsIgnoreCase(difficulty) && !"medium".equalsIgnoreCase(difficulty)
&& !"hard".equalsIgnoreCase(difficulty))
throw new XmlPullParserException("Invalidly formatted file");
} else if ("bin".equals(element)) { //Parse Bin element
double capacity = new Double(parser.getAttributeValue("","capacity"));
Bin bin = new Bin(capacity);
if ("easy".equalsIgnoreCase(difficulty)) easyBins.add(bin);
else if ("medium".equalsIgnoreCase(difficulty)) mediumBins.add(bin);
else if ("hard".equalsIgnoreCase(difficulty)) hardBins.add(bin);
else throw new XmlPullParserException("Invalidly formatted file");
} else if ("object".equals(element)) { //Parse BinObject element
double weight = new Double(parser.getAttributeValue("","weight"));
double value = new Double(parser.getAttributeValue("","value"));
String type = parser.getAttributeValue("","type");
BinObject obj = new BinObject(weight, value, type);
if ("easy".equalsIgnoreCase(difficulty)) easyObjects.add(obj);
else if ("medium".equalsIgnoreCase(difficulty)) mediumObjects.add(obj);
else if ("hard".equalsIgnoreCase(difficulty)) hardObjects.add(obj);
else throw new XmlPullParserException("Invalidly formatted file");
}
}
event = parser.next();
}
} catch (Exception e) { //Invalidly formatted XML file
System.err.println("Problem parsing res/values/problems.xml - please check file format");
System.exit(-1);
} finally {
parser.close();
}
//TODO Calculate optimal solutions
}
|
diff --git a/src/main/java/net/craftminecraft/bungee/bungeeyaml/BungeeYAML.java b/src/main/java/net/craftminecraft/bungee/bungeeyaml/BungeeYAML.java
index b030c3e..57c13aa 100644
--- a/src/main/java/net/craftminecraft/bungee/bungeeyaml/BungeeYAML.java
+++ b/src/main/java/net/craftminecraft/bungee/bungeeyaml/BungeeYAML.java
@@ -1,134 +1,135 @@
package net.craftminecraft.bungee.bungeeyaml;
import com.ning.http.client.Response;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import com.thebuzzmedia.sjxp.rule.IRule;
import com.thebuzzmedia.sjxp.rule.DefaultRule;
import com.thebuzzmedia.sjxp.rule.IRule.Type;
import com.thebuzzmedia.sjxp.XMLParser;
import net.craftminecraft.bungee.bungeeyaml.pluginapi.ConfigurablePlugin;
public class BungeeYAML extends ConfigurablePlugin {
private Metrics metrics;
private static final String updaterelurl = "http://teamcity.craftminecraft.net/guestAuth/app/rest/builds/?locator=pinned:true,buildType:bt7,sinceBuild:number:%d,count:1";
private static final String updatedevurl = "http://teamcity.craftminecraft.net/guestAuth/app/rest/builds/?locator=buildType:bt7,sinceBuild:number:%d,count:1";
private static final String getartifactrelurl = "http://teamcity.craftminecraft.net/guestAuth/repository/download/bt7/.lastPinned/teamcity-ivy.xml";
private static final String getartifactdevurl = "http://teamcity.craftminecraft.net/guestAuth/repository/download/bt7/.lastSuccessful/teamcity-ivy.xml";
private static final String downloadrelurl = "http://teamcity.craftminecraft.net/guestAuth/repository/download/bt7/.lastPinned/%s.jar";
private static final String downloaddevurl = "http://teamcity.craftminecraft.net/guestAuth/repository/download/bt7/.lastSuccessful/%s.jar";
private String buildnumber;
@SuppressWarnings("unchecked")
@Override
public void onLoading() {
// Set version
String[] version = this.getDescription().getVersion().split("-");
buildnumber = version[version.length-1];
// Save a copy of the default config.yml if one is not there
this.saveDefaultConfig();
// If we don't autoupdate, then GTFO.
if (!this.getConfig().getBoolean("autoupdate", true)) {
return;
}
try {
Response resp;
final boolean dev;
// Should we get a dev or a release build ?
switch (this.getConfig().getString("updatechannel", "rel")) {
case "development":
case "dev":
dev = true;
resp = this.getProxy().getHttpClient().prepareGet(String.format(updatedevurl, Integer.parseInt(buildnumber))).execute().get();
break;
default:
dev = false;
resp = this.getProxy().getHttpClient().prepareGet(String.format(updaterelurl, Integer.parseInt(buildnumber))).execute().get();
break;
}
IRule<BungeeYAML> versionrule = new DefaultRule<BungeeYAML>(Type.ATTRIBUTE, "/builds/build", "number") {
@Override
public void handleParsedAttribute(XMLParser<BungeeYAML> parser, int index, String value, BungeeYAML plugin) {
// We are looking for attribute called "number"
if (!getAttributeNames()[index].equals("number")) {
return;
}
try {
// If the attribute value is not the same, trigger "plugin.update" with correct URI.
if (!value.equals(plugin.buildnumber)) {
if (dev) {
String filename = plugin.getArtifactUrl(getartifactdevurl);
plugin.update(String.format(downloaddevurl,filename));
} else {
String filename = plugin.getArtifactUrl(getartifactrelurl);
plugin.update(String.format(downloadrelurl,filename));
}
// Updating once is enough...
parser.stop();
}
} catch (Exception ex) {plugin.getProxy().getLogger().log(Level.WARNING, "[BungeeYAML] Update of BungeeYAML failed.",ex);return;}
}
};
// Start the update process.
XMLParser<BungeeYAML> parser = new XMLParser<BungeeYAML>(versionrule);
parser.parse(resp.getResponseBodyAsStream(), this);
} catch (NumberFormatException ex) {this.getProxy().getLogger().log(Level.INFO, "[BungeeYAML] Using custom version of BungeeYAML. Will not autoupdate.");return;
- } catch (Exception ex) {this.getProxy().getLogger().log(Level.WARNING, "[BungeeYAML] Update of BungeeYAML failed.",ex);return;}
+ } catch (Exception ex) {this.getProxy().getLogger().log(Level.WARNING, "[BungeeYAML] Update of BungeeYAML failed.",ex);return;
+ } catch (ExceptionInInitializerError err) {this.getProxy().getLogger().log(Level.WARNING, "[BungeeYAML] Update of BungeeYAML failed.",err);return;}
}
@SuppressWarnings("unchecked")
private String getArtifactUrl(String url) throws Exception {
IRule<StringBuilder> artifactrule = new DefaultRule<StringBuilder>(Type.ATTRIBUTE, "/ivy-module/publications/artifact", "name") {
@Override
public void handleParsedAttribute(XMLParser<StringBuilder> parser, int index, String value, StringBuilder returnvalue) {
if (!getAttributeNames()[index].equals("name")) {
return;
}
returnvalue.append(value);
parser.stop();
}
};
StringBuilder returnvalue = new StringBuilder();
Response resp = this.getProxy().getHttpClient().prepareGet(url).execute().get();
XMLParser<StringBuilder> artifactparser = new XMLParser<>(artifactrule);
artifactparser.parse(resp.getResponseBodyAsStream(), returnvalue);
return returnvalue.toString();
}
private void update(String url) throws Exception {
Response resp = this.getProxy().getHttpClient().prepareGet(url).execute().get();
File bungeeyamlfile;
try {
bungeeyamlfile = this.getFile();
} catch (NoSuchMethodError ex) { // If we are running on a slightly older version of BungeeCord.
bungeeyamlfile = new File(this.getProxy().getPluginsFolder(), "BungeeYAML.jar"); // Should add a this.getFile();
}
FileOutputStream bungeeyamlstream = new FileOutputStream(bungeeyamlfile);
bungeeyamlstream.write(resp.getResponseBodyAsBytes());
bungeeyamlstream.close();
this.getProxy().getPluginManager().loadPlugin(bungeeyamlfile);
getProxy().getLogger().log(Level.INFO, "BungeeYAML has been auto-updated.");
}
public void onEnable() {
try {
metrics = new Metrics(this);
metrics.start();
} catch (IOException e) {
}
}
public void onDisable() {
}
}
| true | true | public void onLoading() {
// Set version
String[] version = this.getDescription().getVersion().split("-");
buildnumber = version[version.length-1];
// Save a copy of the default config.yml if one is not there
this.saveDefaultConfig();
// If we don't autoupdate, then GTFO.
if (!this.getConfig().getBoolean("autoupdate", true)) {
return;
}
try {
Response resp;
final boolean dev;
// Should we get a dev or a release build ?
switch (this.getConfig().getString("updatechannel", "rel")) {
case "development":
case "dev":
dev = true;
resp = this.getProxy().getHttpClient().prepareGet(String.format(updatedevurl, Integer.parseInt(buildnumber))).execute().get();
break;
default:
dev = false;
resp = this.getProxy().getHttpClient().prepareGet(String.format(updaterelurl, Integer.parseInt(buildnumber))).execute().get();
break;
}
IRule<BungeeYAML> versionrule = new DefaultRule<BungeeYAML>(Type.ATTRIBUTE, "/builds/build", "number") {
@Override
public void handleParsedAttribute(XMLParser<BungeeYAML> parser, int index, String value, BungeeYAML plugin) {
// We are looking for attribute called "number"
if (!getAttributeNames()[index].equals("number")) {
return;
}
try {
// If the attribute value is not the same, trigger "plugin.update" with correct URI.
if (!value.equals(plugin.buildnumber)) {
if (dev) {
String filename = plugin.getArtifactUrl(getartifactdevurl);
plugin.update(String.format(downloaddevurl,filename));
} else {
String filename = plugin.getArtifactUrl(getartifactrelurl);
plugin.update(String.format(downloadrelurl,filename));
}
// Updating once is enough...
parser.stop();
}
} catch (Exception ex) {plugin.getProxy().getLogger().log(Level.WARNING, "[BungeeYAML] Update of BungeeYAML failed.",ex);return;}
}
};
// Start the update process.
XMLParser<BungeeYAML> parser = new XMLParser<BungeeYAML>(versionrule);
parser.parse(resp.getResponseBodyAsStream(), this);
} catch (NumberFormatException ex) {this.getProxy().getLogger().log(Level.INFO, "[BungeeYAML] Using custom version of BungeeYAML. Will not autoupdate.");return;
} catch (Exception ex) {this.getProxy().getLogger().log(Level.WARNING, "[BungeeYAML] Update of BungeeYAML failed.",ex);return;}
}
| public void onLoading() {
// Set version
String[] version = this.getDescription().getVersion().split("-");
buildnumber = version[version.length-1];
// Save a copy of the default config.yml if one is not there
this.saveDefaultConfig();
// If we don't autoupdate, then GTFO.
if (!this.getConfig().getBoolean("autoupdate", true)) {
return;
}
try {
Response resp;
final boolean dev;
// Should we get a dev or a release build ?
switch (this.getConfig().getString("updatechannel", "rel")) {
case "development":
case "dev":
dev = true;
resp = this.getProxy().getHttpClient().prepareGet(String.format(updatedevurl, Integer.parseInt(buildnumber))).execute().get();
break;
default:
dev = false;
resp = this.getProxy().getHttpClient().prepareGet(String.format(updaterelurl, Integer.parseInt(buildnumber))).execute().get();
break;
}
IRule<BungeeYAML> versionrule = new DefaultRule<BungeeYAML>(Type.ATTRIBUTE, "/builds/build", "number") {
@Override
public void handleParsedAttribute(XMLParser<BungeeYAML> parser, int index, String value, BungeeYAML plugin) {
// We are looking for attribute called "number"
if (!getAttributeNames()[index].equals("number")) {
return;
}
try {
// If the attribute value is not the same, trigger "plugin.update" with correct URI.
if (!value.equals(plugin.buildnumber)) {
if (dev) {
String filename = plugin.getArtifactUrl(getartifactdevurl);
plugin.update(String.format(downloaddevurl,filename));
} else {
String filename = plugin.getArtifactUrl(getartifactrelurl);
plugin.update(String.format(downloadrelurl,filename));
}
// Updating once is enough...
parser.stop();
}
} catch (Exception ex) {plugin.getProxy().getLogger().log(Level.WARNING, "[BungeeYAML] Update of BungeeYAML failed.",ex);return;}
}
};
// Start the update process.
XMLParser<BungeeYAML> parser = new XMLParser<BungeeYAML>(versionrule);
parser.parse(resp.getResponseBodyAsStream(), this);
} catch (NumberFormatException ex) {this.getProxy().getLogger().log(Level.INFO, "[BungeeYAML] Using custom version of BungeeYAML. Will not autoupdate.");return;
} catch (Exception ex) {this.getProxy().getLogger().log(Level.WARNING, "[BungeeYAML] Update of BungeeYAML failed.",ex);return;
} catch (ExceptionInInitializerError err) {this.getProxy().getLogger().log(Level.WARNING, "[BungeeYAML] Update of BungeeYAML failed.",err);return;}
}
|
diff --git a/src/main/groovy/org/ajoberstar/gradle/git/tasks/GitAdd.java b/src/main/groovy/org/ajoberstar/gradle/git/tasks/GitAdd.java
index 8a49a09..4671feb 100644
--- a/src/main/groovy/org/ajoberstar/gradle/git/tasks/GitAdd.java
+++ b/src/main/groovy/org/ajoberstar/gradle/git/tasks/GitAdd.java
@@ -1,78 +1,78 @@
/*
* Copyright 2012-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ajoberstar.gradle.git.tasks;
import org.eclipse.jgit.api.AddCommand;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.api.errors.NoFilepatternException;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileVisitDetails;
import org.gradle.api.file.FileVisitor;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.TaskAction;
/**
* Task to add files to a Git repository's
* staging area.
* @since 0.1.0
*/
public class GitAdd extends GitSource {
private boolean ignoreUntracked = false;
/**
* Adds the selected files to the staging area.
*/
@TaskAction
void add() {
final AddCommand cmd = getGit().add();
cmd.setUpdate(isIgnoreUntracked());
getSource().visit(new FileVisitor() {
public void visitDir(FileVisitDetails arg0) {
- visitFile(arg0);
+ // visitFile(arg0);
}
public void visitFile(FileVisitDetails arg0) {
cmd.addFilepattern(arg0.getPath());
}
});
try {
cmd.call();
} catch (NoFilepatternException e) {
getLogger().info("No files included in the add command for task {}", getName());
} catch (GitAPIException e) {
throw new GradleException("Problem adding files to staging area.", e);
}
}
/**
* Gets whether untracked files should be ignored.
* @return whether untracked files should be ignored
*/
@Input
public boolean isIgnoreUntracked() {
return ignoreUntracked;
}
/**
* Sets whether untracked files should be ignored.
* @param ignoreUntracked whether untracked files should be ignored
*/
public void setIgnoreUntracked(boolean ignoreUntracked) {
this.ignoreUntracked = ignoreUntracked;
}
}
| true | true | void add() {
final AddCommand cmd = getGit().add();
cmd.setUpdate(isIgnoreUntracked());
getSource().visit(new FileVisitor() {
public void visitDir(FileVisitDetails arg0) {
visitFile(arg0);
}
public void visitFile(FileVisitDetails arg0) {
cmd.addFilepattern(arg0.getPath());
}
});
try {
cmd.call();
} catch (NoFilepatternException e) {
getLogger().info("No files included in the add command for task {}", getName());
} catch (GitAPIException e) {
throw new GradleException("Problem adding files to staging area.", e);
}
}
| void add() {
final AddCommand cmd = getGit().add();
cmd.setUpdate(isIgnoreUntracked());
getSource().visit(new FileVisitor() {
public void visitDir(FileVisitDetails arg0) {
// visitFile(arg0);
}
public void visitFile(FileVisitDetails arg0) {
cmd.addFilepattern(arg0.getPath());
}
});
try {
cmd.call();
} catch (NoFilepatternException e) {
getLogger().info("No files included in the add command for task {}", getName());
} catch (GitAPIException e) {
throw new GradleException("Problem adding files to staging area.", e);
}
}
|
diff --git a/src/com/paypal/core/ReflectionUtil.java b/src/com/paypal/core/ReflectionUtil.java
index 0c080b4..f072cd4 100644
--- a/src/com/paypal/core/ReflectionUtil.java
+++ b/src/com/paypal/core/ReflectionUtil.java
@@ -1,125 +1,130 @@
package com.paypal.core;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ReflectionUtil {
public static Map<String, String> decodeResponseObject(Object responseType, String prefix) {
Map<String, String> returnMap = new HashMap<String, String>();
Map<String, Object> rMap = ReflectionUtil.generateMapFromResponse(responseType, "");
if(rMap != null && rMap.size() > 0) {
for (String key : rMap.keySet()) {
returnMap.put(key, rMap.get(key).toString());
}
}
return returnMap;
}
public static Map<String, Object> generateMapFromResponse(Object responseType,
String prefix) {
if (responseType == null) {
return null;
}
Map<String, Object> responseMap = new HashMap<String, Object>();
// To check return types
Map<String, Object> returnMap;
Object returnObject;
try {
Class klazz = responseType.getClass();
Method[] methods = klazz.getMethods();
Package packageName;
String propertyName;
AccessibleObject.setAccessible(methods, true);
for (Method m : methods) {
if (m.getName().startsWith("get")
&& !m.getName().equalsIgnoreCase("getClass")) {
packageName = m.getReturnType().getPackage();
try {
if (!prefix.isEmpty()) {
propertyName = prefix + "."
+ m.getName().substring(3, 4).toLowerCase()
+ m.getName().substring(4);
} else {
propertyName = m.getName().substring(3, 4)
.toLowerCase()
+ m.getName().substring(4);
}
if (packageName != null) {
if (!packageName.getName().contains("com.paypal")) {
returnObject = m.invoke(responseType, null);
if (returnObject != null
&& List.class.isAssignableFrom(m
.getReturnType())) {
List listObj = (List) returnObject;
int i = 0;
for (Object o : listObj) {
- responseMap
- .putAll(generateMapFromResponse(
- o, propertyName + "(" + i
- + ")"));
+ if (o.getClass().getPackage().getName().contains("com.paypal")) {
+ responseMap
+ .putAll(generateMapFromResponse(
+ o, propertyName + "(" + i
+ + ")"));
+ } else {
+ responseMap.put(propertyName + "(" + i
+ + ")", o);
+ }
i++;
}
} else if (returnObject != null) {
if(responseType.getClass().getSimpleName().equalsIgnoreCase("ErrorParameter") &&
propertyName.endsWith("value")) {
propertyName = propertyName.substring(0, propertyName.lastIndexOf("."));
}
responseMap.put(propertyName, returnObject);
}
} else {
returnObject = m.invoke(responseType, null);
if (returnObject != null
&& m.getReturnType().isEnum()) {
responseMap
.put(propertyName,
returnObject
.getClass()
.getMethod(
"getValue",
null)
.invoke(returnObject,
null));
} else if (returnObject != null) {
returnMap = generateMapFromResponse(
returnObject, propertyName);
if (returnMap != null
&& returnMap.size() > 0) {
responseMap.putAll(returnMap);
}
}
}
} else {
responseMap.put(propertyName,
m.invoke(klazz.newInstance(), null));
}
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return responseMap;
}
}
| true | true | public static Map<String, Object> generateMapFromResponse(Object responseType,
String prefix) {
if (responseType == null) {
return null;
}
Map<String, Object> responseMap = new HashMap<String, Object>();
// To check return types
Map<String, Object> returnMap;
Object returnObject;
try {
Class klazz = responseType.getClass();
Method[] methods = klazz.getMethods();
Package packageName;
String propertyName;
AccessibleObject.setAccessible(methods, true);
for (Method m : methods) {
if (m.getName().startsWith("get")
&& !m.getName().equalsIgnoreCase("getClass")) {
packageName = m.getReturnType().getPackage();
try {
if (!prefix.isEmpty()) {
propertyName = prefix + "."
+ m.getName().substring(3, 4).toLowerCase()
+ m.getName().substring(4);
} else {
propertyName = m.getName().substring(3, 4)
.toLowerCase()
+ m.getName().substring(4);
}
if (packageName != null) {
if (!packageName.getName().contains("com.paypal")) {
returnObject = m.invoke(responseType, null);
if (returnObject != null
&& List.class.isAssignableFrom(m
.getReturnType())) {
List listObj = (List) returnObject;
int i = 0;
for (Object o : listObj) {
responseMap
.putAll(generateMapFromResponse(
o, propertyName + "(" + i
+ ")"));
i++;
}
} else if (returnObject != null) {
if(responseType.getClass().getSimpleName().equalsIgnoreCase("ErrorParameter") &&
propertyName.endsWith("value")) {
propertyName = propertyName.substring(0, propertyName.lastIndexOf("."));
}
responseMap.put(propertyName, returnObject);
}
} else {
returnObject = m.invoke(responseType, null);
if (returnObject != null
&& m.getReturnType().isEnum()) {
responseMap
.put(propertyName,
returnObject
.getClass()
.getMethod(
"getValue",
null)
.invoke(returnObject,
null));
} else if (returnObject != null) {
returnMap = generateMapFromResponse(
returnObject, propertyName);
if (returnMap != null
&& returnMap.size() > 0) {
responseMap.putAll(returnMap);
}
}
}
} else {
responseMap.put(propertyName,
m.invoke(klazz.newInstance(), null));
}
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return responseMap;
}
| public static Map<String, Object> generateMapFromResponse(Object responseType,
String prefix) {
if (responseType == null) {
return null;
}
Map<String, Object> responseMap = new HashMap<String, Object>();
// To check return types
Map<String, Object> returnMap;
Object returnObject;
try {
Class klazz = responseType.getClass();
Method[] methods = klazz.getMethods();
Package packageName;
String propertyName;
AccessibleObject.setAccessible(methods, true);
for (Method m : methods) {
if (m.getName().startsWith("get")
&& !m.getName().equalsIgnoreCase("getClass")) {
packageName = m.getReturnType().getPackage();
try {
if (!prefix.isEmpty()) {
propertyName = prefix + "."
+ m.getName().substring(3, 4).toLowerCase()
+ m.getName().substring(4);
} else {
propertyName = m.getName().substring(3, 4)
.toLowerCase()
+ m.getName().substring(4);
}
if (packageName != null) {
if (!packageName.getName().contains("com.paypal")) {
returnObject = m.invoke(responseType, null);
if (returnObject != null
&& List.class.isAssignableFrom(m
.getReturnType())) {
List listObj = (List) returnObject;
int i = 0;
for (Object o : listObj) {
if (o.getClass().getPackage().getName().contains("com.paypal")) {
responseMap
.putAll(generateMapFromResponse(
o, propertyName + "(" + i
+ ")"));
} else {
responseMap.put(propertyName + "(" + i
+ ")", o);
}
i++;
}
} else if (returnObject != null) {
if(responseType.getClass().getSimpleName().equalsIgnoreCase("ErrorParameter") &&
propertyName.endsWith("value")) {
propertyName = propertyName.substring(0, propertyName.lastIndexOf("."));
}
responseMap.put(propertyName, returnObject);
}
} else {
returnObject = m.invoke(responseType, null);
if (returnObject != null
&& m.getReturnType().isEnum()) {
responseMap
.put(propertyName,
returnObject
.getClass()
.getMethod(
"getValue",
null)
.invoke(returnObject,
null));
} else if (returnObject != null) {
returnMap = generateMapFromResponse(
returnObject, propertyName);
if (returnMap != null
&& returnMap.size() > 0) {
responseMap.putAll(returnMap);
}
}
}
} else {
responseMap.put(propertyName,
m.invoke(klazz.newInstance(), null));
}
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return responseMap;
}
|
diff --git a/nfctools-ndef/src/main/java/org/nfctools/ndef/unknown/UnknownRecordDecoder.java b/nfctools-ndef/src/main/java/org/nfctools/ndef/unknown/UnknownRecordDecoder.java
index a2e4c98..b79d364 100644
--- a/nfctools-ndef/src/main/java/org/nfctools/ndef/unknown/UnknownRecordDecoder.java
+++ b/nfctools-ndef/src/main/java/org/nfctools/ndef/unknown/UnknownRecordDecoder.java
@@ -1,58 +1,58 @@
/**
* Copyright 2011 Adrian Stabiszewski, [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.nfctools.ndef.unknown;
import org.nfctools.ndef.NdefConstants;
import org.nfctools.ndef.NdefMessageDecoder;
import org.nfctools.ndef.NdefRecord;
import org.nfctools.ndef.wkt.decoder.AbstractRecordDecoder;
/**
*
* @author Thomas Rorvik Skjolberg ([email protected])
*
*/
public class UnknownRecordDecoder extends AbstractRecordDecoder<UnknownRecord> {
public UnknownRecordDecoder() {
super(NdefConstants.TNF_UNKNOWN);
}
@Override
protected UnknownRecord createRecord(NdefRecord ndefRecord, NdefMessageDecoder messageDecoder) {
/**
The value 0x05 (Unknown) SHOULD be used to indicate that the type of the payload is
unknown. This is similar to the �application/octet-stream� media type defined by MIME [RFC
2046]. When used, the TYPE_LENGTH field MUST be zero and thus the TYPE field is omitted
from the NDEF record. Regarding implementation, it is RECOMMENDED that an NDEF parser
receiving an NDEF record of this type, without further context to its use, provides a mechanism
for storing but not processing the payload (see section 4.2).
*/
// check that type is zero length
byte[] type = ndefRecord.getType();
if(type != null && type.length > 0) {
- throw new IllegalArgumentException("Record type expected");
+ throw new IllegalArgumentException("Record type not expected");
}
return new UnknownRecord(ndefRecord.getPayload());
}
}
| true | true | protected UnknownRecord createRecord(NdefRecord ndefRecord, NdefMessageDecoder messageDecoder) {
/**
The value 0x05 (Unknown) SHOULD be used to indicate that the type of the payload is
unknown. This is similar to the �application/octet-stream� media type defined by MIME [RFC
2046]. When used, the TYPE_LENGTH field MUST be zero and thus the TYPE field is omitted
from the NDEF record. Regarding implementation, it is RECOMMENDED that an NDEF parser
receiving an NDEF record of this type, without further context to its use, provides a mechanism
for storing but not processing the payload (see section 4.2).
*/
// check that type is zero length
byte[] type = ndefRecord.getType();
if(type != null && type.length > 0) {
throw new IllegalArgumentException("Record type expected");
}
return new UnknownRecord(ndefRecord.getPayload());
}
| protected UnknownRecord createRecord(NdefRecord ndefRecord, NdefMessageDecoder messageDecoder) {
/**
The value 0x05 (Unknown) SHOULD be used to indicate that the type of the payload is
unknown. This is similar to the �application/octet-stream� media type defined by MIME [RFC
2046]. When used, the TYPE_LENGTH field MUST be zero and thus the TYPE field is omitted
from the NDEF record. Regarding implementation, it is RECOMMENDED that an NDEF parser
receiving an NDEF record of this type, without further context to its use, provides a mechanism
for storing but not processing the payload (see section 4.2).
*/
// check that type is zero length
byte[] type = ndefRecord.getType();
if(type != null && type.length > 0) {
throw new IllegalArgumentException("Record type not expected");
}
return new UnknownRecord(ndefRecord.getPayload());
}
|
diff --git a/PlayerSDK/src/com/kaltura/playersdk/PlayerViewController.java b/PlayerSDK/src/com/kaltura/playersdk/PlayerViewController.java
index 2a790868..a40de755 100644
--- a/PlayerSDK/src/com/kaltura/playersdk/PlayerViewController.java
+++ b/PlayerSDK/src/com/kaltura/playersdk/PlayerViewController.java
@@ -1,670 +1,670 @@
package com.kaltura.playersdk;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.BounceInterpolator;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RelativeLayout;
import com.google.android.gms.cast.CastDevice;
import com.kaltura.playersdk.chromecast.CastPlayer;
import com.kaltura.playersdk.chromecast.ChromecastHandler;
import com.kaltura.playersdk.events.KPlayerEventListener;
import com.kaltura.playersdk.events.KPlayerJsCallbackReadyListener;
import com.kaltura.playersdk.events.OnCastDeviceChangeListener;
import com.kaltura.playersdk.events.OnCastRouteDetectedListener;
import com.kaltura.playersdk.events.OnPlayerStateChangeListener;
import com.kaltura.playersdk.events.OnPlayheadUpdateListener;
import com.kaltura.playersdk.events.OnProgressListener;
import com.kaltura.playersdk.events.OnToggleFullScreenListener;
import com.kaltura.playersdk.types.PlayerStates;
import com.kaltura.playersdk.widevine.WidevineHandler;
/**
* Created by michalradwantzor on 9/24/13.
*/
public class PlayerViewController extends RelativeLayout {
public static String TAG = "PlayerViewController";
public static String DEFAULT_HOST = "http://cdnbakmi.kaltura.com";
public static String DEFAULT_HTML5_URL = "/html5/html5lib/v2.1.1/mwEmbedFrame.php";
public static String DEFAULT_PLAYER_ID = "21384602";
private VideoPlayerInterface mVideoInterface;
private PlayerView mPlayerView;
private WebView mWebView;
private double mCurSec;
private Activity mActivity;
private double mDuration = 0;
private OnToggleFullScreenListener mFSListener;
private HashMap<String, ArrayList<KPlayerEventListener>> mKplayerEventsMap = new HashMap<String, ArrayList<KPlayerEventListener>>();
private HashMap<String, KPlayerEventListener> mKplayerEvaluatedMap = new HashMap<String, KPlayerEventListener>();
private KPlayerJsCallbackReadyListener mJsReadyListener;
public String host = DEFAULT_HOST;
public String html5Url = DEFAULT_HTML5_URL;
public String playerId = DEFAULT_PLAYER_ID;
private String mVideoUrl;
private String mVideoTitle = "";
private String mThumbUrl ="";
private PlayerStates mState = PlayerStates.START;
public PlayerViewController(final Context context) {
super(context);
// Get a handler that can be used to post to the main thread
Handler mainHandler = new Handler(context.getMainLooper());
Runnable myRunnable = new Runnable() {
@Override
public void run() {
if ( !ChromecastHandler.initialized )
ChromecastHandler.initialize(context, new OnCastDeviceChangeListener() {
@Override
public void onCastDeviceChange(CastDevice oldDevice, CastDevice newDevice) {
if ( ChromecastHandler.selectedDevice != null ) {
notifyKPlayer("trigger", new String[] { "chromecastDeviceConnected" });
} else {
notifyKPlayer("trigger", new String[] { "chromecastDeviceDisConnected" });
}
createPlayerInstance();
}
},
new OnCastRouteDetectedListener(){
@Override
public void onCastRouteDetected() {
setChromecastVisiblity();
}
});
}
};
mainHandler.post(myRunnable);
}
public PlayerViewController(Context context, AttributeSet attrs) {
super(context, attrs);
}
public PlayerViewController(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
}
public void setOnFullScreenListener(OnToggleFullScreenListener listener) {
mFSListener = listener;
}
public void setPlayerViewDimensions(int width, int height, int xPadding, int yPadding) {
setPadding(xPadding, yPadding, 0, 0);
setPlayerViewDimensions( width+xPadding, height+yPadding);
}
public void setPlayerViewDimensions(int width, int height) {
ViewGroup.LayoutParams lp = getLayoutParams();
if ( lp == null ) {
lp = new ViewGroup.LayoutParams( width, height );
} else {
lp.width = width;
lp.height = height;
}
this.setLayoutParams(lp);
if (mWebView != null) {
ViewGroup.LayoutParams wvlp = mWebView.getLayoutParams();
wvlp.width = width;
wvlp.height = height;
updateViewLayout(mWebView, wvlp);
}
if ( mPlayerView != null ) {
LayoutParams plp = (LayoutParams) mPlayerView.getLayoutParams();
plp.width = width;
plp.height = height;
updateViewLayout(mPlayerView, plp);
}
invalidate();
}
private void setChromecastVisiblity() {
if ( ChromecastHandler.routeInfos.size() > 0 ) {
setKDPAttribute("chromecast", "visible", true);
} else {
setKDPAttribute("chromecast", "visible", false);
}
}
/**
* Build player URL and load it to player view
* @param partnerId partner ID
* @param entryId entry ID
* @param activity bounding activity
*/
public void addComponents(String partnerId, String entryId, Activity activity) {
String iframeUrl = host + html5Url + "?wid=_" + partnerId + "&uiconf_id=" + playerId + "&entry_id=" + entryId;
addComponents( iframeUrl, activity );
}
/**
* load given url to the player view
*
* @param iframeUrl
* url to payer
* @param activity
* bounding activity
*/
public void addComponents(String iframeUrl, Activity activity) {
mActivity = activity;
mCurSec = 0;
ViewGroup.LayoutParams currLP = getLayoutParams();
mPlayerView = new PlayerView(mActivity);
super.addView(mPlayerView, currLP);
mVideoInterface = mPlayerView;
setPlayerListeners();
createPlayerInstance();
LayoutParams wvLp = new LayoutParams(currLP.width, currLP.height);
mWebView = new WebView(mActivity);
this.addView(mWebView, wvLp);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new CustomWebViewClient());
mWebView.setWebChromeClient(new WebChromeClient());
mWebView.getSettings().setUserAgentString(
mWebView.getSettings().getUserAgentString()
+ " kalturaNativeCordovaPlayer");
if (Build.VERSION.SDK_INT >= 11) {
mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
mWebView.loadUrl(iframeUrl);
mWebView.setBackgroundColor(0);
}
/**
* create PlayerView / CastPlayer instance according to cast status
*/
private void createPlayerInstance() {
if ( mVideoInterface != null ) {
mVideoInterface.removePlayheadUpdateListener();
if ( mVideoInterface instanceof CastPlayer )
mVideoInterface.stop();
}
if ( ChromecastHandler.selectedDevice != null ) {
mVideoInterface = new CastPlayer(getContext(), mVideoTitle, null, null, mThumbUrl, mVideoUrl);
} else {
mVideoInterface = mPlayerView;
}
mVideoInterface.setStartingPoint( (int) (mCurSec * 1000) );
setPlayerListeners();
}
/**
* slides with animation according the given values
*
* @param x
* x offset to slide
* @param duration
* animation time in milliseconds
*/
public void slideView(int x, int duration) {
this.animate().xBy(x).setDuration(duration)
.setInterpolator(new BounceInterpolator());
}
public void destroy() {
this.stop();
}
// /////////////////////////////////////////////////////////////////////////////////////////////
// VideoPlayerInterface methods
// /////////////////////////////////////////////////////////////////////////////////////////////
public boolean isPlaying() {
return (mVideoInterface != null && mVideoInterface.isPlaying());
}
/**
*
* @return duration in seconds
*/
public double getDuration() {
double duration = 0;
if (mVideoInterface != null)
duration = mVideoInterface.getDuration() / 1000;
return duration;
}
public String getVideoUrl() {
String url = null;
if (mVideoInterface != null)
url = mVideoInterface.getVideoUrl();
return url;
}
public void play() {
if (mVideoInterface != null) {
mVideoInterface.play();
}
}
public void pause() {
if (mVideoInterface != null) {
mVideoInterface.pause();
}
}
public void stop() {
if (mVideoInterface != null) {
mVideoInterface.stop();
}
}
public void seek(int msec) {
if (mVideoInterface != null) {
mVideoInterface.seek(msec);
}
}
// /////////////////////////////////////////////////////////////////////////////////////////////
// Kaltura Player external API
// /////////////////////////////////////////////////////////////////////////////////////////////
public void registerJsCallbackReady( KPlayerJsCallbackReadyListener listener ) {
mJsReadyListener = listener;
}
public void sendNotification(String noteName, JSONObject noteBody) {
notifyKPlayer("sendNotification", new String[] { noteName, noteBody.toString() });
}
public void addKPlayerEventListener(String eventName,
KPlayerEventListener listener) {
ArrayList<KPlayerEventListener> listeners = mKplayerEventsMap
.get(eventName);
boolean isNewEvent = false;
if ( listeners == null ) {
listeners = new ArrayList<KPlayerEventListener>();
}
if ( listeners.size() == 0 ) {
isNewEvent = true;
}
listeners.add(listener);
mKplayerEventsMap.put(eventName, listeners);
if ( isNewEvent )
notifyKPlayer("addJsListener", new String[] { eventName });
}
public void removeKPlayerEventListener(String eventName,String callbackName) {
ArrayList<KPlayerEventListener> listeners = mKplayerEventsMap.get(eventName);
if (listeners != null) {
for (int i = 0; i < listeners.size(); i++) {
if ( listeners.get(i).getCallbackName().equals( callbackName )) {
listeners.remove(i);
break;
}
}
if ( listeners.size() == 0 )
notifyKPlayer( "removeJsListener", new String[] { eventName });
}
}
public void setKDPAttribute(String hostName, String propName, Object value) {
notifyKPlayer("setKDPAttribute", new Object[] { hostName, propName, value });
}
public void asyncEvaluate(String expression, KPlayerEventListener listener) {
String callbackName = listener.getCallbackName();
mKplayerEvaluatedMap.put(callbackName, listener);
notifyKPlayer("asyncEvaluate", new String[] { expression, callbackName });
}
// /////////////////////////////////////////////////////////////////////////////////////////////
/**
* call js function on NativeBridge.videoPlayer
*
* @param action
* function name
* @param eventValues
* function arguments
*/
private void notifyKPlayer(final String action, final Object[] eventValues) {
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
String values = "";
if (eventValues != null) {
for ( int i=0; i< eventValues.length; i++ ) {
if ( eventValues[i] instanceof String ) {
values += "'" + eventValues[i] + "'";
} else {
values += eventValues[i].toString();
}
if ( i < eventValues.length - 1 ) {
values += ", ";
}
}
// values = TextUtils.join("', '", eventValues);
}
mWebView.loadUrl("javascript:NativeBridge.videoPlayer."
+ action + "(" + values + ");");
}
});
}
private void setPlayerListeners() {
// notify player state change events
mVideoInterface
.registerPlayerStateChange(new OnPlayerStateChangeListener() {
@Override
public boolean onStateChanged(PlayerStates state) {
if ( state == PlayerStates.START ) {
mDuration = getDuration();
notifyKPlayer("trigger", new Object[]{ "durationchange", mDuration });
notifyKPlayer("trigger", new Object[]{ "loadedmetadata" });
}
if ( state != mState ) {
mState = state;
String stateName = "";
switch (state) {
case PLAY:
stateName = "play";
break;
case PAUSE:
stateName = "pause";
break;
case END:
stateName = "ended";
break;
case SEEKING:
stateName = "seeking";
break;
case SEEKED:
stateName = "seeked";
break;
default:
break;
}
if (stateName != "") {
final String eventName = stateName;
notifyKPlayer("trigger", new String[] { eventName });
}
}
return false;
}
});
// trigger timeupdate events
final Runnable runUpdatePlayehead = new Runnable() {
@Override
public void run() {
notifyKPlayer( "trigger", new Object[]{ "timeupdate", mCurSec});
}
};
// listens for playhead update
mVideoInterface.registerPlayheadUpdate(new OnPlayheadUpdateListener() {
@Override
public void onPlayheadUpdated(int msec) {
double curSec = msec / 1000.0;
if ( curSec <= mDuration ) {
mCurSec = curSec;
mActivity.runOnUiThread(runUpdatePlayehead);
}
}
});
// listens for progress events and notify javascript
mVideoInterface.registerProgressUpdate(new OnProgressListener() {
@Override
public void onProgressUpdate(int progress) {
double percent = progress / 100.0;
notifyKPlayer( "trigger", new Object[]{ "progress", percent});
}
});
}
private class CustomWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url != null) {
- Log.d(TAG, "--------------------url to load: " + url);
+ Log.d(TAG, "shouldOverrideUrlLoading::url to load: " + url);
if ( url.startsWith("js-frame:") ) {
String[] arr = url.split(":");
if (arr != null && arr.length > 1) {
String action = arr[1];
if (action.equals("notifyJsReady")) {
if ( mJsReadyListener != null ) {
mJsReadyListener.jsCallbackReady();
}
}
else if (action.equals("notifyLayoutReady")) {
setChromecastVisiblity();
return true;
}
else if (action.equals("play")) {
mVideoInterface.play();
return true;
}
else if (action.equals("pause")) {
if (mVideoInterface.canPause()) {
mVideoInterface.pause();
return true;
}
}
else if (action.equals("toggleFullscreen")) {
if (mFSListener != null) {
mFSListener.onToggleFullScreen();
return true;
}
}
else if ( action.equals("showChromecastDeviceList") ) {
if(!mActivity.isFinishing())
{
//workaround to fix weird exception sometimes
try {
ChromecastHandler.showCCDialog(getContext());
} catch (Exception e ) {
Log.d(TAG, "failed to open cc list");
}
}
}
// action with params
else if (arr.length > 3) {
try {
String value = URLDecoder.decode(arr[3], "UTF-8");
if (value != null && value.length() > 2) {
if (action.equals("setAttribute")) {
String[] params = getStrippedString(value)
.split(",");
if (params != null && params.length > 1) {
if (params[0].equals("\"currentTime\"")) {
int seekTo = Math
.round(Float
.parseFloat(params[1]) * 1000);
mVideoInterface.seek(seekTo);
} else if (params[0].equals("\"src\"")) {
// remove " from the edges
mVideoUrl = getStrippedString(params[1]);
mVideoInterface.setVideoUrl(mVideoUrl);
asyncEvaluate("{mediaProxy.entry.name}", new KPlayerEventListener() {
@Override
public void onKPlayerEvent(
Object body) {
mVideoTitle = (String) body;
}
@Override
public String getCallbackName() {
return "getEntryName";
}
});
asyncEvaluate("{mediaProxy.entry.thumbnailUrl}", new KPlayerEventListener() {
@Override
public void onKPlayerEvent(
Object body) {
mThumbUrl = (String) body;
}
@Override
public String getCallbackName() {
return "getEntryThumb";
}
});
} else if (params[0]
.equals("\"wvServerKey\"")) {
String licenseUrl = getStrippedString(params[1]);
WidevineHandler.acquireRights(
mActivity,
mVideoInterface.getVideoUrl(),
licenseUrl);
}
}
} else if (action.equals("notifyKPlayerEvent")) {
return notifyKPlayerEvent(value, mKplayerEventsMap, false);
} else if (action.equals("notifyKPlayerEvaluated")) {
return notifyKPlayerEvent(value, mKplayerEvaluatedMap, true);
}
}
} catch (Exception e) {
Log.w(TAG, "action failed: " + action);
}
}
}
} else {
if (mVideoInterface.canPause()) {
mVideoInterface.pause();
mVideoInterface.setStartingPoint((int) (mCurSec * 1000));
}
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse( url ));
mActivity.startActivity(browserIntent);
return true;
}
}
return false;
}
/**
*
* @param input
* string
* @return given string without its first and last characters
*/
private String getStrippedString(String input) {
return input.substring(1, input.length() - 1);
}
/**
* Notify the matching listener that event has occured
*
* @param input
* String with event params
* @param hashMap
* data provider to look the listener in
* @param clearListeners
* whether to remove listeners after notifying them
* @return true if listener was noticed, else false
*/
private boolean notifyKPlayerEvent(String input,
HashMap hashMap,
boolean clearListeners) {
if (hashMap != null) {
String value = getStrippedString(input);
// //
// replace inner json "," delimiter so we can split with harming
// json objects
// value = value.replaceAll("([{][^}]+)(,)", "$1;");
// ///
value = value.replaceAll(("\\\\\""), "\"");
boolean isObject = true;
// can't split by "," since jsonString might have inner ","
String[] params = value.split("\\{");
// if parameter is not a json object, the delimiter is ","
if (params.length == 1) {
isObject = false;
params = value.split(",");
} else {
params[0] = params[0].substring(0, params[0].indexOf(","));
}
String key = getStrippedString(params[0]);
// parse object, if sent
Object bodyObj = null;
if (params.length > 1 && params[1] != "null") {
if (isObject) { // json string
String body = "{" + params[1] + "}";
try {
bodyObj = new JSONObject(body);
} catch (JSONException e) {
Log.w(TAG, "failed to parse object");
}
} else { // simple string
if ( params[1].startsWith("\"") )
bodyObj = getStrippedString(params[1]);
else
bodyObj = params[1];
}
}
Object mapValue = hashMap.get(key);
if ( mapValue instanceof KPlayerEventListener ) {
((KPlayerEventListener)mapValue).onKPlayerEvent(bodyObj);
}
else if ( mapValue instanceof ArrayList) {
ArrayList<KPlayerEventListener> listeners = (ArrayList)mapValue;
for (Iterator<KPlayerEventListener> i = listeners.iterator(); i
.hasNext();) {
i.next().onKPlayerEvent(bodyObj);
}
}
if (clearListeners) {
hashMap.remove(key);
}
return true;
}
return false;
}
}
}
| true | true | public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url != null) {
Log.d(TAG, "--------------------url to load: " + url);
if ( url.startsWith("js-frame:") ) {
String[] arr = url.split(":");
if (arr != null && arr.length > 1) {
String action = arr[1];
if (action.equals("notifyJsReady")) {
if ( mJsReadyListener != null ) {
mJsReadyListener.jsCallbackReady();
}
}
else if (action.equals("notifyLayoutReady")) {
setChromecastVisiblity();
return true;
}
else if (action.equals("play")) {
mVideoInterface.play();
return true;
}
else if (action.equals("pause")) {
if (mVideoInterface.canPause()) {
mVideoInterface.pause();
return true;
}
}
else if (action.equals("toggleFullscreen")) {
if (mFSListener != null) {
mFSListener.onToggleFullScreen();
return true;
}
}
else if ( action.equals("showChromecastDeviceList") ) {
if(!mActivity.isFinishing())
{
//workaround to fix weird exception sometimes
try {
ChromecastHandler.showCCDialog(getContext());
} catch (Exception e ) {
Log.d(TAG, "failed to open cc list");
}
}
}
// action with params
else if (arr.length > 3) {
try {
String value = URLDecoder.decode(arr[3], "UTF-8");
if (value != null && value.length() > 2) {
if (action.equals("setAttribute")) {
String[] params = getStrippedString(value)
.split(",");
if (params != null && params.length > 1) {
if (params[0].equals("\"currentTime\"")) {
int seekTo = Math
.round(Float
.parseFloat(params[1]) * 1000);
mVideoInterface.seek(seekTo);
} else if (params[0].equals("\"src\"")) {
// remove " from the edges
mVideoUrl = getStrippedString(params[1]);
mVideoInterface.setVideoUrl(mVideoUrl);
asyncEvaluate("{mediaProxy.entry.name}", new KPlayerEventListener() {
@Override
public void onKPlayerEvent(
Object body) {
mVideoTitle = (String) body;
}
@Override
public String getCallbackName() {
return "getEntryName";
}
});
asyncEvaluate("{mediaProxy.entry.thumbnailUrl}", new KPlayerEventListener() {
@Override
public void onKPlayerEvent(
Object body) {
mThumbUrl = (String) body;
}
@Override
public String getCallbackName() {
return "getEntryThumb";
}
});
} else if (params[0]
.equals("\"wvServerKey\"")) {
String licenseUrl = getStrippedString(params[1]);
WidevineHandler.acquireRights(
mActivity,
mVideoInterface.getVideoUrl(),
licenseUrl);
}
}
} else if (action.equals("notifyKPlayerEvent")) {
return notifyKPlayerEvent(value, mKplayerEventsMap, false);
} else if (action.equals("notifyKPlayerEvaluated")) {
return notifyKPlayerEvent(value, mKplayerEvaluatedMap, true);
}
}
} catch (Exception e) {
Log.w(TAG, "action failed: " + action);
}
}
}
} else {
if (mVideoInterface.canPause()) {
mVideoInterface.pause();
mVideoInterface.setStartingPoint((int) (mCurSec * 1000));
}
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse( url ));
mActivity.startActivity(browserIntent);
return true;
}
}
return false;
}
| public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url != null) {
Log.d(TAG, "shouldOverrideUrlLoading::url to load: " + url);
if ( url.startsWith("js-frame:") ) {
String[] arr = url.split(":");
if (arr != null && arr.length > 1) {
String action = arr[1];
if (action.equals("notifyJsReady")) {
if ( mJsReadyListener != null ) {
mJsReadyListener.jsCallbackReady();
}
}
else if (action.equals("notifyLayoutReady")) {
setChromecastVisiblity();
return true;
}
else if (action.equals("play")) {
mVideoInterface.play();
return true;
}
else if (action.equals("pause")) {
if (mVideoInterface.canPause()) {
mVideoInterface.pause();
return true;
}
}
else if (action.equals("toggleFullscreen")) {
if (mFSListener != null) {
mFSListener.onToggleFullScreen();
return true;
}
}
else if ( action.equals("showChromecastDeviceList") ) {
if(!mActivity.isFinishing())
{
//workaround to fix weird exception sometimes
try {
ChromecastHandler.showCCDialog(getContext());
} catch (Exception e ) {
Log.d(TAG, "failed to open cc list");
}
}
}
// action with params
else if (arr.length > 3) {
try {
String value = URLDecoder.decode(arr[3], "UTF-8");
if (value != null && value.length() > 2) {
if (action.equals("setAttribute")) {
String[] params = getStrippedString(value)
.split(",");
if (params != null && params.length > 1) {
if (params[0].equals("\"currentTime\"")) {
int seekTo = Math
.round(Float
.parseFloat(params[1]) * 1000);
mVideoInterface.seek(seekTo);
} else if (params[0].equals("\"src\"")) {
// remove " from the edges
mVideoUrl = getStrippedString(params[1]);
mVideoInterface.setVideoUrl(mVideoUrl);
asyncEvaluate("{mediaProxy.entry.name}", new KPlayerEventListener() {
@Override
public void onKPlayerEvent(
Object body) {
mVideoTitle = (String) body;
}
@Override
public String getCallbackName() {
return "getEntryName";
}
});
asyncEvaluate("{mediaProxy.entry.thumbnailUrl}", new KPlayerEventListener() {
@Override
public void onKPlayerEvent(
Object body) {
mThumbUrl = (String) body;
}
@Override
public String getCallbackName() {
return "getEntryThumb";
}
});
} else if (params[0]
.equals("\"wvServerKey\"")) {
String licenseUrl = getStrippedString(params[1]);
WidevineHandler.acquireRights(
mActivity,
mVideoInterface.getVideoUrl(),
licenseUrl);
}
}
} else if (action.equals("notifyKPlayerEvent")) {
return notifyKPlayerEvent(value, mKplayerEventsMap, false);
} else if (action.equals("notifyKPlayerEvaluated")) {
return notifyKPlayerEvent(value, mKplayerEvaluatedMap, true);
}
}
} catch (Exception e) {
Log.w(TAG, "action failed: " + action);
}
}
}
} else {
if (mVideoInterface.canPause()) {
mVideoInterface.pause();
mVideoInterface.setStartingPoint((int) (mCurSec * 1000));
}
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse( url ));
mActivity.startActivity(browserIntent);
return true;
}
}
return false;
}
|
diff --git a/src/play/modules/gtengineplugin/gt_integration/GTJavaBase1xImpl.java b/src/play/modules/gtengineplugin/gt_integration/GTJavaBase1xImpl.java
index cd99c2d..beec33c 100644
--- a/src/play/modules/gtengineplugin/gt_integration/GTJavaBase1xImpl.java
+++ b/src/play/modules/gtengineplugin/gt_integration/GTJavaBase1xImpl.java
@@ -1,96 +1,96 @@
package play.modules.gtengineplugin.gt_integration;
import org.apache.commons.lang.StringEscapeUtils;
import play.Play;
import play.cache.Cache;
import play.data.validation.Validation;
import play.i18n.Messages;
import play.mvc.Router;
import play.template2.GTGroovyBase;
import play.template2.GTJavaBase;
import play.template2.GTTemplateLocation;
import play.template2.exceptions.GTRuntimeException;
import play.template2.exceptions.GTTemplateNotFoundWithSourceInfo;
import play.templates.BaseTemplate;
import play.utils.HTML;
import java.util.Map;
public abstract class GTJavaBase1xImpl extends GTJavaBase {
public GTJavaBase1xImpl(Class<? extends GTGroovyBase> groovyClass, GTTemplateLocation templateLocation) {
super(groovyClass, templateLocation);
}
// add extra methods used when resolving actions
public String __reverseWithCheck_absolute_true(String action) {
return __reverseWithCheck(action, true);
}
public String __reverseWithCheck_absolute_false(String action) {
return __reverseWithCheck(action, false);
}
public static String __reverseWithCheck(String action, boolean absolute) {
return Router.reverseWithCheck(action, Play.getVirtualFile(action), absolute);
}
@Override
public boolean validationHasErrors() {
return Validation.hasErrors();
}
@Override
public boolean validationHasError(String key) {
return Validation.hasError( key );
}
@Override
protected String resolveMessage(Object key, Object[] args) {
return Messages.get(key, args);
}
@Override
public Class getRawDataClass() {
return BaseTemplate.RawData.class;
}
@Override
public String convertRawDataToString(Object rawData) {
return ((BaseTemplate.RawData)rawData).data;
}
@Override
public String escapeHTML(String s) {
return HTML.htmlEscape(s);
}
@Override
public String escapeXML(String s) {
return StringEscapeUtils.escapeXml(s);
}
@Override
public String escapeCsv(String s) {
return StringEscapeUtils.escapeCsv(s);
}
@Override
- public void internalRenderTemplate(Map<String, Object> args, boolean startingNewRendering) throws GTTemplateNotFoundWithSourceInfo, GTRuntimeException {
+ public void internalRenderTemplate(Map<String, Object> args, GTJavaBase callingTemplate) throws GTTemplateNotFoundWithSourceInfo, GTRuntimeException {
// make sure the old layoutData referees to the same in map-instance as what the new impl uses
BaseTemplate.layoutData.set( GTJavaBase.layoutData.get() );
- super.internalRenderTemplate(args, startingNewRendering);
+ super.internalRenderTemplate(args, callingTemplate);
}
@Override
public Object cacheGet(String key) {
return Cache.get(key);
}
@Override
public void cacheSet(String key, Object data, String duration) {
Cache.set(key, data, duration);
}
}
| false | true | public void internalRenderTemplate(Map<String, Object> args, boolean startingNewRendering) throws GTTemplateNotFoundWithSourceInfo, GTRuntimeException {
// make sure the old layoutData referees to the same in map-instance as what the new impl uses
BaseTemplate.layoutData.set( GTJavaBase.layoutData.get() );
super.internalRenderTemplate(args, startingNewRendering);
}
| public void internalRenderTemplate(Map<String, Object> args, GTJavaBase callingTemplate) throws GTTemplateNotFoundWithSourceInfo, GTRuntimeException {
// make sure the old layoutData referees to the same in map-instance as what the new impl uses
BaseTemplate.layoutData.set( GTJavaBase.layoutData.get() );
super.internalRenderTemplate(args, callingTemplate);
}
|
diff --git a/src/org/jetbrains/idea/plugin/gitbar/action/BasicProxyAction.java b/src/org/jetbrains/idea/plugin/gitbar/action/BasicProxyAction.java
index c8090cf..fb16d47 100644
--- a/src/org/jetbrains/idea/plugin/gitbar/action/BasicProxyAction.java
+++ b/src/org/jetbrains/idea/plugin/gitbar/action/BasicProxyAction.java
@@ -1,85 +1,85 @@
package org.jetbrains.idea.plugin.gitbar.action;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import org.jetbrains.idea.plugin.gitbar.GitBar;
import org.jetbrains.idea.plugin.gitbar.GitUtils;
import javax.swing.*;
/**
* basic proxy action
*
* @author [email protected]
*/
public abstract class BasicProxyAction extends AnAction {
/**
* constructor
*/
public BasicProxyAction() {
super();
}
/**
* constructor
*
* @param text action's text
*/
public BasicProxyAction(String text) {
super(text);
}
/**
* constructor
*
* @param text action text
* @param description action description
* @param icon action icon
*/
public BasicProxyAction(String text, String description, Icon icon) {
super(text, description, icon);
}
/**
* target action id
*
* @return target action id
*/
protected abstract String getActionId();
/**
* action perform
*
* @param actionEvent action event
*/
public void actionPerformed(AnActionEvent actionEvent) {
AnAction anaction = ActionManager.getInstance().getAction(getActionId());
if (anaction != null)
anaction.actionPerformed(actionEvent);
}
/**
* presentation update
*
* @param actionEvent action event
*/
public void update(AnActionEvent actionEvent) {
try {
AnAction anaction = ActionManager.getInstance().getAction(getActionId());
if (anaction != null)
anaction.beforeActionPerformedUpdate(actionEvent);
else {
Project project = actionEvent.getData(DataKeys.PROJECT);
- Messages.showMessageDialog(project, "Action not found: " + getActionId(), "SVN Bar error", Messages.getErrorIcon());
+ Messages.showMessageDialog(project, "Action not found: " + getActionId(), "Git Bar error", Messages.getErrorIcon());
}
}
catch (Exception e) {
e.printStackTrace();
}
Project project = GitUtils.getProject(actionEvent);
GitBar bar = GitUtils.getGitBar();
Presentation presentation = actionEvent.getPresentation();
presentation.setVisible(bar.isVisible(this, project) && (presentation.isEnabled()));
}
}
| true | true | public void update(AnActionEvent actionEvent) {
try {
AnAction anaction = ActionManager.getInstance().getAction(getActionId());
if (anaction != null)
anaction.beforeActionPerformedUpdate(actionEvent);
else {
Project project = actionEvent.getData(DataKeys.PROJECT);
Messages.showMessageDialog(project, "Action not found: " + getActionId(), "SVN Bar error", Messages.getErrorIcon());
}
}
catch (Exception e) {
e.printStackTrace();
}
Project project = GitUtils.getProject(actionEvent);
GitBar bar = GitUtils.getGitBar();
Presentation presentation = actionEvent.getPresentation();
presentation.setVisible(bar.isVisible(this, project) && (presentation.isEnabled()));
}
| public void update(AnActionEvent actionEvent) {
try {
AnAction anaction = ActionManager.getInstance().getAction(getActionId());
if (anaction != null)
anaction.beforeActionPerformedUpdate(actionEvent);
else {
Project project = actionEvent.getData(DataKeys.PROJECT);
Messages.showMessageDialog(project, "Action not found: " + getActionId(), "Git Bar error", Messages.getErrorIcon());
}
}
catch (Exception e) {
e.printStackTrace();
}
Project project = GitUtils.getProject(actionEvent);
GitBar bar = GitUtils.getGitBar();
Presentation presentation = actionEvent.getPresentation();
presentation.setVisible(bar.isVisible(this, project) && (presentation.isEnabled()));
}
|
diff --git a/src/main/java/org/unigram/docvalidator/validator/SentenceIterator.java b/src/main/java/org/unigram/docvalidator/validator/SentenceIterator.java
index 4663e6a3..5aab021d 100644
--- a/src/main/java/org/unigram/docvalidator/validator/SentenceIterator.java
+++ b/src/main/java/org/unigram/docvalidator/validator/SentenceIterator.java
@@ -1,120 +1,120 @@
package org.unigram.docvalidator.validator;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import org.unigram.docvalidator.store.FileContent;
import org.unigram.docvalidator.store.Paragraph;
import org.unigram.docvalidator.store.Sentence;
import org.unigram.docvalidator.store.Section;
import org.unigram.docvalidator.util.CharacterTable;
import org.unigram.docvalidator.util.ResultDistributor;
import org.unigram.docvalidator.util.ValidationError;
import org.unigram.docvalidator.util.Configuration;
import org.unigram.docvalidator.util.DocumentValidatorException;
import org.unigram.docvalidator.validator.sentence.CommaNumberValidator;
import org.unigram.docvalidator.validator.sentence.InvalidExpressionValidator;
import org.unigram.docvalidator.validator.sentence.InvalidCharacterValidator;
import org.unigram.docvalidator.validator.sentence.WordNumberValidator;
import org.unigram.docvalidator.validator.sentence.SentenceLengthValidator;
import org.unigram.docvalidator.validator.sentence.SpaceBegginingOfSentenceValidator;
import org.unigram.docvalidator.validator.sentence.SymbolWithSpaceValidator;
import org.unigram.docvalidator.validator.sentence.SuggestExpressionValidator;
/**
* Validator for input sentences. Sentence iterator calls appended
* SentenceValidators and check the input using the validators.
*/
public class SentenceIterator implements Validator {
/**
* constructor.
* @throws DocumentValidatorException
*/
public SentenceIterator() throws DocumentValidatorException {
this.lineValidators = new Vector<SentenceValidator>();
}
public List<ValidationError> check(FileContent file,
ResultDistributor distributor) {
List<ValidationError> errors = new ArrayList<ValidationError>();
for (Iterator<SentenceValidator> iterator =
this.lineValidators.iterator(); iterator.hasNext();) {
SentenceValidator validator = iterator.next();
for (Iterator<Section> sectionIterator =
file.getChilds(); sectionIterator.hasNext();) {
Section currentSection = sectionIterator.next();
checkSection(distributor, errors, validator,
currentSection, file.getFileName());
}
}
return errors;
}
public boolean loadConfiguration(Configuration conf,
CharacterTable charTable) throws DocumentValidatorException {
for (Iterator<Configuration> confIterator = conf.getChildren();
confIterator.hasNext();) {
Configuration currentConfiguration = confIterator.next();
String confName = currentConfiguration.getConfigurationName();
SentenceValidator validator = null;
if (confName.equals("SentenceLength")) {
validator = (SentenceValidator) new SentenceLengthValidator();
} else if (confName.equals("InvalidExpression")) {
validator = (SentenceValidator) new InvalidExpressionValidator();
} else if (confName.equals("SpaceAfterPeriod")) {
validator = (SentenceValidator) new SpaceBegginingOfSentenceValidator();
- } else if (confName.equals("MaxCommaNumber")) {
+ } else if (confName.equals("CommaNumber")) {
validator = (SentenceValidator) new CommaNumberValidator();
} else if (confName.equals("WordNumber")) {
validator = (SentenceValidator) new WordNumberValidator();
} else if (confName.equals("SuggestExpression")) {
validator = (SentenceValidator) new SuggestExpressionValidator();
} else if (confName.equals("InvalidCharacter")) {
validator = (SentenceValidator) new InvalidCharacterValidator();
} else if (confName.equals("SpaceWithSymbol")) {
validator = (SentenceValidator) new SymbolWithSpaceValidator();
} else {
throw new DocumentValidatorException(
"There is no validator like " + confName);
}
validator.initialize(currentConfiguration, charTable);
this.lineValidators.add(validator);
}
return true;
}
// @TODO reduce the number of parameters (need refactoring)
private void checkSection(ResultDistributor distributor,
List<ValidationError> errors, SentenceValidator validator,
Section currentSection, String fileName) {
for (Iterator<Paragraph> paraIterator =
currentSection.getParagraph(); paraIterator.hasNext();) {
Paragraph currentParagraph = paraIterator.next();
for (Iterator<Sentence> lineIterator =
currentParagraph.getChilds(); lineIterator.hasNext();) {
List<ValidationError> validationErrors =
validator.check(lineIterator.next());
for (Iterator<ValidationError> errorIterator =
validationErrors.iterator();
errorIterator.hasNext();) {
appendError(distributor, errors, fileName, errorIterator.next());
}
}
}
}
private void appendError(ResultDistributor distributor,
List<ValidationError> errors, String fileName, ValidationError e) {
if (e != null) {
//NOTE: fileName is not specified in validators to reduce the task of them
e.setFileName(fileName);
distributor.flushResult(e);
errors.add(e);
}
}
private Vector<SentenceValidator> lineValidators;
}
| true | true | public boolean loadConfiguration(Configuration conf,
CharacterTable charTable) throws DocumentValidatorException {
for (Iterator<Configuration> confIterator = conf.getChildren();
confIterator.hasNext();) {
Configuration currentConfiguration = confIterator.next();
String confName = currentConfiguration.getConfigurationName();
SentenceValidator validator = null;
if (confName.equals("SentenceLength")) {
validator = (SentenceValidator) new SentenceLengthValidator();
} else if (confName.equals("InvalidExpression")) {
validator = (SentenceValidator) new InvalidExpressionValidator();
} else if (confName.equals("SpaceAfterPeriod")) {
validator = (SentenceValidator) new SpaceBegginingOfSentenceValidator();
} else if (confName.equals("MaxCommaNumber")) {
validator = (SentenceValidator) new CommaNumberValidator();
} else if (confName.equals("WordNumber")) {
validator = (SentenceValidator) new WordNumberValidator();
} else if (confName.equals("SuggestExpression")) {
validator = (SentenceValidator) new SuggestExpressionValidator();
} else if (confName.equals("InvalidCharacter")) {
validator = (SentenceValidator) new InvalidCharacterValidator();
} else if (confName.equals("SpaceWithSymbol")) {
validator = (SentenceValidator) new SymbolWithSpaceValidator();
} else {
throw new DocumentValidatorException(
"There is no validator like " + confName);
}
validator.initialize(currentConfiguration, charTable);
this.lineValidators.add(validator);
}
return true;
}
| public boolean loadConfiguration(Configuration conf,
CharacterTable charTable) throws DocumentValidatorException {
for (Iterator<Configuration> confIterator = conf.getChildren();
confIterator.hasNext();) {
Configuration currentConfiguration = confIterator.next();
String confName = currentConfiguration.getConfigurationName();
SentenceValidator validator = null;
if (confName.equals("SentenceLength")) {
validator = (SentenceValidator) new SentenceLengthValidator();
} else if (confName.equals("InvalidExpression")) {
validator = (SentenceValidator) new InvalidExpressionValidator();
} else if (confName.equals("SpaceAfterPeriod")) {
validator = (SentenceValidator) new SpaceBegginingOfSentenceValidator();
} else if (confName.equals("CommaNumber")) {
validator = (SentenceValidator) new CommaNumberValidator();
} else if (confName.equals("WordNumber")) {
validator = (SentenceValidator) new WordNumberValidator();
} else if (confName.equals("SuggestExpression")) {
validator = (SentenceValidator) new SuggestExpressionValidator();
} else if (confName.equals("InvalidCharacter")) {
validator = (SentenceValidator) new InvalidCharacterValidator();
} else if (confName.equals("SpaceWithSymbol")) {
validator = (SentenceValidator) new SymbolWithSpaceValidator();
} else {
throw new DocumentValidatorException(
"There is no validator like " + confName);
}
validator.initialize(currentConfiguration, charTable);
this.lineValidators.add(validator);
}
return true;
}
|
diff --git a/src/labo_json/User.java b/src/labo_json/User.java
index 63f4dbc..6d5882e 100644
--- a/src/labo_json/User.java
+++ b/src/labo_json/User.java
@@ -1,68 +1,68 @@
package labo_json;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import com.google.gson.*;
public class User {
static ArrayList<User> list = new ArrayList<User>();
String name;
int followers;
int repos;
int gist;
String avatar;
public User(String name, int followers, int repos, int gist, String avatar){
this.name = name;
this.gist = gist;
this.followers = followers;
this.repos = repos;
this.avatar = avatar;
list.add(this);
}
public int score(){
return followers + repos + gist;
}
public static String list(){
ArrayList<Map> arrayOfSerializedObject = new ArrayList<Map>();
for(User user : ordonnerListe()){
arrayOfSerializedObject.add(user.toMap());
}
Gson gson = new GsonBuilder().setPrettyPrinting().create();
return gson.toJson(arrayOfSerializedObject);
}
public static ArrayList<User> ordonnerListe(){
ArrayList<User> liste = list;
Collections.sort(liste, new Comparator<User>(){
@Override
public int compare(User user1, User user2){
- return user1.score() - user2.score();
+ return user2.score() - user1.score();
}
});
return liste;
}
public String toJson(){
Gson gson = new GsonBuilder().setPrettyPrinting().create();
return gson.toJson(toMap());
}
public Map toMap(){
Map hash = new HashMap<String,String>();
hash.put("name", name);
hash.put("followers", followers);
hash.put("repos", repos);
hash.put("gist", gist);
hash.put("avatar", avatar);
hash.put("score", score());
return hash;
}
}
| true | true | public static ArrayList<User> ordonnerListe(){
ArrayList<User> liste = list;
Collections.sort(liste, new Comparator<User>(){
@Override
public int compare(User user1, User user2){
return user1.score() - user2.score();
}
});
return liste;
}
| public static ArrayList<User> ordonnerListe(){
ArrayList<User> liste = list;
Collections.sort(liste, new Comparator<User>(){
@Override
public int compare(User user1, User user2){
return user2.score() - user1.score();
}
});
return liste;
}
|
diff --git a/jxr/maven-jxr/maven-jxr-js/src/main/java/org/apache/maven/jxr/js/doc/GenerateHTMLDoc.java b/jxr/maven-jxr/maven-jxr-js/src/main/java/org/apache/maven/jxr/js/doc/GenerateHTMLDoc.java
index 03a3cee9d..16704b598 100644
--- a/jxr/maven-jxr/maven-jxr-js/src/main/java/org/apache/maven/jxr/js/doc/GenerateHTMLDoc.java
+++ b/jxr/maven-jxr/maven-jxr-js/src/main/java/org/apache/maven/jxr/js/doc/GenerateHTMLDoc.java
@@ -1,228 +1,228 @@
package org.apache.maven.jxr.js.doc;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.log4j.Logger;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
/**
* Class that mounts a Document in HTML as document
*
* @version $Id$
*/
public class GenerateHTMLDoc
{
/** Logger for this class */
private static final Logger log = Logger.getLogger( GenerateHTMLDoc.class );
private static FileOutputStream fos;
private static BufferedReader br;
private static String LINE_SEPARATOR = String.valueOf( (char) 13 ) + String.valueOf( (char) 10 );
private static String stringReader;
private static int functionCount = 0;
private static String functionName = "";
private static boolean parameterList = false;
private static boolean useList = false;
private boolean summary = true;
private boolean description = true;
public GenerateHTMLDoc( File fis, String destDir )
{
String nomeArquivo = fis.getName();
try
{
fos = new FileOutputStream( destDir + nomeArquivo.substring( 0, nomeArquivo.indexOf( "." ) ) + ".htm" );
br = new BufferedReader( new FileReader( fis ) );
}
catch ( FileNotFoundException fnfe )
{
log.error( "FileNotFoundException: " + fnfe.getMessage(), fnfe );
}
try
{
fos.write( ( "<html>" + LINE_SEPARATOR ).getBytes() );
fos.write( ( "<head>" + LINE_SEPARATOR ).getBytes() );
fos.write( ( "<style type='text/css'>" + LINE_SEPARATOR ).getBytes() );
fos.write( ( ".TableHeadingColor { background: #CCCCFF } /* Dark mauve */" + LINE_SEPARATOR )
.getBytes() );
fos.write( ( ".NavBarCell1 { background-color:#EEEEFF;}/* Light mauve */" + LINE_SEPARATOR ).getBytes() );
fos.write( ( "</style>" + LINE_SEPARATOR ).getBytes() );
fos
.write( ( "<TABLE WIDTH='100%'><TR><TD WIDTH='100%' CLASS='NavBarCell1'><H1>Javascript code documentation</H1></TD></TR></TABLE>" + LINE_SEPARATOR )
.getBytes() );
fos.write( ( "<title>Javascript code documentation</title>" + LINE_SEPARATOR ).getBytes() );
fos.write( ( "</head>" + LINE_SEPARATOR ).getBytes() );
fos.write( ( "<body>" + LINE_SEPARATOR ).getBytes() );
fos.write( ( "<H2>Filename: " + nomeArquivo + "</H2>" + LINE_SEPARATOR ).getBytes() );
fos.write( ( "<br>" + LINE_SEPARATOR ).getBytes() );
fos.write( ( "<br>" + LINE_SEPARATOR ).getBytes() );
fos.write( ( "<TABLE BORDER='1' CELLPADDING='3' CELLSPACING='0' WIDTH='100%'>" + LINE_SEPARATOR )
.getBytes() );
fos.write( ( "<TR CLASS='TableHeadingColor'>" + LINE_SEPARATOR ).getBytes() );
fos.write( ( "<TD ALIGN='left' colspan='2'><FONT SIZE='+2'>" + LINE_SEPARATOR ).getBytes() );
fos.write( ( "<B>Function Summary</B></FONT></TD>" + LINE_SEPARATOR ).getBytes() );
fos.write( ( "</TR>" + LINE_SEPARATOR ).getBytes() );
while ( br.ready() )
{
stringReader = br.readLine();
while ( summary && null != stringReader && stringReader.indexOf( "summary" ) == -1 )
{
stringReader = br.readLine();
}
summary = false;
if ( null != stringReader && stringReader.indexOf( "/**" ) != -1 )
{
fos.write( ( "<TR>" + LINE_SEPARATOR ).getBytes() );
fos.write( ( "<TD WIDTH='30%' BGCOLOR='#f3f3f3'><font face='Verdana'><b><span id='Function"
- + functionCount + "'></b></font></span></TD>" + LINE_SEPARATOR ).getBytes() );
+ + functionCount + "'></span></b></font></TD>" + LINE_SEPARATOR ).getBytes() );
fos.write( ( "<TD WIDTH='70%'>" + LINE_SEPARATOR ).getBytes() );
stringReader = br.readLine();
while ( null != stringReader && stringReader.indexOf( "*/" ) == -1 )
{
if ( stringReader.indexOf( "* @" ) != -1 )
{
if ( ( stringReader.indexOf( "author" ) == -1 ) )
{
if ( stringReader.indexOf( "param" ) != -1 )
{
if ( parameterList == false )
{
parameterList = true;
fos.write( "<font size='-1' face='Verdana'><b>Parameters: </b></font>"
.getBytes() );
fos.write( "<BR>".getBytes() );
}
fos.write( " ".getBytes() );
fos
.write( ( stringReader.substring( stringReader.indexOf( "* @param" ) + 9 ) + LINE_SEPARATOR )
.getBytes() );
}
else if ( stringReader.indexOf( "use" ) != -1 )
{
if ( useList == false )
{
useList = true;
fos.write( "<font size='-1' face='Verdana'><b>Uso: </b></font>".getBytes() );
fos.write( "<BR>".getBytes() );
}
fos.write( " ".getBytes() );
fos
.write( ( stringReader.substring( stringReader.indexOf( "* @use" ) + 7 ) + LINE_SEPARATOR )
.getBytes() );
}
else if ( stringReader.indexOf( "return" ) != -1 )
{
fos.write( "<font size='-1' face='Verdana'><b>Return type: </b></font>".getBytes() );
fos
.write( ( stringReader.substring( stringReader.indexOf( "* @return" ) + 10 ) + LINE_SEPARATOR )
.getBytes() );
}
fos.write( "<BR>".getBytes() );
}
}
else
{
if ( description )
{
description = false;
fos.write( "<font size='-1' face='Verdana'><b>Description: </b></font>".getBytes() );
}
else
fos.write( " ".getBytes() );
fos.write( ( stringReader.substring( stringReader.indexOf( "*" ) + 1 ) + LINE_SEPARATOR )
.getBytes() );
fos.write( "<BR>".getBytes() );
}
stringReader = br.readLine();
}
description = true;
parameterList = false;
useList = false;
while ( null != stringReader && stringReader.indexOf( "function" ) == -1 )
{
stringReader = br.readLine();
}
if ( stringReader.indexOf( "function" ) != -1 )
{
if ( stringReader.indexOf( "{" ) != -1 )
{
functionName = stringReader.substring( stringReader.indexOf( "function" ) + 9, stringReader
.indexOf( "{" ) );
}
else
{
functionName = stringReader.substring( stringReader.indexOf( "function" ) + 9 );
}
}
fos.write( ( "</TD>" + LINE_SEPARATOR ).getBytes() );
- fos.write( ( "<script>document.all.Function" + functionCount + ".innerText = '" + functionName
+ fos.write( ( "<script>document.all.Function" + functionCount + ".innerHTML = '" + functionName
+ "'; </script>" + LINE_SEPARATOR ).getBytes() );
functionCount++;
fos.write( ( "</TR>" + LINE_SEPARATOR ).getBytes() );
}
}
fos.write( ( "</TABLE>" + LINE_SEPARATOR ).getBytes() );
fos.write( "</br>".getBytes() );
fos.write( ( "<a href='javascript:history.back()'><font size='+1'>Back</font></a>" + LINE_SEPARATOR )
.getBytes() );
fos.write( "</body>".getBytes() );
fos.write( "</html>".getBytes() );
}
catch ( IOException ioe )
{
log.error( "IOException: " + ioe.getMessage(), ioe );
}
if ( log.isInfoEnabled() )
{
log.info( "Html generated with success!" );
}
}
public static void main( String args[] )
throws Exception
{
GenerateHTMLDoc main1 = new GenerateHTMLDoc( new File( args[0] ), args[1] );
}
}
| false | true | public GenerateHTMLDoc( File fis, String destDir )
{
String nomeArquivo = fis.getName();
try
{
fos = new FileOutputStream( destDir + nomeArquivo.substring( 0, nomeArquivo.indexOf( "." ) ) + ".htm" );
br = new BufferedReader( new FileReader( fis ) );
}
catch ( FileNotFoundException fnfe )
{
log.error( "FileNotFoundException: " + fnfe.getMessage(), fnfe );
}
try
{
fos.write( ( "<html>" + LINE_SEPARATOR ).getBytes() );
fos.write( ( "<head>" + LINE_SEPARATOR ).getBytes() );
fos.write( ( "<style type='text/css'>" + LINE_SEPARATOR ).getBytes() );
fos.write( ( ".TableHeadingColor { background: #CCCCFF } /* Dark mauve */" + LINE_SEPARATOR )
.getBytes() );
fos.write( ( ".NavBarCell1 { background-color:#EEEEFF;}/* Light mauve */" + LINE_SEPARATOR ).getBytes() );
fos.write( ( "</style>" + LINE_SEPARATOR ).getBytes() );
fos
.write( ( "<TABLE WIDTH='100%'><TR><TD WIDTH='100%' CLASS='NavBarCell1'><H1>Javascript code documentation</H1></TD></TR></TABLE>" + LINE_SEPARATOR )
.getBytes() );
fos.write( ( "<title>Javascript code documentation</title>" + LINE_SEPARATOR ).getBytes() );
fos.write( ( "</head>" + LINE_SEPARATOR ).getBytes() );
fos.write( ( "<body>" + LINE_SEPARATOR ).getBytes() );
fos.write( ( "<H2>Filename: " + nomeArquivo + "</H2>" + LINE_SEPARATOR ).getBytes() );
fos.write( ( "<br>" + LINE_SEPARATOR ).getBytes() );
fos.write( ( "<br>" + LINE_SEPARATOR ).getBytes() );
fos.write( ( "<TABLE BORDER='1' CELLPADDING='3' CELLSPACING='0' WIDTH='100%'>" + LINE_SEPARATOR )
.getBytes() );
fos.write( ( "<TR CLASS='TableHeadingColor'>" + LINE_SEPARATOR ).getBytes() );
fos.write( ( "<TD ALIGN='left' colspan='2'><FONT SIZE='+2'>" + LINE_SEPARATOR ).getBytes() );
fos.write( ( "<B>Function Summary</B></FONT></TD>" + LINE_SEPARATOR ).getBytes() );
fos.write( ( "</TR>" + LINE_SEPARATOR ).getBytes() );
while ( br.ready() )
{
stringReader = br.readLine();
while ( summary && null != stringReader && stringReader.indexOf( "summary" ) == -1 )
{
stringReader = br.readLine();
}
summary = false;
if ( null != stringReader && stringReader.indexOf( "/**" ) != -1 )
{
fos.write( ( "<TR>" + LINE_SEPARATOR ).getBytes() );
fos.write( ( "<TD WIDTH='30%' BGCOLOR='#f3f3f3'><font face='Verdana'><b><span id='Function"
+ functionCount + "'></b></font></span></TD>" + LINE_SEPARATOR ).getBytes() );
fos.write( ( "<TD WIDTH='70%'>" + LINE_SEPARATOR ).getBytes() );
stringReader = br.readLine();
while ( null != stringReader && stringReader.indexOf( "*/" ) == -1 )
{
if ( stringReader.indexOf( "* @" ) != -1 )
{
if ( ( stringReader.indexOf( "author" ) == -1 ) )
{
if ( stringReader.indexOf( "param" ) != -1 )
{
if ( parameterList == false )
{
parameterList = true;
fos.write( "<font size='-1' face='Verdana'><b>Parameters: </b></font>"
.getBytes() );
fos.write( "<BR>".getBytes() );
}
fos.write( " ".getBytes() );
fos
.write( ( stringReader.substring( stringReader.indexOf( "* @param" ) + 9 ) + LINE_SEPARATOR )
.getBytes() );
}
else if ( stringReader.indexOf( "use" ) != -1 )
{
if ( useList == false )
{
useList = true;
fos.write( "<font size='-1' face='Verdana'><b>Uso: </b></font>".getBytes() );
fos.write( "<BR>".getBytes() );
}
fos.write( " ".getBytes() );
fos
.write( ( stringReader.substring( stringReader.indexOf( "* @use" ) + 7 ) + LINE_SEPARATOR )
.getBytes() );
}
else if ( stringReader.indexOf( "return" ) != -1 )
{
fos.write( "<font size='-1' face='Verdana'><b>Return type: </b></font>".getBytes() );
fos
.write( ( stringReader.substring( stringReader.indexOf( "* @return" ) + 10 ) + LINE_SEPARATOR )
.getBytes() );
}
fos.write( "<BR>".getBytes() );
}
}
else
{
if ( description )
{
description = false;
fos.write( "<font size='-1' face='Verdana'><b>Description: </b></font>".getBytes() );
}
else
fos.write( " ".getBytes() );
fos.write( ( stringReader.substring( stringReader.indexOf( "*" ) + 1 ) + LINE_SEPARATOR )
.getBytes() );
fos.write( "<BR>".getBytes() );
}
stringReader = br.readLine();
}
description = true;
parameterList = false;
useList = false;
while ( null != stringReader && stringReader.indexOf( "function" ) == -1 )
{
stringReader = br.readLine();
}
if ( stringReader.indexOf( "function" ) != -1 )
{
if ( stringReader.indexOf( "{" ) != -1 )
{
functionName = stringReader.substring( stringReader.indexOf( "function" ) + 9, stringReader
.indexOf( "{" ) );
}
else
{
functionName = stringReader.substring( stringReader.indexOf( "function" ) + 9 );
}
}
fos.write( ( "</TD>" + LINE_SEPARATOR ).getBytes() );
fos.write( ( "<script>document.all.Function" + functionCount + ".innerText = '" + functionName
+ "'; </script>" + LINE_SEPARATOR ).getBytes() );
functionCount++;
fos.write( ( "</TR>" + LINE_SEPARATOR ).getBytes() );
}
}
fos.write( ( "</TABLE>" + LINE_SEPARATOR ).getBytes() );
fos.write( "</br>".getBytes() );
fos.write( ( "<a href='javascript:history.back()'><font size='+1'>Back</font></a>" + LINE_SEPARATOR )
.getBytes() );
fos.write( "</body>".getBytes() );
fos.write( "</html>".getBytes() );
}
catch ( IOException ioe )
{
log.error( "IOException: " + ioe.getMessage(), ioe );
}
if ( log.isInfoEnabled() )
{
log.info( "Html generated with success!" );
}
}
| public GenerateHTMLDoc( File fis, String destDir )
{
String nomeArquivo = fis.getName();
try
{
fos = new FileOutputStream( destDir + nomeArquivo.substring( 0, nomeArquivo.indexOf( "." ) ) + ".htm" );
br = new BufferedReader( new FileReader( fis ) );
}
catch ( FileNotFoundException fnfe )
{
log.error( "FileNotFoundException: " + fnfe.getMessage(), fnfe );
}
try
{
fos.write( ( "<html>" + LINE_SEPARATOR ).getBytes() );
fos.write( ( "<head>" + LINE_SEPARATOR ).getBytes() );
fos.write( ( "<style type='text/css'>" + LINE_SEPARATOR ).getBytes() );
fos.write( ( ".TableHeadingColor { background: #CCCCFF } /* Dark mauve */" + LINE_SEPARATOR )
.getBytes() );
fos.write( ( ".NavBarCell1 { background-color:#EEEEFF;}/* Light mauve */" + LINE_SEPARATOR ).getBytes() );
fos.write( ( "</style>" + LINE_SEPARATOR ).getBytes() );
fos
.write( ( "<TABLE WIDTH='100%'><TR><TD WIDTH='100%' CLASS='NavBarCell1'><H1>Javascript code documentation</H1></TD></TR></TABLE>" + LINE_SEPARATOR )
.getBytes() );
fos.write( ( "<title>Javascript code documentation</title>" + LINE_SEPARATOR ).getBytes() );
fos.write( ( "</head>" + LINE_SEPARATOR ).getBytes() );
fos.write( ( "<body>" + LINE_SEPARATOR ).getBytes() );
fos.write( ( "<H2>Filename: " + nomeArquivo + "</H2>" + LINE_SEPARATOR ).getBytes() );
fos.write( ( "<br>" + LINE_SEPARATOR ).getBytes() );
fos.write( ( "<br>" + LINE_SEPARATOR ).getBytes() );
fos.write( ( "<TABLE BORDER='1' CELLPADDING='3' CELLSPACING='0' WIDTH='100%'>" + LINE_SEPARATOR )
.getBytes() );
fos.write( ( "<TR CLASS='TableHeadingColor'>" + LINE_SEPARATOR ).getBytes() );
fos.write( ( "<TD ALIGN='left' colspan='2'><FONT SIZE='+2'>" + LINE_SEPARATOR ).getBytes() );
fos.write( ( "<B>Function Summary</B></FONT></TD>" + LINE_SEPARATOR ).getBytes() );
fos.write( ( "</TR>" + LINE_SEPARATOR ).getBytes() );
while ( br.ready() )
{
stringReader = br.readLine();
while ( summary && null != stringReader && stringReader.indexOf( "summary" ) == -1 )
{
stringReader = br.readLine();
}
summary = false;
if ( null != stringReader && stringReader.indexOf( "/**" ) != -1 )
{
fos.write( ( "<TR>" + LINE_SEPARATOR ).getBytes() );
fos.write( ( "<TD WIDTH='30%' BGCOLOR='#f3f3f3'><font face='Verdana'><b><span id='Function"
+ functionCount + "'></span></b></font></TD>" + LINE_SEPARATOR ).getBytes() );
fos.write( ( "<TD WIDTH='70%'>" + LINE_SEPARATOR ).getBytes() );
stringReader = br.readLine();
while ( null != stringReader && stringReader.indexOf( "*/" ) == -1 )
{
if ( stringReader.indexOf( "* @" ) != -1 )
{
if ( ( stringReader.indexOf( "author" ) == -1 ) )
{
if ( stringReader.indexOf( "param" ) != -1 )
{
if ( parameterList == false )
{
parameterList = true;
fos.write( "<font size='-1' face='Verdana'><b>Parameters: </b></font>"
.getBytes() );
fos.write( "<BR>".getBytes() );
}
fos.write( " ".getBytes() );
fos
.write( ( stringReader.substring( stringReader.indexOf( "* @param" ) + 9 ) + LINE_SEPARATOR )
.getBytes() );
}
else if ( stringReader.indexOf( "use" ) != -1 )
{
if ( useList == false )
{
useList = true;
fos.write( "<font size='-1' face='Verdana'><b>Uso: </b></font>".getBytes() );
fos.write( "<BR>".getBytes() );
}
fos.write( " ".getBytes() );
fos
.write( ( stringReader.substring( stringReader.indexOf( "* @use" ) + 7 ) + LINE_SEPARATOR )
.getBytes() );
}
else if ( stringReader.indexOf( "return" ) != -1 )
{
fos.write( "<font size='-1' face='Verdana'><b>Return type: </b></font>".getBytes() );
fos
.write( ( stringReader.substring( stringReader.indexOf( "* @return" ) + 10 ) + LINE_SEPARATOR )
.getBytes() );
}
fos.write( "<BR>".getBytes() );
}
}
else
{
if ( description )
{
description = false;
fos.write( "<font size='-1' face='Verdana'><b>Description: </b></font>".getBytes() );
}
else
fos.write( " ".getBytes() );
fos.write( ( stringReader.substring( stringReader.indexOf( "*" ) + 1 ) + LINE_SEPARATOR )
.getBytes() );
fos.write( "<BR>".getBytes() );
}
stringReader = br.readLine();
}
description = true;
parameterList = false;
useList = false;
while ( null != stringReader && stringReader.indexOf( "function" ) == -1 )
{
stringReader = br.readLine();
}
if ( stringReader.indexOf( "function" ) != -1 )
{
if ( stringReader.indexOf( "{" ) != -1 )
{
functionName = stringReader.substring( stringReader.indexOf( "function" ) + 9, stringReader
.indexOf( "{" ) );
}
else
{
functionName = stringReader.substring( stringReader.indexOf( "function" ) + 9 );
}
}
fos.write( ( "</TD>" + LINE_SEPARATOR ).getBytes() );
fos.write( ( "<script>document.all.Function" + functionCount + ".innerHTML = '" + functionName
+ "'; </script>" + LINE_SEPARATOR ).getBytes() );
functionCount++;
fos.write( ( "</TR>" + LINE_SEPARATOR ).getBytes() );
}
}
fos.write( ( "</TABLE>" + LINE_SEPARATOR ).getBytes() );
fos.write( "</br>".getBytes() );
fos.write( ( "<a href='javascript:history.back()'><font size='+1'>Back</font></a>" + LINE_SEPARATOR )
.getBytes() );
fos.write( "</body>".getBytes() );
fos.write( "</html>".getBytes() );
}
catch ( IOException ioe )
{
log.error( "IOException: " + ioe.getMessage(), ioe );
}
if ( log.isInfoEnabled() )
{
log.info( "Html generated with success!" );
}
}
|
diff --git a/src/Client/ConfigForm.java b/src/Client/ConfigForm.java
index de123748..4c71373b 100644
--- a/src/Client/ConfigForm.java
+++ b/src/Client/ConfigForm.java
@@ -1,485 +1,485 @@
/*
* ConfigForm.java
*
* Created on 20.05.2008, 22:47
* Copyright (c) 2006-2008, Daniel Apatin (ad), http://apatin.net.ru
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* You can also redistribute and/or modify this program under the
* terms of the Psi License, specified in the accompanied COPYING
* file, as published by the Psi Project; either dated January 1st,
* 2005, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
package Client;
import java.util.Vector;
import locale.SR;
import ui.VirtualList;
import ui.controls.form.CheckBox;
import ui.controls.form.DropChoiceBox;
import ui.controls.form.DefForm;
import ui.controls.form.NumberInput;
import ui.controls.form.SimpleString;
import ui.controls.form.SpacerItem;
import util.StringLoader;
import com.alsutton.jabber.datablocks.Presence;
import ui.VirtualCanvas;
import xmpp.EntityCaps;
public class ConfigForm
extends DefForm {
private CheckBox showOfflineContacts;
private CheckBox selfContact;
private CheckBox showTransports;
private CheckBox ignore;
private CheckBox collapsedGroups;
private CheckBox autoFocus;
private CheckBox showResources;
private CheckBox useBoldFont;
private CheckBox rosterStatus;
//#ifdef CLIENTS_ICONS
//# private CheckBox showClientIcon;
//#endif
private DropChoiceBox subscr;
//#ifdef SMILES
//# private CheckBox smiles;
//#endif
private CheckBox eventComposing;
private CheckBox capsState;
private CheckBox storeConfPresence;
private CheckBox autoScroll;
private CheckBox useTabs;
private CheckBox showBalloons;
private CheckBox eventDelivery;
private CheckBox executeByNum;
//#ifdef DETRANSLIT
//# private CheckBox autoDetranslit;
//#endif
//#ifdef CLIPBOARD
//# private CheckBox useClipBoard;
//#endif
//#if LOGROTATE
//# private NumberInput messageCountLimit;
//#endif
private NumberInput messageLimit;
private NumberInput widthScroll2;
private NumberInput minItemHeight;
private CheckBox autoLogin;
private CheckBox autoJoinConferences;
private NumberInput reconnectCount;
private NumberInput reconnectTime;
//#ifdef FILE_TRANSFER
//# private CheckBox fileTransfer;
//#endif
//#ifdef HISTORY
//# private CheckBox saveHistory;
//#endif
//#ifdef ADHOC
//# private CheckBox adhoc;
//#endif
private CheckBox fullscreen;
//#ifdef MEMORY_USAGE
//# private CheckBox memMonitor;
//#endif
private CheckBox enableVersionOs;
private CheckBox queryExit;
private CheckBox lightState;
private CheckBox popupFromMinimized;
private CheckBox widthSystemgc;
private CheckBox advTouch;
private CheckBox autoClean;
private NumberInput fieldGmt;
private DropChoiceBox textWrap;
private DropChoiceBox langFiles;
//#ifdef AUTOSTATUS
//# private DropChoiceBox autoAwayType;
//# private NumberInput fieldAwayDelay;
//# private CheckBox awayStatus;
//#endif
//#ifdef RUNNING_MESSAGE
//# private CheckBox notifyWhenMessageType;
//#endif
//#ifdef POPUPS
//# private CheckBox popUps;
//#endif
private DropChoiceBox panels;
private CheckBox drawMenuCommand;
private CheckBox showNickNames;
private CheckBox swapSendAndSuspend;
private Vector langs[];
/** Creates a new instance of ConfigForm
*/
public ConfigForm() {
super(SR.MS_OPTIONS);
cf=Config.getInstance();
itemsList.addElement(new SimpleString(SR.MS_ROSTER_ELEMENTS, true));
showOfflineContacts = new CheckBox(SR.MS_OFFLINE_CONTACTS, cf.showOfflineContacts); itemsList.addElement(showOfflineContacts);
selfContact = new CheckBox(SR.MS_SELF_CONTACT, cf.selfContact); itemsList.addElement(selfContact);
showTransports = new CheckBox(SR.MS_TRANSPORTS, cf.showTransports); itemsList.addElement(showTransports);
ignore = new CheckBox(SR.MS_IGNORE_LIST, cf.ignore); itemsList.addElement(ignore);
collapsedGroups = new CheckBox(SR.MS_COLLAPSED_GROUPS, cf.collapsedGroups); itemsList.addElement(collapsedGroups);
autoFocus = new CheckBox(SR.MS_AUTOFOCUS, cf.autoFocus); itemsList.addElement(autoFocus);
showResources = new CheckBox(SR.MS_SHOW_RESOURCES, cf.showResources); itemsList.addElement(showResources);
useBoldFont = new CheckBox(SR.MS_BOLD_FONT, cf.useBoldFont); itemsList.addElement(useBoldFont);
rosterStatus = new CheckBox(SR.MS_SHOW_STATUSES, cf.rosterStatus); itemsList.addElement(rosterStatus);
//#ifdef CLIENTS_ICONS
//# showClientIcon = new CheckBox(SR.MS_SHOW_CLIENTS_ICONS, cf.showClientIcon);
//# itemsList.addElement(showClientIcon);
//#endif
autoClean = new CheckBox(SR.MS_AUTOCLEAN_GROUPS, cf.autoClean);
itemsList.addElement(autoClean);
itemsList.addElement(new SpacerItem(10));
subscr=new DropChoiceBox(SR.MS_AUTH_NEW);
subscr.add(SR.MS_SUBSCR_AUTO);
subscr.add(SR.MS_SUBSCR_ASK);
subscr.add(SR.MS_SUBSCR_DROP);
subscr.add(SR.MS_SUBSCR_REJECT);
subscr.setSelectedIndex(cf.autoSubscribe);
itemsList.addElement(subscr);
itemsList.addElement(new SpacerItem(10));
itemsList.addElement(new SpacerItem(10));
itemsList.addElement(new SimpleString(SR.MS_MESSAGES, true));
//#ifdef SMILES
//# smiles = new CheckBox(SR.MS_SMILES, cf.smiles); itemsList.addElement(smiles);
//#endif
eventComposing = new CheckBox(SR.MS_COMPOSING_EVENTS, cf.eventComposing); itemsList.addElement(eventComposing);
capsState = new CheckBox(SR.MS_CAPS_STATE, cf.capsState); itemsList.addElement(capsState);
//#ifndef WMUC
storeConfPresence = new CheckBox(SR.MS_STORE_PRESENCE, cf.storeConfPresence); itemsList.addElement(storeConfPresence);
//#endif
autoScroll = new CheckBox(SR.MS_AUTOSCROLL, cf.autoScroll); itemsList.addElement(autoScroll);
useTabs = new CheckBox(SR.MS_EMULATE_TABS, cf.useTabs); itemsList.addElement(useTabs);
//#ifdef RUNNING_MESSAGE
//# notifyWhenMessageType = new CheckBox(SR.MS_RUNNING_MESSAGE, cf.notifyWhenMessageType); itemsList.addElement(notifyWhenMessageType);
//#endif
//#ifdef POPUPS
//# popUps = new CheckBox(SR.MS_POPUPS, cf.popUps); itemsList.addElement(popUps);
//#endif
showBalloons = new CheckBox(SR.MS_HIDE_TIMESTAMPS, cf.hideTimestamps); itemsList.addElement(showBalloons);
eventDelivery = new CheckBox(SR.MS_DELIVERY, cf.eventDelivery); itemsList.addElement(eventDelivery);
//#ifdef CLIPBOARD
//# useClipBoard = new CheckBox(SR.MS_CLIPBOARD, cf.useClipBoard); itemsList.addElement(useClipBoard);
//#endif
//#ifdef DETRANSLIT
//# autoDetranslit = new CheckBox(SR.MS_AUTODETRANSLIT, cf.autoDeTranslit); itemsList.addElement(autoDetranslit);
//#endif
showNickNames = new CheckBox(SR.MS_SHOW_NACKNAMES, cf.showNickNames); itemsList.addElement(showNickNames);
swapSendAndSuspend = new CheckBox("swap \""+SR.MS_SEND+"\" and \""+SR.MS_SUSPEND+"\" commands", cf.swapSendAndSuspend); itemsList.addElement(swapSendAndSuspend);
//#if LOGROTATE
//# messageCountLimit=new NumberInput(SR.MS_MESSAGE_COUNT_LIMIT, Integer.toString(cf.msglistLimit), 3, 1000);
//# itemsList.addElement(messageCountLimit);
//#endif
itemsList.addElement(new SpacerItem(10));
messageLimit=new NumberInput(SR.MS_MESSAGE_COLLAPSE_LIMIT, Integer.toString(cf.messageLimit), 200, 1000);
itemsList.addElement(messageLimit);
minItemHeight = new NumberInput(SR.MS_ITEM_HEIGHT, Integer.toString(cf.minItemHeight), 0, 100);
itemsList.addElement(minItemHeight);
if (VirtualCanvas.getInstance().hasPointerEvents()) {
widthScroll2=new NumberInput(SR.MS_MESSAGE_WIDTH_SCROLL_2, Integer.toString(cf.widthScroll2), 1, 50);
itemsList.addElement(widthScroll2);
advTouch = new CheckBox(SR.MS_SINGLE_CLICK, cf.advTouch);
itemsList.addElement(advTouch);
}
itemsList.addElement(new SpacerItem(10));
itemsList.addElement(new SimpleString(SR.MS_STARTUP_ACTIONS, true));
autoLogin = new CheckBox(SR.MS_AUTOLOGIN, cf.autoLogin); itemsList.addElement(autoLogin);
//#ifndef WMUC
autoJoinConferences = new CheckBox(SR.MS_AUTO_CONFERENCES, cf.autoJoinConferences); itemsList.addElement(autoJoinConferences);
//#endif
itemsList.addElement(new SpacerItem(10));
itemsList.addElement(new SimpleString(SR.MS_RECONNECT, true));
reconnectCount=new NumberInput(SR.MS_RECONNECT_COUNT_RETRY, Integer.toString(cf.reconnectCount), 0, 100); itemsList.addElement(reconnectCount);
reconnectTime=new NumberInput(SR.MS_RECONNECT_WAIT, Integer.toString(cf.reconnectTime), 1, 60 ); itemsList.addElement(reconnectTime);
itemsList.addElement(new SpacerItem(10));
itemsList.addElement(new SimpleString(SR.MS_APPLICATION, true));
fullscreen = new CheckBox(SR.MS_FULLSCREEN, Config.fullscreen); itemsList.addElement(fullscreen);
//#ifdef MEMORY_USAGE
//# memMonitor = new CheckBox(SR.MS_HEAP_MONITOR, cf.memMonitor); itemsList.addElement(memMonitor);
//#endif
enableVersionOs = new CheckBox(SR.MS_SHOW_HARDWARE, cf.enableVersionOs); itemsList.addElement(enableVersionOs);
queryExit = new CheckBox(SR.MS_CONFIRM_EXIT, cf.queryExit); itemsList.addElement(queryExit);
//#ifdef LIGHT_CONFIG
//# lightState = new CheckBox(SR.L_CONFIG, cf.lightState);
//# if (phoneManufacturer==Config.SIEMENS || phoneManufacturer==Config.SIEMENS2 || phoneManufacturer==Config.SONYE || phoneManufacturer==Config.NOKIA) itemsList.addElement(lightState);
//#endif
//#ifdef FILE_TRANSFER
//# fileTransfer = new CheckBox(SR.MS_FILE_TRANSFERS, cf.fileTransfer);
//# itemsList.addElement(fileTransfer);
//#endif
//#ifdef HISTORY
//# saveHistory = new CheckBox(SR.MS_HISTORY, cf.saveHistory);
//# itemsList.addElement(saveHistory);
//#endif
//#ifdef ADHOC
//# adhoc = new CheckBox(SR.MS_ADHOC, cf.adhoc);
//# itemsList.addElement(adhoc);
//#endif
if (cf.allowMinimize) {
popupFromMinimized = new CheckBox(SR.MS_ENABLE_POPUP, cf.popupFromMinimized);
itemsList.addElement(popupFromMinimized);
}
executeByNum = new CheckBox(SR.MS_EXECUTE_MENU_BY_NUMKEY, cf.executeByNum); itemsList.addElement(executeByNum);
itemsList.addElement(new SpacerItem(10));
itemsList.addElement(new SimpleString(SR.MS_TIME_SETTINGS, true));
fieldGmt=new NumberInput(SR.MS_GMT_OFFSET, Integer.toString(cf.gmtOffset), -12, 12);
itemsList.addElement(fieldGmt);
itemsList.addElement(new SpacerItem(10));
textWrap=new DropChoiceBox(SR.MS_TEXTWRAP);
textWrap.add(SR.MS_TEXTWRAP_CHARACTER);
textWrap.add(SR.MS_TEXTWRAP_WORD);
textWrap.setSelectedIndex(cf.textWrap);
itemsList.addElement(textWrap);
itemsList.addElement(new SpacerItem(10));
panels=new DropChoiceBox(SR.MS_PANELS);
panels.add(SR.MS_NO_BAR+" : "+SR.MS_NO_BAR);
panels.add(SR.MS_MAIN_BAR+" : "+SR.MS_NO_BAR);
panels.add(SR.MS_MAIN_BAR+" : "+SR.MS_INFO_BAR);
panels.add(SR.MS_NO_BAR+" : "+SR.MS_INFO_BAR);
panels.add(SR.MS_INFO_BAR+" : "+SR.MS_NO_BAR);
panels.add(SR.MS_INFO_BAR+" : "+SR.MS_MAIN_BAR);
panels.add(SR.MS_NO_BAR+" : "+SR.MS_MAIN_BAR);
panels.setSelectedIndex(cf.panelsState);
itemsList.addElement(panels);
drawMenuCommand = new CheckBox(SR.MS_SHOW_TIME_TRAFFIC, cf.showTimeTraffic);
itemsList.addElement(drawMenuCommand);
//#ifdef AUTOSTATUS
//# itemsList.addElement(new SpacerItem(10));
//# autoAwayType=new DropChoiceBox(SR.MS_AWAY_TYPE);
//# autoAwayType.add(SR.MS_AWAY_OFF);
//# autoAwayType.add(SR.MS_AWAY_LOCK);
//# autoAwayType.add(SR.MS_MESSAGE_LOCK);
//# autoAwayType.add(SR.MS_IDLE);
//# autoAwayType.setSelectedIndex(cf.autoAwayType);
//# itemsList.addElement(autoAwayType);
//#
-//# fieldAwayDelay=new NumberInput(sd.canvas, SR.MS_AWAY_PERIOD, Integer.toString(cf.autoAwayDelay), 1, 60);
+//# fieldAwayDelay=new NumberInput(SR.MS_AWAY_PERIOD, Integer.toString(cf.autoAwayDelay), 1, 60);
//# itemsList.addElement(fieldAwayDelay);
//#
//# awayStatus=new CheckBox(SR.MS_USE_MY_STATUS_MESSAGES, cf.useMyStatusMessages);
//# itemsList.addElement(awayStatus);
//#endif
langs=new StringLoader().stringLoader("/lang/res.txt",3);
if (langs[0].size()>1) {
itemsList.addElement(new SpacerItem(10));
langFiles=new DropChoiceBox(SR.MS_LANGUAGE);
String tempLang=cf.lang;
if (tempLang==null) { //not detected
String locale=System.getProperty("microedition.locale");
if (locale!=null) {
tempLang=locale.substring(0, 2).toLowerCase();
}
}
for (int i=0; i<langs[0].size(); i++) {
String label=(String) langs[2].elementAt(i);
String langCode=(String) langs[0].elementAt(i);
langFiles.add(label);
if (tempLang.equals(langCode))
langFiles.setSelectedIndex(i);
}
itemsList.addElement(langFiles);
}
moveCursorTo(getNextSelectableRef(-1));
}
public void cmdOk() {
cf.showOfflineContacts=showOfflineContacts.getValue();
cf.selfContact=selfContact.getValue();
cf.showTransports=showTransports.getValue();
cf.ignore=ignore.getValue();
cf.collapsedGroups=collapsedGroups.getValue();
cf.autoFocus=autoFocus.getValue();
cf.showResources=showResources.getValue();
cf.useBoldFont=useBoldFont.getValue();
cf.rosterStatus=rosterStatus.getValue();
//#ifdef CLIENTS_ICONS
//# cf.showClientIcon=showClientIcon.getValue();
//#endif
cf.autoSubscribe=subscr.getSelectedIndex();
//#ifdef SMILES
//# cf.smiles=smiles.getValue();
//#endif
cf.eventComposing=eventComposing.getValue();
cf.capsState=capsState.getValue();
//#ifndef WMUC
cf.storeConfPresence=storeConfPresence.getValue();
//#endif
cf.autoScroll=autoScroll.getValue();
cf.useTabs=useTabs.getValue();
//#ifdef RUNNING_MESSAGE
//# cf.notifyWhenMessageType=notifyWhenMessageType.getValue();
//#endif
//#ifdef POPUPS
//# cf.popUps=popUps.getValue();
//#endif
cf.hideTimestamps=showBalloons.getValue();
cf.eventDelivery=eventDelivery.getValue();
//#ifdef CLIPBOARD
//# cf.useClipBoard=useClipBoard.getValue();
//#endif
//#ifdef DETRANSLIT
//# cf.autoDeTranslit=autoDetranslit.getValue();
//#endif
cf.showNickNames=showNickNames.getValue();
cf.executeByNum=executeByNum.getValue();
cf.autoLogin=autoLogin.getValue();
//#ifndef WMUC
cf.autoJoinConferences=autoJoinConferences.getValue();
//#endif
cf.reconnectCount=Integer.parseInt(reconnectCount.getValue());
cf.reconnectTime=Integer.parseInt(reconnectTime.getValue());
//#ifdef FILE_TRANSFER
//# cf.fileTransfer=fileTransfer.getValue();
//#endif
//#ifdef HISTORY
//# cf.saveHistory=saveHistory.getValue();
//#endif
//#ifdef ADHOC
//# cf.adhoc=adhoc.getValue();
//#endif
VirtualList.showTimeTraffic=cf.showTimeTraffic=drawMenuCommand.getValue();
Config.fullscreen = fullscreen.getValue();
//#ifdef MEMORY_USAGE
//# VirtualList.memMonitor=cf.memMonitor=memMonitor.getValue();
//#endif
cf.enableVersionOs=enableVersionOs.getValue();
cf.queryExit=queryExit.getValue();
//#ifdef LIGHT_CONFIG
//# cf.lightState=lightState.getValue();
//#endif
if (cf.allowMinimize)
cf.popupFromMinimized=popupFromMinimized.getValue();
cf.autoClean=autoClean.getValue();
if (VirtualCanvas.getInstance().hasPointerEvents())
cf.advTouch = advTouch.getValue();
cf.swapSendAndSuspend=swapSendAndSuspend.getValue();
cf.gmtOffset=Integer.parseInt(fieldGmt.getValue());
cf.textWrap=textWrap.getSelectedIndex();
if (langs[0].size()>1) {
cf.lang=(String) langs[0].elementAt( langFiles.getSelectedIndex() );
}
//#ifdef AUTOSTATUS
//# cf.useMyStatusMessages=awayStatus.getValue();
//# cf.autoAwayDelay=Integer.parseInt(fieldAwayDelay.getValue());
//# cf.autoAwayType=autoAwayType.getSelectedIndex();
//# if (autoAwayType.getSelectedIndex() != Config.AWAY_LOCK) {
//# if (AutoStatus.getInstance().active()) {
//# AutoStatus.getInstance().reset();
//# }
//# }
//#endif
cf.messageLimit=Integer.parseInt(messageLimit.getValue());
if (VirtualCanvas.getInstance().hasPointerEvents())
cf.widthScroll2=Integer.parseInt(widthScroll2.getValue());
cf.minItemHeight = Integer.parseInt(minItemHeight.getValue());
//#if LOGROTATE
//# cf.msglistLimit=Integer.parseInt(messageCountLimit.getValue());
//#endif
if (cf.panelsState!=panels.getSelectedIndex()) {
cf.panelsState=panels.getSelectedIndex();
VirtualList.changeOrient(cf.panelsState);
}
//sd.roster.setLight(cf.lightState); TODO: correct for new light control
VirtualCanvas.getInstance().setFullScreenMode(Config.fullscreen);
cf.firstRun=false;
cf.updateTime();
cf.saveToStorage();
String oldVerHash=EntityCaps.calcVerHash();
EntityCaps.initCaps();
if (!oldVerHash.equals(EntityCaps.calcVerHash()))
if (sd.roster.isLoggedIn())
sd.roster.sendPresence(Presence.PRESENCE_SAME, null);
sd.roster.reEnumRoster();
destroyView();
}
public boolean doUserKeyAction(int command_id) {
switch (command_id) {
case 1:
destroyView();
return true;
}
return super.doUserKeyAction(command_id);
}
public void destroyView() {
//#ifdef AUTOSTATUS
//# if (sd.roster.isLoggedIn()) {
//# if ((Config.getInstance().autoAwayType==Config.AWAY_OFF) || Config.getInstance().autoAwayType == Config.AWAY_LOCK) {
//# AutoStatus.getInstance().stop();
//# } else {
//# AutoStatus.getInstance().start();
//# }
//# }
//#endif
super.destroyView();
}
}
| true | true | public ConfigForm() {
super(SR.MS_OPTIONS);
cf=Config.getInstance();
itemsList.addElement(new SimpleString(SR.MS_ROSTER_ELEMENTS, true));
showOfflineContacts = new CheckBox(SR.MS_OFFLINE_CONTACTS, cf.showOfflineContacts); itemsList.addElement(showOfflineContacts);
selfContact = new CheckBox(SR.MS_SELF_CONTACT, cf.selfContact); itemsList.addElement(selfContact);
showTransports = new CheckBox(SR.MS_TRANSPORTS, cf.showTransports); itemsList.addElement(showTransports);
ignore = new CheckBox(SR.MS_IGNORE_LIST, cf.ignore); itemsList.addElement(ignore);
collapsedGroups = new CheckBox(SR.MS_COLLAPSED_GROUPS, cf.collapsedGroups); itemsList.addElement(collapsedGroups);
autoFocus = new CheckBox(SR.MS_AUTOFOCUS, cf.autoFocus); itemsList.addElement(autoFocus);
showResources = new CheckBox(SR.MS_SHOW_RESOURCES, cf.showResources); itemsList.addElement(showResources);
useBoldFont = new CheckBox(SR.MS_BOLD_FONT, cf.useBoldFont); itemsList.addElement(useBoldFont);
rosterStatus = new CheckBox(SR.MS_SHOW_STATUSES, cf.rosterStatus); itemsList.addElement(rosterStatus);
//#ifdef CLIENTS_ICONS
//# showClientIcon = new CheckBox(SR.MS_SHOW_CLIENTS_ICONS, cf.showClientIcon);
//# itemsList.addElement(showClientIcon);
//#endif
autoClean = new CheckBox(SR.MS_AUTOCLEAN_GROUPS, cf.autoClean);
itemsList.addElement(autoClean);
itemsList.addElement(new SpacerItem(10));
subscr=new DropChoiceBox(SR.MS_AUTH_NEW);
subscr.add(SR.MS_SUBSCR_AUTO);
subscr.add(SR.MS_SUBSCR_ASK);
subscr.add(SR.MS_SUBSCR_DROP);
subscr.add(SR.MS_SUBSCR_REJECT);
subscr.setSelectedIndex(cf.autoSubscribe);
itemsList.addElement(subscr);
itemsList.addElement(new SpacerItem(10));
itemsList.addElement(new SpacerItem(10));
itemsList.addElement(new SimpleString(SR.MS_MESSAGES, true));
//#ifdef SMILES
//# smiles = new CheckBox(SR.MS_SMILES, cf.smiles); itemsList.addElement(smiles);
//#endif
eventComposing = new CheckBox(SR.MS_COMPOSING_EVENTS, cf.eventComposing); itemsList.addElement(eventComposing);
capsState = new CheckBox(SR.MS_CAPS_STATE, cf.capsState); itemsList.addElement(capsState);
//#ifndef WMUC
storeConfPresence = new CheckBox(SR.MS_STORE_PRESENCE, cf.storeConfPresence); itemsList.addElement(storeConfPresence);
//#endif
autoScroll = new CheckBox(SR.MS_AUTOSCROLL, cf.autoScroll); itemsList.addElement(autoScroll);
useTabs = new CheckBox(SR.MS_EMULATE_TABS, cf.useTabs); itemsList.addElement(useTabs);
//#ifdef RUNNING_MESSAGE
//# notifyWhenMessageType = new CheckBox(SR.MS_RUNNING_MESSAGE, cf.notifyWhenMessageType); itemsList.addElement(notifyWhenMessageType);
//#endif
//#ifdef POPUPS
//# popUps = new CheckBox(SR.MS_POPUPS, cf.popUps); itemsList.addElement(popUps);
//#endif
showBalloons = new CheckBox(SR.MS_HIDE_TIMESTAMPS, cf.hideTimestamps); itemsList.addElement(showBalloons);
eventDelivery = new CheckBox(SR.MS_DELIVERY, cf.eventDelivery); itemsList.addElement(eventDelivery);
//#ifdef CLIPBOARD
//# useClipBoard = new CheckBox(SR.MS_CLIPBOARD, cf.useClipBoard); itemsList.addElement(useClipBoard);
//#endif
//#ifdef DETRANSLIT
//# autoDetranslit = new CheckBox(SR.MS_AUTODETRANSLIT, cf.autoDeTranslit); itemsList.addElement(autoDetranslit);
//#endif
showNickNames = new CheckBox(SR.MS_SHOW_NACKNAMES, cf.showNickNames); itemsList.addElement(showNickNames);
swapSendAndSuspend = new CheckBox("swap \""+SR.MS_SEND+"\" and \""+SR.MS_SUSPEND+"\" commands", cf.swapSendAndSuspend); itemsList.addElement(swapSendAndSuspend);
//#if LOGROTATE
//# messageCountLimit=new NumberInput(SR.MS_MESSAGE_COUNT_LIMIT, Integer.toString(cf.msglistLimit), 3, 1000);
//# itemsList.addElement(messageCountLimit);
//#endif
itemsList.addElement(new SpacerItem(10));
messageLimit=new NumberInput(SR.MS_MESSAGE_COLLAPSE_LIMIT, Integer.toString(cf.messageLimit), 200, 1000);
itemsList.addElement(messageLimit);
minItemHeight = new NumberInput(SR.MS_ITEM_HEIGHT, Integer.toString(cf.minItemHeight), 0, 100);
itemsList.addElement(minItemHeight);
if (VirtualCanvas.getInstance().hasPointerEvents()) {
widthScroll2=new NumberInput(SR.MS_MESSAGE_WIDTH_SCROLL_2, Integer.toString(cf.widthScroll2), 1, 50);
itemsList.addElement(widthScroll2);
advTouch = new CheckBox(SR.MS_SINGLE_CLICK, cf.advTouch);
itemsList.addElement(advTouch);
}
itemsList.addElement(new SpacerItem(10));
itemsList.addElement(new SimpleString(SR.MS_STARTUP_ACTIONS, true));
autoLogin = new CheckBox(SR.MS_AUTOLOGIN, cf.autoLogin); itemsList.addElement(autoLogin);
//#ifndef WMUC
autoJoinConferences = new CheckBox(SR.MS_AUTO_CONFERENCES, cf.autoJoinConferences); itemsList.addElement(autoJoinConferences);
//#endif
itemsList.addElement(new SpacerItem(10));
itemsList.addElement(new SimpleString(SR.MS_RECONNECT, true));
reconnectCount=new NumberInput(SR.MS_RECONNECT_COUNT_RETRY, Integer.toString(cf.reconnectCount), 0, 100); itemsList.addElement(reconnectCount);
reconnectTime=new NumberInput(SR.MS_RECONNECT_WAIT, Integer.toString(cf.reconnectTime), 1, 60 ); itemsList.addElement(reconnectTime);
itemsList.addElement(new SpacerItem(10));
itemsList.addElement(new SimpleString(SR.MS_APPLICATION, true));
fullscreen = new CheckBox(SR.MS_FULLSCREEN, Config.fullscreen); itemsList.addElement(fullscreen);
//#ifdef MEMORY_USAGE
//# memMonitor = new CheckBox(SR.MS_HEAP_MONITOR, cf.memMonitor); itemsList.addElement(memMonitor);
//#endif
enableVersionOs = new CheckBox(SR.MS_SHOW_HARDWARE, cf.enableVersionOs); itemsList.addElement(enableVersionOs);
queryExit = new CheckBox(SR.MS_CONFIRM_EXIT, cf.queryExit); itemsList.addElement(queryExit);
//#ifdef LIGHT_CONFIG
//# lightState = new CheckBox(SR.L_CONFIG, cf.lightState);
//# if (phoneManufacturer==Config.SIEMENS || phoneManufacturer==Config.SIEMENS2 || phoneManufacturer==Config.SONYE || phoneManufacturer==Config.NOKIA) itemsList.addElement(lightState);
//#endif
//#ifdef FILE_TRANSFER
//# fileTransfer = new CheckBox(SR.MS_FILE_TRANSFERS, cf.fileTransfer);
//# itemsList.addElement(fileTransfer);
//#endif
//#ifdef HISTORY
//# saveHistory = new CheckBox(SR.MS_HISTORY, cf.saveHistory);
//# itemsList.addElement(saveHistory);
//#endif
//#ifdef ADHOC
//# adhoc = new CheckBox(SR.MS_ADHOC, cf.adhoc);
//# itemsList.addElement(adhoc);
//#endif
if (cf.allowMinimize) {
popupFromMinimized = new CheckBox(SR.MS_ENABLE_POPUP, cf.popupFromMinimized);
itemsList.addElement(popupFromMinimized);
}
executeByNum = new CheckBox(SR.MS_EXECUTE_MENU_BY_NUMKEY, cf.executeByNum); itemsList.addElement(executeByNum);
itemsList.addElement(new SpacerItem(10));
itemsList.addElement(new SimpleString(SR.MS_TIME_SETTINGS, true));
fieldGmt=new NumberInput(SR.MS_GMT_OFFSET, Integer.toString(cf.gmtOffset), -12, 12);
itemsList.addElement(fieldGmt);
itemsList.addElement(new SpacerItem(10));
textWrap=new DropChoiceBox(SR.MS_TEXTWRAP);
textWrap.add(SR.MS_TEXTWRAP_CHARACTER);
textWrap.add(SR.MS_TEXTWRAP_WORD);
textWrap.setSelectedIndex(cf.textWrap);
itemsList.addElement(textWrap);
itemsList.addElement(new SpacerItem(10));
panels=new DropChoiceBox(SR.MS_PANELS);
panels.add(SR.MS_NO_BAR+" : "+SR.MS_NO_BAR);
panels.add(SR.MS_MAIN_BAR+" : "+SR.MS_NO_BAR);
panels.add(SR.MS_MAIN_BAR+" : "+SR.MS_INFO_BAR);
panels.add(SR.MS_NO_BAR+" : "+SR.MS_INFO_BAR);
panels.add(SR.MS_INFO_BAR+" : "+SR.MS_NO_BAR);
panels.add(SR.MS_INFO_BAR+" : "+SR.MS_MAIN_BAR);
panels.add(SR.MS_NO_BAR+" : "+SR.MS_MAIN_BAR);
panels.setSelectedIndex(cf.panelsState);
itemsList.addElement(panels);
drawMenuCommand = new CheckBox(SR.MS_SHOW_TIME_TRAFFIC, cf.showTimeTraffic);
itemsList.addElement(drawMenuCommand);
//#ifdef AUTOSTATUS
//# itemsList.addElement(new SpacerItem(10));
//# autoAwayType=new DropChoiceBox(SR.MS_AWAY_TYPE);
//# autoAwayType.add(SR.MS_AWAY_OFF);
//# autoAwayType.add(SR.MS_AWAY_LOCK);
//# autoAwayType.add(SR.MS_MESSAGE_LOCK);
//# autoAwayType.add(SR.MS_IDLE);
//# autoAwayType.setSelectedIndex(cf.autoAwayType);
//# itemsList.addElement(autoAwayType);
//#
//# fieldAwayDelay=new NumberInput(sd.canvas, SR.MS_AWAY_PERIOD, Integer.toString(cf.autoAwayDelay), 1, 60);
//# itemsList.addElement(fieldAwayDelay);
//#
//# awayStatus=new CheckBox(SR.MS_USE_MY_STATUS_MESSAGES, cf.useMyStatusMessages);
//# itemsList.addElement(awayStatus);
//#endif
langs=new StringLoader().stringLoader("/lang/res.txt",3);
if (langs[0].size()>1) {
itemsList.addElement(new SpacerItem(10));
langFiles=new DropChoiceBox(SR.MS_LANGUAGE);
String tempLang=cf.lang;
if (tempLang==null) { //not detected
String locale=System.getProperty("microedition.locale");
if (locale!=null) {
tempLang=locale.substring(0, 2).toLowerCase();
}
}
for (int i=0; i<langs[0].size(); i++) {
String label=(String) langs[2].elementAt(i);
String langCode=(String) langs[0].elementAt(i);
langFiles.add(label);
if (tempLang.equals(langCode))
langFiles.setSelectedIndex(i);
}
itemsList.addElement(langFiles);
}
moveCursorTo(getNextSelectableRef(-1));
}
| public ConfigForm() {
super(SR.MS_OPTIONS);
cf=Config.getInstance();
itemsList.addElement(new SimpleString(SR.MS_ROSTER_ELEMENTS, true));
showOfflineContacts = new CheckBox(SR.MS_OFFLINE_CONTACTS, cf.showOfflineContacts); itemsList.addElement(showOfflineContacts);
selfContact = new CheckBox(SR.MS_SELF_CONTACT, cf.selfContact); itemsList.addElement(selfContact);
showTransports = new CheckBox(SR.MS_TRANSPORTS, cf.showTransports); itemsList.addElement(showTransports);
ignore = new CheckBox(SR.MS_IGNORE_LIST, cf.ignore); itemsList.addElement(ignore);
collapsedGroups = new CheckBox(SR.MS_COLLAPSED_GROUPS, cf.collapsedGroups); itemsList.addElement(collapsedGroups);
autoFocus = new CheckBox(SR.MS_AUTOFOCUS, cf.autoFocus); itemsList.addElement(autoFocus);
showResources = new CheckBox(SR.MS_SHOW_RESOURCES, cf.showResources); itemsList.addElement(showResources);
useBoldFont = new CheckBox(SR.MS_BOLD_FONT, cf.useBoldFont); itemsList.addElement(useBoldFont);
rosterStatus = new CheckBox(SR.MS_SHOW_STATUSES, cf.rosterStatus); itemsList.addElement(rosterStatus);
//#ifdef CLIENTS_ICONS
//# showClientIcon = new CheckBox(SR.MS_SHOW_CLIENTS_ICONS, cf.showClientIcon);
//# itemsList.addElement(showClientIcon);
//#endif
autoClean = new CheckBox(SR.MS_AUTOCLEAN_GROUPS, cf.autoClean);
itemsList.addElement(autoClean);
itemsList.addElement(new SpacerItem(10));
subscr=new DropChoiceBox(SR.MS_AUTH_NEW);
subscr.add(SR.MS_SUBSCR_AUTO);
subscr.add(SR.MS_SUBSCR_ASK);
subscr.add(SR.MS_SUBSCR_DROP);
subscr.add(SR.MS_SUBSCR_REJECT);
subscr.setSelectedIndex(cf.autoSubscribe);
itemsList.addElement(subscr);
itemsList.addElement(new SpacerItem(10));
itemsList.addElement(new SpacerItem(10));
itemsList.addElement(new SimpleString(SR.MS_MESSAGES, true));
//#ifdef SMILES
//# smiles = new CheckBox(SR.MS_SMILES, cf.smiles); itemsList.addElement(smiles);
//#endif
eventComposing = new CheckBox(SR.MS_COMPOSING_EVENTS, cf.eventComposing); itemsList.addElement(eventComposing);
capsState = new CheckBox(SR.MS_CAPS_STATE, cf.capsState); itemsList.addElement(capsState);
//#ifndef WMUC
storeConfPresence = new CheckBox(SR.MS_STORE_PRESENCE, cf.storeConfPresence); itemsList.addElement(storeConfPresence);
//#endif
autoScroll = new CheckBox(SR.MS_AUTOSCROLL, cf.autoScroll); itemsList.addElement(autoScroll);
useTabs = new CheckBox(SR.MS_EMULATE_TABS, cf.useTabs); itemsList.addElement(useTabs);
//#ifdef RUNNING_MESSAGE
//# notifyWhenMessageType = new CheckBox(SR.MS_RUNNING_MESSAGE, cf.notifyWhenMessageType); itemsList.addElement(notifyWhenMessageType);
//#endif
//#ifdef POPUPS
//# popUps = new CheckBox(SR.MS_POPUPS, cf.popUps); itemsList.addElement(popUps);
//#endif
showBalloons = new CheckBox(SR.MS_HIDE_TIMESTAMPS, cf.hideTimestamps); itemsList.addElement(showBalloons);
eventDelivery = new CheckBox(SR.MS_DELIVERY, cf.eventDelivery); itemsList.addElement(eventDelivery);
//#ifdef CLIPBOARD
//# useClipBoard = new CheckBox(SR.MS_CLIPBOARD, cf.useClipBoard); itemsList.addElement(useClipBoard);
//#endif
//#ifdef DETRANSLIT
//# autoDetranslit = new CheckBox(SR.MS_AUTODETRANSLIT, cf.autoDeTranslit); itemsList.addElement(autoDetranslit);
//#endif
showNickNames = new CheckBox(SR.MS_SHOW_NACKNAMES, cf.showNickNames); itemsList.addElement(showNickNames);
swapSendAndSuspend = new CheckBox("swap \""+SR.MS_SEND+"\" and \""+SR.MS_SUSPEND+"\" commands", cf.swapSendAndSuspend); itemsList.addElement(swapSendAndSuspend);
//#if LOGROTATE
//# messageCountLimit=new NumberInput(SR.MS_MESSAGE_COUNT_LIMIT, Integer.toString(cf.msglistLimit), 3, 1000);
//# itemsList.addElement(messageCountLimit);
//#endif
itemsList.addElement(new SpacerItem(10));
messageLimit=new NumberInput(SR.MS_MESSAGE_COLLAPSE_LIMIT, Integer.toString(cf.messageLimit), 200, 1000);
itemsList.addElement(messageLimit);
minItemHeight = new NumberInput(SR.MS_ITEM_HEIGHT, Integer.toString(cf.minItemHeight), 0, 100);
itemsList.addElement(minItemHeight);
if (VirtualCanvas.getInstance().hasPointerEvents()) {
widthScroll2=new NumberInput(SR.MS_MESSAGE_WIDTH_SCROLL_2, Integer.toString(cf.widthScroll2), 1, 50);
itemsList.addElement(widthScroll2);
advTouch = new CheckBox(SR.MS_SINGLE_CLICK, cf.advTouch);
itemsList.addElement(advTouch);
}
itemsList.addElement(new SpacerItem(10));
itemsList.addElement(new SimpleString(SR.MS_STARTUP_ACTIONS, true));
autoLogin = new CheckBox(SR.MS_AUTOLOGIN, cf.autoLogin); itemsList.addElement(autoLogin);
//#ifndef WMUC
autoJoinConferences = new CheckBox(SR.MS_AUTO_CONFERENCES, cf.autoJoinConferences); itemsList.addElement(autoJoinConferences);
//#endif
itemsList.addElement(new SpacerItem(10));
itemsList.addElement(new SimpleString(SR.MS_RECONNECT, true));
reconnectCount=new NumberInput(SR.MS_RECONNECT_COUNT_RETRY, Integer.toString(cf.reconnectCount), 0, 100); itemsList.addElement(reconnectCount);
reconnectTime=new NumberInput(SR.MS_RECONNECT_WAIT, Integer.toString(cf.reconnectTime), 1, 60 ); itemsList.addElement(reconnectTime);
itemsList.addElement(new SpacerItem(10));
itemsList.addElement(new SimpleString(SR.MS_APPLICATION, true));
fullscreen = new CheckBox(SR.MS_FULLSCREEN, Config.fullscreen); itemsList.addElement(fullscreen);
//#ifdef MEMORY_USAGE
//# memMonitor = new CheckBox(SR.MS_HEAP_MONITOR, cf.memMonitor); itemsList.addElement(memMonitor);
//#endif
enableVersionOs = new CheckBox(SR.MS_SHOW_HARDWARE, cf.enableVersionOs); itemsList.addElement(enableVersionOs);
queryExit = new CheckBox(SR.MS_CONFIRM_EXIT, cf.queryExit); itemsList.addElement(queryExit);
//#ifdef LIGHT_CONFIG
//# lightState = new CheckBox(SR.L_CONFIG, cf.lightState);
//# if (phoneManufacturer==Config.SIEMENS || phoneManufacturer==Config.SIEMENS2 || phoneManufacturer==Config.SONYE || phoneManufacturer==Config.NOKIA) itemsList.addElement(lightState);
//#endif
//#ifdef FILE_TRANSFER
//# fileTransfer = new CheckBox(SR.MS_FILE_TRANSFERS, cf.fileTransfer);
//# itemsList.addElement(fileTransfer);
//#endif
//#ifdef HISTORY
//# saveHistory = new CheckBox(SR.MS_HISTORY, cf.saveHistory);
//# itemsList.addElement(saveHistory);
//#endif
//#ifdef ADHOC
//# adhoc = new CheckBox(SR.MS_ADHOC, cf.adhoc);
//# itemsList.addElement(adhoc);
//#endif
if (cf.allowMinimize) {
popupFromMinimized = new CheckBox(SR.MS_ENABLE_POPUP, cf.popupFromMinimized);
itemsList.addElement(popupFromMinimized);
}
executeByNum = new CheckBox(SR.MS_EXECUTE_MENU_BY_NUMKEY, cf.executeByNum); itemsList.addElement(executeByNum);
itemsList.addElement(new SpacerItem(10));
itemsList.addElement(new SimpleString(SR.MS_TIME_SETTINGS, true));
fieldGmt=new NumberInput(SR.MS_GMT_OFFSET, Integer.toString(cf.gmtOffset), -12, 12);
itemsList.addElement(fieldGmt);
itemsList.addElement(new SpacerItem(10));
textWrap=new DropChoiceBox(SR.MS_TEXTWRAP);
textWrap.add(SR.MS_TEXTWRAP_CHARACTER);
textWrap.add(SR.MS_TEXTWRAP_WORD);
textWrap.setSelectedIndex(cf.textWrap);
itemsList.addElement(textWrap);
itemsList.addElement(new SpacerItem(10));
panels=new DropChoiceBox(SR.MS_PANELS);
panels.add(SR.MS_NO_BAR+" : "+SR.MS_NO_BAR);
panels.add(SR.MS_MAIN_BAR+" : "+SR.MS_NO_BAR);
panels.add(SR.MS_MAIN_BAR+" : "+SR.MS_INFO_BAR);
panels.add(SR.MS_NO_BAR+" : "+SR.MS_INFO_BAR);
panels.add(SR.MS_INFO_BAR+" : "+SR.MS_NO_BAR);
panels.add(SR.MS_INFO_BAR+" : "+SR.MS_MAIN_BAR);
panels.add(SR.MS_NO_BAR+" : "+SR.MS_MAIN_BAR);
panels.setSelectedIndex(cf.panelsState);
itemsList.addElement(panels);
drawMenuCommand = new CheckBox(SR.MS_SHOW_TIME_TRAFFIC, cf.showTimeTraffic);
itemsList.addElement(drawMenuCommand);
//#ifdef AUTOSTATUS
//# itemsList.addElement(new SpacerItem(10));
//# autoAwayType=new DropChoiceBox(SR.MS_AWAY_TYPE);
//# autoAwayType.add(SR.MS_AWAY_OFF);
//# autoAwayType.add(SR.MS_AWAY_LOCK);
//# autoAwayType.add(SR.MS_MESSAGE_LOCK);
//# autoAwayType.add(SR.MS_IDLE);
//# autoAwayType.setSelectedIndex(cf.autoAwayType);
//# itemsList.addElement(autoAwayType);
//#
//# fieldAwayDelay=new NumberInput(SR.MS_AWAY_PERIOD, Integer.toString(cf.autoAwayDelay), 1, 60);
//# itemsList.addElement(fieldAwayDelay);
//#
//# awayStatus=new CheckBox(SR.MS_USE_MY_STATUS_MESSAGES, cf.useMyStatusMessages);
//# itemsList.addElement(awayStatus);
//#endif
langs=new StringLoader().stringLoader("/lang/res.txt",3);
if (langs[0].size()>1) {
itemsList.addElement(new SpacerItem(10));
langFiles=new DropChoiceBox(SR.MS_LANGUAGE);
String tempLang=cf.lang;
if (tempLang==null) { //not detected
String locale=System.getProperty("microedition.locale");
if (locale!=null) {
tempLang=locale.substring(0, 2).toLowerCase();
}
}
for (int i=0; i<langs[0].size(); i++) {
String label=(String) langs[2].elementAt(i);
String langCode=(String) langs[0].elementAt(i);
langFiles.add(label);
if (tempLang.equals(langCode))
langFiles.setSelectedIndex(i);
}
itemsList.addElement(langFiles);
}
moveCursorTo(getNextSelectableRef(-1));
}
|
diff --git a/modules/cpr/src/main/java/org/atmosphere/websocket/DefaultWebSocketProcessor.java b/modules/cpr/src/main/java/org/atmosphere/websocket/DefaultWebSocketProcessor.java
index dedddba79..0c970ad5f 100644
--- a/modules/cpr/src/main/java/org/atmosphere/websocket/DefaultWebSocketProcessor.java
+++ b/modules/cpr/src/main/java/org/atmosphere/websocket/DefaultWebSocketProcessor.java
@@ -1,718 +1,718 @@
/*
* Copyright 2013 Jeanfrancois Arcand
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.atmosphere.websocket;
import org.atmosphere.annotation.AnnotationUtil;
import org.atmosphere.config.service.Singleton;
import org.atmosphere.config.service.WebSocketHandlerService;
import org.atmosphere.cpr.Action;
import org.atmosphere.cpr.AsynchronousProcessor;
import org.atmosphere.cpr.AtmosphereConfig;
import org.atmosphere.cpr.AtmosphereFramework;
import org.atmosphere.cpr.AtmosphereMappingException;
import org.atmosphere.cpr.AtmosphereRequest;
import org.atmosphere.cpr.AtmosphereResource;
import org.atmosphere.cpr.AtmosphereResourceEventImpl;
import org.atmosphere.cpr.AtmosphereResourceEventListener;
import org.atmosphere.cpr.AtmosphereResourceFactory;
import org.atmosphere.cpr.AtmosphereResourceImpl;
import org.atmosphere.cpr.AtmosphereResponse;
import org.atmosphere.cpr.HeaderConfig;
import org.atmosphere.util.DefaultEndpointMapper;
import org.atmosphere.util.EndpointMapper;
import org.atmosphere.util.ExecutorsFactory;
import org.atmosphere.util.VoidExecutorService;
import org.atmosphere.websocket.protocol.StreamingHttpProtocol;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.Serializable;
import java.io.StringReader;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import static org.atmosphere.cpr.ApplicationConfig.IN_MEMORY_STREAMING_BUFFER_SIZE;
import static org.atmosphere.cpr.ApplicationConfig.RECYCLE_ATMOSPHERE_REQUEST_RESPONSE;
import static org.atmosphere.cpr.ApplicationConfig.SUSPENDED_ATMOSPHERE_RESOURCE_UUID;
import static org.atmosphere.cpr.ApplicationConfig.WEBSOCKET_PROTOCOL_EXECUTION;
import static org.atmosphere.cpr.AtmosphereFramework.REFLECTOR_ATMOSPHEREHANDLER;
import static org.atmosphere.cpr.FrameworkConfig.ASYNCHRONOUS_HOOK;
import static org.atmosphere.cpr.FrameworkConfig.INJECTED_ATMOSPHERE_RESOURCE;
import static org.atmosphere.websocket.WebSocketEventListener.WebSocketEvent.TYPE.CLOSE;
import static org.atmosphere.websocket.WebSocketEventListener.WebSocketEvent.TYPE.CONNECT;
import static org.atmosphere.websocket.WebSocketEventListener.WebSocketEvent.TYPE.MESSAGE;
/**
* Like the {@link org.atmosphere.cpr.AsynchronousProcessor} class, this class is responsible for dispatching WebSocket request to the
* proper {@link org.atmosphere.websocket.WebSocket} implementation. This class can be extended in order to support any protocol
* running on top websocket.
*
* @author Jeanfrancois Arcand
*/
public class DefaultWebSocketProcessor implements WebSocketProcessor, Serializable {
private static final Logger logger = LoggerFactory.getLogger(DefaultWebSocketProcessor.class);
private final AtmosphereFramework framework;
private final WebSocketProtocol webSocketProtocol;
private final boolean destroyable;
private final boolean executeAsync;
private ExecutorService asyncExecutor;
private ScheduledExecutorService scheduler;
private final Map<String, WebSocketHandlerProxy> handlers = new ConcurrentHashMap<String, WebSocketHandlerProxy>();
private final EndpointMapper<WebSocketHandlerProxy> mapper = new DefaultEndpointMapper<WebSocketHandlerProxy>();
private boolean wildcardMapping = false;
// 2MB - like maxPostSize
private int byteBufferMaxSize = 2097152;
private int charBufferMaxSize = 2097152;
public DefaultWebSocketProcessor(AtmosphereFramework framework) {
this.framework = framework;
this.webSocketProtocol = framework.getWebSocketProtocol();
String s = framework.getAtmosphereConfig().getInitParameter(RECYCLE_ATMOSPHERE_REQUEST_RESPONSE);
if (s != null && Boolean.valueOf(s)) {
destroyable = true;
} else {
destroyable = false;
}
s = framework.getAtmosphereConfig().getInitParameter(WEBSOCKET_PROTOCOL_EXECUTION);
if (s != null && Boolean.valueOf(s)) {
executeAsync = true;
} else {
executeAsync = false;
}
s = framework.getAtmosphereConfig().getInitParameter(IN_MEMORY_STREAMING_BUFFER_SIZE);
if (s != null) {
byteBufferMaxSize = Integer.valueOf(s);
charBufferMaxSize = byteBufferMaxSize;
}
AtmosphereConfig config = framework.getAtmosphereConfig();
if (executeAsync) {
asyncExecutor = ExecutorsFactory.getAsyncOperationExecutor(config, "WebSocket");
} else {
asyncExecutor = VoidExecutorService.VOID;
}
scheduler = ExecutorsFactory.getScheduler(config);
optimizeMapping();
}
@Override
public boolean handshake(HttpServletRequest request) {
if (request != null) {
logger.trace("Processing request {}", request);
}
return true;
}
@Override
public WebSocketProcessor registerWebSocketHandler(String path, WebSocketHandlerProxy webSockethandler) {
handlers.put(path, webSockethandler.path(path));
return this;
}
@Override
public final void open(final WebSocket webSocket, final AtmosphereRequest request, final AtmosphereResponse response) throws IOException {
// TODO: Fix this. Instead add an Interceptor.
if (framework.getAtmosphereConfig().handlers().size() == 0) {
framework.addAtmosphereHandler("/*", REFLECTOR_ATMOSPHEREHANDLER);
}
request.headers(configureHeader(request)).setAttribute(WebSocket.WEBSOCKET_SUSPEND, true);
AtmosphereResource r = AtmosphereResourceFactory.getDefault().create(framework.getAtmosphereConfig(),
response,
framework.getAsyncSupport());
request.setAttribute(INJECTED_ATMOSPHERE_RESOURCE, r);
request.setAttribute(SUSPENDED_ATMOSPHERE_RESOURCE_UUID, r.uuid());
webSocket.resource(r);
webSocketProtocol.onOpen(webSocket);
WebSocketHandler proxy = null;
if (handlers.size() != 0) {
WebSocketHandlerProxy handler = mapper.map(request, handlers);
if (handler == null) {
logger.debug("No WebSocketHandler maps request for {} with mapping {}", request.getRequestURI(), handlers);
throw new AtmosphereMappingException("No AtmosphereHandler maps request for " + request.getRequestURI());
}
proxy = postProcessMapping(webSocket, request, handler);
}
// We must dispatch to execute AtmosphereInterceptor
dispatch(webSocket, request, response);
if (proxy != null) {
proxy.onOpen(webSocket);
webSocket.webSocketHandler(proxy).resource().suspend(-1);
}
request.removeAttribute(INJECTED_ATMOSPHERE_RESOURCE);
if (webSocket.resource() != null) {
final AsynchronousProcessor.AsynchronousProcessorHook hook =
new AsynchronousProcessor.AsynchronousProcessorHook((AtmosphereResourceImpl) webSocket.resource());
request.setAttribute(ASYNCHRONOUS_HOOK, hook);
final Action action = ((AtmosphereResourceImpl) webSocket.resource()).action();
if (action.timeout() != -1 && !framework.getAsyncSupport().getContainerName().contains("Netty")) {
final AtomicReference<Future<?>> f = new AtomicReference();
f.set(scheduler.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
if (WebSocket.class.isAssignableFrom(webSocket.getClass())
&& System.currentTimeMillis() - WebSocket.class.cast(webSocket).lastWriteTimeStampInMilliseconds() > action.timeout()) {
hook.timedOut();
f.get().cancel(true);
}
}
}, action.timeout(), action.timeout(), TimeUnit.MILLISECONDS));
}
} else {
logger.warn("AtmosphereResource was null");
}
notifyListener(webSocket, new WebSocketEventListener.WebSocketEvent("", CONNECT, webSocket));
}
protected WebSocketHandler postProcessMapping(WebSocket webSocket, AtmosphereRequest request, WebSocketHandlerProxy w) {
WebSocketHandlerProxy p = null;
String path = w.path();
if (wildcardMapping()) {
String pathInfo = null;
try {
pathInfo = request.getPathInfo();
} catch (IllegalStateException ex) {
// http://java.net/jira/browse/GRIZZLY-1301
}
if (pathInfo != null) {
path = request.getServletPath() + pathInfo;
} else {
path = request.getServletPath();
}
if (path == null || path.isEmpty()) {
path = "/";
}
synchronized (handlers) {
p = handlers.get(path);
if (p == null) {
// AtmosphereHandlerService
WebSocketHandlerService a = w.proxied.getClass().getAnnotation(WebSocketHandlerService.class);
if (a != null) {
String targetPath = a.path();
if (targetPath.indexOf("{") != -1 && targetPath.indexOf("}") != -1) {
try {
boolean singleton = w.proxied.getClass().getAnnotation(Singleton.class) != null;
if (!singleton) {
registerWebSocketHandler(path, new WebSocketHandlerProxy(a.broadcaster(),
framework.newClassInstance(w.proxied.getClass())));
} else {
registerWebSocketHandler(path, new WebSocketHandlerProxy(a.broadcaster(), w));
}
p = handlers.get(path);
} catch (Throwable e) {
logger.warn("Unable to create WebSocketHandler", e);
}
}
}
}
}
}
try {
webSocket.resource().setBroadcaster(AnnotationUtil.broadcaster(framework, p != null ? p.broadcasterClazz : w.broadcasterClazz, path));
} catch (Exception e) {
logger.error("", e);
}
return p != null ? p.proxied : w.proxied;
}
private void dispatch(final WebSocket webSocket, List<AtmosphereRequest> list) {
if (list == null) return;
for (final AtmosphereRequest r : list) {
if (r != null) {
r.dispatchRequestAsynchronously();
asyncExecutor.execute(new Runnable() {
@Override
public void run() {
AtmosphereResponse w = new AtmosphereResponse(webSocket, r, destroyable);
try {
dispatch(webSocket, r, w);
} finally {
r.destroy();
w.destroy();
}
}
});
}
}
}
@Override
public void invokeWebSocketProtocol(final WebSocket webSocket, String webSocketMessage) {
WebSocketHandler webSocketHandler = webSocket.webSocketHandler();
if (webSocketHandler == null) {
if (!WebSocketProtocolStream.class.isAssignableFrom(webSocketProtocol.getClass())) {
List<AtmosphereRequest> list = webSocketProtocol.onMessage(webSocket, webSocketMessage);
dispatch(webSocket, list);
} else {
logger.debug("The WebServer doesn't support streaming. Wrapping the message as stream.");
invokeWebSocketProtocol(webSocket, new StringReader(webSocketMessage));
return;
}
} else {
if (!WebSocketStreamingHandler.class.isAssignableFrom(webSocketHandler.getClass())) {
try {
webSocketHandler.onTextMessage(webSocket, webSocketMessage);
} catch (Exception ex) {
handleException(ex, webSocket, webSocketHandler);
}
} else {
logger.debug("The WebServer doesn't support streaming. Wrapping the message as stream.");
invokeWebSocketProtocol(webSocket, new StringReader(webSocketMessage));
return;
}
}
notifyListener(webSocket, new WebSocketEventListener.WebSocketEvent(webSocketMessage, MESSAGE, webSocket));
}
@Override
public void invokeWebSocketProtocol(WebSocket webSocket, byte[] data, int offset, int length) {
WebSocketHandler webSocketHandler = webSocket.webSocketHandler();
if (webSocketHandler == null) {
if (!WebSocketProtocolStream.class.isAssignableFrom(webSocketProtocol.getClass())) {
List<AtmosphereRequest> list = webSocketProtocol.onMessage(webSocket, data, offset, length);
dispatch(webSocket, list);
} else {
logger.debug("The WebServer doesn't support streaming. Wrapping the message as stream.");
invokeWebSocketProtocol(webSocket, new ByteArrayInputStream(data, offset, length));
return;
}
} else {
if (!WebSocketStreamingHandler.class.isAssignableFrom(webSocketHandler.getClass())) {
try {
webSocketHandler.onByteMessage(webSocket, data, offset, length);
} catch (Exception ex) {
handleException(ex, webSocket, webSocketHandler);
}
} else {
logger.debug("The WebServer doesn't support streaming. Wrapping the message as stream.");
invokeWebSocketProtocol(webSocket, new ByteArrayInputStream(data, offset, length));
return;
}
}
notifyListener(webSocket, new WebSocketEventListener.WebSocketEvent<byte[]>(data, MESSAGE, webSocket));
}
private void handleException(Exception ex, WebSocket webSocket, WebSocketHandler webSocketHandler) {
logger.error("", ex);
AtmosphereResource r = webSocket.resource();
if (r != null) {
webSocketHandler.onError(webSocket, new WebSocketException(ex,
new AtmosphereResponse.Builder()
.request(r != null ? AtmosphereResourceImpl.class.cast(r).getRequest(false) : null)
.status(500)
.statusMessage("Server Error").build()));
}
}
@Override
public void invokeWebSocketProtocol(WebSocket webSocket, InputStream stream) {
WebSocketHandler webSocketHandler = webSocket.webSocketHandler();
try {
if (webSocketHandler == null) {
if (WebSocketProtocolStream.class.isAssignableFrom(webSocketProtocol.getClass())) {
List<AtmosphereRequest> list = WebSocketProtocolStream.class.cast(webSocketProtocol).onBinaryStream(webSocket, stream);
dispatch(webSocket, list);
} else {
dispatchStream(webSocket, stream);
return;
}
} else {
if (WebSocketStreamingHandler.class.isAssignableFrom(webSocketHandler.getClass())) {
WebSocketStreamingHandler.class.cast(webSocketHandler).onBinaryStream(webSocket, stream);
} else {
dispatchStream(webSocket, stream);
return;
}
}
} catch (Exception ex) {
handleException(ex, webSocket, webSocketHandler);
}
notifyListener(webSocket, new WebSocketEventListener.WebSocketEvent<InputStream>(stream, MESSAGE, webSocket));
}
@Override
public void invokeWebSocketProtocol(WebSocket webSocket, Reader reader) {
WebSocketHandler webSocketHandler = webSocket.webSocketHandler();
try {
if (webSocketHandler == null) {
if (WebSocketProtocolStream.class.isAssignableFrom(webSocketProtocol.getClass())) {
List<AtmosphereRequest> list = WebSocketProtocolStream.class.cast(webSocketProtocol).onTextStream(webSocket, reader);
dispatch(webSocket, list);
} else {
dispatchReader(webSocket, reader);
return;
}
} else {
if (WebSocketStreamingHandler.class.isAssignableFrom(webSocketHandler.getClass())) {
WebSocketStreamingHandler.class.cast(webSocketHandler).onTextStream(webSocket, reader);
} else {
dispatchReader(webSocket, reader);
return;
}
}
} catch (Exception ex) {
handleException(ex, webSocket, webSocketHandler);
}
notifyListener(webSocket, new WebSocketEventListener.WebSocketEvent<Reader>(reader, MESSAGE, webSocket));
}
/**
* Dispatch to request/response to the {@link org.atmosphere.cpr.AsyncSupport} implementation as it was a normal HTTP request.
*
* @param request a {@link AtmosphereRequest}
* @param r a {@link AtmosphereResponse}
*/
public final void dispatch(WebSocket webSocket, final AtmosphereRequest request, final AtmosphereResponse r) {
if (request == null) return;
try {
framework.doCometSupport(request, r);
} catch (Throwable e) {
logger.warn("Failed invoking AtmosphereFramework.doCometSupport()", e);
webSocketProtocol.onError(webSocket, new WebSocketException(e,
new AtmosphereResponse.Builder()
.request(request)
.status(500)
.statusMessage("Server Error").build()));
return;
}
if (r.getStatus() >= 400) {
webSocketProtocol.onError(webSocket, new WebSocketException("Status code higher or equal than 400", r));
}
}
@Override
public void close(WebSocket webSocket, int closeCode) {
logger.trace("WebSocket closed with {}", closeCode);
WebSocketHandler webSocketHandler = webSocket.webSocketHandler();
// A message might be in the process of being processed and the websocket gets closed. In that corner
// case the webSocket.resource will be set to false and that might cause NPE in some WebSocketProcol implementation
// We could potentially synchronize on webSocket but since it is a rare case, it is better to not synchronize.
// synchronized (webSocket) {
closeCode = closeCode(closeCode);
notifyListener(webSocket, new WebSocketEventListener.WebSocketEvent(closeCode, CLOSE, webSocket));
AtmosphereResourceImpl resource = (AtmosphereResourceImpl) webSocket.resource();
if (resource == null) {
logger.debug("Already closed {}", webSocket);
} else {
logger.trace("About to close AtmosphereResource for {}", resource.uuid());
AtmosphereRequest r = resource.getRequest(false);
AtmosphereResponse s = resource.getResponse(false);
try {
webSocketProtocol.onClose(webSocket);
if (resource != null && resource.isInScope()) {
if (webSocketHandler != null) {
webSocketHandler.onClose(webSocket);
}
Object o = r.getAttribute(ASYNCHRONOUS_HOOK);
AsynchronousProcessor.AsynchronousProcessorHook h;
- if (o != null && AsynchronousProcessor.class.isAssignableFrom(o.getClass())) {
+ if (o != null && AsynchronousProcessor.AsynchronousProcessorHook.class.isAssignableFrom(o.getClass())) {
h = (AsynchronousProcessor.AsynchronousProcessorHook) o;
if (!resource.isCancelled()) {
if (closeCode == 1005) {
h.closed();
} else {
h.timedOut();
}
}
}
resource.setIsInScope(false);
try {
resource.cancel();
} catch (IOException e) {
logger.trace("", e);
}
AtmosphereResourceImpl.class.cast(resource)._destroy();
}
} finally {
if (webSocket != null) {
try {
r.setAttribute(WebSocket.CLEAN_CLOSE, Boolean.TRUE);
webSocket.resource(null).close(s);
} catch (IOException e) {
logger.trace("", e);
}
}
if (r != null) {
r.destroy(true);
}
if (s != null) {
s.destroy(true);
}
}
}
}
@Override
public void destroy() {
boolean shared = framework.isShareExecutorServices();
if (asyncExecutor != null && !shared) {
asyncExecutor.shutdown();
}
if (scheduler != null && !shared) {
scheduler.shutdown();
}
}
private int closeCode(int closeCode) {
// Tomcat and Jetty differ, same with browser
if (closeCode == 1000 && framework.getAsyncSupport().getContainerName().contains("Tomcat")) {
closeCode = 1005;
}
return closeCode;
}
@Override
public void notifyListener(WebSocket webSocket, WebSocketEventListener.WebSocketEvent event) {
AtmosphereResource resource = webSocket.resource();
if (resource == null) return;
AtmosphereResourceImpl r = AtmosphereResourceImpl.class.cast(resource);
for (AtmosphereResourceEventListener l : r.atmosphereResourceEventListener()) {
if (WebSocketEventListener.class.isAssignableFrom(l.getClass())) {
try {
switch (event.type()) {
case CONNECT:
WebSocketEventListener.class.cast(l).onConnect(event);
break;
case DISCONNECT:
WebSocketEventListener.class.cast(l).onDisconnect(event);
break;
case CONTROL:
WebSocketEventListener.class.cast(l).onControl(event);
break;
case MESSAGE:
WebSocketEventListener.class.cast(l).onMessage(event);
break;
case HANDSHAKE:
WebSocketEventListener.class.cast(l).onHandshake(event);
break;
case CLOSE:
boolean isClosedByClient = r.getAtmosphereResourceEvent().isClosedByClient();
l.onDisconnect(new AtmosphereResourceEventImpl(r, !isClosedByClient, false, isClosedByClient, null));
WebSocketEventListener.class.cast(l).onDisconnect(event);
WebSocketEventListener.class.cast(l).onClose(event);
break;
}
} catch (Throwable t) {
logger.debug("Listener error {}", t);
try {
WebSocketEventListener.class.cast(l).onThrowable(new AtmosphereResourceEventImpl(r, false, false, t));
} catch (Throwable t2) {
logger.warn("Listener error {}", t2);
}
}
} else {
switch (event.type()) {
case DISCONNECT:
case CLOSE:
boolean isClosedByClient = r.getAtmosphereResourceEvent().isClosedByClient();
l.onDisconnect(new AtmosphereResourceEventImpl(r, !isClosedByClient, false, isClosedByClient, null));
break;
}
}
}
}
public static final Map<String, String> configureHeader(AtmosphereRequest request) {
Map<String, String> headers = new HashMap<String, String>();
Enumeration<String> e = request.getParameterNames();
String s;
while (e.hasMoreElements()) {
s = e.nextElement();
headers.put(s, request.getParameter(s));
}
headers.put(HeaderConfig.X_ATMOSPHERE_TRANSPORT, HeaderConfig.WEBSOCKET_TRANSPORT);
return headers;
}
protected void dispatchStream(WebSocket webSocket, InputStream is) throws IOException {
int read = 0;
ByteBuffer bb = webSocket.bb;
try {
while (read > -1) {
bb.position(bb.position() + read);
if (bb.remaining() == 0) {
resizeByteBuffer(webSocket);
}
read = is.read(bb.array(), bb.position(), bb.remaining());
}
bb.flip();
invokeWebSocketProtocol(webSocket, bb.array(), 0, bb.limit());
} finally {
bb.clear();
}
}
protected void dispatchReader(WebSocket webSocket, Reader r) throws IOException {
int read = 0;
CharBuffer cb = webSocket.cb;
try {
while (read > -1) {
cb.position(cb.position() + read);
if (cb.remaining() == 0) {
resizeCharBuffer(webSocket);
}
read = r.read(cb.array(), cb.position(), cb.remaining());
}
cb.flip();
invokeWebSocketProtocol(webSocket, cb.toString());
} finally {
cb.clear();
}
}
private void resizeByteBuffer(WebSocket webSocket) throws IOException {
int maxSize = getByteBufferMaxSize();
ByteBuffer bb = webSocket.bb;
if (bb.limit() >= maxSize) {
throw new IOException("Message Buffer too small. Use " + StreamingHttpProtocol.class.getName() + " when streaming over websocket.");
}
long newSize = bb.limit() * 2;
if (newSize > maxSize) {
newSize = maxSize;
}
// Cast is safe. newSize < maxSize and maxSize is an int
ByteBuffer newBuffer = ByteBuffer.allocate((int) newSize);
bb.rewind();
newBuffer.put(bb);
webSocket.bb = newBuffer;
}
private void resizeCharBuffer(WebSocket webSocket) throws IOException {
int maxSize = getCharBufferMaxSize();
CharBuffer cb = webSocket.cb;
if (cb.limit() >= maxSize) {
throw new IOException("Message Buffer too small. Use " + StreamingHttpProtocol.class.getName() + " when streaming over websocket.");
}
long newSize = cb.limit() * 2;
if (newSize > maxSize) {
newSize = maxSize;
}
// Cast is safe. newSize < maxSize and maxSize is an int
CharBuffer newBuffer = CharBuffer.allocate((int) newSize);
cb.rewind();
newBuffer.put(cb);
webSocket.cb = newBuffer;
}
/**
* Obtain the current maximum size (in bytes) of the buffer used for binary
* messages.
*/
public final int getByteBufferMaxSize() {
return byteBufferMaxSize;
}
/**
* Set the maximum size (in bytes) of the buffer used for binary messages.
*/
public final void setByteBufferMaxSize(int byteBufferMaxSize) {
this.byteBufferMaxSize = byteBufferMaxSize;
}
/**
* Obtain the current maximum size (in characters) of the buffer used for
* binary messages.
*/
public final int getCharBufferMaxSize() {
return charBufferMaxSize;
}
/**
* Set the maximum size (in characters) of the buffer used for textual
* messages.
*/
public final void setCharBufferMaxSize(int charBufferMaxSize) {
this.charBufferMaxSize = charBufferMaxSize;
}
protected void optimizeMapping() {
for (String w : framework.getAtmosphereConfig().handlers().keySet()) {
if (w.contains("{") && w.contains("}")) {
wildcardMapping = true;
}
}
}
public boolean wildcardMapping() {
return wildcardMapping;
}
}
| true | true | public void close(WebSocket webSocket, int closeCode) {
logger.trace("WebSocket closed with {}", closeCode);
WebSocketHandler webSocketHandler = webSocket.webSocketHandler();
// A message might be in the process of being processed and the websocket gets closed. In that corner
// case the webSocket.resource will be set to false and that might cause NPE in some WebSocketProcol implementation
// We could potentially synchronize on webSocket but since it is a rare case, it is better to not synchronize.
// synchronized (webSocket) {
closeCode = closeCode(closeCode);
notifyListener(webSocket, new WebSocketEventListener.WebSocketEvent(closeCode, CLOSE, webSocket));
AtmosphereResourceImpl resource = (AtmosphereResourceImpl) webSocket.resource();
if (resource == null) {
logger.debug("Already closed {}", webSocket);
} else {
logger.trace("About to close AtmosphereResource for {}", resource.uuid());
AtmosphereRequest r = resource.getRequest(false);
AtmosphereResponse s = resource.getResponse(false);
try {
webSocketProtocol.onClose(webSocket);
if (resource != null && resource.isInScope()) {
if (webSocketHandler != null) {
webSocketHandler.onClose(webSocket);
}
Object o = r.getAttribute(ASYNCHRONOUS_HOOK);
AsynchronousProcessor.AsynchronousProcessorHook h;
if (o != null && AsynchronousProcessor.class.isAssignableFrom(o.getClass())) {
h = (AsynchronousProcessor.AsynchronousProcessorHook) o;
if (!resource.isCancelled()) {
if (closeCode == 1005) {
h.closed();
} else {
h.timedOut();
}
}
}
resource.setIsInScope(false);
try {
resource.cancel();
} catch (IOException e) {
logger.trace("", e);
}
AtmosphereResourceImpl.class.cast(resource)._destroy();
}
} finally {
if (webSocket != null) {
try {
r.setAttribute(WebSocket.CLEAN_CLOSE, Boolean.TRUE);
webSocket.resource(null).close(s);
} catch (IOException e) {
logger.trace("", e);
}
}
if (r != null) {
r.destroy(true);
}
if (s != null) {
s.destroy(true);
}
}
}
}
| public void close(WebSocket webSocket, int closeCode) {
logger.trace("WebSocket closed with {}", closeCode);
WebSocketHandler webSocketHandler = webSocket.webSocketHandler();
// A message might be in the process of being processed and the websocket gets closed. In that corner
// case the webSocket.resource will be set to false and that might cause NPE in some WebSocketProcol implementation
// We could potentially synchronize on webSocket but since it is a rare case, it is better to not synchronize.
// synchronized (webSocket) {
closeCode = closeCode(closeCode);
notifyListener(webSocket, new WebSocketEventListener.WebSocketEvent(closeCode, CLOSE, webSocket));
AtmosphereResourceImpl resource = (AtmosphereResourceImpl) webSocket.resource();
if (resource == null) {
logger.debug("Already closed {}", webSocket);
} else {
logger.trace("About to close AtmosphereResource for {}", resource.uuid());
AtmosphereRequest r = resource.getRequest(false);
AtmosphereResponse s = resource.getResponse(false);
try {
webSocketProtocol.onClose(webSocket);
if (resource != null && resource.isInScope()) {
if (webSocketHandler != null) {
webSocketHandler.onClose(webSocket);
}
Object o = r.getAttribute(ASYNCHRONOUS_HOOK);
AsynchronousProcessor.AsynchronousProcessorHook h;
if (o != null && AsynchronousProcessor.AsynchronousProcessorHook.class.isAssignableFrom(o.getClass())) {
h = (AsynchronousProcessor.AsynchronousProcessorHook) o;
if (!resource.isCancelled()) {
if (closeCode == 1005) {
h.closed();
} else {
h.timedOut();
}
}
}
resource.setIsInScope(false);
try {
resource.cancel();
} catch (IOException e) {
logger.trace("", e);
}
AtmosphereResourceImpl.class.cast(resource)._destroy();
}
} finally {
if (webSocket != null) {
try {
r.setAttribute(WebSocket.CLEAN_CLOSE, Boolean.TRUE);
webSocket.resource(null).close(s);
} catch (IOException e) {
logger.trace("", e);
}
}
if (r != null) {
r.destroy(true);
}
if (s != null) {
s.destroy(true);
}
}
}
}
|
diff --git a/blocks/sublima-app/src/main/java/com/computas/sublima/app/service/AdminService.java b/blocks/sublima-app/src/main/java/com/computas/sublima/app/service/AdminService.java
index 9e417535..1239da4c 100644
--- a/blocks/sublima-app/src/main/java/com/computas/sublima/app/service/AdminService.java
+++ b/blocks/sublima-app/src/main/java/com/computas/sublima/app/service/AdminService.java
@@ -1,1193 +1,1193 @@
package com.computas.sublima.app.service;
import com.computas.sublima.query.SparqlDispatcher;
import com.computas.sublima.query.SparulDispatcher;
import com.computas.sublima.query.impl.DefaultSparqlDispatcher;
import com.computas.sublima.query.impl.DefaultSparulDispatcher;
import com.computas.sublima.query.service.DatabaseService;
import static com.computas.sublima.query.service.SettingsService.getProperty;
import com.hp.hpl.jena.sparql.util.StringUtils;
import org.apache.cocoon.components.flow.apples.AppleRequest;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.LinkedHashSet;
/**
* A class to support the administration of Sublima
* Has methods for getting topics, statuses, languages, media types, audience etc.
*
* @author: mha
* Date: 13.mar.2008
*/
//todo Use selected interface language for all labels
public class AdminService {
private static Logger logger = Logger.getLogger(AdminService.class);
private SparqlDispatcher sparqlDispatcher = new DefaultSparqlDispatcher();
private SparulDispatcher sparulDispatcher = new DefaultSparulDispatcher();
/**
* Method to get all relation types
*
* @return RDF XML result
*/
public String getAllRelationTypes() {
String queryResult;
String queryString = StringUtils.join("\n", new String[]{
"PREFIX skos: <http://www.w3.org/2004/02/skos/core#>",
"PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>",
"DESCRIBE ?relation WHERE {",
"?relation rdfs:subPropertyOf skos:semanticRelation .",
"}"});
logger.trace("AdminService.getAllRelationTypes() executing");
queryResult = sparqlDispatcher.query(queryString).toString();
return queryResult;
}
/**
* Method to get all publishers
*
* @return A String RDF/XML containing all the publishers
*/
public String getAllPublishers() {
String queryString = StringUtils.join("\n", new String[]{
"PREFIX dct: <http://purl.org/dc/terms/>",
"PREFIX foaf: <http://xmlns.com/foaf/0.1/>",
"PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>",
"CONSTRUCT {",
" ?publisher a foaf:Agent ;",
" foaf:name ?name .",
"}",
"WHERE {",
"?publisher a foaf:Agent ;",
"foaf:name ?name .",
"}"});
logger.trace("AdminService.getAllPublishers() executing");
Object queryResult = sparqlDispatcher.query(queryString);
return queryResult.toString();
}
/**
* Method to get all statuses
*
* @return A String RDF/XML containing all the statuses
*/
public String getAllStatuses() {
String queryString = StringUtils.join("\n", new String[]{
"PREFIX wdr: <http://www.w3.org/2007/05/powder#>",
"PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>",
"CONSTRUCT {",
" ?status a wdr:DR ;",
" rdfs:label ?label .",
"}",
"WHERE {",
" ?status a wdr:DR ;",
" rdfs:label ?label .",
"}"});
logger.trace("AdminService.getAllStatuses() executing");
Object queryResult = sparqlDispatcher.query(queryString);
return queryResult.toString();
}
/**
* Method to get all statuses valid for user administration
*
* @return A String RDF/XML containing all the statuses
*/
public String getAllStatusesForUser() {
String queryString = StringUtils.join("\n", new String[]{
"PREFIX wdr: <http://www.w3.org/2007/05/powder#>\n" +
"PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n" +
"CONSTRUCT {\n" +
" <http://sublima.computas.com/status/godkjent_av_administrator> a wdr:DR ;\n" +
" rdfs:label ?label1 .\n" +
" <http://sublima.computas.com/status/inaktiv> a wdr:DR ;\n" +
" rdfs:label ?label2 .\n" +
"}\n" +
"WHERE {\n" +
" OPTIONAL {\n" +
" <http://sublima.computas.com/status/godkjent_av_administrator> a wdr:DR ;\n" +
" rdfs:label ?label1 .}\n" +
" OPTIONAL {\n" +
" <http://sublima.computas.com/status/inaktiv> a wdr:DR ;\n" +
" rdfs:label ?label2 .}\n" +
"}"});
logger.trace("AdminService.getAllStatusesForUser() executing");
Object queryResult = sparqlDispatcher.query(queryString);
return queryResult.toString();
}
/**
* Method to get all languages
*
* @return A String RDF/XML containing all the languages
*/
public String getAllLanguages() {
String queryString = StringUtils.join("\n", new String[]{
"PREFIX lingvoj: <http://www.lingvoj.org/ontology#>",
"PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>",
"CONSTRUCT {",
"?language a lingvoj:Lingvo ;",
" rdfs:label ?label .",
"}",
"WHERE {",
"?language a lingvoj:Lingvo ;",
" rdfs:label ?label .",
"}"});
logger.trace("AdminService.getAllLanguages() executing");
Object queryResult = sparqlDispatcher.query(queryString);
return queryResult.toString();
}
/**
* Method to get distinct labels for different properties
* NOTE: This doesn't anymore check what is actually used. It became such a performance liability that we had to skip it.
*
* @param rdfType The full URI (unless it is in the dct or rdfs namespaces) with pointy brackets for the type of subject that you want.
* @param property The full URI (unless it is in the dct or rdfs namespaces) with pointy brackets for the property that connects the resource to the subject. Not used at the moment.
* @return A String containing SPARQL Result Set XML with the languages
*/
public String getDistinctAndUsedLabels(String rdfType, String property) {
String queryString = StringUtils.join("\n", new String[]{
"PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>",
"PREFIX dct: <http://purl.org/dc/terms/>",
"SELECT DISTINCT ?uri ?label",
"WHERE {",
"?uri a " + rdfType + " ;",
" rdfs:label ?label .",
"}"});
logger.trace("AdminService.getDistinctAndUsedLabels() executing");
Object queryResult = sparqlDispatcher.query(queryString);
return queryResult.toString();
}
/**
* Method to get all media types
*
* @return A String RDF/XML containing all the media types
*/
public String getAllMediaTypes() {
String queryString = StringUtils.join("\n", new String[]{
"PREFIX dct: <http://purl.org/dc/terms/>",
"PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>",
"CONSTRUCT {",
" ?mediatype a dct:MediaType ;",
" rdfs:label ?label .",
"}",
"WHERE {",
" ?mediatype a dct:MediaType ;",
" rdfs:label ?label .",
"}"});
logger.trace("AdminService.getAllMediaTypes() executing");
Object queryResult = sparqlDispatcher.query(queryString);
return queryResult.toString();
}
/**
* Method to get all audiences
*
* @return A String RDF/XML containing all the audiences
*/
public String getAllAudiences() {
String queryString = StringUtils.join("\n", new String[]{
"PREFIX dct: <http://purl.org/dc/terms/>",
"PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>",
"CONSTRUCT {",
" ?audience a dct:AgentClass ;",
" rdfs:label ?label .",
"}",
"WHERE {",
" ?audience a dct:AgentClass ;",
" rdfs:label ?label .",
"}"});
logger.trace("AdminService.getAllAudiences() executing");
Object queryResult = sparqlDispatcher.query(queryString);
return queryResult.toString();
}
/**
* Method to get a resource by its URI
*
* @return A String RDF/XML containing the resource
*/
public Object getResourceByURI(String uri) {
try {
uri = "<" + uri + ">";
} catch (Exception e) {
e.printStackTrace();
}
String queryString = StringUtils.join("\n", new String[]{
"PREFIX dct: <http://purl.org/dc/terms/>",
"PREFIX sub: <http://xmlns.computas.com/sublima#>",
"PREFIX sioc: <http://rdfs.org/sioc/ns#>",
"DESCRIBE " + uri + " ?comment ?commentcreator",
"WHERE {",
" OPTIONAL { " + uri + " sub:comment ?comment . ",
" ?comment sioc:has_creator ?commentcreator .",
"}",
"}"});
logger.trace("AdminService.getResourceByURI() executing");
Object queryResult = sparqlDispatcher.query(queryString);
return queryResult.toString();
}
public String insertPublisher(String publishername, String language) {
String publisherURI = publishername.replace(" ", "_");
publisherURI = publisherURI.replace(".", "_");
publisherURI = publisherURI.replace(",", "_");
publisherURI = publisherURI.replace("/", "_");
publisherURI = publisherURI.replace("-", "_");
publisherURI = publisherURI.replace("'", "_");
publisherURI = getProperty("sublima.base.url") + "agent/" + publisherURI;
String insertPublisherByName =
"PREFIX dct: <http://purl.org/dc/terms/>\n" +
"PREFIX foaf: <http://xmlns.com/foaf/0.1/>\n" +
"INSERT\n" +
"{\n" +
"<" + publisherURI + "> a foaf:Agent ;\n" +
"foaf:name \"" + publishername + "\"@" + language + " .\n" +
"}";
logger.info("updatePublisherByURI() executing");
boolean success = false;
success = sparulDispatcher.query(insertPublisherByName);
logger.info("updatePublisherByURI() ---> " + publisherURI + " -- INSERT NEW NAME --> " + success);
if (success) {
return publisherURI;
} else {
return "";
}
}
/**
* Method to get all topics
*
* @return A String RDF/XML containing all the topics
*/
public String getAllTopics() {
String queryString = StringUtils.join("\n", new String[]{
"PREFIX skos: <http://www.w3.org/2004/02/skos/core#>",
"PREFIX wdr: <http://www.w3.org/2007/05/powder#>",
"CONSTRUCT {",
" ?topic a skos:Concept ;",
" skos:prefLabel ?label ;",
" wdr:describedBy ?status .",
"}",
"WHERE {",
" ?topic a skos:Concept ;",
" skos:prefLabel ?label ;",
" wdr:describedBy ?status .",
"}"});
logger.trace("AdminService.getAllTopics() executing");
Object queryResult = sparqlDispatcher.query(queryString);
return queryResult.toString();
}
public String getTopicByURI(String uri) {
String queryString = StringUtils.join("\n", new String[]{
"PREFIX dct: <http://purl.org/dc/terms/>",
"PREFIX skos: <http://www.w3.org/2004/02/skos/core#>",
"PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>",
"PREFIX wdr: <http://www.w3.org/2007/05/powder#>",
"DESCRIBE <" + uri + ">",
"WHERE {",
"<" + uri + "> a skos:Concept . }"});
logger.trace("AdminService.getTopicByURI() executing");
Object queryResult = sparqlDispatcher.query(queryString);
return queryResult.toString();
}
public String getTopicsAsJSON() {
String queryString = StringUtils.join("\n", new String[]{
"PREFIX skos: <http://www.w3.org/2004/02/skos/core#>",
"PREFIX wdr: <http://www.w3.org/2007/05/powder#>",
"SELECT ?label",
"WHERE {",
" ?topic a skos:Concept .",
" {?topic skos:prefLabel ?label .}",
" UNION {",
" ?topic skos:altLabel ?label . }",
" ?topic wdr:describedBy <http://sublima.computas.com/status/godkjent_av_administrator> .",
"}",
"ORDER BY ?label"});
logger.trace("AdminService.getTopicByPartialName() executing");
Object queryResult = sparqlDispatcher.getResultsAsJSON(queryString);
return queryResult.toString();
}
public String getPublishersAsJSON() {
String queryString = StringUtils.join("\n", new String[]{
"PREFIX dct: <http://purl.org/dc/terms/>",
"PREFIX foaf: <http://xmlns.com/foaf/0.1/>",
"PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>",
"SELECT ?label",
"WHERE {",
"?o a foaf:Agent ; ",
" foaf:name ?label .",
"?s ?p ?o .",
"}",
"ORDER BY ?label"});
logger.trace("AdminService.getPublishersAsJSON() executing");
Object queryResult = sparqlDispatcher.getResultsAsJSON(queryString);
return queryResult.toString();
}
public String getTopicResourcesByURI(String uri) {
String queryString = StringUtils.join("\n", new String[]{
"PREFIX dct: <http://purl.org/dc/terms/>",
"PREFIX skos: <http://www.w3.org/2004/02/skos/core#>",
"DESCRIBE ?resource",
"WHERE {",
" ?resource dct:subject <" + uri + "> . ",
"}"});
logger.trace("AdminService.getTopicResourcesByURI() executing");
Object queryResult = sparqlDispatcher.query(queryString);
return queryResult.toString();
}
public String getThemeTopics() {
String queryString = StringUtils.join("\n", new String[]{
"PREFIX sub: <http://xmlns.computas.com/sublima#>",
"PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>",
"PREFIX skos: <http://www.w3.org/2004/02/skos/core#>",
"PREFIX wdr: <http://www.w3.org/2007/05/powder#>",
"DESCRIBE ?theme",
"WHERE {",
" ?theme a skos:Concept .",
" ?theme sub:theme \"true\"^^xsd:boolean .",
" ?theme wdr:describedBy <http://sublima.computas.com/status/godkjent_av_administrator> .",
"}"});
logger.trace("AdminService.getTopicByURI() executing");
Object queryResult = sparqlDispatcher.query(queryString);
return queryResult.toString();
}
public String getAllUsers() {
String queryString = StringUtils.join("\n", new String[]{
"PREFIX sioc: <http://rdfs.org/sioc/ns#>",
"PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>",
"DESCRIBE ?user",
"WHERE {",
" ?user a sioc:User ;",
" rdfs:label ?label .",
"}"});
logger.trace("AdminService.getAllUsers() executing");
Object queryResult = sparqlDispatcher.query(queryString);
return queryResult.toString();
}
public String getUserByURI(String uri) {
if (uri == null) {
return "";
}
String queryString = StringUtils.join("\n", new String[]{
"PREFIX sioc: <http://rdfs.org/sioc/ns#>",
"DESCRIBE <" + uri + ">"});
logger.trace("AdminService.getUserbyURI() executing");
Object queryResult = sparqlDispatcher.query(queryString);
return queryResult.toString();
}
public String getRelationByURI(String uri) {
String queryString = StringUtils.join("\n", new String[]{
"DESCRIBE <" + uri + ">"});
logger.trace("AdminService.getRelationByURI() executing");
Object queryResult = sparqlDispatcher.query(queryString);
return queryResult.toString();
}
private static String convertToHex(byte[] data) {
StringBuilder buf = new StringBuilder();
for (int i = 0; i < data.length; i++) {
int halfbyte = (data[i] >>> 4) & 0x0F;
int two_halfs = 0;
do {
if ((0 <= halfbyte) && (halfbyte <= 9))
buf.append((char) ('0' + halfbyte));
else
buf.append((char) ('a' + (halfbyte - 10)));
halfbyte = data[i] & 0x0F;
} while (two_halfs++ < 1);
}
return buf.toString();
}
public String generateSHA1(String text)
throws NoSuchAlgorithmException, UnsupportedEncodingException {
MessageDigest md;
md = MessageDigest.getInstance("SHA-1");
byte[] sha1hash = new byte[40];
md.update(text.getBytes("UTF-8"), 0, text.length());
//todo simplify
sha1hash = md.digest();
return convertToHex(sha1hash);
}
public String getTopicsByLetter(String letter) {
if (letter.equalsIgnoreCase("0-9")) {
letter = "[0-9]";
}
String queryString = StringUtils.join("\n", new String[]{
"PREFIX skos: <http://www.w3.org/2004/02/skos/core#>",
"PREFIX wdr: <http://www.w3.org/2007/05/powder#>",
"PREFIX dct: <http://purl.org/dc/terms/>",
"PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>",
"CONSTRUCT { ?topic a skos:Concept ; rdfs:label ?label . }",
"WHERE {",
" ?topic a skos:Concept .",
" {?topic skos:prefLabel ?label .}",
" UNION {",
" ?topic skos:altLabel ?label . }",
" ?topic wdr:describedBy <http://sublima.computas.com/status/godkjent_av_administrator> .",
"FILTER regex(str(?label), \"^" + letter + "\", \"i\")",
"}"});
logger.trace("AdminService.getTopicResourcesByURI() executing");
Object queryResult = sparqlDispatcher.query(queryString);
if (queryResult == null) {
return "<rdf:RDF></rdf:RDF>";
} else {
return queryResult.toString();
}
}
public boolean validateURL(String url) {
String ourcode;
try {
// Do a URL check so that we know we have a valid URL
URLActions urlAction = new URLActions(url);
ourcode = urlAction.getCode();
}
catch (NullPointerException e) {
e.printStackTrace();
return false;
}
return "302".equals(ourcode) ||
"303".equals(ourcode) ||
"304".equals(ourcode) ||
"305".equals(ourcode) ||
"307".equals(ourcode) ||
ourcode.startsWith("2");
}
public String getAllRoles() {
String queryString = StringUtils.join("\n", new String[]{
"PREFIX sioc: <http://rdfs.org/sioc/ns#>",
"PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>",
"DESCRIBE ?role",
"WHERE {",
" ?role a sioc:Role ;",
" rdfs:label ?label .",
"}"});
logger.trace("AdminService.getAllRoles() executing");
Object queryResult = sparqlDispatcher.query(queryString);
return queryResult.toString();
}
public String getRoleByURI(String uri) {
String queryString = StringUtils.join("\n", new String[]{
"DESCRIBE <" + uri + ">"});
logger.trace("AdminService.getRoleByURI() --> executing");
Object queryResult = sparqlDispatcher.query(queryString);
return queryResult.toString();
}
/**
* Method to get the role privileges based on the given URI.
* Returns the privileges as XML.
*
* @param roleuri
* @return
*/
public String getRolePrivilegesAsXML(String roleuri) {
DatabaseService dbService = new DatabaseService();
Statement statement;
ResultSet resultSet;
StringBuilder xmlBuffer = new StringBuilder();
String getRolePrivilegesString = "SELECT privilege FROM roleprivilege WHERE role = '" + roleuri + "';";
xmlBuffer.append("<c:privileges xmlns:c=\"http://xmlns.computas.com/cocoon\">\n");
logger.trace("AdminService.getRolePrivilegesAsXML --> " + getRolePrivilegesString);
try {
ResultSet rs;
Connection connection = dbService.getJavaSQLConnection();
statement = connection.createStatement();
resultSet = statement.executeQuery(getRolePrivilegesString);
while (resultSet.next()) {
xmlBuffer.append("<c:privilege>" + resultSet.getString(1) + "</c:privilege>");
}
xmlBuffer.append("</c:privileges>\n");
} catch (SQLException e) {
xmlBuffer.append("</c:privileges>\n");
e.printStackTrace();
logger.trace("AdminService.getRolePrivilegesAsXML --> FAILED\n");
}
return xmlBuffer.toString();
}
/**
* Method to get the user role based on the username
* This method use JAXP to perform a XPATH operation on the results from Joseki.
*
* @param name
* @return role
*/
public String getUserRole(String name) {
String queryString = StringUtils.join("\n", new String[]{
"PREFIX sioc: <http://rdfs.org/sioc/ns#>",
"SELECT ?role",
"WHERE {",
"?user a sioc:User ;",
" sioc:email " + name + " ;",
" sioc:has_function ?role .",
"?role a sioc:Role . }"});
logger.trace("AdminService.getUserRole() executing");
Object queryResult = sparqlDispatcher.query(queryString);
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(queryResult.toString().getBytes("UTF-8")));
XPathExpression expr = XPathFactory.newInstance().newXPath().compile("/sparql/results/result/binding/uri");
NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
return getTextContent(nodes.item(0));
} catch (Exception e) {
e.printStackTrace();
return "<empty/>";
}
}
/**
* Recursive implementation of the method
* org.w3c.dom.Node.getTextContent which is present in JDK 1.5 but not 1.4
*
* @param node Node that you need to get the text content of
* @return
* @author Tobias Hinnerup
*/
private static String getTextContent(Node node) {
Node child;
String sContent = node.getNodeValue() != null ? node.getNodeValue() : "";
NodeList nodes = node.getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
child = nodes.item(i);
sContent += child.getNodeValue() != null ? child.getNodeValue() : "";
if (nodes.item(i).getChildNodes().getLength() > 0) {
sContent += getTextContent(nodes.item(i));
}
}
return sContent;
}
/**
* Method to get the user based on the e-mail
*
* @param email
* @return role
*/
public String getUserByEmail(String email) {
String queryString = StringUtils.join("\n", new String[]{
"PREFIX sioc: <http://rdfs.org/sioc/ns#>",
"DESCRIBE ?user",
"WHERE {",
"?user a sioc:User ;",
" sioc:email " + email + " . }"});
logger.trace("AdminService.getUserByName() executing");
return (String) sparqlDispatcher.query(queryString);
}
/**
* Method to check if a given URL already exists as and URI in the data. Checks both with and without a trailing /.
*
* @param url
* @return
*/
public boolean checkForDuplicatesByURI(String url) {
String resourceWithEndingSlash;
String resourceWithoutEndingSlash;
try {
// We have to check the url both with and without an ending /
if (url.endsWith("/")) {
resourceWithEndingSlash = (String) getResourceByURI(url);
url = url.substring(0, url.length() - 1);
resourceWithoutEndingSlash = (String) getResourceByURI(url);
} else {
resourceWithoutEndingSlash = (String) getResourceByURI(url);
resourceWithEndingSlash = (String) getResourceByURI(url + "/");
}
if (resourceWithEndingSlash.contains(url)
|| resourceWithoutEndingSlash.contains(url)) {
return true;
} else {
return false;
}
} catch (Exception e) {
return false;
}
}
public StringBuilder getMostOfTheRequestXML(AppleRequest req) {
// This is such a 1999 way of doing things. There should be a generic SAX events generator
// or something that would serialise this data structure automatically in a one-liner,
// but I couldn't find it. Arguably a TODO.
StringBuilder params = new StringBuilder();
String uri = req.getCocoonRequest().getRequestURI();
int paramcount = 0;
params.append(" <request justbaseurl=\"" + uri + "\" ");
if (req.getCocoonRequest().getQueryString() != null) {
uri += "?" + req.getCocoonRequest().getQueryString();
uri = uri.replace("&", "&");
uri = uri.replace("<", "%3C");
uri = uri.replace(">", "%3E");
uri = uri.replace("#", "%23"); // A hack to get the hash alive through a clickable URL
paramcount = req.getCocoonRequest().getParameters().size();
}
params.append("paramcount=\"" + paramcount + "\" ");
params.append("requesturl=\"" + uri);
params.append("\">\n");
for (Enumeration keys = req.getCocoonRequest().getParameterNames(); keys.hasMoreElements();) {
String key = keys.nextElement().toString();
params.append("\n <param key=\"" + key.replace("<", "%3C").replace(">", "%3E") + "\">");
String[] values = req.getCocoonRequest().getParameterValues(key);
for (String value : values) {
value = value.replace("&", "&");
value = value.replace("<", "%3C");
value = value.replace(">", "%3E");
value = value.replace("#", "%23"); // A hack to get the hash alive through a clickable URL
params.append("\n <value>" + value + "</value>");
}
params.append("\n </param>");
}
return params;
}
public StringBuilder getMostOfTheRequestXMLWithPrefix(AppleRequest req) {
// This is such a 1999 way of doing things. There should be a generic SAX events generator
// or something that would serialise this data structure automatically in a one-liner,
// but I couldn't find it. Arguably a TODO.
StringBuilder params = new StringBuilder();
String uri = req.getCocoonRequest().getRequestURI();
int paramcount = 0;
params.append(" <c:request xmlns:c=\"http://xmlns.computas.com/cocoon\" justbaseurl=\"" + uri + "\" ");
if (req.getCocoonRequest().getQueryString() != null) {
uri += "?" + req.getCocoonRequest().getQueryString();
uri = uri.replace("&", "&");
uri = uri.replace("&", "&");
uri = uri.replace("<", "%3C");
uri = uri.replace(">", "%3E");
uri = uri.replace("#", "%23"); // A hack to get the hash alive through a clickable URL
paramcount = req.getCocoonRequest().getParameters().size();
}
params.append("paramcount=\"" + paramcount + "\" ");
params.append("requesturl=\"" + uri);
params.append("\">\n");
for (Enumeration keys = req.getCocoonRequest().getParameterNames(); keys.hasMoreElements();) {
String key = keys.nextElement().toString();
params.append("\n <c:param key=\"" + key + "\">");
String[] values = req.getCocoonRequest().getParameterValues(key);
for (String value : values) {
value = value.replace("&", "&");
value = value.replace("<", "%3C");
value = value.replace(">", "%3E");
value = value.replace("#", "%23"); // A hack to get the hash alive through a clickable URL
params.append("\n <c:value>" + value + "</c:value>");
}
params.append("\n </c:param>");
}
return params;
}
public String getAllTopicsByStatus(String status) {
String queryString = StringUtils.join("\n", new String[]{
"PREFIX skos: <http://www.w3.org/2004/02/skos/core#>",
"PREFIX wdr: <http://www.w3.org/2007/05/powder#>",
"PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>",
"CONSTRUCT { ?topic a skos:Concept ; rdfs:label ?label . }",
"WHERE {",
" ?topic a skos:Concept .",
" {?topic skos:prefLabel ?label .}",
" UNION {",
" ?topic skos:altLabel ?label . }",
" ?topic wdr:describedBy <" + status + "> .",
"}"});
logger.trace("AdminService.getAllTopics() executing");
Object queryResult = sparqlDispatcher.query(queryString);
return queryResult.toString();
}
/**
* Method to get all topics
*
* @return A String RDF/XML containing all the topics
*/
public String getAllTopicsWithPrefAndAltLabel() {
String queryString = StringUtils.join("\n", new String[]{
"PREFIX skos: <http://www.w3.org/2004/02/skos/core#>",
"PREFIX wdr: <http://www.w3.org/2007/05/powder#>",
"PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>",
"CONSTRUCT { ?topic a skos:Concept ; rdfs:label ?label . }",
"WHERE {",
" ?topic a skos:Concept .",
" {?topic skos:prefLabel ?label .}",
" UNION {",
" ?topic skos:altLabel ?label . }",
"}"});
logger.trace("AdminService.getAllTopics() executing");
Object queryResult = sparqlDispatcher.query(queryString);
return queryResult.toString();
}
/**
* Method to return a boolean if the expected number of hits for the given query exceeds a threshold
*
* @param query A query counting the number of hits
* @return boolean if above the given treshold.
*/
public boolean isAboveMaxNumberOfHits(String query) {
logger.trace("AdminService.isAboveMaxNumberOfHits() executing");
if (query == null) {
return true;
}
if (!query.contains("pf:textMatch")) {
return false;
}
try {
return sparqlDispatcher.query(query).toString().contains("<uri>");
} catch (Exception e) {
logger.warn("AdminService.isAboveMaxNumberOfHits() returned an error: " + e.getMessage());
e.printStackTrace();
return false;
}
}
public ArrayList<String[]> createArrayOfTopics() {
String result = getTopicsAsJSON();
ArrayList<String[]> topicList = new ArrayList<String[]>();
try {
JSONObject json = new JSONObject(result);
json = json.getJSONObject("results");
JSONArray jsonArray = json.getJSONArray("bindings");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj2 = (JSONObject) jsonArray.get(i);
obj2 = (JSONObject) obj2.get("label");
String language;
try {
language = obj2.get("xml:lang").toString();
} catch (Exception e) {
language = "";
}
topicList.add(new String[]{obj2.get("value").toString(), language});
}
} catch (JSONException e) {
e.printStackTrace();
}
return topicList;
}
public LinkedHashSet<String> createArrayOfPublishers() {
String result = getPublishersAsJSON();
LinkedHashSet<String> publisherSet = new LinkedHashSet<String>();
try {
JSONObject json = new JSONObject(result);
json = json.getJSONObject("results");
JSONArray jsonArray = json.getJSONArray("bindings");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj2 = (JSONObject) jsonArray.get(i);
obj2 = (JSONObject) obj2.get("label");
publisherSet.add(obj2.get("value").toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
return publisherSet;
}
public ArrayList<String> getTopicsByPartialName(String name, String language) {
ArrayList<String> results = new ArrayList<String>();
for (String[] s : AutocompleteCache.getTopicList()) {
if (s[0].toLowerCase().startsWith(name.toLowerCase()) && (language.equalsIgnoreCase(s[1]) || language.equals(""))) {
results.add(s[0]);
}
}
return results;
}
public ArrayList<String> getPublishersByPartialName(String name) {
ArrayList<String> results = new ArrayList<String>();
for (String s : AutocompleteCache.getPublisherSet()) {
if (s != null && s.toLowerCase().startsWith(name.toLowerCase())) {
results.add(s);
}
}
return results;
}
public String describeResource(String identifier) {
String query = "DESCRIBE <" + identifier + "> ?rest WHERE {\n" +
"<" + identifier + "> ?p ?rest . \n}";
Object result = sparqlDispatcher.query(query);
return result.toString();
}
public String getAllComments() {
String queryString = StringUtils.join("\n", new String[]{
"PREFIX sioc: <http://rdfs.org/sioc/ns#>\n" +
"PREFIX sub: <http://xmlns.computas.com/sublima#>\n" +
"PREFIX dct: <http://purl.org/dc/terms/>\n" +
"\n" +
"CONSTRUCT {\n" +
" ?comment a sioc:Item ;\n" +
" sioc:content ?content ;\n" +
" dct:dateAccepted ?date ;\n" +
" sioc:has_creator ?creator ;\n" +
" sioc:has_owner ?owner .\n" +
" ?owner a sub:Resource ;\n" +
" dct:title ?title ; \n" +
" dct:identifier ?identifier .\n" +
"}\n" +
"WHERE {\n" +
" ?comment a sioc:Item ;\n" +
" sioc:content ?content ;\n" +
" dct:dateAccepted ?date ;\n" +
" sioc:has_creator ?creator ;\n" +
" sioc:has_owner ?owner .\n" +
" ?owner a sub:Resource ;\n" +
" dct:title ?title ; \n" +
" dct:identifier ?identifier .\n" +
"}"});
logger.trace("AdminService.getAllComments() executing");
Object queryResult = sparqlDispatcher.query(queryString);
return queryResult.toString();
}
public String getTopicDetailsForTopicPage(String subject) {
String queryString = StringUtils.join("\n", new String[]{
"PREFIX dct: <http://purl.org/dc/terms/>",
"PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>",
"PREFIX skos: <http://www.w3.org/2004/02/skos/core#>",
"PREFIX wdr: <http://www.w3.org/2007/05/powder#>",
"DESCRIBE ?resource " + subject + " ?publisher ?subjects ?rest",
"WHERE {",
" ?resource dct:language ?lang;",
" dct:publisher ?publisher ;",
" dct:subject " + subject + ", ?subjects ;",
" wdr:describedBy <http://sublima.computas.com/status/godkjent_av_administrator> ;",
" ?p ?rest .}"});
logger.trace("AdminService.getTopicDetailsForTopicPage() executing");
Object queryResult = sparqlDispatcher.query(queryString);
return queryResult.toString();
}
public String getTopicDetailsForTopicPageFromAdmin(String subject) {
String queryString = StringUtils.join("\n", new String[]{
"PREFIX dct: <http://purl.org/dc/terms/>",
"PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>",
"PREFIX skos: <http://www.w3.org/2004/02/skos/core#>",
"PREFIX wdr: <http://www.w3.org/2007/05/powder#>",
"DESCRIBE ?resource " + subject + " ?publisher ?subjects ?rest",
"WHERE {",
" ?resource dct:language ?lang;",
" dct:publisher ?publisher ;",
" dct:subject " + subject + ", ?subjects ;",
" ?p ?rest .}"});
logger.trace("AdminService.getTopicDetailsForTopicPage() executing");
Object queryResult = sparqlDispatcher.query(queryString);
return queryResult.toString();
}
public String getNavigationDetailsForTopicPage(String subject) {
// This query, relies on that all relations are explicitly stated.
// I.e. a triple for both skos:broader and skos:narrower must exist.
// Small fix added allowing concepts to not have relations at all.
String sparqlConstructQuery =
"prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> \n" +
"prefix skos: <http://www.w3.org/2004/02/skos/core#> \n" +
"prefix owl: <http://www.w3.org/2002/07/owl#> \n" +
"CONSTRUCT {\n" +
subject + "\n" +
" a skos:Concept ;\n" +
" skos:prefLabel ?preflabel ; \n" +
" skos:altLabel ?altlabel ; \n" +
" skos:definition ?definition ; \n" +
" ?semrelation ?object . \n" +
"?semrelation rdfs:subPropertyOf skos:semanticRelation ;\n" +
" rdfs:label ?semrellabel ;\n" +
" a owl:ObjectProperty .\n" +
"?object skos:prefLabel ?preflabel2 ; \n" +
" a skos:Concept .\n" +
"}\n" +
"WHERE {\n" +
subject + "\n" +
" skos:prefLabel ?preflabel ;\n" +
" a skos:Concept .\n" +
"OPTIONAL {\n" +
subject + "\n" +
" skos:altLabel ?altlabel .\n" +
"}\n" +
"OPTIONAL {\n" +
subject + "\n" +
- " skos:definition ?definition ;\n" +
+ " skos:definition ?definition .\n" +
"}\n" +
"OPTIONAL {\n" +
subject + "\n" +
" ?semrelation ?object .\n" +
"?semrelation rdfs:subPropertyOf skos:semanticRelation ;\n" +
" rdfs:label ?semrellabel ;\n" +
" a owl:ObjectProperty .\n" +
"?object a skos:Concept ;\n" +
" skos:prefLabel ?preflabel2 .\n" +
"}\n" +
"}";
logger.trace("AdminService.getNavigationDetailsForTopicPage() executing");
Object queryResult = sparqlDispatcher.query(sparqlConstructQuery);
return queryResult.toString();
}
/**
* This method returns the uri of the inverse relation if such a relation exists
*
* @param relationUri The uri of the relation to check wether has an inverse relation or not
* @return a String with the uri of the inverse relation if any
*/
public String getInverseRelationUriIfAny(String relationUri) {
if (!relationUri.startsWith("<") && !relationUri.endsWith(">")) {
relationUri = "<" + relationUri + ">";
}
String sparqlConstructQuery = "PREFIX owl: <http://www.w3.org/2002/07/owl#>\n" +
"\n" +
"SELECT ?uri \n" +
"WHERE {\n" +
relationUri + " owl:inverseOf ?uri .\n" +
"}";
logger.trace("AdminService.getInverseRelationUriIfAny() executing");
Object queryResult = sparqlDispatcher.query(sparqlConstructQuery);
String inverseUri = "";
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(queryResult.toString().getBytes("UTF-8")));
XPathExpression expr = XPathFactory.newInstance().newXPath().compile("/sparql/results/result/binding/uri");
NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
return nodes.item(0) == null ? "" : getTextContent(nodes.item(0));
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
public boolean isSymmetricProperty(String relationUri) {
if (!relationUri.startsWith("<") && !relationUri.endsWith(">")) {
relationUri = "<" + relationUri + ">";
}
String sparqlConstructQuery = "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n" +
"PREFIX owl: <http://www.w3.org/2002/07/owl#>\n" +
"\n" +
"ASK { " + relationUri + " a owl:SymmetricProperty . \n" +
"}";
logger.trace("AdminService.isSymmetricProperty() executing");
Object queryResult = sparqlDispatcher.query(sparqlConstructQuery);
return queryResult.toString().contains("true");
}
public boolean isRelation(String relationUri) {
if (!relationUri.startsWith("<") && !relationUri.endsWith(">")) {
relationUri = "<" + relationUri + ">";
}
String sparqlConstructQuery = "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n" +
"\n" +
"ASK { " + relationUri + " rdfs:subPropertyOf <http://www.w3.org/2004/02/skos/core#semanticRelation> .\n}";
logger.trace("AdminService.isRelation() executing");
Object queryResult = sparqlDispatcher.query(sparqlConstructQuery);
return queryResult.toString().contains("true");
}
public boolean isInactiveUser(String name) {
String sparqlAsk = "PREFIX wdr: <http://www.w3.org/2007/05/powder#>" +
"PREFIX sioc: <http://rdfs.org/sioc/ns#>" +
"ASK { ?s sioc:email <mailto:" + name + "> ;" +
" wdr:describedBy <http://sublima.computas.com/status/inaktiv> . }";
logger.trace("AdminService.isInactiveUser() executing");
Object queryResult = sparqlDispatcher.query(sparqlAsk);
return queryResult.toString().contains("true");
}
public String query(String query) {
logger.trace("AdminService.query() executing");
Object queryResult = sparqlDispatcher.query(query);
return queryResult.toString();
}
public boolean deleteComment(String uri) {
String sparqlDelete = "DELETE {<" + uri + "> ?p1 ?o1 . ?s ?p2 <" + uri + "> .} WHERE {<" + uri + "> ?p1 ?o1 . ?s ?p2 <" + uri + "> .}";
return sparulDispatcher.query(sparqlDelete);
}
public boolean hasPublisherResources(String uri) {
String sparqlAsk = "ASK { ?s ?p <" + uri + "> . }";
logger.trace("AdminService.hasPublisherResources() executing");
Object queryResult = sparqlDispatcher.query(sparqlAsk);
return queryResult.toString().contains("true");
}
public String getPublisherByURI(String publisherURI) {
String findPublisherByURIQuery = StringUtils.join("\n", new String[]{
"PREFIX dct: <http://purl.org/dc/terms/>",
"DESCRIBE <" + publisherURI + "> ?resource ?subject",
"WHERE {",
"OPTIONAL { ?resource dct:publisher <" + publisherURI + "> .",
"?resource dct:subject ?subject . }",
"}"});
logger.trace("AdminController.showPublisherByURI() --> SPARQL query sent to dispatcher: \n" + findPublisherByURIQuery);
Object queryResult = sparqlDispatcher.query(findPublisherByURIQuery);
return queryResult.toString();
}
}
| true | true | public String getNavigationDetailsForTopicPage(String subject) {
// This query, relies on that all relations are explicitly stated.
// I.e. a triple for both skos:broader and skos:narrower must exist.
// Small fix added allowing concepts to not have relations at all.
String sparqlConstructQuery =
"prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> \n" +
"prefix skos: <http://www.w3.org/2004/02/skos/core#> \n" +
"prefix owl: <http://www.w3.org/2002/07/owl#> \n" +
"CONSTRUCT {\n" +
subject + "\n" +
" a skos:Concept ;\n" +
" skos:prefLabel ?preflabel ; \n" +
" skos:altLabel ?altlabel ; \n" +
" skos:definition ?definition ; \n" +
" ?semrelation ?object . \n" +
"?semrelation rdfs:subPropertyOf skos:semanticRelation ;\n" +
" rdfs:label ?semrellabel ;\n" +
" a owl:ObjectProperty .\n" +
"?object skos:prefLabel ?preflabel2 ; \n" +
" a skos:Concept .\n" +
"}\n" +
"WHERE {\n" +
subject + "\n" +
" skos:prefLabel ?preflabel ;\n" +
" a skos:Concept .\n" +
"OPTIONAL {\n" +
subject + "\n" +
" skos:altLabel ?altlabel .\n" +
"}\n" +
"OPTIONAL {\n" +
subject + "\n" +
" skos:definition ?definition ;\n" +
"}\n" +
"OPTIONAL {\n" +
subject + "\n" +
" ?semrelation ?object .\n" +
"?semrelation rdfs:subPropertyOf skos:semanticRelation ;\n" +
" rdfs:label ?semrellabel ;\n" +
" a owl:ObjectProperty .\n" +
"?object a skos:Concept ;\n" +
" skos:prefLabel ?preflabel2 .\n" +
"}\n" +
"}";
logger.trace("AdminService.getNavigationDetailsForTopicPage() executing");
Object queryResult = sparqlDispatcher.query(sparqlConstructQuery);
return queryResult.toString();
}
| public String getNavigationDetailsForTopicPage(String subject) {
// This query, relies on that all relations are explicitly stated.
// I.e. a triple for both skos:broader and skos:narrower must exist.
// Small fix added allowing concepts to not have relations at all.
String sparqlConstructQuery =
"prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> \n" +
"prefix skos: <http://www.w3.org/2004/02/skos/core#> \n" +
"prefix owl: <http://www.w3.org/2002/07/owl#> \n" +
"CONSTRUCT {\n" +
subject + "\n" +
" a skos:Concept ;\n" +
" skos:prefLabel ?preflabel ; \n" +
" skos:altLabel ?altlabel ; \n" +
" skos:definition ?definition ; \n" +
" ?semrelation ?object . \n" +
"?semrelation rdfs:subPropertyOf skos:semanticRelation ;\n" +
" rdfs:label ?semrellabel ;\n" +
" a owl:ObjectProperty .\n" +
"?object skos:prefLabel ?preflabel2 ; \n" +
" a skos:Concept .\n" +
"}\n" +
"WHERE {\n" +
subject + "\n" +
" skos:prefLabel ?preflabel ;\n" +
" a skos:Concept .\n" +
"OPTIONAL {\n" +
subject + "\n" +
" skos:altLabel ?altlabel .\n" +
"}\n" +
"OPTIONAL {\n" +
subject + "\n" +
" skos:definition ?definition .\n" +
"}\n" +
"OPTIONAL {\n" +
subject + "\n" +
" ?semrelation ?object .\n" +
"?semrelation rdfs:subPropertyOf skos:semanticRelation ;\n" +
" rdfs:label ?semrellabel ;\n" +
" a owl:ObjectProperty .\n" +
"?object a skos:Concept ;\n" +
" skos:prefLabel ?preflabel2 .\n" +
"}\n" +
"}";
logger.trace("AdminService.getNavigationDetailsForTopicPage() executing");
Object queryResult = sparqlDispatcher.query(sparqlConstructQuery);
return queryResult.toString();
}
|
diff --git a/TekkitRestrict/src/com/github/dreadslicer/tekkitrestrict/TRNoDupe.java b/TekkitRestrict/src/com/github/dreadslicer/tekkitrestrict/TRNoDupe.java
index 0f55423..d49efdc 100644
--- a/TekkitRestrict/src/com/github/dreadslicer/tekkitrestrict/TRNoDupe.java
+++ b/TekkitRestrict/src/com/github/dreadslicer/tekkitrestrict/TRNoDupe.java
@@ -1,138 +1,138 @@
package com.github.dreadslicer.tekkitrestrict;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryClickEvent;
public class TRNoDupe {
@SuppressWarnings("unused")
private static boolean preventAlcDupe, preventRMDupe, preventTransmuteDupe;
public static int dupeAttempts = 0;
public static String lastPlayer = "";
public static void reload() {
preventAlcDupe = tekkitrestrict.config.getBoolean("PreventAlcDupe");
preventRMDupe = tekkitrestrict.config
.getBoolean("PreventRMFurnaceDupe");
preventTransmuteDupe = tekkitrestrict.config
.getBoolean("PreventTransmuteDupe");
}
public static void handleDupes(InventoryClickEvent event) {
// event.getInventory();
Player player = tekkitrestrict.getInstance().getServer()
.getPlayer(event.getWhoClicked().getName());
int slot = event.getSlot();
String title = event.getView().getTopInventory().getTitle()
.toLowerCase();
- tekkitrestrict.log.info("t0-"+title+"-"+slot+"-"+event.isShiftClick());
+ //tekkitrestrict.log.info("t0-"+title+"-"+slot+"-"+event.isShiftClick());
// RMDupe Slot35
if (!TRPermHandler.hasPermission(player, "dupe", "bypass", "")) {
// tekkitrestrict.log.info("t0-"+title+"-");
if (title.equals("rm furnace")) {
// tekkitrestrict.log.info("t1");
if (slot == 35) {
// tekkitrestrict.log.info("t2");
if (event.isShiftClick()) {
// tekkitrestrict.log.info("t3");
if (preventRMDupe) {
event.setCancelled(true);
player.sendRawMessage("[TRDupe] you are not allowed to Shift+Click here while using a RM Furnace!");
TRLogger.Log("Dupe", player.getName()
+ " attempted to dupe using a RM Furnace!");
} else {
TRLogger.Log("Dupe", player.getName()
+ " duped using a RM Furnace!");
}
dupeAttempts++;
TRLogger.broadcastDupe(player.getName(),
"the RM Furnace", "RMFurnace");
}
}
} else if (title.equals("tank cart")) {
// tekkitrestrict.log.info("t1");
if (slot == 35) {
// tekkitrestrict.log.info("t2");
if (event.isShiftClick()) {
event.setCancelled(true);
player.sendRawMessage("[TRDupe] you are not allowed to Shift+Click here while using a Tank Cart!");
TRLogger.Log("Dupe", player.getName()
+ " attempted to dupe using a Tank Cart!");
dupeAttempts++;
TRLogger.broadcastDupe(player.getName(),
"the Tank Cart", "TankCart");
}
}
} else if (title.equals("trans tablet")) {
// slots-6 7 5 3 1 0 2
int item = event.getCurrentItem().getTypeId();
if (item == 27557) {
}
if (item == 27558) {
}
if (item == 27559) {
}
if (item == 27560) {
}
if (item == 27561) {
}
if (item == 27591) {
}
if (event.isShiftClick()) {
// if (isKlein) {
boolean isslot = slot == 0 || slot == 1 || slot == 2
|| slot == 3 || slot == 4 || slot == 5 || slot == 6
|| slot == 7;
if (isslot) {
if (preventTransmuteDupe) {
event.setCancelled(true);
player.sendRawMessage("[TRDupe] you are not allowed to Shift+Click any ");
player.sendRawMessage(" item out of the transmutation table!");
TRLogger.Log("Dupe", player.getName()
+ " attempted to transmute dupe!");
} else {
TRLogger.Log("Dupe", player.getName()
+ " attempted to transmute dupe!");
}
dupeAttempts++;
TRLogger.broadcastDupe(player.getName(),
"the Transmutation Table", "transmute");
}
// }
}
}
}
}
public static void handleDropDupes(
org.bukkit.event.player.PlayerDropItemEvent e) {
Player player = e.getPlayer();
TRNoDupe_BagCache cache;
if ((cache = TRNoDupe_BagCache.check(player)) != null) {
if (cache.hasBHBInBag) {
try {
TRNoDupe_BagCache.expire(cache);
e.setCancelled(true);
player.kickPlayer("[TRDupe] you have a Black Hole Band in your ["
+ cache.inBagColor
+ "] Alchemy Bag! Please remove it NOW!");
TRLogger.Log("Dupe", player.getName() + " ["
+ cache.inBagColor
+ " bag] attempted to dupe with the "
+ cache.dupeItem + "!");
TRLogger.broadcastDupe(player.getName(),
"the Alchemy Bag and " + cache.dupeItem, "alc");
} catch (Exception err) {
}
}
}
}
}
| true | true | public static void handleDupes(InventoryClickEvent event) {
// event.getInventory();
Player player = tekkitrestrict.getInstance().getServer()
.getPlayer(event.getWhoClicked().getName());
int slot = event.getSlot();
String title = event.getView().getTopInventory().getTitle()
.toLowerCase();
tekkitrestrict.log.info("t0-"+title+"-"+slot+"-"+event.isShiftClick());
// RMDupe Slot35
if (!TRPermHandler.hasPermission(player, "dupe", "bypass", "")) {
// tekkitrestrict.log.info("t0-"+title+"-");
if (title.equals("rm furnace")) {
// tekkitrestrict.log.info("t1");
if (slot == 35) {
// tekkitrestrict.log.info("t2");
if (event.isShiftClick()) {
// tekkitrestrict.log.info("t3");
if (preventRMDupe) {
event.setCancelled(true);
player.sendRawMessage("[TRDupe] you are not allowed to Shift+Click here while using a RM Furnace!");
TRLogger.Log("Dupe", player.getName()
+ " attempted to dupe using a RM Furnace!");
} else {
TRLogger.Log("Dupe", player.getName()
+ " duped using a RM Furnace!");
}
dupeAttempts++;
TRLogger.broadcastDupe(player.getName(),
"the RM Furnace", "RMFurnace");
}
}
} else if (title.equals("tank cart")) {
// tekkitrestrict.log.info("t1");
if (slot == 35) {
// tekkitrestrict.log.info("t2");
if (event.isShiftClick()) {
event.setCancelled(true);
player.sendRawMessage("[TRDupe] you are not allowed to Shift+Click here while using a Tank Cart!");
TRLogger.Log("Dupe", player.getName()
+ " attempted to dupe using a Tank Cart!");
dupeAttempts++;
TRLogger.broadcastDupe(player.getName(),
"the Tank Cart", "TankCart");
}
}
} else if (title.equals("trans tablet")) {
// slots-6 7 5 3 1 0 2
int item = event.getCurrentItem().getTypeId();
if (item == 27557) {
}
if (item == 27558) {
}
if (item == 27559) {
}
if (item == 27560) {
}
if (item == 27561) {
}
if (item == 27591) {
}
if (event.isShiftClick()) {
// if (isKlein) {
boolean isslot = slot == 0 || slot == 1 || slot == 2
|| slot == 3 || slot == 4 || slot == 5 || slot == 6
|| slot == 7;
if (isslot) {
if (preventTransmuteDupe) {
event.setCancelled(true);
player.sendRawMessage("[TRDupe] you are not allowed to Shift+Click any ");
player.sendRawMessage(" item out of the transmutation table!");
TRLogger.Log("Dupe", player.getName()
+ " attempted to transmute dupe!");
} else {
TRLogger.Log("Dupe", player.getName()
+ " attempted to transmute dupe!");
}
dupeAttempts++;
TRLogger.broadcastDupe(player.getName(),
"the Transmutation Table", "transmute");
}
// }
}
}
}
}
| public static void handleDupes(InventoryClickEvent event) {
// event.getInventory();
Player player = tekkitrestrict.getInstance().getServer()
.getPlayer(event.getWhoClicked().getName());
int slot = event.getSlot();
String title = event.getView().getTopInventory().getTitle()
.toLowerCase();
//tekkitrestrict.log.info("t0-"+title+"-"+slot+"-"+event.isShiftClick());
// RMDupe Slot35
if (!TRPermHandler.hasPermission(player, "dupe", "bypass", "")) {
// tekkitrestrict.log.info("t0-"+title+"-");
if (title.equals("rm furnace")) {
// tekkitrestrict.log.info("t1");
if (slot == 35) {
// tekkitrestrict.log.info("t2");
if (event.isShiftClick()) {
// tekkitrestrict.log.info("t3");
if (preventRMDupe) {
event.setCancelled(true);
player.sendRawMessage("[TRDupe] you are not allowed to Shift+Click here while using a RM Furnace!");
TRLogger.Log("Dupe", player.getName()
+ " attempted to dupe using a RM Furnace!");
} else {
TRLogger.Log("Dupe", player.getName()
+ " duped using a RM Furnace!");
}
dupeAttempts++;
TRLogger.broadcastDupe(player.getName(),
"the RM Furnace", "RMFurnace");
}
}
} else if (title.equals("tank cart")) {
// tekkitrestrict.log.info("t1");
if (slot == 35) {
// tekkitrestrict.log.info("t2");
if (event.isShiftClick()) {
event.setCancelled(true);
player.sendRawMessage("[TRDupe] you are not allowed to Shift+Click here while using a Tank Cart!");
TRLogger.Log("Dupe", player.getName()
+ " attempted to dupe using a Tank Cart!");
dupeAttempts++;
TRLogger.broadcastDupe(player.getName(),
"the Tank Cart", "TankCart");
}
}
} else if (title.equals("trans tablet")) {
// slots-6 7 5 3 1 0 2
int item = event.getCurrentItem().getTypeId();
if (item == 27557) {
}
if (item == 27558) {
}
if (item == 27559) {
}
if (item == 27560) {
}
if (item == 27561) {
}
if (item == 27591) {
}
if (event.isShiftClick()) {
// if (isKlein) {
boolean isslot = slot == 0 || slot == 1 || slot == 2
|| slot == 3 || slot == 4 || slot == 5 || slot == 6
|| slot == 7;
if (isslot) {
if (preventTransmuteDupe) {
event.setCancelled(true);
player.sendRawMessage("[TRDupe] you are not allowed to Shift+Click any ");
player.sendRawMessage(" item out of the transmutation table!");
TRLogger.Log("Dupe", player.getName()
+ " attempted to transmute dupe!");
} else {
TRLogger.Log("Dupe", player.getName()
+ " attempted to transmute dupe!");
}
dupeAttempts++;
TRLogger.broadcastDupe(player.getName(),
"the Transmutation Table", "transmute");
}
// }
}
}
}
}
|
diff --git a/src/org/accesointeligente/client/presenters/RequestStatusPresenter.java b/src/org/accesointeligente/client/presenters/RequestStatusPresenter.java
index 1e35cc1..96e34a2 100644
--- a/src/org/accesointeligente/client/presenters/RequestStatusPresenter.java
+++ b/src/org/accesointeligente/client/presenters/RequestStatusPresenter.java
@@ -1,201 +1,201 @@
/**
* Acceso Inteligente
*
* Copyright (C) 2010-2011 Fundación Ciudadano Inteligente
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.accesointeligente.client.presenters;
import org.accesointeligente.client.UserGatekeeper;
import org.accesointeligente.client.services.RequestServiceAsync;
import org.accesointeligente.client.uihandlers.RequestStatusUiHandlers;
import org.accesointeligente.model.Request;
import org.accesointeligente.model.RequestCategory;
import org.accesointeligente.shared.*;
import com.gwtplatform.mvp.client.HasUiHandlers;
import com.gwtplatform.mvp.client.Presenter;
import com.gwtplatform.mvp.client.View;
import com.gwtplatform.mvp.client.annotations.NameToken;
import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit;
import com.gwtplatform.mvp.client.annotations.UseGatekeeper;
import com.gwtplatform.mvp.client.proxy.*;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.rpc.AsyncCallback;
import java.util.Date;
import java.util.Set;
import javax.inject.Inject;
public class RequestStatusPresenter extends Presenter<RequestStatusPresenter.MyView, RequestStatusPresenter.MyProxy> implements RequestStatusUiHandlers {
public interface MyView extends View, HasUiHandlers<RequestStatusUiHandlers> {
void setDate(Date date);
void setStatus(RequestStatus status);
void setInstitutionName(String name);
void setRequestInfo(String info);
void setRequestContext(String context);
void setRequestTitle(String title);
void addRequestCategories(RequestCategory category);
void setRequestCategories(Set<RequestCategory> categories);
void editOptions(Boolean allowEdit);
}
@ProxyCodeSplit
@UseGatekeeper(UserGatekeeper.class)
@NameToken(AppPlace.REQUESTSTATUS)
public interface MyProxy extends ProxyPlace<RequestStatusPresenter> {
}
@Inject
private PlaceManager placeManager;
@Inject
private RequestServiceAsync requestService;
@Inject
public RequestStatusPresenter(EventBus eventBus, MyView view, MyProxy proxy) {
super(eventBus, view, proxy);
getView().setUiHandlers(this);
}
private Integer requestId;
private Request request;
@Override
protected void onReset() {
if (requestId != null) {
showRequest(requestId);
}
}
@Override
protected void revealInParent() {
fireEvent(new RevealContentEvent(MainPresenter.SLOT_MAIN_CONTENT, this));
}
@Override
public void prepareFromRequest(PlaceRequest request) {
super.prepareFromRequest(request);
try {
requestId = Integer.parseInt(request.getParameter("requestId", null));
} catch (Exception ex) {
requestId = null;
}
}
@Override
public void showRequest(Integer requestId) {
requestService.getRequest(requestId, new AsyncCallback<Request>() {
@Override
public void onFailure(Throwable caught) {
showNotification("No es posible recuperar la solicitud", NotificationEventType.ERROR);
}
@Override
public void onSuccess(Request result) {
if (result != null) {
setRequest(result);
getView().setStatus(result.getStatus());
getView().setInstitutionName(result.getInstitution().getName());
getView().setRequestInfo(result.getInformation());
getView().setRequestContext(result.getContext());
getView().setRequestTitle(result.getTitle());
getView().setRequestCategories(result.getCategories());
- getView().setDate(result.getConfirmationDate());
+ getView().setDate(result.getCreationDate());
getView().editOptions(requestIsEditable());
} else {
showNotification("No se puede cargar la solicitud", NotificationEventType.ERROR);
}
}
});
}
@Override
public void deleteRequest() {
requestService.deleteRequest(getRequest(), new AsyncCallback<Void>() {
@Override
public void onFailure(Throwable caught) {
showNotification("No se ha podido eliminar la solicitud", NotificationEventType.ERROR);
}
@Override
public void onSuccess(Void result) {
showNotification("Se ha eliminado la solicitud", NotificationEventType.SUCCESS);
placeManager.revealPlace(new PlaceRequest(AppPlace.LIST).with("type", RequestListType.MYREQUESTS.getType()));
}
});
}
@Override
public Request getRequest() {
return request;
}
@Override
public void setRequest(Request request) {
this.request = request;
}
@Override
public Boolean requestIsEditable() {
if (request.getStatus() == RequestStatus.DRAFT) {
return true;
} else {
return false;
}
}
@Override
public void confirmRequest() {
request.setStatus(RequestStatus.NEW);
request.setConfirmationDate(new Date());
requestService.saveRequest(request, new AsyncCallback<Request>() {
@Override
public void onFailure(Throwable caught) {
showNotification("No es posible confirmar su borrador de solicitud, por favor intentelo nuevamente", NotificationEventType.NOTICE);
}
@Override
public void onSuccess(Request result) {
showNotification("Ha confirmado su borrador de solicitud. Su solicitud será procesada a la brevedad", NotificationEventType.SUCCESS);
}
});
}
@Override
public void showNotification(String message, NotificationEventType type) {
NotificationEventParams params = new NotificationEventParams();
params.setMessage(message);
params.setType(type);
params.setDuration(NotificationEventParams.DURATION_NORMAL);
fireEvent(new NotificationEvent(params));
}
@Override
public void editRequest() {
placeManager.revealPlace(new PlaceRequest(AppPlace.EDITREQUEST).with("requestId", request.getId().toString()));
}
@Override
public void gotoMyRequests() {
placeManager.revealPlace(new PlaceRequest(AppPlace.LIST).with("type", RequestListType.MYREQUESTS.getType()));
}
}
| true | true | public void showRequest(Integer requestId) {
requestService.getRequest(requestId, new AsyncCallback<Request>() {
@Override
public void onFailure(Throwable caught) {
showNotification("No es posible recuperar la solicitud", NotificationEventType.ERROR);
}
@Override
public void onSuccess(Request result) {
if (result != null) {
setRequest(result);
getView().setStatus(result.getStatus());
getView().setInstitutionName(result.getInstitution().getName());
getView().setRequestInfo(result.getInformation());
getView().setRequestContext(result.getContext());
getView().setRequestTitle(result.getTitle());
getView().setRequestCategories(result.getCategories());
getView().setDate(result.getConfirmationDate());
getView().editOptions(requestIsEditable());
} else {
showNotification("No se puede cargar la solicitud", NotificationEventType.ERROR);
}
}
});
}
| public void showRequest(Integer requestId) {
requestService.getRequest(requestId, new AsyncCallback<Request>() {
@Override
public void onFailure(Throwable caught) {
showNotification("No es posible recuperar la solicitud", NotificationEventType.ERROR);
}
@Override
public void onSuccess(Request result) {
if (result != null) {
setRequest(result);
getView().setStatus(result.getStatus());
getView().setInstitutionName(result.getInstitution().getName());
getView().setRequestInfo(result.getInformation());
getView().setRequestContext(result.getContext());
getView().setRequestTitle(result.getTitle());
getView().setRequestCategories(result.getCategories());
getView().setDate(result.getCreationDate());
getView().editOptions(requestIsEditable());
} else {
showNotification("No se puede cargar la solicitud", NotificationEventType.ERROR);
}
}
});
}
|
diff --git a/dspace/src/org/dspace/content/InstallItem.java b/dspace/src/org/dspace/content/InstallItem.java
index 5b80c347b..bb1c20b23 100644
--- a/dspace/src/org/dspace/content/InstallItem.java
+++ b/dspace/src/org/dspace/content/InstallItem.java
@@ -1,188 +1,188 @@
/*
* InstallItem.java
*
* $Id$
*
* Version: $Revision$
*
* Date: $Date$
*
* Copyright (c) 2002, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.content;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import org.dspace.browse.Browse;
import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.AuthorizeManager;
import org.dspace.core.Context;
import org.dspace.core.Constants;
import org.dspace.eperson.EPerson;
import org.dspace.handle.HandleManager;
import org.dspace.search.DSIndexer;
import org.dspace.storage.rdbms.TableRowIterator;
import org.dspace.storage.rdbms.DatabaseManager;
/**
* Support to install item in the archive
*
* @author dstuve
* @version $Revision$
*/
public class InstallItem
{
/**
* Take an InProgressSubmission and turn it into a fully-archived Item.
* @param Context
* @param InProgressSubmission
*/
public static Item installItem(Context c, InProgressSubmission is)
throws SQLException, IOException, AuthorizeException
{
return installItem(c, is, c.getCurrentUser());
}
/**
* Take an InProgressSubmission and turn it into a fully-archived Item.
* @param Context
* @param InProgressSubmission
* @param EPerson (unused, should be removed from API)
*/
public static Item installItem(Context c, InProgressSubmission is, EPerson e2)
throws SQLException, IOException, AuthorizeException
{
Item item = is.getItem();
// create accession date
DCDate now = DCDate.getCurrent();
item.addDC("date", "accessioned", null, now.toString());
item.addDC("date", "available", null, now.toString());
// create issue date if not present
DCValue[] currentDateIssued = item.getDC("date", "issued", Item.ANY);
if(currentDateIssued.length == 0)
{
item.addDC("date", "issued", null, now.toString());
}
// create handle
String handle = HandleManager.createHandle(c, item);
String handleref = HandleManager.getCanonicalForm(handle);
// Add handle as identifier.uri DC value
item.addDC("identifier", "uri", null, handleref);
// Add format.mimetype and format.extent DC values
Bitstream[] bitstreams = item.getNonInternalBitstreams();
for (int i = 0; i < bitstreams.length; i++)
{
BitstreamFormat bf = bitstreams[i].getFormat();
item.addDC("format",
"extent",
null,
- String.valueOf(bitstreams[i].getSize()));
+ String.valueOf(bitstreams[i].getSize()) + " bytes");
item.addDC("format", "mimetype", null, bf.getMIMEType());
}
String provDescription = "Made available in DSpace on " + now +
" (GMT). " + getBitstreamProvenanceMessage(item);
if (currentDateIssued.length != 0)
{
DCDate d = new DCDate(currentDateIssued[0].value);
provDescription = provDescription + " Previous issue date: " +
d.toString();
}
// Add provenance description
item.addDC("description", "provenance", "en", provDescription);
// create collection2item mapping
is.getCollection().addItem(item);
// set in_archive=true
item.setArchived(true);
// save changes ;-)
item.update();
// add item to search and browse indices
DSIndexer.indexContent(c, item);
// remove in-progress submission
is.deleteWrapper();
// remove the submit authorization policies
// and replace them with the collection's READ
// policies
// FIXME: this is an inelegant hack, but out of time!
List policies = AuthorizeManager.getPoliciesActionFilter(c,
is.getCollection(), Constants.READ );
item.replaceAllPolicies(policies);
return item;
}
/** generate provenance-worthy description of the bitstreams
* contained in an item
* @param item
*/
public static String getBitstreamProvenanceMessage(Item myitem)
{
// Get non-internal format bitstreams
Bitstream[] bitstreams = myitem.getNonInternalBitstreams();
// Create provenance description
String mymessage = "No. of bitstreams: " + bitstreams.length + "\n";
// Add sizes and checksums of bitstreams
for (int j = 0; j < bitstreams.length; j++)
{
mymessage = mymessage + bitstreams[j].getName() + ": " +
bitstreams[j].getSize() + " bytes, checksum: " +
bitstreams[j].getChecksum() + " (" +
bitstreams[j].getChecksumAlgorithm() + ")\n";
}
return mymessage;
}
}
| true | true | public static Item installItem(Context c, InProgressSubmission is, EPerson e2)
throws SQLException, IOException, AuthorizeException
{
Item item = is.getItem();
// create accession date
DCDate now = DCDate.getCurrent();
item.addDC("date", "accessioned", null, now.toString());
item.addDC("date", "available", null, now.toString());
// create issue date if not present
DCValue[] currentDateIssued = item.getDC("date", "issued", Item.ANY);
if(currentDateIssued.length == 0)
{
item.addDC("date", "issued", null, now.toString());
}
// create handle
String handle = HandleManager.createHandle(c, item);
String handleref = HandleManager.getCanonicalForm(handle);
// Add handle as identifier.uri DC value
item.addDC("identifier", "uri", null, handleref);
// Add format.mimetype and format.extent DC values
Bitstream[] bitstreams = item.getNonInternalBitstreams();
for (int i = 0; i < bitstreams.length; i++)
{
BitstreamFormat bf = bitstreams[i].getFormat();
item.addDC("format",
"extent",
null,
String.valueOf(bitstreams[i].getSize()));
item.addDC("format", "mimetype", null, bf.getMIMEType());
}
String provDescription = "Made available in DSpace on " + now +
" (GMT). " + getBitstreamProvenanceMessage(item);
if (currentDateIssued.length != 0)
{
DCDate d = new DCDate(currentDateIssued[0].value);
provDescription = provDescription + " Previous issue date: " +
d.toString();
}
// Add provenance description
item.addDC("description", "provenance", "en", provDescription);
// create collection2item mapping
is.getCollection().addItem(item);
// set in_archive=true
item.setArchived(true);
// save changes ;-)
item.update();
// add item to search and browse indices
DSIndexer.indexContent(c, item);
// remove in-progress submission
is.deleteWrapper();
// remove the submit authorization policies
// and replace them with the collection's READ
// policies
// FIXME: this is an inelegant hack, but out of time!
List policies = AuthorizeManager.getPoliciesActionFilter(c,
is.getCollection(), Constants.READ );
item.replaceAllPolicies(policies);
return item;
}
| public static Item installItem(Context c, InProgressSubmission is, EPerson e2)
throws SQLException, IOException, AuthorizeException
{
Item item = is.getItem();
// create accession date
DCDate now = DCDate.getCurrent();
item.addDC("date", "accessioned", null, now.toString());
item.addDC("date", "available", null, now.toString());
// create issue date if not present
DCValue[] currentDateIssued = item.getDC("date", "issued", Item.ANY);
if(currentDateIssued.length == 0)
{
item.addDC("date", "issued", null, now.toString());
}
// create handle
String handle = HandleManager.createHandle(c, item);
String handleref = HandleManager.getCanonicalForm(handle);
// Add handle as identifier.uri DC value
item.addDC("identifier", "uri", null, handleref);
// Add format.mimetype and format.extent DC values
Bitstream[] bitstreams = item.getNonInternalBitstreams();
for (int i = 0; i < bitstreams.length; i++)
{
BitstreamFormat bf = bitstreams[i].getFormat();
item.addDC("format",
"extent",
null,
String.valueOf(bitstreams[i].getSize()) + " bytes");
item.addDC("format", "mimetype", null, bf.getMIMEType());
}
String provDescription = "Made available in DSpace on " + now +
" (GMT). " + getBitstreamProvenanceMessage(item);
if (currentDateIssued.length != 0)
{
DCDate d = new DCDate(currentDateIssued[0].value);
provDescription = provDescription + " Previous issue date: " +
d.toString();
}
// Add provenance description
item.addDC("description", "provenance", "en", provDescription);
// create collection2item mapping
is.getCollection().addItem(item);
// set in_archive=true
item.setArchived(true);
// save changes ;-)
item.update();
// add item to search and browse indices
DSIndexer.indexContent(c, item);
// remove in-progress submission
is.deleteWrapper();
// remove the submit authorization policies
// and replace them with the collection's READ
// policies
// FIXME: this is an inelegant hack, but out of time!
List policies = AuthorizeManager.getPoliciesActionFilter(c,
is.getCollection(), Constants.READ );
item.replaceAllPolicies(policies);
return item;
}
|
diff --git a/cubecomps/src/net/gnehzr/tnoodle/cubecomps/InitializeCubecompsDbServlet.java b/cubecomps/src/net/gnehzr/tnoodle/cubecomps/InitializeCubecompsDbServlet.java
index 339f9a5f..23665f1f 100644
--- a/cubecomps/src/net/gnehzr/tnoodle/cubecomps/InitializeCubecompsDbServlet.java
+++ b/cubecomps/src/net/gnehzr/tnoodle/cubecomps/InitializeCubecompsDbServlet.java
@@ -1,83 +1,83 @@
package net.gnehzr.tnoodle.cubecomps;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.sql.DataSource;
import net.gnehzr.tnoodle.utils.Utils;
@SuppressWarnings("serial")
public class InitializeCubecompsDbServlet extends HttpServlet {
private static final Logger l = Logger.getLogger(InitializeCubecompsDbServlet.class.getName());
@Override
public void init() throws ServletException {
super.init();
try {
safeInit();
} catch(Throwable t) {
l.log(Level.SEVERE, "", t);
}
}
private void safeInit() throws IOException, SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException, NamingException {
StringBuilder schema;
String dataStructurePath = getServletContext().getRealPath("cubecomps/DATA-STRUCTURE.md");
FileInputStream dataStructureInputStream = new FileInputStream(dataStructurePath);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Utils.fullyReadInputStream(dataStructureInputStream, baos);
schema = new StringBuilder(baos.toString());
final String SCHEMA_START = "<pre><code>";
final String SCHEMA_END = "</code></pre>";
int schemaStartIndex = schema.indexOf(SCHEMA_START) + SCHEMA_START.length();
int schemaEndIndex = schema.indexOf(SCHEMA_END, schemaStartIndex);
schema.replace(schemaEndIndex, schema.length(), "");
schema.replace(0, schemaStartIndex, "");
// Remove trailing CREATE TABLE options that h2 doesn't support, like:
// ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 AUTO_INCREMENT=6
Pattern p = Pattern.compile("\\).*ENGINE=.*");
Matcher m = p.matcher(schema);
StringBuffer sanitizedSchema = new StringBuffer();
while(m.find()) {
m.appendReplacement(sanitizedSchema, ");");
}
m.appendTail(sanitizedSchema);
Connection conn = null;
try {
InitialContext jdniContext = new InitialContext();
DataSource ds = (DataSource) jdniContext.lookup("java:comp/env/jdbc/connPool");
conn = ds.getConnection();
Statement stmt = conn.createStatement();
stmt.execute(sanitizedSchema.toString());
- stmt.execute("insert into competitions (admin_pw, country, date_b, date_e, intro_pw, name, place, website) values('pass', 'AF', now(), now(), 'pass', 'Foo comp', 'Place', 'foo.bar.com');");
+ stmt.execute("MERGE INTO competitions (id, admin_pw, country, date_b, date_e, intro_pw, name, place, website) VALUES(1, 'pass', 'AF', now(), now(), 'pass', 'Foo comp', 'Place', 'foo.bar.com');");
} catch (SQLException e) {
l.log(Level.SEVERE, "", e);
} catch (NamingException e) {
l.log(Level.SEVERE, "", e);
} finally {
if(conn != null) {
conn.close();
}
}
}
}
| true | true | private void safeInit() throws IOException, SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException, NamingException {
StringBuilder schema;
String dataStructurePath = getServletContext().getRealPath("cubecomps/DATA-STRUCTURE.md");
FileInputStream dataStructureInputStream = new FileInputStream(dataStructurePath);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Utils.fullyReadInputStream(dataStructureInputStream, baos);
schema = new StringBuilder(baos.toString());
final String SCHEMA_START = "<pre><code>";
final String SCHEMA_END = "</code></pre>";
int schemaStartIndex = schema.indexOf(SCHEMA_START) + SCHEMA_START.length();
int schemaEndIndex = schema.indexOf(SCHEMA_END, schemaStartIndex);
schema.replace(schemaEndIndex, schema.length(), "");
schema.replace(0, schemaStartIndex, "");
// Remove trailing CREATE TABLE options that h2 doesn't support, like:
// ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 AUTO_INCREMENT=6
Pattern p = Pattern.compile("\\).*ENGINE=.*");
Matcher m = p.matcher(schema);
StringBuffer sanitizedSchema = new StringBuffer();
while(m.find()) {
m.appendReplacement(sanitizedSchema, ");");
}
m.appendTail(sanitizedSchema);
Connection conn = null;
try {
InitialContext jdniContext = new InitialContext();
DataSource ds = (DataSource) jdniContext.lookup("java:comp/env/jdbc/connPool");
conn = ds.getConnection();
Statement stmt = conn.createStatement();
stmt.execute(sanitizedSchema.toString());
stmt.execute("insert into competitions (admin_pw, country, date_b, date_e, intro_pw, name, place, website) values('pass', 'AF', now(), now(), 'pass', 'Foo comp', 'Place', 'foo.bar.com');");
} catch (SQLException e) {
l.log(Level.SEVERE, "", e);
} catch (NamingException e) {
l.log(Level.SEVERE, "", e);
} finally {
if(conn != null) {
conn.close();
}
}
}
| private void safeInit() throws IOException, SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException, NamingException {
StringBuilder schema;
String dataStructurePath = getServletContext().getRealPath("cubecomps/DATA-STRUCTURE.md");
FileInputStream dataStructureInputStream = new FileInputStream(dataStructurePath);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Utils.fullyReadInputStream(dataStructureInputStream, baos);
schema = new StringBuilder(baos.toString());
final String SCHEMA_START = "<pre><code>";
final String SCHEMA_END = "</code></pre>";
int schemaStartIndex = schema.indexOf(SCHEMA_START) + SCHEMA_START.length();
int schemaEndIndex = schema.indexOf(SCHEMA_END, schemaStartIndex);
schema.replace(schemaEndIndex, schema.length(), "");
schema.replace(0, schemaStartIndex, "");
// Remove trailing CREATE TABLE options that h2 doesn't support, like:
// ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 AUTO_INCREMENT=6
Pattern p = Pattern.compile("\\).*ENGINE=.*");
Matcher m = p.matcher(schema);
StringBuffer sanitizedSchema = new StringBuffer();
while(m.find()) {
m.appendReplacement(sanitizedSchema, ");");
}
m.appendTail(sanitizedSchema);
Connection conn = null;
try {
InitialContext jdniContext = new InitialContext();
DataSource ds = (DataSource) jdniContext.lookup("java:comp/env/jdbc/connPool");
conn = ds.getConnection();
Statement stmt = conn.createStatement();
stmt.execute(sanitizedSchema.toString());
stmt.execute("MERGE INTO competitions (id, admin_pw, country, date_b, date_e, intro_pw, name, place, website) VALUES(1, 'pass', 'AF', now(), now(), 'pass', 'Foo comp', 'Place', 'foo.bar.com');");
} catch (SQLException e) {
l.log(Level.SEVERE, "", e);
} catch (NamingException e) {
l.log(Level.SEVERE, "", e);
} finally {
if(conn != null) {
conn.close();
}
}
}
|
diff --git a/src/instructions/USI_POP.java b/src/instructions/USI_POP.java
index d802266..22a4d47 100644
--- a/src/instructions/USI_POP.java
+++ b/src/instructions/USI_POP.java
@@ -1,152 +1,152 @@
package instructions;
import static assemblernator.ErrorReporting.makeError;
import assemblernator.AbstractInstruction;
import assemblernator.ErrorReporting.ErrorHandler;
import assemblernator.Instruction;
import assemblernator.Module;
import assemblernator.OperandChecker;
/**
* The POP instruction.
*
* @author Generate.java
* @date Apr 08, 2012; 08:26:19
* @specRef S1
*/
public class USI_POP extends AbstractInstruction {
/**
* The operation identifier of this instruction; while comments should not
* be treated as an instruction, specification says they must be included in
* the user report. Hence, we will simply give this class a semicolon as its
* instruction ID.
*/
private static final String opId = "POP";
/** This instruction's identifying opcode. */
private static final int opCode = 0x00000031; // 0b11000100000000000000000000000000
/** The static instance for this instruction. */
static USI_POP staticInstance = new USI_POP(true);
/** @see assemblernator.Instruction#getNewLC(int, Module) */
@Override public int getNewLC(int lc, Module mod) {
return lc+1;
}
/** @see assemblernator.Instruction#check(ErrorHandler, Module) */
@Override public boolean check(ErrorHandler hErr, Module module) {
boolean isValid = true;
int value;
if(this.operands.size() > 2) {
hErr.reportError(makeError("extraOperandsIns", this.getOpId()), this.lineNum, -1);
isValid = false;
} else if(this.operands.size() < 1) {
hErr.reportError(makeError("tooFewOperandsIns", this.getOpId()), this.lineNum, -1);
} else if(this.hasOperand("DR")) {
value = module.evaluate(this.getOperand("DR"), false, hErr, this, this.getOperandData("DR").keywordStartPosition);
//range checking
isValid = OperandChecker.isValidReg(value);
if(!isValid) hErr.reportError(makeError("OORarithReg", "DR", this.getOpId()), this.lineNum, -1);
} else if(this.hasOperand("DM") && this.hasOperand("DX")){
//range checking
value = module.evaluate(this.getOperand("DM"), false, hErr, this, this.getOperandData("DM").keywordStartPosition);
isValid = OperandChecker.isValidMem(value);
if(!isValid) hErr.reportError(makeError("OORmemAddr", "DM", this.getOpId()), this.lineNum, -1);
value = module.evaluate(this.getOperand("DX"), false, hErr, this, this.getOperandData("DX").keywordStartPosition);
isValid = OperandChecker.isValidIndex(value);
if(!isValid) hErr.reportError(makeError("OORidxReg", "DX", this.getOpId()), this.lineNum, -1);
} else if(this.hasOperand("DM") && this.hasOperand("DM")){
//range checking
value = module.evaluate(this.getOperand("DM"), false, hErr, this, this.getOperandData("DM").keywordStartPosition);
isValid = OperandChecker.isValidMem(value);
if(!isValid) hErr.reportError(makeError("OORmemAddr", "DM", this.getOpId()), this.lineNum, -1);
- hErr.reportError(makeError("operandInsWrong", "DM", this.getOpId()), this.lineNum, -1);
+ hErr.reportError(makeError("operandInsBeWith", "DM", "DX",this.getOpId()), this.lineNum, -1);
} else if(this.hasOperand("DM") && this.operands.size() == 1) {
value = module.evaluate(this.getOperand("DM"), false, hErr, this, this.getOperandData("DM").keywordStartPosition);
isValid = OperandChecker.isValidMem(value);
if(!isValid) hErr.reportError(makeError("OORmemAddr", "DM", this.getOpId()), this.lineNum, -1);
- } else{
+ } else if(this.hasOperand("DM")){
isValid = false;
if(this.hasOperand("FR")){
hErr.reportError(makeError("operandInsWrong", "FR", this.getOpId()), this.lineNum, -1);
} else if(this.hasOperand("FC")){
hErr.reportError(makeError("operandInsWrong", "FC", this.getOpId()), this.lineNum, -1);
} else if(this.hasOperand("FL")){
hErr.reportError(makeError("operandInsWrong", "FL", this.getOpId()), this.lineNum, -1);
} else if(this.hasOperand("FS")){
hErr.reportError(makeError("operandInsWrong", "FS", this.getOpId()), this.lineNum, -1);
} else if(this.hasOperand("LR")){
hErr.reportError(makeError("operandInsWrong", "LR", this.getOpId()), this.lineNum, -1);
} else if(this.hasOperand("FM")){
hErr.reportError(makeError("operandInsWrong", "FM", this.getOpId()), this.lineNum, -1);
} else if(this.hasOperand("EX")){
hErr.reportError(makeError("operandInsWrong", "EX", this.getOpId()), this.lineNum, -1);
} else if(this.hasOperand("NW")){
hErr.reportError(makeError("operandInsWrong", "NW", this.getOpId()), this.lineNum, -1);
} else if(this.hasOperand("ST")){
hErr.reportError(makeError("operandInsWrong", "ST", this.getOpId()), this.lineNum, -1);
}
}
return isValid;
}
/** @see assemblernator.Instruction#assemble() */
@Override public int[] assemble() {
return null; // TODO: IMPLEMENT
}
/** @see assemblernator.Instruction#execute(int) */
@Override public void execute(int instruction) {
// TODO: IMPLEMENT
}
// =========================================================
// === Redundant code ======================================
// =========================================================
// === This code's the same in all instruction classes, ====
// === But Java lacks the mechanism to allow stuffing it ===
// === in super() where it belongs. ========================
// =========================================================
/**
* @see Instruction
* @return The static instance of this instruction.
*/
public static Instruction getInstance() {
return staticInstance;
}
/** @see assemblernator.Instruction#getOpId() */
@Override public String getOpId() {
return opId;
}
/** @see assemblernator.Instruction#getOpcode() */
@Override public int getOpcode() {
return opCode;
}
/** @see assemblernator.Instruction#getNewInstance() */
@Override public Instruction getNewInstance() {
return new USI_POP();
}
/**
* Calls the Instance(String,int) constructor to track this instruction.
*
* @param ignored
* Unused parameter; used to distinguish the constructor for the
* static instance.
*/
private USI_POP(boolean ignored) {
super(opId, opCode);
}
/** Default constructor; does nothing. */
private USI_POP() {}
}
| false | true | @Override public boolean check(ErrorHandler hErr, Module module) {
boolean isValid = true;
int value;
if(this.operands.size() > 2) {
hErr.reportError(makeError("extraOperandsIns", this.getOpId()), this.lineNum, -1);
isValid = false;
} else if(this.operands.size() < 1) {
hErr.reportError(makeError("tooFewOperandsIns", this.getOpId()), this.lineNum, -1);
} else if(this.hasOperand("DR")) {
value = module.evaluate(this.getOperand("DR"), false, hErr, this, this.getOperandData("DR").keywordStartPosition);
//range checking
isValid = OperandChecker.isValidReg(value);
if(!isValid) hErr.reportError(makeError("OORarithReg", "DR", this.getOpId()), this.lineNum, -1);
} else if(this.hasOperand("DM") && this.hasOperand("DX")){
//range checking
value = module.evaluate(this.getOperand("DM"), false, hErr, this, this.getOperandData("DM").keywordStartPosition);
isValid = OperandChecker.isValidMem(value);
if(!isValid) hErr.reportError(makeError("OORmemAddr", "DM", this.getOpId()), this.lineNum, -1);
value = module.evaluate(this.getOperand("DX"), false, hErr, this, this.getOperandData("DX").keywordStartPosition);
isValid = OperandChecker.isValidIndex(value);
if(!isValid) hErr.reportError(makeError("OORidxReg", "DX", this.getOpId()), this.lineNum, -1);
} else if(this.hasOperand("DM") && this.hasOperand("DM")){
//range checking
value = module.evaluate(this.getOperand("DM"), false, hErr, this, this.getOperandData("DM").keywordStartPosition);
isValid = OperandChecker.isValidMem(value);
if(!isValid) hErr.reportError(makeError("OORmemAddr", "DM", this.getOpId()), this.lineNum, -1);
hErr.reportError(makeError("operandInsWrong", "DM", this.getOpId()), this.lineNum, -1);
} else if(this.hasOperand("DM") && this.operands.size() == 1) {
value = module.evaluate(this.getOperand("DM"), false, hErr, this, this.getOperandData("DM").keywordStartPosition);
isValid = OperandChecker.isValidMem(value);
if(!isValid) hErr.reportError(makeError("OORmemAddr", "DM", this.getOpId()), this.lineNum, -1);
} else{
isValid = false;
if(this.hasOperand("FR")){
hErr.reportError(makeError("operandInsWrong", "FR", this.getOpId()), this.lineNum, -1);
} else if(this.hasOperand("FC")){
hErr.reportError(makeError("operandInsWrong", "FC", this.getOpId()), this.lineNum, -1);
} else if(this.hasOperand("FL")){
hErr.reportError(makeError("operandInsWrong", "FL", this.getOpId()), this.lineNum, -1);
} else if(this.hasOperand("FS")){
hErr.reportError(makeError("operandInsWrong", "FS", this.getOpId()), this.lineNum, -1);
} else if(this.hasOperand("LR")){
hErr.reportError(makeError("operandInsWrong", "LR", this.getOpId()), this.lineNum, -1);
} else if(this.hasOperand("FM")){
hErr.reportError(makeError("operandInsWrong", "FM", this.getOpId()), this.lineNum, -1);
} else if(this.hasOperand("EX")){
hErr.reportError(makeError("operandInsWrong", "EX", this.getOpId()), this.lineNum, -1);
} else if(this.hasOperand("NW")){
hErr.reportError(makeError("operandInsWrong", "NW", this.getOpId()), this.lineNum, -1);
} else if(this.hasOperand("ST")){
hErr.reportError(makeError("operandInsWrong", "ST", this.getOpId()), this.lineNum, -1);
}
}
return isValid;
}
| @Override public boolean check(ErrorHandler hErr, Module module) {
boolean isValid = true;
int value;
if(this.operands.size() > 2) {
hErr.reportError(makeError("extraOperandsIns", this.getOpId()), this.lineNum, -1);
isValid = false;
} else if(this.operands.size() < 1) {
hErr.reportError(makeError("tooFewOperandsIns", this.getOpId()), this.lineNum, -1);
} else if(this.hasOperand("DR")) {
value = module.evaluate(this.getOperand("DR"), false, hErr, this, this.getOperandData("DR").keywordStartPosition);
//range checking
isValid = OperandChecker.isValidReg(value);
if(!isValid) hErr.reportError(makeError("OORarithReg", "DR", this.getOpId()), this.lineNum, -1);
} else if(this.hasOperand("DM") && this.hasOperand("DX")){
//range checking
value = module.evaluate(this.getOperand("DM"), false, hErr, this, this.getOperandData("DM").keywordStartPosition);
isValid = OperandChecker.isValidMem(value);
if(!isValid) hErr.reportError(makeError("OORmemAddr", "DM", this.getOpId()), this.lineNum, -1);
value = module.evaluate(this.getOperand("DX"), false, hErr, this, this.getOperandData("DX").keywordStartPosition);
isValid = OperandChecker.isValidIndex(value);
if(!isValid) hErr.reportError(makeError("OORidxReg", "DX", this.getOpId()), this.lineNum, -1);
} else if(this.hasOperand("DM") && this.hasOperand("DM")){
//range checking
value = module.evaluate(this.getOperand("DM"), false, hErr, this, this.getOperandData("DM").keywordStartPosition);
isValid = OperandChecker.isValidMem(value);
if(!isValid) hErr.reportError(makeError("OORmemAddr", "DM", this.getOpId()), this.lineNum, -1);
hErr.reportError(makeError("operandInsBeWith", "DM", "DX",this.getOpId()), this.lineNum, -1);
} else if(this.hasOperand("DM") && this.operands.size() == 1) {
value = module.evaluate(this.getOperand("DM"), false, hErr, this, this.getOperandData("DM").keywordStartPosition);
isValid = OperandChecker.isValidMem(value);
if(!isValid) hErr.reportError(makeError("OORmemAddr", "DM", this.getOpId()), this.lineNum, -1);
} else if(this.hasOperand("DM")){
isValid = false;
if(this.hasOperand("FR")){
hErr.reportError(makeError("operandInsWrong", "FR", this.getOpId()), this.lineNum, -1);
} else if(this.hasOperand("FC")){
hErr.reportError(makeError("operandInsWrong", "FC", this.getOpId()), this.lineNum, -1);
} else if(this.hasOperand("FL")){
hErr.reportError(makeError("operandInsWrong", "FL", this.getOpId()), this.lineNum, -1);
} else if(this.hasOperand("FS")){
hErr.reportError(makeError("operandInsWrong", "FS", this.getOpId()), this.lineNum, -1);
} else if(this.hasOperand("LR")){
hErr.reportError(makeError("operandInsWrong", "LR", this.getOpId()), this.lineNum, -1);
} else if(this.hasOperand("FM")){
hErr.reportError(makeError("operandInsWrong", "FM", this.getOpId()), this.lineNum, -1);
} else if(this.hasOperand("EX")){
hErr.reportError(makeError("operandInsWrong", "EX", this.getOpId()), this.lineNum, -1);
} else if(this.hasOperand("NW")){
hErr.reportError(makeError("operandInsWrong", "NW", this.getOpId()), this.lineNum, -1);
} else if(this.hasOperand("ST")){
hErr.reportError(makeError("operandInsWrong", "ST", this.getOpId()), this.lineNum, -1);
}
}
return isValid;
}
|
diff --git a/ps3mediaserver/net/pms/network/UPNPHelper.java b/ps3mediaserver/net/pms/network/UPNPHelper.java
index 0c780af5..df4e36e3 100644
--- a/ps3mediaserver/net/pms/network/UPNPHelper.java
+++ b/ps3mediaserver/net/pms/network/UPNPHelper.java
@@ -1,280 +1,282 @@
/*
* PS3 Media Server, for streaming any medias to your PS3.
* Copyright (C) 2008 A.Brochard
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; version 2
* of the License only.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package net.pms.network;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.NetworkInterface;
import java.util.Enumeration;
import org.apache.commons.lang.StringUtils;
import net.pms.PMS;
public class UPNPHelper {
private final static String CRLF = "\r\n";
private final static String ALIVE = "ssdp:alive";
private final static String UPNP_HOST = "239.255.255.250";
private final static int UPNP_PORT = 1900;
private final static String BYEBYE = "ssdp:byebye";
private static Thread listener;
private static Thread aliveThread;
private static void sendDiscover(String host, int port, String st) throws IOException
{
String usn = PMS.get().usn();
if (st.equals(usn))
usn = "";
String discovery =
"HTTP/1.1 200 OK" + CRLF +
"SERVER: " + PMS.get().getServerName() + CRLF +
"ST: " + st + CRLF +
"CACHE-CONTROL: max-age=1800" + CRLF +
"EXT: " + CRLF +
"USN: " + usn + st + CRLF +
"LOCATION: http://" + PMS.get().getServer().getHost() + ":" + PMS.get().getServer().getPort() + "/description/fetch" + CRLF +
"DATE: Wed, 31 Dec 2008 14:18:57 GMT" + CRLF +
"Content-Length: 0" + CRLF + CRLF;
sendReply(host, port, discovery);
}
private static void sendReply(String host, int port, String msg) throws IOException
{
try
{
DatagramSocket ssdpUniSock = new DatagramSocket();
PMS.debug( "Sending this reply: " + StringUtils.replace(msg, CRLF, "<CRLF>"));
InetAddress inetAddr = InetAddress.getByName(host);
DatagramPacket dgmPacket = new DatagramPacket(msg.getBytes(), msg.length(), inetAddr, port);
ssdpUniSock.send(dgmPacket);
ssdpUniSock.close();
}
catch (Exception ex)
{
PMS.minimal(ex.getMessage());
}
}
public static void sendAlive() throws IOException {
PMS.info( "Sending ALIVE...");
MulticastSocket ssdpSocket = getNewMulticastSocket();
sendMessage(ssdpSocket, "upnp:rootdevice", ALIVE);
sendMessage(ssdpSocket, PMS.get().usn(), ALIVE);
sendMessage(ssdpSocket, "urn:schemas-upnp-org:device:MediaServer:1", ALIVE);
sendMessage(ssdpSocket, "urn:schemas-upnp-org:service:ContentDirectory:1", ALIVE);
sendMessage(ssdpSocket, "urn:schemas-upnp-org:service:ConnectionManager:1", ALIVE);
//sendMessage(ssdpSocket, "urn:microsoft.com:service:X_MS_MediaReceiverRegistrar:1", ALIVE);
ssdpSocket.leaveGroup(getUPNPAddress());
ssdpSocket.close();
ssdpSocket = null;
}
private static MulticastSocket getNewMulticastSocket() throws IOException {
MulticastSocket ssdpSocket = new MulticastSocket();
ssdpSocket.setReuseAddress(true);
if (PMS.getConfiguration().getServerHostname() != null && PMS.getConfiguration().getServerHostname().length() > 0) {
PMS.debug("Searching network interface for " + PMS.getConfiguration().getServerHostname());
NetworkInterface ni = NetworkInterface.getByInetAddress(InetAddress.getByName(PMS.getConfiguration().getServerHostname()));
if (ni != null) {
ssdpSocket.setNetworkInterface(ni);
// force IPv4 address
Enumeration<InetAddress> enm = ni.getInetAddresses();
while (enm.hasMoreElements()) {
InetAddress ia = enm.nextElement();
if (!(ia instanceof Inet6Address)) {
ssdpSocket.setInterface(ia);
break;
}
}
}
} else if ( PMS.get().getServer().getNi() != null) {
PMS.debug("Setting multicast network interface: " + PMS.get().getServer().getNi());
ssdpSocket.setNetworkInterface( PMS.get().getServer().getNi());
}
PMS.debug("Sending message from multicast socket on network interface: " + ssdpSocket.getNetworkInterface());
PMS.debug("Multicast socket is on interface: " + ssdpSocket.getInterface());
ssdpSocket.setTimeToLive(32);
//ssdpSocket.setLoopbackMode(true);
ssdpSocket.joinGroup(getUPNPAddress());
PMS.debug("Socket Timeout: " + ssdpSocket.getSoTimeout());
PMS.debug("Socket TTL: " + ssdpSocket.getTimeToLive());
return ssdpSocket;
}
public static void sendByeBye() throws IOException {
PMS.info( "Sending BYEBYE...");
MulticastSocket ssdpSocket = getNewMulticastSocket();
sendMessage(ssdpSocket, "upnp:rootdevice", BYEBYE);
sendMessage(ssdpSocket, PMS.get().usn(), BYEBYE);
sendMessage(ssdpSocket, "urn:schemas-upnp-org:device:MediaServer:1", BYEBYE);
sendMessage(ssdpSocket, "urn:schemas-upnp-org:service:ContentDirectory:1", BYEBYE);
sendMessage(ssdpSocket, "urn:schemas-upnp-org:service:ConnectionManager:1", ALIVE);
//sendMessage(ssdpSocket, "urn:microsoft.com:service:X_MS_MediaReceiverRegistrar:1", ALIVE);
ssdpSocket.leaveGroup(getUPNPAddress());
ssdpSocket.close();
ssdpSocket = null;
}
private static void sendMessage(DatagramSocket socket, String nt, String message) throws IOException {
String msg = buildMsg(nt, message);
PMS.debug( "Sending this SSDP packet: " + StringUtils.replace(msg, CRLF, "<CRLF>"));
DatagramPacket ssdpPacket = new DatagramPacket(msg.getBytes(), msg.length(), getUPNPAddress(), UPNP_PORT);
socket.send(ssdpPacket);
try {
Thread.sleep(30);
} catch (InterruptedException e) { }
socket.send(ssdpPacket);
try {
Thread.sleep(30);
} catch (InterruptedException e) { }
}
public static void listen() throws IOException {
Runnable rAlive = new Runnable() {
public void run() {
- try {
- Thread.sleep(180000); // every 180s
- sendAlive();
- } catch (Exception e) {
- PMS.info("Error while sending periodic alive message: " + e.getMessage());
+ while (true) {
+ try {
+ Thread.sleep(180000); // every 180s
+ sendAlive();
+ } catch (Exception e) {
+ PMS.info("Error while sending periodic alive message: " + e.getMessage());
+ }
}
}
};
aliveThread = new Thread(rAlive);
aliveThread.start();
Runnable r = new Runnable() {
public void run() {
while (true) {
byte[] buf = new byte[1024];
DatagramPacket packet_r = new DatagramPacket(buf, buf.length);
try {
MulticastSocket socket = new MulticastSocket(1900);
if (PMS.getConfiguration().getServerHostname() != null && PMS.getConfiguration().getServerHostname().length() > 0) {
PMS.debug("Searching network interface for " + PMS.getConfiguration().getServerHostname());
NetworkInterface ni = NetworkInterface.getByInetAddress(InetAddress.getByName(PMS.getConfiguration().getServerHostname()));
if (ni != null)
socket.setNetworkInterface(ni);
} else if ( PMS.get().getServer().getNi() != null) {
PMS.debug("Setting multicast network interface: " + PMS.get().getServer().getNi());
socket.setNetworkInterface( PMS.get().getServer().getNi());
}
socket.setTimeToLive(4);
socket.setReuseAddress(true);
socket.joinGroup(getUPNPAddress());
socket.receive(packet_r);
socket.leaveGroup(getUPNPAddress());
socket.close();
String s = new String(packet_r.getData());
if (s.startsWith("M-SEARCH")) {
PMS.minimal( "Receiving search request from " + packet_r.getAddress().getHostAddress() + "! Sending DISCOVER message...");
String remoteAddr = packet_r.getAddress().getHostAddress();
int remotePort = packet_r.getPort();
sendDiscover(remoteAddr, remotePort, "urn:schemas-upnp-org:device:MediaServer:1");
sendDiscover(remoteAddr, remotePort, PMS.get().usn());
sendDiscover(remoteAddr, remotePort, "upnp:rootdevice");
sendDiscover(remoteAddr, remotePort, "urn:schemas-upnp-org:service:ContentDirectory:1");
sendAlive();
}
} catch (IOException e) {
PMS.error("UPNP network exception", e);
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {}
}
}
}};
listener = new Thread(r);
listener.start();
}
public static void shutDownListener() {
listener.interrupt();
aliveThread.interrupt();
}
private static String buildMsg(String nt, String message) {
StringBuffer sb = new StringBuffer();
sb.append("NOTIFY * HTTP/1.1");
sb.append(CRLF);
sb.append("HOST: ");
sb.append(UPNP_HOST);
sb.append(":");
sb.append(UPNP_PORT);
sb.append(CRLF);
if (!message.equals(BYEBYE)) {
sb.append("CACHE-CONTROL: max-age=1800");
sb.append(CRLF);
sb.append("LOCATION: http://");
sb.append(PMS.get().getServer().getHost());
sb.append(":");
sb.append(PMS.get().getServer().getPort());
sb.append("/description/fetch");
sb.append(CRLF);
}
sb.append("NT: ");
sb.append(nt);
sb.append(CRLF);
sb.append("NTS: ");
sb.append(message);
sb.append(CRLF);
if (!message.equals(BYEBYE)) {
sb.append("Server: ");
sb.append(PMS.get().getServerName());
sb.append(CRLF);
}
sb.append("USN: ");
sb.append(PMS.get().usn());
if (!nt.equals(PMS.get().usn()))
sb.append(nt);
sb.append(CRLF);
sb.append(CRLF);
return sb.toString();
}
private static InetAddress getUPNPAddress() throws IOException {
return InetAddress.getByAddress(UPNP_HOST, new byte[]{(byte) 239, (byte)255, (byte)255, (byte)250});
}
}
| true | true | public static void listen() throws IOException {
Runnable rAlive = new Runnable() {
public void run() {
try {
Thread.sleep(180000); // every 180s
sendAlive();
} catch (Exception e) {
PMS.info("Error while sending periodic alive message: " + e.getMessage());
}
}
};
aliveThread = new Thread(rAlive);
aliveThread.start();
Runnable r = new Runnable() {
public void run() {
while (true) {
byte[] buf = new byte[1024];
DatagramPacket packet_r = new DatagramPacket(buf, buf.length);
try {
MulticastSocket socket = new MulticastSocket(1900);
if (PMS.getConfiguration().getServerHostname() != null && PMS.getConfiguration().getServerHostname().length() > 0) {
PMS.debug("Searching network interface for " + PMS.getConfiguration().getServerHostname());
NetworkInterface ni = NetworkInterface.getByInetAddress(InetAddress.getByName(PMS.getConfiguration().getServerHostname()));
if (ni != null)
socket.setNetworkInterface(ni);
} else if ( PMS.get().getServer().getNi() != null) {
PMS.debug("Setting multicast network interface: " + PMS.get().getServer().getNi());
socket.setNetworkInterface( PMS.get().getServer().getNi());
}
socket.setTimeToLive(4);
socket.setReuseAddress(true);
socket.joinGroup(getUPNPAddress());
socket.receive(packet_r);
socket.leaveGroup(getUPNPAddress());
socket.close();
String s = new String(packet_r.getData());
if (s.startsWith("M-SEARCH")) {
PMS.minimal( "Receiving search request from " + packet_r.getAddress().getHostAddress() + "! Sending DISCOVER message...");
String remoteAddr = packet_r.getAddress().getHostAddress();
int remotePort = packet_r.getPort();
sendDiscover(remoteAddr, remotePort, "urn:schemas-upnp-org:device:MediaServer:1");
sendDiscover(remoteAddr, remotePort, PMS.get().usn());
sendDiscover(remoteAddr, remotePort, "upnp:rootdevice");
sendDiscover(remoteAddr, remotePort, "urn:schemas-upnp-org:service:ContentDirectory:1");
sendAlive();
}
} catch (IOException e) {
PMS.error("UPNP network exception", e);
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {}
}
}
}};
listener = new Thread(r);
listener.start();
}
| public static void listen() throws IOException {
Runnable rAlive = new Runnable() {
public void run() {
while (true) {
try {
Thread.sleep(180000); // every 180s
sendAlive();
} catch (Exception e) {
PMS.info("Error while sending periodic alive message: " + e.getMessage());
}
}
}
};
aliveThread = new Thread(rAlive);
aliveThread.start();
Runnable r = new Runnable() {
public void run() {
while (true) {
byte[] buf = new byte[1024];
DatagramPacket packet_r = new DatagramPacket(buf, buf.length);
try {
MulticastSocket socket = new MulticastSocket(1900);
if (PMS.getConfiguration().getServerHostname() != null && PMS.getConfiguration().getServerHostname().length() > 0) {
PMS.debug("Searching network interface for " + PMS.getConfiguration().getServerHostname());
NetworkInterface ni = NetworkInterface.getByInetAddress(InetAddress.getByName(PMS.getConfiguration().getServerHostname()));
if (ni != null)
socket.setNetworkInterface(ni);
} else if ( PMS.get().getServer().getNi() != null) {
PMS.debug("Setting multicast network interface: " + PMS.get().getServer().getNi());
socket.setNetworkInterface( PMS.get().getServer().getNi());
}
socket.setTimeToLive(4);
socket.setReuseAddress(true);
socket.joinGroup(getUPNPAddress());
socket.receive(packet_r);
socket.leaveGroup(getUPNPAddress());
socket.close();
String s = new String(packet_r.getData());
if (s.startsWith("M-SEARCH")) {
PMS.minimal( "Receiving search request from " + packet_r.getAddress().getHostAddress() + "! Sending DISCOVER message...");
String remoteAddr = packet_r.getAddress().getHostAddress();
int remotePort = packet_r.getPort();
sendDiscover(remoteAddr, remotePort, "urn:schemas-upnp-org:device:MediaServer:1");
sendDiscover(remoteAddr, remotePort, PMS.get().usn());
sendDiscover(remoteAddr, remotePort, "upnp:rootdevice");
sendDiscover(remoteAddr, remotePort, "urn:schemas-upnp-org:service:ContentDirectory:1");
sendAlive();
}
} catch (IOException e) {
PMS.error("UPNP network exception", e);
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {}
}
}
}};
listener = new Thread(r);
listener.start();
}
|
diff --git a/webapp/src/main/java/org/imirsel/nema/webapp/controller/FlowController.java b/webapp/src/main/java/org/imirsel/nema/webapp/controller/FlowController.java
index 19827ec..ed4d1ed 100644
--- a/webapp/src/main/java/org/imirsel/nema/webapp/controller/FlowController.java
+++ b/webapp/src/main/java/org/imirsel/nema/webapp/controller/FlowController.java
@@ -1,80 +1,80 @@
package org.imirsel.nema.webapp.controller;
import java.util.ArrayList;
import java.util.Set;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.imirsel.nema.Constants;
import org.imirsel.nema.flowservice.FlowService;
import org.imirsel.nema.model.Flow;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
/**
* This controller exposes list of flows.
* @author kumaramit01
* @since 0.4.0
*
*/
public class FlowController extends MultiActionController{
private final static Logger log = Logger.getLogger(FlowController.class.getName());
private FlowService flowService = null;
public FlowService getFlowService() {
return flowService;
}
public void setFlowService(FlowService flowService) {
this.flowService = flowService;
}
/**Returns a view that displays Template Flows
*
* @param req
* @param res
* @return flow/flowType.jsp
*/
public ModelAndView getTemplateFlows(HttpServletRequest req, HttpServletResponse res){
String type = req.getParameter("type");
if(type==null){
type="all";
}
ModelAndView mav;
String uri = req.getRequestURI();
if (uri.substring(uri.length() - 4).equalsIgnoreCase("json")) {
mav = new ModelAndView("jsonView");
} else {
mav =new ModelAndView("flow/flowType");
}
Set<Flow> flowSet=this.flowService.getFlowTemplates();
if(!type.equalsIgnoreCase("all")){
ArrayList<Flow> list = new ArrayList<Flow>();
for(Flow flow:flowSet){
log.info("Name is: "+ flow.getName());
log.info("Flow Type is: " + flow.getTypeName());
- System.out.println(flow.getType());
+ //System.out.println(flow.getType());
//if(flow.getTypeName().toUpperCase().indexOf(type.toUpperCase())!=-1){
// System.out.println("adding: " + flow.getName() + " "+flow.getType());
list.add(flow);
//}
}
log.info("done loading for flowlist");
mav.addObject(Constants.FLOW_LIST, list);
}else{
log.info("done loading for flowlist");
mav.addObject(Constants.FLOW_LIST, flowSet);
}
mav.addObject(Constants.FLOW_TYPE, type);
return mav;
}
}
| true | true | public ModelAndView getTemplateFlows(HttpServletRequest req, HttpServletResponse res){
String type = req.getParameter("type");
if(type==null){
type="all";
}
ModelAndView mav;
String uri = req.getRequestURI();
if (uri.substring(uri.length() - 4).equalsIgnoreCase("json")) {
mav = new ModelAndView("jsonView");
} else {
mav =new ModelAndView("flow/flowType");
}
Set<Flow> flowSet=this.flowService.getFlowTemplates();
if(!type.equalsIgnoreCase("all")){
ArrayList<Flow> list = new ArrayList<Flow>();
for(Flow flow:flowSet){
log.info("Name is: "+ flow.getName());
log.info("Flow Type is: " + flow.getTypeName());
System.out.println(flow.getType());
//if(flow.getTypeName().toUpperCase().indexOf(type.toUpperCase())!=-1){
// System.out.println("adding: " + flow.getName() + " "+flow.getType());
list.add(flow);
//}
}
log.info("done loading for flowlist");
mav.addObject(Constants.FLOW_LIST, list);
}else{
log.info("done loading for flowlist");
mav.addObject(Constants.FLOW_LIST, flowSet);
}
mav.addObject(Constants.FLOW_TYPE, type);
return mav;
}
| public ModelAndView getTemplateFlows(HttpServletRequest req, HttpServletResponse res){
String type = req.getParameter("type");
if(type==null){
type="all";
}
ModelAndView mav;
String uri = req.getRequestURI();
if (uri.substring(uri.length() - 4).equalsIgnoreCase("json")) {
mav = new ModelAndView("jsonView");
} else {
mav =new ModelAndView("flow/flowType");
}
Set<Flow> flowSet=this.flowService.getFlowTemplates();
if(!type.equalsIgnoreCase("all")){
ArrayList<Flow> list = new ArrayList<Flow>();
for(Flow flow:flowSet){
log.info("Name is: "+ flow.getName());
log.info("Flow Type is: " + flow.getTypeName());
//System.out.println(flow.getType());
//if(flow.getTypeName().toUpperCase().indexOf(type.toUpperCase())!=-1){
// System.out.println("adding: " + flow.getName() + " "+flow.getType());
list.add(flow);
//}
}
log.info("done loading for flowlist");
mav.addObject(Constants.FLOW_LIST, list);
}else{
log.info("done loading for flowlist");
mav.addObject(Constants.FLOW_LIST, flowSet);
}
mav.addObject(Constants.FLOW_TYPE, type);
return mav;
}
|
diff --git a/src/main/java/org/spout/vanilla/protocol/handler/EntityInteractionMessageHandler.java b/src/main/java/org/spout/vanilla/protocol/handler/EntityInteractionMessageHandler.java
index 44edc033..9feb9e7a 100644
--- a/src/main/java/org/spout/vanilla/protocol/handler/EntityInteractionMessageHandler.java
+++ b/src/main/java/org/spout/vanilla/protocol/handler/EntityInteractionMessageHandler.java
@@ -1,84 +1,83 @@
/*
* This file is part of Vanilla (http://www.spout.org/).
*
* Vanilla is licensed under the SpoutDev License Version 1.
*
* Vanilla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* In addition, 180 days after any changes are published, you can use the
* software, incorporating those changes, under the terms of the MIT license,
* as described in the SpoutDev License Version 1.
*
* Vanilla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License,
* the MIT license and the SpoutDev License Version 1 along with this program.
* If not, see <http://www.gnu.org/licenses/> for the GNU Lesser General Public
* License and see <http://www.spout.org/SpoutDevLicenseV1.txt> for the full license,
* including the MIT license.
*/
package org.spout.vanilla.protocol.handler;
import org.spout.api.entity.Entity;
import org.spout.api.inventory.ItemStack;
import org.spout.api.material.ItemMaterial;
import org.spout.api.material.Material;
import org.spout.api.player.Player;
import org.spout.api.protocol.MessageHandler;
import org.spout.api.protocol.Session;
import org.spout.vanilla.configuration.VanillaConfiguration;
import org.spout.vanilla.controller.VanillaController;
import org.spout.vanilla.controller.living.player.VanillaPlayer;
import org.spout.vanilla.material.Weapon;
import org.spout.vanilla.protocol.msg.EntityAnimationMessage;
import org.spout.vanilla.protocol.msg.EntityInteractionMessage;
import org.spout.vanilla.protocol.msg.EntityStatusMessage;
public class EntityInteractionMessageHandler extends MessageHandler<EntityInteractionMessage> {
@Override
public void handle(Session session, Player player, EntityInteractionMessage message) {
- //TODO what happens if the controller is in a different region?
- Entity clickedEntity = player.getEntity().getWorld().getRegion(player.getEntity().getPosition()).getEntity(message.getTarget());
+ Entity clickedEntity = player.getEntity().getWorld().getEntity(message.getTarget());
if (clickedEntity == null) {
return;
}
if (message.isPunching()) {
if (clickedEntity.getController() instanceof VanillaPlayer && !VanillaConfiguration.PLAYER_PVP_ENABLED.getBoolean()) {
return;
}
if (clickedEntity.getController() instanceof VanillaController) {
ItemStack is = player.getEntity().getInventory().getCurrentItem();
int damage = 1;
if (is != null && is.getMaterial() != null && is.getMaterial() instanceof Weapon) {
damage = ((Weapon) is.getMaterial()).getDamage();
}
VanillaController temp = (VanillaController) clickedEntity.getController();
if (!temp.getParent().isDead()) {
temp.damage(damage);
temp.sendMessage(temp.getParent().getWorld().getPlayers(), new EntityAnimationMessage(temp.getParent().getId(), EntityAnimationMessage.ANIMATION_HURT), new EntityStatusMessage(temp.getParent().getId(), EntityStatusMessage.ENTITY_HURT));
}
}
} else {
ItemStack holding = player.getEntity().getInventory().getCurrentItem();
if (holding == null) {
return;
}
Material mat = holding.getMaterial();
if (mat instanceof ItemMaterial) {
((ItemMaterial) mat).onInteract(player.getEntity(), clickedEntity);
}
}
}
}
| true | true | public void handle(Session session, Player player, EntityInteractionMessage message) {
//TODO what happens if the controller is in a different region?
Entity clickedEntity = player.getEntity().getWorld().getRegion(player.getEntity().getPosition()).getEntity(message.getTarget());
if (clickedEntity == null) {
return;
}
if (message.isPunching()) {
if (clickedEntity.getController() instanceof VanillaPlayer && !VanillaConfiguration.PLAYER_PVP_ENABLED.getBoolean()) {
return;
}
if (clickedEntity.getController() instanceof VanillaController) {
ItemStack is = player.getEntity().getInventory().getCurrentItem();
int damage = 1;
if (is != null && is.getMaterial() != null && is.getMaterial() instanceof Weapon) {
damage = ((Weapon) is.getMaterial()).getDamage();
}
VanillaController temp = (VanillaController) clickedEntity.getController();
if (!temp.getParent().isDead()) {
temp.damage(damage);
temp.sendMessage(temp.getParent().getWorld().getPlayers(), new EntityAnimationMessage(temp.getParent().getId(), EntityAnimationMessage.ANIMATION_HURT), new EntityStatusMessage(temp.getParent().getId(), EntityStatusMessage.ENTITY_HURT));
}
}
} else {
ItemStack holding = player.getEntity().getInventory().getCurrentItem();
if (holding == null) {
return;
}
Material mat = holding.getMaterial();
if (mat instanceof ItemMaterial) {
((ItemMaterial) mat).onInteract(player.getEntity(), clickedEntity);
}
}
}
| public void handle(Session session, Player player, EntityInteractionMessage message) {
Entity clickedEntity = player.getEntity().getWorld().getEntity(message.getTarget());
if (clickedEntity == null) {
return;
}
if (message.isPunching()) {
if (clickedEntity.getController() instanceof VanillaPlayer && !VanillaConfiguration.PLAYER_PVP_ENABLED.getBoolean()) {
return;
}
if (clickedEntity.getController() instanceof VanillaController) {
ItemStack is = player.getEntity().getInventory().getCurrentItem();
int damage = 1;
if (is != null && is.getMaterial() != null && is.getMaterial() instanceof Weapon) {
damage = ((Weapon) is.getMaterial()).getDamage();
}
VanillaController temp = (VanillaController) clickedEntity.getController();
if (!temp.getParent().isDead()) {
temp.damage(damage);
temp.sendMessage(temp.getParent().getWorld().getPlayers(), new EntityAnimationMessage(temp.getParent().getId(), EntityAnimationMessage.ANIMATION_HURT), new EntityStatusMessage(temp.getParent().getId(), EntityStatusMessage.ENTITY_HURT));
}
}
} else {
ItemStack holding = player.getEntity().getInventory().getCurrentItem();
if (holding == null) {
return;
}
Material mat = holding.getMaterial();
if (mat instanceof ItemMaterial) {
((ItemMaterial) mat).onInteract(player.getEntity(), clickedEntity);
}
}
}
|
diff --git a/src/java/fedora/utilities/install/InstallOptions.java b/src/java/fedora/utilities/install/InstallOptions.java
index b3c699dff..016011385 100644
--- a/src/java/fedora/utilities/install/InstallOptions.java
+++ b/src/java/fedora/utilities/install/InstallOptions.java
@@ -1,420 +1,420 @@
package fedora.utilities.install;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import fedora.utilities.DriverShim;
import fedora.utilities.FileUtils;
public class InstallOptions {
public static final String INSTALL_TYPE = "install.type";
public static final String FEDORA_HOME = "fedora.home";
public static final String FEDORA_SERVERHOST = "fedora.serverHost";
public static final String APIA_AUTH_REQUIRED = "apia.auth.required";
public static final String SSL_AVAILABLE = "ssl.available";
public static final String APIA_SSL_REQUIRED = "apia.ssl.required";
public static final String APIM_SSL_REQUIRED = "apim.ssl.required";
public static final String SERVLET_ENGINE = "servlet.engine";
public static final String TOMCAT_HOME = "tomcat.home";
public static final String FEDORA_ADMIN_PASS = "fedora.admin.pass";
public static final String TOMCAT_SHUTDOWN_PORT = "tomcat.shutdown.port";
public static final String TOMCAT_HTTP_PORT = "tomcat.http.port";
public static final String TOMCAT_SSL_PORT = "tomcat.ssl.port";
public static final String KEYSTORE_FILE = "keystore.file";
public static final String DATABASE = "database";
public static final String DATABASE_DRIVER = "database.driver";
public static final String DATABASE_JDBCURL = "database.jdbcURL";
public static final String DATABASE_DRIVERCLASS = "database.jdbcDriverClass";
public static final String DATABASE_USERNAME = "database.username";
public static final String DATABASE_PASSWORD = "database.password";
public static final String XACML_ENABLED = "xacml.enabled";
public static final String DEPLOY_LOCAL_SERVICES = "deploy.local.services";
public static final String UNATTENDED = "unattended";
public static final String DATABASE_UPDATE = "database.update";
public static final String INSTALL_QUICK = "quick";
public static final String INCLUDED = "included";
public static final String MCKOI = "mckoi";
public static final String MYSQL = "mysql";
public static final String ORACLE = "oracle";
public static final String POSTGRESQL = "postgresql";
public static final String OTHER = "other";
public static final String EXISTING_TOMCAT = "existingTomcat";
private Map<Object, Object> _map;
private Distribution _dist;
/**
* Initialize options from the given map of String values, keyed by
* option id.
*/
public InstallOptions(Distribution dist, Map<Object, Object> map)
throws OptionValidationException {
_dist = dist;
_map = map;
applyDefaults();
validateAll();
}
/**
* Initialize options interactively, via input from the console.
*/
public InstallOptions(Distribution dist)
throws InstallationCancelledException {
_dist = dist;
_map = new HashMap<Object, Object>();
System.out.println();
System.out.println("**********************");
System.out.println(" Fedora Installation ");
System.out.println("**********************");
System.out.println();
System.out.println("Please answer the following questions to install Fedora.");
System.out.println("You can enter CANCEL at any time to abort installation.");
System.out.println();
inputOption(INSTALL_TYPE);
inputOption(FEDORA_HOME);
inputOption(FEDORA_ADMIN_PASS);
String fedoraHome = new File(getValue(InstallOptions.FEDORA_HOME)).getAbsolutePath();
String includedJDBCURL = "jdbc:mckoi:local://" + fedoraHome +
"/" + Distribution.MCKOI_BASENAME +"/db.conf?create_or_boot=true";
if (getValue(INSTALL_TYPE).equals(INSTALL_QUICK)) {
// See the defaultValues defined in OptionDefinition.properties
// for the null values below
_map.put(FEDORA_SERVERHOST, null); // localhost
_map.put(APIA_AUTH_REQUIRED, null); // false
_map.put(SSL_AVAILABLE, Boolean.toString(false));
_map.put(APIM_SSL_REQUIRED, Boolean.toString(false));
_map.put(SERVLET_ENGINE, null); // included
_map.put(TOMCAT_HOME, fedoraHome + File.separator + "tomcat");
_map.put(TOMCAT_HTTP_PORT, null); // 8080
_map.put(TOMCAT_SHUTDOWN_PORT, null); // 8005
//_map.put(TOMCAT_SSL_PORT, null); // 8443
//_map.put(KEYSTORE_FILE, null); // included
_map.put(XACML_ENABLED, Boolean.toString(false));
_map.put(DATABASE, INCLUDED); // included
_map.put(DATABASE_USERNAME, "fedoraAdmin");
_map.put(DATABASE_PASSWORD, "fedoraAdmin");
_map.put(DATABASE_JDBCURL, includedJDBCURL);
_map.put(DATABASE_DRIVERCLASS, "com.mckoi.JDBCDriver");
_map.put(DEPLOY_LOCAL_SERVICES, null); // true
applyDefaults();
return;
}
inputOption(FEDORA_SERVERHOST);
inputOption(APIA_AUTH_REQUIRED);
inputOption(SSL_AVAILABLE);
boolean sslAvailable = getBooleanValue(SSL_AVAILABLE, true);
if (sslAvailable) {
inputOption(APIA_SSL_REQUIRED);
inputOption(APIM_SSL_REQUIRED);
}
inputOption(SERVLET_ENGINE);
if (!getValue(SERVLET_ENGINE).equals(OTHER)) {
inputOption(TOMCAT_HOME);
inputOption(TOMCAT_HTTP_PORT);
inputOption(TOMCAT_SHUTDOWN_PORT);
if (sslAvailable) {
inputOption(TOMCAT_SSL_PORT);
if (getValue(SERVLET_ENGINE).equals(INCLUDED) || getValue(SERVLET_ENGINE).equals(EXISTING_TOMCAT)) {
inputOption(KEYSTORE_FILE);
}
}
}
inputOption(XACML_ENABLED);
// Database selection
// Ultimately we want to provide the following properties:
// database, database.username, database.password,
// database.driver, database.jdbcURL, database.jdbcDriverClass
inputOption(DATABASE);
String db = DATABASE + "." + getValue(DATABASE);
// The following lets us use the database-specific OptionDefinition.properties
// for the user prompts and defaults
String driver = db + ".driver";
String jdbcURL = db + ".jdbcURL";
String jdbcDriverClass = db + ".jdbcDriverClass";
if ( getValue(DATABASE).equals(INCLUDED) ) {
_map.put(DATABASE_USERNAME, "fedoraAdmin");
_map.put(DATABASE_PASSWORD, "fedoraAdmin");
_map.put(DATABASE_JDBCURL, includedJDBCURL);
- _map.put(DATABASE_DRIVERCLASS, OptionDefinition.get(DATABASE_DRIVERCLASS).getDefaultValue());
+ _map.put(DATABASE_DRIVERCLASS, "com.mckoi.JDBCDriver");
} else {
boolean dbValidated = false;
while (!dbValidated) {
inputOption(driver);
_map.put(DATABASE_DRIVER, getValue(driver));
inputOption(DATABASE_USERNAME);
inputOption(DATABASE_PASSWORD);
inputOption(jdbcURL);
_map.put(DATABASE_JDBCURL, getValue(jdbcURL));
inputOption(jdbcDriverClass);
_map.put(DATABASE_DRIVERCLASS, getValue(jdbcDriverClass));
dbValidated = validateDatabaseConnection();
}
}
inputOption(DEPLOY_LOCAL_SERVICES);
}
private String dashes(int len) {
StringBuffer out = new StringBuffer();
for (int i = 0; i < len; i++) {
out.append('-');
}
return out.toString();
}
/**
* Get the indicated option from the console.
*
* Continue prompting until the value is valid, or the user has
* indicated they want to cancel the installation.
*/
private void inputOption(String optionId)
throws InstallationCancelledException {
OptionDefinition opt = OptionDefinition.get(optionId);
if (opt.getLabel() == null || opt.getLabel().length() == 0) {
throw new InstallationCancelledException(optionId +
" is missing label (check OptionDefinition.properties?)");
}
System.out.println(opt.getLabel());
System.out.println(dashes(opt.getLabel().length()));
System.out.println(opt.getDescription());
System.out.println();
String[] valids = opt.getValidValues();
if (valids != null) {
System.out.print("Options : ");
for (int i = 0; i < valids.length; i++) {
if (i > 0) System.out.print(", ");
System.out.print(valids[i]);
}
System.out.println();
}
String defaultVal = opt.getDefaultValue();
if (valids != null || defaultVal != null) {
System.out.println();
}
boolean gotValidValue = false;
while (!gotValidValue) {
System.out.print("Enter a value ");
if (defaultVal != null) {
System.out.print("[default is " + defaultVal + "] ");
}
System.out.print("==> ");
String value = readLine().trim();
if (value.length() == 0 && defaultVal != null) {
value = defaultVal;
}
System.out.println();
if (value.equalsIgnoreCase("cancel")) {
throw new InstallationCancelledException("Cancelled by user.");
}
try {
opt.validateValue(value);
gotValidValue = true;
_map.put(optionId, value);
System.out.println();
} catch (OptionValidationException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
private String readLine() {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
return reader.readLine();
} catch (Exception e) {
throw new RuntimeException("Error: Unable to read from STDIN");
}
}
/**
* Dump all options (including any defaults that were applied)
* to the given stream, in java properties file format.
*
* The output stream remains open after this method returns.
*/
public void dump(OutputStream out)
throws IOException {
Properties props = new Properties();
Iterator iter = _map.keySet().iterator();
while (iter.hasNext()) {
String key = (String) iter.next();
props.setProperty(key, getValue(key));
}
props.store(out, "Install Options");
}
/**
* Get the value of the given option, or <code>null</code> if it doesn't exist.
*/
public String getValue(String name) {
return (String) _map.get(name);
}
/**
* Get the value of the given option as an integer, or the given default value
* if unspecified.
*
* @throws NumberFormatException if the value is specified, but cannot be parsed
* as an integer.
*/
public int getIntValue(String name, int defaultValue) throws NumberFormatException {
String value = getValue(name);
if (value == null) {
return defaultValue;
} else {
return Integer.parseInt(value);
}
}
/**
* Get the value of the given option as a boolean, or the given default value
* if unspecified.
*
* If specified, the value is assumed to be <code>true</code> if given as "true",
* regardless of case. All other values are assumed to be <code>false</code>.
*/
public boolean getBooleanValue(String name, boolean defaultValue) {
String value = getValue(name);
if (value == null) {
return defaultValue;
} else {
return value.equals("true");
}
}
/**
* Get an iterator of the names of all specified options.
*/
public Iterator getOptionNames() {
return _map.keySet().iterator();
}
/**
* Apply defaults to the options, where possible.
*/
private void applyDefaults() {
Iterator names = getOptionNames();
while (names.hasNext()) {
String name = (String) names.next();
String val = (String) _map.get(name);
if (val == null || val.length() == 0) {
OptionDefinition opt = OptionDefinition.get(name);
_map.put(name, opt.getDefaultValue());
}
}
}
/**
* Validate the options, assuming defaults have already been applied.
*
* Validation for a given option might entail more than a syntax check.
* It might check whether a given directory exists, for example.
*/
private void validateAll() throws OptionValidationException {
boolean unattended = getBooleanValue(UNATTENDED, false);
Iterator keys = getOptionNames();
while (keys.hasNext()) {
String optionId = (String) keys.next();
OptionDefinition opt = OptionDefinition.get(optionId);
opt.validateValue(getValue(optionId), unattended);
}
}
private boolean validateDatabaseConnection() {
String database = getValue(DATABASE);
if (database.equals(InstallOptions.INCLUDED)) {
return true;
}
File driver = null;
if (getValue(DATABASE_DRIVER).equals(InstallOptions.INCLUDED)) {
InputStream is;
boolean success = false;
try {
if (database.equals(InstallOptions.MCKOI)) {
is = _dist.get(Distribution.JDBC_MCKOI);
driver = new File(System.getProperty("java.io.tmpdir"), Distribution.JDBC_MCKOI);
success = FileUtils.copy(is, new FileOutputStream(driver));
} else if (database.equals(InstallOptions.MYSQL)) {
is = _dist.get(Distribution.JDBC_MYSQL);
driver = new File(System.getProperty("java.io.tmpdir"), Distribution.JDBC_MYSQL);
success = FileUtils.copy(is, new FileOutputStream(driver));
}
if (!success) {
System.err.println("Extraction of included JDBC driver failed.");
return false;
}
} catch(IOException e) {
e.printStackTrace();
return false;
}
} else {
driver = new File(getValue(DATABASE_DRIVER));
}
try {
DriverShim.loadAndRegister(driver, getValue(DATABASE_DRIVERCLASS));
Connection conn = DriverManager.getConnection(getValue(DATABASE_JDBCURL), getValue(DATABASE_USERNAME),
getValue(DATABASE_PASSWORD));
DatabaseMetaData dmd = conn.getMetaData();
System.out.println("Successfully connected to " + dmd.getDatabaseProductName());
// check if we need to update old table
ResultSet rs = dmd.getTables(null, null, "%", null);
while (rs.next()) {
if (rs.getString("TABLE_NAME").equals("do")) {
inputOption(DATABASE_UPDATE);
break;
}
}
conn.close();
return true;
} catch(Exception e) {
e.printStackTrace();
return false;
}
}
}
| true | true | public InstallOptions(Distribution dist)
throws InstallationCancelledException {
_dist = dist;
_map = new HashMap<Object, Object>();
System.out.println();
System.out.println("**********************");
System.out.println(" Fedora Installation ");
System.out.println("**********************");
System.out.println();
System.out.println("Please answer the following questions to install Fedora.");
System.out.println("You can enter CANCEL at any time to abort installation.");
System.out.println();
inputOption(INSTALL_TYPE);
inputOption(FEDORA_HOME);
inputOption(FEDORA_ADMIN_PASS);
String fedoraHome = new File(getValue(InstallOptions.FEDORA_HOME)).getAbsolutePath();
String includedJDBCURL = "jdbc:mckoi:local://" + fedoraHome +
"/" + Distribution.MCKOI_BASENAME +"/db.conf?create_or_boot=true";
if (getValue(INSTALL_TYPE).equals(INSTALL_QUICK)) {
// See the defaultValues defined in OptionDefinition.properties
// for the null values below
_map.put(FEDORA_SERVERHOST, null); // localhost
_map.put(APIA_AUTH_REQUIRED, null); // false
_map.put(SSL_AVAILABLE, Boolean.toString(false));
_map.put(APIM_SSL_REQUIRED, Boolean.toString(false));
_map.put(SERVLET_ENGINE, null); // included
_map.put(TOMCAT_HOME, fedoraHome + File.separator + "tomcat");
_map.put(TOMCAT_HTTP_PORT, null); // 8080
_map.put(TOMCAT_SHUTDOWN_PORT, null); // 8005
//_map.put(TOMCAT_SSL_PORT, null); // 8443
//_map.put(KEYSTORE_FILE, null); // included
_map.put(XACML_ENABLED, Boolean.toString(false));
_map.put(DATABASE, INCLUDED); // included
_map.put(DATABASE_USERNAME, "fedoraAdmin");
_map.put(DATABASE_PASSWORD, "fedoraAdmin");
_map.put(DATABASE_JDBCURL, includedJDBCURL);
_map.put(DATABASE_DRIVERCLASS, "com.mckoi.JDBCDriver");
_map.put(DEPLOY_LOCAL_SERVICES, null); // true
applyDefaults();
return;
}
inputOption(FEDORA_SERVERHOST);
inputOption(APIA_AUTH_REQUIRED);
inputOption(SSL_AVAILABLE);
boolean sslAvailable = getBooleanValue(SSL_AVAILABLE, true);
if (sslAvailable) {
inputOption(APIA_SSL_REQUIRED);
inputOption(APIM_SSL_REQUIRED);
}
inputOption(SERVLET_ENGINE);
if (!getValue(SERVLET_ENGINE).equals(OTHER)) {
inputOption(TOMCAT_HOME);
inputOption(TOMCAT_HTTP_PORT);
inputOption(TOMCAT_SHUTDOWN_PORT);
if (sslAvailable) {
inputOption(TOMCAT_SSL_PORT);
if (getValue(SERVLET_ENGINE).equals(INCLUDED) || getValue(SERVLET_ENGINE).equals(EXISTING_TOMCAT)) {
inputOption(KEYSTORE_FILE);
}
}
}
inputOption(XACML_ENABLED);
// Database selection
// Ultimately we want to provide the following properties:
// database, database.username, database.password,
// database.driver, database.jdbcURL, database.jdbcDriverClass
inputOption(DATABASE);
String db = DATABASE + "." + getValue(DATABASE);
// The following lets us use the database-specific OptionDefinition.properties
// for the user prompts and defaults
String driver = db + ".driver";
String jdbcURL = db + ".jdbcURL";
String jdbcDriverClass = db + ".jdbcDriverClass";
if ( getValue(DATABASE).equals(INCLUDED) ) {
_map.put(DATABASE_USERNAME, "fedoraAdmin");
_map.put(DATABASE_PASSWORD, "fedoraAdmin");
_map.put(DATABASE_JDBCURL, includedJDBCURL);
_map.put(DATABASE_DRIVERCLASS, OptionDefinition.get(DATABASE_DRIVERCLASS).getDefaultValue());
} else {
boolean dbValidated = false;
while (!dbValidated) {
inputOption(driver);
_map.put(DATABASE_DRIVER, getValue(driver));
inputOption(DATABASE_USERNAME);
inputOption(DATABASE_PASSWORD);
inputOption(jdbcURL);
_map.put(DATABASE_JDBCURL, getValue(jdbcURL));
inputOption(jdbcDriverClass);
_map.put(DATABASE_DRIVERCLASS, getValue(jdbcDriverClass));
dbValidated = validateDatabaseConnection();
}
}
inputOption(DEPLOY_LOCAL_SERVICES);
}
| public InstallOptions(Distribution dist)
throws InstallationCancelledException {
_dist = dist;
_map = new HashMap<Object, Object>();
System.out.println();
System.out.println("**********************");
System.out.println(" Fedora Installation ");
System.out.println("**********************");
System.out.println();
System.out.println("Please answer the following questions to install Fedora.");
System.out.println("You can enter CANCEL at any time to abort installation.");
System.out.println();
inputOption(INSTALL_TYPE);
inputOption(FEDORA_HOME);
inputOption(FEDORA_ADMIN_PASS);
String fedoraHome = new File(getValue(InstallOptions.FEDORA_HOME)).getAbsolutePath();
String includedJDBCURL = "jdbc:mckoi:local://" + fedoraHome +
"/" + Distribution.MCKOI_BASENAME +"/db.conf?create_or_boot=true";
if (getValue(INSTALL_TYPE).equals(INSTALL_QUICK)) {
// See the defaultValues defined in OptionDefinition.properties
// for the null values below
_map.put(FEDORA_SERVERHOST, null); // localhost
_map.put(APIA_AUTH_REQUIRED, null); // false
_map.put(SSL_AVAILABLE, Boolean.toString(false));
_map.put(APIM_SSL_REQUIRED, Boolean.toString(false));
_map.put(SERVLET_ENGINE, null); // included
_map.put(TOMCAT_HOME, fedoraHome + File.separator + "tomcat");
_map.put(TOMCAT_HTTP_PORT, null); // 8080
_map.put(TOMCAT_SHUTDOWN_PORT, null); // 8005
//_map.put(TOMCAT_SSL_PORT, null); // 8443
//_map.put(KEYSTORE_FILE, null); // included
_map.put(XACML_ENABLED, Boolean.toString(false));
_map.put(DATABASE, INCLUDED); // included
_map.put(DATABASE_USERNAME, "fedoraAdmin");
_map.put(DATABASE_PASSWORD, "fedoraAdmin");
_map.put(DATABASE_JDBCURL, includedJDBCURL);
_map.put(DATABASE_DRIVERCLASS, "com.mckoi.JDBCDriver");
_map.put(DEPLOY_LOCAL_SERVICES, null); // true
applyDefaults();
return;
}
inputOption(FEDORA_SERVERHOST);
inputOption(APIA_AUTH_REQUIRED);
inputOption(SSL_AVAILABLE);
boolean sslAvailable = getBooleanValue(SSL_AVAILABLE, true);
if (sslAvailable) {
inputOption(APIA_SSL_REQUIRED);
inputOption(APIM_SSL_REQUIRED);
}
inputOption(SERVLET_ENGINE);
if (!getValue(SERVLET_ENGINE).equals(OTHER)) {
inputOption(TOMCAT_HOME);
inputOption(TOMCAT_HTTP_PORT);
inputOption(TOMCAT_SHUTDOWN_PORT);
if (sslAvailable) {
inputOption(TOMCAT_SSL_PORT);
if (getValue(SERVLET_ENGINE).equals(INCLUDED) || getValue(SERVLET_ENGINE).equals(EXISTING_TOMCAT)) {
inputOption(KEYSTORE_FILE);
}
}
}
inputOption(XACML_ENABLED);
// Database selection
// Ultimately we want to provide the following properties:
// database, database.username, database.password,
// database.driver, database.jdbcURL, database.jdbcDriverClass
inputOption(DATABASE);
String db = DATABASE + "." + getValue(DATABASE);
// The following lets us use the database-specific OptionDefinition.properties
// for the user prompts and defaults
String driver = db + ".driver";
String jdbcURL = db + ".jdbcURL";
String jdbcDriverClass = db + ".jdbcDriverClass";
if ( getValue(DATABASE).equals(INCLUDED) ) {
_map.put(DATABASE_USERNAME, "fedoraAdmin");
_map.put(DATABASE_PASSWORD, "fedoraAdmin");
_map.put(DATABASE_JDBCURL, includedJDBCURL);
_map.put(DATABASE_DRIVERCLASS, "com.mckoi.JDBCDriver");
} else {
boolean dbValidated = false;
while (!dbValidated) {
inputOption(driver);
_map.put(DATABASE_DRIVER, getValue(driver));
inputOption(DATABASE_USERNAME);
inputOption(DATABASE_PASSWORD);
inputOption(jdbcURL);
_map.put(DATABASE_JDBCURL, getValue(jdbcURL));
inputOption(jdbcDriverClass);
_map.put(DATABASE_DRIVERCLASS, getValue(jdbcDriverClass));
dbValidated = validateDatabaseConnection();
}
}
inputOption(DEPLOY_LOCAL_SERVICES);
}
|
diff --git a/src/main/java/me/ase34/citylanterns/executor/SettingsComandExecutor.java b/src/main/java/me/ase34/citylanterns/executor/SettingsComandExecutor.java
index e976851..d1ab33e 100644
--- a/src/main/java/me/ase34/citylanterns/executor/SettingsComandExecutor.java
+++ b/src/main/java/me/ase34/citylanterns/executor/SettingsComandExecutor.java
@@ -1,59 +1,59 @@
package me.ase34.citylanterns.executor;
import me.ase34.citylanterns.CityLanterns;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
public class SettingsComandExecutor implements CommandExecutor {
private CityLanterns plugin;
public SettingsComandExecutor(CityLanterns plugin) {
this.plugin = plugin;
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (args.length < 2) {
return false;
}
String group = "main";
if (args.length == 3) {
group = args[0];
}
String variable = args[args.length - 2];
String value = args[args.length - 1];
try {
if (variable.equalsIgnoreCase("day")) {
int time = Integer.parseInt(value);
plugin.getSettings().setDaytime(group, time);
sender.sendMessage(ChatColor.GOLD + "Set daytime of group " + ChatColor.GRAY + "'" + group + "'" + ChatColor.GOLD + " to " + ChatColor.WHITE + time);
return true;
} else if (variable.equalsIgnoreCase("night")) {
int time = Integer.parseInt(value);
plugin.getSettings().setNighttime(group, time);
sender.sendMessage(ChatColor.GOLD + "Set nighttime of group " + ChatColor.GRAY + "'" + group + "'" + ChatColor.GOLD + " to " + ChatColor.WHITE + time);
return true;
} else if (variable.equalsIgnoreCase("thunder")) {
boolean thunder = value.equalsIgnoreCase("true");
plugin.getSettings().setThunder(group, thunder);
- sender.sendMessage(ChatColor.GOLD + "During thunder lanterns of group " + ChatColor.GRAY + "'" + group + "'" + ChatColor.GOLD + (thunder ? "will" : "won't") + " toggle");
+ sender.sendMessage(ChatColor.GOLD + "During thunder lanterns of group " + ChatColor.GRAY + "'" + group + "' " + ChatColor.GOLD + (thunder ? "will" : "won't") + " toggle");
return true;
}
} catch (NumberFormatException e) {
sender.sendMessage(ChatColor.GRAY + value + ChatColor.RED + " is expected to be a number!");
return true;
}
return false;
}
}
| true | true | public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (args.length < 2) {
return false;
}
String group = "main";
if (args.length == 3) {
group = args[0];
}
String variable = args[args.length - 2];
String value = args[args.length - 1];
try {
if (variable.equalsIgnoreCase("day")) {
int time = Integer.parseInt(value);
plugin.getSettings().setDaytime(group, time);
sender.sendMessage(ChatColor.GOLD + "Set daytime of group " + ChatColor.GRAY + "'" + group + "'" + ChatColor.GOLD + " to " + ChatColor.WHITE + time);
return true;
} else if (variable.equalsIgnoreCase("night")) {
int time = Integer.parseInt(value);
plugin.getSettings().setNighttime(group, time);
sender.sendMessage(ChatColor.GOLD + "Set nighttime of group " + ChatColor.GRAY + "'" + group + "'" + ChatColor.GOLD + " to " + ChatColor.WHITE + time);
return true;
} else if (variable.equalsIgnoreCase("thunder")) {
boolean thunder = value.equalsIgnoreCase("true");
plugin.getSettings().setThunder(group, thunder);
sender.sendMessage(ChatColor.GOLD + "During thunder lanterns of group " + ChatColor.GRAY + "'" + group + "'" + ChatColor.GOLD + (thunder ? "will" : "won't") + " toggle");
return true;
}
} catch (NumberFormatException e) {
sender.sendMessage(ChatColor.GRAY + value + ChatColor.RED + " is expected to be a number!");
return true;
}
return false;
}
| public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (args.length < 2) {
return false;
}
String group = "main";
if (args.length == 3) {
group = args[0];
}
String variable = args[args.length - 2];
String value = args[args.length - 1];
try {
if (variable.equalsIgnoreCase("day")) {
int time = Integer.parseInt(value);
plugin.getSettings().setDaytime(group, time);
sender.sendMessage(ChatColor.GOLD + "Set daytime of group " + ChatColor.GRAY + "'" + group + "'" + ChatColor.GOLD + " to " + ChatColor.WHITE + time);
return true;
} else if (variable.equalsIgnoreCase("night")) {
int time = Integer.parseInt(value);
plugin.getSettings().setNighttime(group, time);
sender.sendMessage(ChatColor.GOLD + "Set nighttime of group " + ChatColor.GRAY + "'" + group + "'" + ChatColor.GOLD + " to " + ChatColor.WHITE + time);
return true;
} else if (variable.equalsIgnoreCase("thunder")) {
boolean thunder = value.equalsIgnoreCase("true");
plugin.getSettings().setThunder(group, thunder);
sender.sendMessage(ChatColor.GOLD + "During thunder lanterns of group " + ChatColor.GRAY + "'" + group + "' " + ChatColor.GOLD + (thunder ? "will" : "won't") + " toggle");
return true;
}
} catch (NumberFormatException e) {
sender.sendMessage(ChatColor.GRAY + value + ChatColor.RED + " is expected to be a number!");
return true;
}
return false;
}
|
diff --git a/portlet/exoadmin/src/main/java/org/exoplatform/organization/webui/component/UIMembershipTypeForm.java b/portlet/exoadmin/src/main/java/org/exoplatform/organization/webui/component/UIMembershipTypeForm.java
index eaf27bd29..da2e0d54b 100644
--- a/portlet/exoadmin/src/main/java/org/exoplatform/organization/webui/component/UIMembershipTypeForm.java
+++ b/portlet/exoadmin/src/main/java/org/exoplatform/organization/webui/component/UIMembershipTypeForm.java
@@ -1,141 +1,142 @@
/**
* Copyright (C) 2009 eXo Platform SAS.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.exoplatform.organization.webui.component;
import org.exoplatform.services.organization.MembershipType;
import org.exoplatform.services.organization.OrganizationService;
import org.exoplatform.web.application.ApplicationMessage;
import org.exoplatform.commons.serialization.api.annotations.Serialized;
import org.exoplatform.webui.config.annotation.ComponentConfig;
import org.exoplatform.webui.config.annotation.EventConfig;
import org.exoplatform.webui.core.UIApplication;
import org.exoplatform.webui.core.lifecycle.UIFormLifecycle;
import org.exoplatform.webui.event.Event;
import org.exoplatform.webui.event.EventListener;
import org.exoplatform.webui.event.Event.Phase;
import org.exoplatform.webui.form.UIForm;
import org.exoplatform.webui.form.UIFormStringInput;
import org.exoplatform.webui.form.UIFormTextAreaInput;
import org.exoplatform.webui.form.validator.MandatoryValidator;
import org.exoplatform.webui.form.validator.NameValidator;
import org.exoplatform.webui.form.validator.SpecialCharacterValidator;
import org.exoplatform.webui.form.validator.StringLengthValidator;
@ComponentConfig(lifecycle = UIFormLifecycle.class, template = "system:/groovy/webui/form/UIFormWithTitle.gtmpl", events = {
@EventConfig(listeners = UIMembershipTypeForm.SaveActionListener.class),
@EventConfig(listeners = UIMembershipTypeForm.ResetActionListener.class, phase = Phase.DECODE)})
@Serialized
public class UIMembershipTypeForm extends UIForm
{
private static String MEMBERSHIP_TYPE_NAME = "name", DESCRIPTION = "description";
private String membershipTypeName;
public UIMembershipTypeForm() throws Exception
{
addUIFormInput(new UIFormStringInput(MEMBERSHIP_TYPE_NAME, MEMBERSHIP_TYPE_NAME, null).setEditable(
UIFormStringInput.ENABLE).addValidator(MandatoryValidator.class).addValidator(StringLengthValidator.class, 3,
30).addValidator(NameValidator.class).addValidator(SpecialCharacterValidator.class));
addUIFormInput(new UIFormTextAreaInput(DESCRIPTION, DESCRIPTION, null));
}
public void setMembershipType(MembershipType membershipType) throws Exception
{
if (membershipType == null)
{
getUIStringInput(MEMBERSHIP_TYPE_NAME).setEditable(UIFormStringInput.ENABLE);
return;
}
else
{
membershipTypeName = membershipType.getName();
getUIStringInput(MEMBERSHIP_TYPE_NAME).setEditable(UIFormStringInput.DISABLE);
}
invokeGetBindingBean(membershipType);
}
public String getMembershipTypeName()
{
return membershipTypeName;
}
static public class SaveActionListener extends EventListener<UIMembershipTypeForm>
{
public void execute(Event<UIMembershipTypeForm> event) throws Exception
{
UIMembershipTypeForm uiForm = event.getSource();
UIMembershipManagement uiMembershipManagement = uiForm.getParent();
OrganizationService service = uiForm.getApplicationComponent(OrganizationService.class);
+ String msTypeName = uiForm.getUIStringInput(MEMBERSHIP_TYPE_NAME).getValue();
- MembershipType mt = service.getMembershipTypeHandler().findMembershipType(uiForm.membershipTypeName);
+ MembershipType mt = service.getMembershipTypeHandler().findMembershipType(msTypeName);
if (mt != null)
{
MembershipType existMembershipType = service.getMembershipTypeHandler().findMembershipType(mt.getName());
if (existMembershipType == null)
{
UIApplication uiApp = event.getRequestContext().getUIApplication();
uiApp.addMessage(new ApplicationMessage("UIMembershipTypeForm.msg.MembershipNotExist", new String[]{mt
.getName()}));
}
else
{
uiForm.invokeSetBindingBean(mt);
service.getMembershipTypeHandler().saveMembershipType(mt, true);
}
}
else
{
mt = service.getMembershipTypeHandler().createMembershipTypeInstance();
uiForm.invokeSetBindingBean(mt);
MembershipType existMembershipType = service.getMembershipTypeHandler().findMembershipType(mt.getName());
if (existMembershipType != null)
{
UIApplication uiApp = event.getRequestContext().getUIApplication();
uiApp.addMessage(new ApplicationMessage("UIMembershipTypeForm.msg.SameName", null));
return;
}
service.getMembershipTypeHandler().createMembershipType(mt, true);
// Update the list of membership under GroupManagment if any
uiMembershipManagement.addOptions(mt);
}
uiMembershipManagement.getChild(UIListMembershipType.class).loadData();
uiForm.getUIStringInput(MEMBERSHIP_TYPE_NAME).setEditable(UIFormStringInput.ENABLE);
uiForm.setMembershipType(null);
uiForm.reset();
}
}
static public class ResetActionListener extends EventListener<UIMembershipTypeForm>
{
public void execute(Event<UIMembershipTypeForm> event) throws Exception
{
UIMembershipTypeForm uiForm = event.getSource();
uiForm.getUIStringInput(MEMBERSHIP_TYPE_NAME).setEditable(UIFormStringInput.ENABLE);
uiForm.setMembershipType(null);
uiForm.reset();
}
}
}
| false | true | public void execute(Event<UIMembershipTypeForm> event) throws Exception
{
UIMembershipTypeForm uiForm = event.getSource();
UIMembershipManagement uiMembershipManagement = uiForm.getParent();
OrganizationService service = uiForm.getApplicationComponent(OrganizationService.class);
MembershipType mt = service.getMembershipTypeHandler().findMembershipType(uiForm.membershipTypeName);
if (mt != null)
{
MembershipType existMembershipType = service.getMembershipTypeHandler().findMembershipType(mt.getName());
if (existMembershipType == null)
{
UIApplication uiApp = event.getRequestContext().getUIApplication();
uiApp.addMessage(new ApplicationMessage("UIMembershipTypeForm.msg.MembershipNotExist", new String[]{mt
.getName()}));
}
else
{
uiForm.invokeSetBindingBean(mt);
service.getMembershipTypeHandler().saveMembershipType(mt, true);
}
}
else
{
mt = service.getMembershipTypeHandler().createMembershipTypeInstance();
uiForm.invokeSetBindingBean(mt);
MembershipType existMembershipType = service.getMembershipTypeHandler().findMembershipType(mt.getName());
if (existMembershipType != null)
{
UIApplication uiApp = event.getRequestContext().getUIApplication();
uiApp.addMessage(new ApplicationMessage("UIMembershipTypeForm.msg.SameName", null));
return;
}
service.getMembershipTypeHandler().createMembershipType(mt, true);
// Update the list of membership under GroupManagment if any
uiMembershipManagement.addOptions(mt);
}
uiMembershipManagement.getChild(UIListMembershipType.class).loadData();
uiForm.getUIStringInput(MEMBERSHIP_TYPE_NAME).setEditable(UIFormStringInput.ENABLE);
uiForm.setMembershipType(null);
uiForm.reset();
}
| public void execute(Event<UIMembershipTypeForm> event) throws Exception
{
UIMembershipTypeForm uiForm = event.getSource();
UIMembershipManagement uiMembershipManagement = uiForm.getParent();
OrganizationService service = uiForm.getApplicationComponent(OrganizationService.class);
String msTypeName = uiForm.getUIStringInput(MEMBERSHIP_TYPE_NAME).getValue();
MembershipType mt = service.getMembershipTypeHandler().findMembershipType(msTypeName);
if (mt != null)
{
MembershipType existMembershipType = service.getMembershipTypeHandler().findMembershipType(mt.getName());
if (existMembershipType == null)
{
UIApplication uiApp = event.getRequestContext().getUIApplication();
uiApp.addMessage(new ApplicationMessage("UIMembershipTypeForm.msg.MembershipNotExist", new String[]{mt
.getName()}));
}
else
{
uiForm.invokeSetBindingBean(mt);
service.getMembershipTypeHandler().saveMembershipType(mt, true);
}
}
else
{
mt = service.getMembershipTypeHandler().createMembershipTypeInstance();
uiForm.invokeSetBindingBean(mt);
MembershipType existMembershipType = service.getMembershipTypeHandler().findMembershipType(mt.getName());
if (existMembershipType != null)
{
UIApplication uiApp = event.getRequestContext().getUIApplication();
uiApp.addMessage(new ApplicationMessage("UIMembershipTypeForm.msg.SameName", null));
return;
}
service.getMembershipTypeHandler().createMembershipType(mt, true);
// Update the list of membership under GroupManagment if any
uiMembershipManagement.addOptions(mt);
}
uiMembershipManagement.getChild(UIListMembershipType.class).loadData();
uiForm.getUIStringInput(MEMBERSHIP_TYPE_NAME).setEditable(UIFormStringInput.ENABLE);
uiForm.setMembershipType(null);
uiForm.reset();
}
|
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/halo/Halo.java b/packages/SystemUI/src/com/android/systemui/statusbar/halo/Halo.java
index ea1a32df..009a6062 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/halo/Halo.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/halo/Halo.java
@@ -1,1178 +1,1192 @@
/*
* Copyright (C) 2013 ParanoidAndroid.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.systemui.statusbar.halo;
import android.app.Activity;
import android.app.ActivityManagerNative;
import android.app.KeyguardManager;
import android.app.PendingIntent;
import android.app.Notification;
import android.app.INotificationManager;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.animation.Keyframe;
import android.animation.PropertyValuesHolder;
import android.content.Context;
import android.content.ContentResolver;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.ContentObserver;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Point;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.PorterDuffColorFilter;
import android.graphics.Matrix;
import android.os.Handler;
import android.os.RemoteException;
import android.os.Vibrator;
import android.os.ServiceManager;
import android.provider.Settings;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.OvershootInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.TranslateAnimation;
import android.animation.TimeInterpolator;
import android.view.Display;
import android.view.View;
import android.view.Gravity;
import android.view.GestureDetector;
import android.view.ViewGroup;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.WindowManager;
import android.view.View.OnTouchListener;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.SoundEffectConstants;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import com.android.systemui.R;
import com.android.systemui.statusbar.BaseStatusBar.NotificationClicker;
import android.service.notification.StatusBarNotification;
import com.android.internal.statusbar.StatusBarIcon;
import com.android.systemui.statusbar.StatusBarIconView;
import com.android.systemui.statusbar.NotificationData;
import com.android.systemui.statusbar.BaseStatusBar;
import com.android.systemui.statusbar.phone.Ticker;
public class Halo extends FrameLayout implements Ticker.TickerCallback {
public static final String TAG = "HaloLauncher";
enum State {
IDLE,
HIDDEN,
SILENT,
DRAG,
GESTURES
}
enum Gesture {
NONE,
TASK,
UP1,
UP2,
DOWN1,
DOWN2
}
private Context mContext;
private PackageManager mPm;
private Handler mHandler;
private BaseStatusBar mBar;
private WindowManager mWindowManager;
private Display mDisplay;
private Vibrator mVibrator;
private LayoutInflater mInflater;
private INotificationManager mNotificationManager;
private SettingsObserver mSettingsObserver;
private GestureDetector mGestureDetector;
private KeyguardManager mKeyguardManager;
private HaloEffect mEffect;
private WindowManager.LayoutParams mTriggerPos;
private State mState = State.IDLE;
private Gesture mGesture = Gesture.NONE;
private View mRoot;
private View mContent, mHaloContent;
private NotificationData.Entry mLastNotificationEntry = null;
private NotificationData.Entry mCurrentNotficationEntry = null;
private NotificationClicker mContentIntent, mTaskIntent;
private NotificationData mNotificationData;
private String mNotificationText = "";
private Paint mPaintHoloBlue = new Paint();
private Paint mPaintWhite = new Paint();
private Paint mPaintHoloRed = new Paint();
private boolean mAttached = false;
private boolean isBeingDragged = false;
private boolean mHapticFeedback;
private boolean mHideTicker;
private boolean mFirstStart = true;
private boolean mInitialized = false;
private boolean mTickerLeft = true;
private boolean mIsNotificationNew = true;
private boolean mOverX = false;
private boolean mInteractionReversed = true;
private boolean hiddenState = false;
private int mIconSize, mIconHalfSize;
private int mScreenWidth, mScreenHeight;
private int mKillX, mKillY;
private int mMarkerIndex = -1;
private int oldIconIndex = -1;
private float initialX = 0;
private float initialY = 0;
// Halo dock position
SharedPreferences preferences;
private String KEY_HALO_POSITION_Y = "halo_position_y";
private String KEY_HALO_POSITION_X = "halo_position_x";
private final class SettingsObserver extends ContentObserver {
SettingsObserver(Handler handler) {
super(handler);
}
void observe() {
ContentResolver resolver = mContext.getContentResolver();
resolver.registerContentObserver(Settings.System.getUriFor(
Settings.System.HALO_REVERSED), false, this);
resolver.registerContentObserver(Settings.System.getUriFor(
Settings.System.HALO_HIDE), false, this);
resolver.registerContentObserver(Settings.System.getUriFor(
Settings.System.HAPTIC_FEEDBACK_ENABLED), false, this);
}
@Override
public void onChange(boolean selfChange) {
mInteractionReversed =
Settings.System.getInt(mContext.getContentResolver(), Settings.System.HALO_REVERSED, 1) == 1;
mHideTicker =
Settings.System.getInt(mContext.getContentResolver(), Settings.System.HALO_HIDE, 0) == 1;
mHapticFeedback = Settings.System.getInt(mContext.getContentResolver(),
Settings.System.HAPTIC_FEEDBACK_ENABLED, 1) != 0;
if (!selfChange) {
mEffect.wake();
mEffect.ping(mPaintHoloBlue, HaloEffect.WAKE_TIME);
mEffect.nap(HaloEffect.SNAP_TIME + 1000);
if (mHideTicker) mEffect.sleep(HaloEffect.SNAP_TIME + HaloEffect.NAP_TIME + 2500, HaloEffect.SLEEP_TIME, false);
}
}
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if (!mAttached) {
mAttached = true;
mSettingsObserver = new SettingsObserver(new Handler());
mSettingsObserver.observe();
mSettingsObserver.onChange(true);
}
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
if (mAttached) {
mContext.getContentResolver().unregisterContentObserver(mSettingsObserver);
mAttached = false;
}
}
public Halo(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public Halo(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mContext = context;
mPm = mContext.getPackageManager();
mWindowManager = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
mInflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mVibrator = (Vibrator) mContext.getSystemService(Context.VIBRATOR_SERVICE);
mNotificationManager = INotificationManager.Stub.asInterface(
ServiceManager.getService(Context.NOTIFICATION_SERVICE));
mDisplay = mWindowManager.getDefaultDisplay();
mGestureDetector = new GestureDetector(mContext, new GestureListener());
mHandler = new Handler();
mRoot = this;
mKeyguardManager = (KeyguardManager) mContext.getSystemService(Context.KEYGUARD_SERVICE);
// Init variables
BitmapDrawable bd = (BitmapDrawable) mContext.getResources().getDrawable(R.drawable.halo_bg);
mIconSize = bd.getBitmap().getWidth();
mIconHalfSize = mIconSize / 2;
mTriggerPos = getWMParams();
// Init colors
mPaintHoloBlue.setAntiAlias(true);
mPaintHoloBlue.setColor(0xff33b5e5);
mPaintWhite.setAntiAlias(true);
mPaintWhite.setColor(0xfff0f0f0);
mPaintHoloRed.setAntiAlias(true);
mPaintHoloRed.setColor(0xffcc0000);
// Create effect layer
mEffect = new HaloEffect(mContext);
mEffect.setLayerType (View.LAYER_TYPE_HARDWARE, null);
mEffect.pingMinRadius = mIconHalfSize;
mEffect.pingMaxRadius = (int)(mIconSize * 1.1f);
WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
| WindowManager.LayoutParams.FLAG_SPLIT_TOUCH
| WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
PixelFormat.TRANSLUCENT);
lp.gravity = Gravity.LEFT|Gravity.TOP;
mWindowManager.addView(mEffect, lp);
}
private void initControl() {
if (mInitialized) return;
mInitialized = true;
// Get actual screen size
mScreenWidth = mEffect.getWidth();
mScreenHeight = mEffect.getHeight();
// Halo dock position
preferences = mContext.getSharedPreferences("Halo", 0);
int msavePositionX = preferences.getInt(KEY_HALO_POSITION_X, 0);
int msavePositionY = preferences.getInt(KEY_HALO_POSITION_Y, mScreenHeight / 2 - mIconHalfSize);
mKillX = mScreenWidth / 2;
mKillY = mIconHalfSize;
if (!mFirstStart) {
if (msavePositionY < 0) mEffect.setHaloY(0);
float mTmpHaloY = (float) msavePositionY / mScreenWidth * (mScreenHeight);
if (msavePositionY > mScreenHeight-mIconSize) {
mEffect.setHaloY((int)mTmpHaloY);
} else {
mEffect.setHaloY(isLandscapeMod() ? msavePositionY : (int)mTmpHaloY);
}
if (mState == State.HIDDEN || mState == State.SILENT) {
mEffect.setHaloX((int)(mTickerLeft ? -mIconSize*0.8f : mScreenWidth - mIconSize*0.2f));
final int triggerWidth = (int)(mTickerLeft ? -mIconSize*0.7f : mScreenWidth - mIconSize*0.3f);
updateTriggerPosition(triggerWidth, mEffect.mHaloY);
} else {
mEffect.nap(500);
if (mHideTicker) mEffect.sleep(HaloEffect.SNAP_TIME + HaloEffect.NAP_TIME + 2500, HaloEffect.SLEEP_TIME, false);
}
} else {
// Do the startup animations only once
mFirstStart = false;
// Halo dock position
mTickerLeft = msavePositionX == 0 ? true : false;
updateTriggerPosition(msavePositionX, msavePositionY);
mEffect.mHaloTextViewL.setVisibility(mTickerLeft ? View.VISIBLE : View.GONE);
mEffect.mHaloTextViewR.setVisibility(mTickerLeft ? View.GONE : View.VISIBLE);
mEffect.setHaloX(msavePositionX);
mEffect.setHaloY(msavePositionY);
mEffect.nap(500);
if (mHideTicker) mEffect.sleep(HaloEffect.SNAP_TIME + HaloEffect.NAP_TIME + 2500, HaloEffect.SLEEP_TIME, false);
}
}
private boolean isLandscapeMod() {
return mScreenWidth < mScreenHeight;
}
private void updateTriggerPosition(int x, int y) {
try {
mTriggerPos.x = x;
mTriggerPos.y = y;
mWindowManager.updateViewLayout(mRoot, mTriggerPos);
} catch(Exception e) {
// Probably some animation still looking to move stuff around
}
}
private void loadLastNotification(boolean includeCurrentDismissable) {
if (mNotificationData.size() > 0) {
//oldEntry = mLastNotificationEntry;
mLastNotificationEntry = mNotificationData.get(mNotificationData.size() - 1);
// If the current notification is dismissable we might want to skip it if so desired
if (!includeCurrentDismissable) {
if (mNotificationData.size() > 1 && mLastNotificationEntry != null &&
mLastNotificationEntry.notification == mCurrentNotficationEntry.notification) {
boolean cancel = (mLastNotificationEntry.notification.notification.flags &
Notification.FLAG_AUTO_CANCEL) == Notification.FLAG_AUTO_CANCEL;
if (cancel) mLastNotificationEntry = mNotificationData.get(mNotificationData.size() - 2);
} else if (mNotificationData.size() == 1) {
boolean cancel = (mLastNotificationEntry.notification.notification.flags &
Notification.FLAG_AUTO_CANCEL) == Notification.FLAG_AUTO_CANCEL;
if (cancel) {
// We have one notification left and it is dismissable, clear it...
clearTicker();
return;
}
}
}
if (mLastNotificationEntry.notification != null
&& mLastNotificationEntry.notification.notification != null
&& mLastNotificationEntry.notification.notification.tickerText != null) {
mNotificationText = mLastNotificationEntry.notification.notification.tickerText.toString();
}
tick(mLastNotificationEntry, "", 0, 0);
} else {
clearTicker();
}
}
public void setStatusBar(BaseStatusBar bar) {
mBar = bar;
if (mBar.getTicker() != null) mBar.getTicker().setUpdateEvent(this);
mNotificationData = mBar.getNotificationData();
loadLastNotification(true);
}
void launchTask(NotificationClicker intent) {
// Do not launch tasks in hidden state or protected lock screen
if (mState == State.HIDDEN || mState == State.SILENT
|| (mKeyguardManager.isKeyguardLocked() && mKeyguardManager.isKeyguardSecure())) return;
try {
ActivityManagerNative.getDefault().resumeAppSwitches();
ActivityManagerNative.getDefault().dismissKeyguardOnNextActivity();
} catch (RemoteException e) {
// ...
}
if (intent!= null) {
intent.onClick(mRoot);
}
}
class GestureListener extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onSingleTapUp (MotionEvent event) {
playSoundEffect(SoundEffectConstants.CLICK);
return true;
}
@Override
public boolean onFling(MotionEvent event1, MotionEvent event2,
float velocityX, float velocityY) {
return true;
}
@Override
public boolean onSingleTapConfirmed(MotionEvent event) {
if (mState != State.DRAG) {
launchTask(mContentIntent);
}
return true;
}
@Override
public boolean onDoubleTap(MotionEvent event) {
if (!mInteractionReversed) {
mState = State.GESTURES;
mEffect.wake();
mBar.setHaloTaskerActive(true, true);
} else {
// Move
mState = State.DRAG;
mEffect.intro();
}
return true;
}
}
void resetIcons() {
final float originalAlpha = mContext.getResources().getFraction(R.dimen.status_bar_icon_drawing_alpha, 1, 1);
for (int i = 0; i < mNotificationData.size(); i++) {
NotificationData.Entry entry = mNotificationData.get(i);
entry.icon.setAlpha(originalAlpha);
}
}
void setIcon(int index) {
float originalAlpha = mContext.getResources().getFraction(R.dimen.status_bar_icon_drawing_alpha, 1, 1);
for (int i = 0; i < mNotificationData.size(); i++) {
NotificationData.Entry entry = mNotificationData.get(i);
entry.icon.setAlpha(index == i ? 1f : originalAlpha);
}
}
private boolean verticalGesture() {
return (mGesture == Gesture.UP1
|| mGesture == Gesture.DOWN1
|| mGesture == Gesture.UP2
|| mGesture == Gesture.DOWN2);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
mGestureDetector.onTouchEvent(event);
final int action = event.getAction();
switch(action) {
case MotionEvent.ACTION_DOWN:
// Stop HALO from moving around, unschedule sleeping patterns
if (mState != State.GESTURES) mEffect.unscheduleSleep();
mMarkerIndex = -1;
oldIconIndex = -1;
mGesture = Gesture.NONE;
hiddenState = (mState == State.HIDDEN || mState == State.SILENT);
if (hiddenState) {
mEffect.wake();
if (mHideTicker) {
mEffect.sleep(2500, HaloEffect.SLEEP_TIME, false);
} else {
mEffect.nap(2500);
}
return true;
}
initialX = event.getRawX();
initialY = event.getRawY();
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
if (hiddenState) break;
resetIcons();
mBar.setHaloTaskerActive(false, true);
mEffect.setHaloOverlay(HaloProperties.Overlay.NONE, 0f);
updateTriggerPosition(mEffect.getHaloX(), mEffect.getHaloY());
mEffect.outro();
mEffect.killTicker();
mEffect.unscheduleSleep();
// Do we erase ourselves?
if (mOverX) {
Settings.System.putInt(mContext.getContentResolver(),
Settings.System.HALO_ACTIVE, 0);
return true;
}
// Halo dock position
float mTmpHaloY = (float) mEffect.mHaloY / mScreenHeight * mScreenWidth;
preferences.edit().putInt(KEY_HALO_POSITION_X, mTickerLeft ?
0 : mScreenWidth - mIconSize).putInt(KEY_HALO_POSITION_Y, isLandscapeMod() ?
mEffect.mHaloY : (int)mTmpHaloY).apply();
if (mGesture == Gesture.TASK) {
// Launch tasks
if (mTaskIntent != null) {
playSoundEffect(SoundEffectConstants.CLICK);
launchTask(mTaskIntent);
}
mEffect.nap(0);
if (mHideTicker) mEffect.sleep(HaloEffect.NAP_TIME + 1500, HaloEffect.SLEEP_TIME, false);
} else if (mGesture == Gesture.DOWN2) {
// Hide & silence
playSoundEffect(SoundEffectConstants.CLICK);
mEffect.sleep(0, HaloEffect.NAP_TIME / 2, true);
} else if (mGesture == Gesture.DOWN1) {
// Hide from sight
playSoundEffect(SoundEffectConstants.CLICK);
mEffect.sleep(0, HaloEffect.NAP_TIME / 2, false);
} else if (mGesture == Gesture.UP2) {
// Clear all notifications
playSoundEffect(SoundEffectConstants.CLICK);
try {
mBar.getService().onClearAllNotifications();
} catch (RemoteException ex) {
// system process is dead if we're here.
}
- loadLastNotification(true);
+ mCurrentNotficationEntry = null;
+ if (mNotificationData.size() > 0) {
+ if (mNotificationData.size() > 0) {
+ for (int i = mNotificationData.size() - 1; i >= 0; i--) {
+ NotificationData.Entry item = mNotificationData.get(i);
+ if (!((item.notification.notification.flags &
+ Notification.FLAG_AUTO_CANCEL) == Notification.FLAG_AUTO_CANCEL)) {
+ tick(item, "", 0, 0);
+ break;
+ }
+ }
+ }
+ }
+ if (mCurrentNotficationEntry == null) clearTicker();
+ mLastNotificationEntry = null;
} else if (mGesture == Gesture.UP1) {
// Dismiss notification
playSoundEffect(SoundEffectConstants.CLICK);
if (mContentIntent != null) {
try {
mBar.getService().onNotificationClear(mContentIntent.mPkg, mContentIntent.mTag, mContentIntent.mId);
} catch (RemoteException ex) {
// system process is dead if we're here.
}
}
// Find next entry
NotificationData.Entry entry = null;
if (mNotificationData.size() > 0) {
for (int i = mNotificationData.size() - 1; i >= 0; i--) {
NotificationData.Entry item = mNotificationData.get(i);
if (mCurrentNotficationEntry != null
&& mCurrentNotficationEntry.notification == item.notification) {
continue;
}
boolean cancel = (item.notification.notification.flags &
Notification.FLAG_AUTO_CANCEL) == Notification.FLAG_AUTO_CANCEL;
if (cancel) {
entry = item;
break;
}
}
}
// When no entry was found, take the last one
if (entry == null && mNotificationData.size() > 0) {
loadLastNotification(false);
} else {
tick(entry, "", 0, 0);
}
mEffect.nap(1500);
if (mHideTicker) mEffect.sleep(HaloEffect.NAP_TIME + 3000, HaloEffect.SLEEP_TIME, false);
} else {
// No gesture, just snap HALO
mEffect.snap(0);
mEffect.nap(HaloEffect.SNAP_TIME + 1000);
if (mHideTicker) mEffect.sleep(HaloEffect.SNAP_TIME + HaloEffect.NAP_TIME + 2500, HaloEffect.SLEEP_TIME, false);
}
mState = State.IDLE;
mGesture = Gesture.NONE;
break;
case MotionEvent.ACTION_MOVE:
if (hiddenState) break;
float distanceX = mKillX-event.getRawX();
float distanceY = mKillY-event.getRawY();
float distanceToKill = (float)Math.sqrt(Math.pow(distanceX, 2) + Math.pow(distanceY, 2));
distanceX = initialX-event.getRawX();
distanceY = initialY-event.getRawY();
float initialDistance = (float)Math.sqrt(Math.pow(distanceX, 2) + Math.pow(distanceY, 2));
if (mState != State.GESTURES) {
// Check kill radius
if (distanceToKill < mIconSize) {
// Magnetize X
mEffect.setHaloX((int)mKillX - mIconHalfSize);
mEffect.setHaloY((int)(mKillY - mIconHalfSize));
if (!mOverX) {
if (mHapticFeedback) mVibrator.vibrate(25);
mEffect.ping(mPaintHoloRed, 0);
mEffect.setHaloOverlay(HaloProperties.Overlay.BLACK_X, 1f);
mOverX = true;
}
return false;
} else {
if (mOverX) mEffect.setHaloOverlay(HaloProperties.Overlay.NONE, 0f);
mOverX = false;
}
// Drag
if (mState != State.DRAG) {
if (initialDistance > mIconSize * 0.7f) {
if (mInteractionReversed) {
mState = State.GESTURES;
mEffect.wake();
mBar.setHaloTaskerActive(true, true);
} else {
mState = State.DRAG;
mEffect.intro();
if (mHapticFeedback) mVibrator.vibrate(25);
}
}
} else {
int posX = (int)event.getRawX() - mIconHalfSize;
int posY = (int)event.getRawY() - mIconHalfSize;
if (posX < 0) posX = 0;
if (posY < 0) posY = 0;
if (posX > mScreenWidth-mIconSize) posX = mScreenWidth-mIconSize;
if (posY > mScreenHeight-mIconSize) posY = mScreenHeight-mIconSize;
mEffect.setHaloX(posX);
mEffect.setHaloY(posY);
// Update resources when the side changes
boolean oldTickerPos = mTickerLeft;
mTickerLeft = (posX + mIconHalfSize < mScreenWidth / 2);
if (oldTickerPos != mTickerLeft) {
mEffect.updateResources();
mEffect.mHaloTextViewL.setVisibility(mTickerLeft ? View.VISIBLE : View.GONE);
mEffect.mHaloTextViewR.setVisibility(mTickerLeft ? View.GONE : View.VISIBLE);
}
}
} else {
// We have three basic gestures, one horizontal for switching through tasks and
// two vertical for dismissing tasks or making HALO fall asleep
int deltaX = (int)(mTickerLeft ? event.getRawX() : mScreenWidth - event.getRawX());
int deltaY = (int)(mEffect.getHaloY() - event.getRawY() + mIconSize);
int horizontalThreshold = (int)(mIconSize * 1.5f);
int verticalThreshold = mIconHalfSize;
int verticalSteps = (int)(mIconSize * 0.6f);
String gestureText = mNotificationText;
// Switch icons
if (deltaX > horizontalThreshold) {
if (mGesture != Gesture.TASK) mEffect.setHaloOverlay(HaloProperties.Overlay.NONE, 0f);
mGesture = Gesture.TASK;
deltaX -= horizontalThreshold;
if (mNotificationData != null && mNotificationData.size() > 0) {
int items = mNotificationData.size();
// This will be the lenght we are going to use
int indexLength = (mScreenWidth - mIconSize * 2) / items;
// Calculate index
mMarkerIndex = mTickerLeft ? (items - deltaX / indexLength) - 1 : (deltaX / indexLength);
// Watch out for margins!
if (mMarkerIndex >= items) mMarkerIndex = items - 1;
if (mMarkerIndex < 0) mMarkerIndex = 0;
}
// Up & down gestures
} else if (Math.abs(deltaY) > verticalThreshold) {
mMarkerIndex = -1;
boolean gestureChanged = false;
final int deltaIndex = (Math.abs(deltaY) - verticalThreshold) / verticalSteps;
if (deltaY > 0) {
if (deltaIndex < 2 && mGesture != Gesture.UP1) {
mGesture = Gesture.UP1;
gestureChanged = true;
mEffect.setHaloOverlay(HaloProperties.Overlay.DISMISS, 1f);
gestureText = mContext.getResources().getString(R.string.halo_dismiss);
} else if (deltaIndex > 1 && mGesture != Gesture.UP2) {
mGesture = Gesture.UP2;
gestureChanged = true;
mEffect.setHaloOverlay(HaloProperties.Overlay.CLEAR_ALL, 1f);
gestureText = mContext.getResources().getString(R.string.halo_clear_all);
}
} else {
if (deltaIndex < 2 && mGesture != Gesture.DOWN1) {
mGesture = Gesture.DOWN1;
gestureChanged = true;
mEffect.setHaloOverlay(mTickerLeft ? HaloProperties.Overlay.BACK_LEFT
: HaloProperties.Overlay.BACK_RIGHT, 1f);
gestureText = mContext.getResources().getString(R.string.halo_hide);
} else if (deltaIndex > 1 && mGesture != Gesture.DOWN2) {
mGesture = Gesture.DOWN2;
gestureChanged = true;
mEffect.setHaloOverlay(HaloProperties.Overlay.SILENCE, 1f);
gestureText = mContext.getResources().getString(R.string.halo_silence);
}
}
if (gestureChanged) {
mMarkerIndex = -1;
// Tasking hasn't changed, we can tick the message here
if (mMarkerIndex == oldIconIndex) {
mEffect.ticker(gestureText, 0, 250);
mEffect.updateResources();
mEffect.invalidate();
}
if (mHapticFeedback) mVibrator.vibrate(10);
}
} else {
mMarkerIndex = -1;
if (mGesture != Gesture.NONE) {
mEffect.setHaloOverlay(HaloProperties.Overlay.NONE, 0f);
if (verticalGesture()) mEffect.killTicker();
}
mGesture = Gesture.NONE;
}
// If the marker index changed, tick
if (mMarkerIndex != oldIconIndex) {
oldIconIndex = mMarkerIndex;
// Make a tiny pop if not so many icons are present
if (mHapticFeedback && mNotificationData.size() < 10) mVibrator.vibrate(1);
try {
if (mMarkerIndex == -1) {
mTaskIntent = null;
resetIcons();
tick(mLastNotificationEntry, gestureText, 0, 250);
// Ping to notify the user we're back where we started
mEffect.ping(mPaintHoloBlue, 0);
} else {
setIcon(mMarkerIndex);
NotificationData.Entry entry = mNotificationData.get(mMarkerIndex);
String text = "";
if (entry.notification.notification.tickerText != null) {
text = entry.notification.notification.tickerText.toString();
}
tick(entry, text, 0, 250);
mTaskIntent = entry.getFloatingIntent();
}
} catch (Exception e) {
// IndexOutOfBoundsException
}
}
}
mEffect.invalidate();
break;
}
return false;
}
public void cleanUp() {
// Remove pending tasks, if we can
mEffect.unscheduleSleep();
mHandler.removeCallbacksAndMessages(null);
// Kill callback
mBar.getTicker().setUpdateEvent(null);
// Flag tasker
mBar.setHaloTaskerActive(false, false);
// Kill the effect layer
if (mEffect != null) mWindowManager.removeView(mEffect);
// Remove resolver
mContext.getContentResolver().unregisterContentObserver(mSettingsObserver);
}
class HaloEffect extends HaloProperties {
public static final int WAKE_TIME = 300;
public static final int SNAP_TIME = 300;
public static final int NAP_TIME = 1000;
public static final int SLEEP_TIME = 2000;
public static final int PING_TIME = 1500;
public static final int PULSE_TIME = 1500;
public static final int TICKER_HIDE_TIME = 2500;
public static final int NAP_DELAY = 4500;
public static final int SLEEP_DELAY = 6500;
private Context mContext;
private Paint mPingPaint;
private int pingRadius = 0;
private int mPingX, mPingY;
protected int pingMinRadius = 0;
protected int pingMaxRadius = 0;
private boolean mPingAllowed = true;
private Bitmap mMarker, mMarkerT, mMarkerB;
private Bitmap mBigRed;
private Paint mMarkerPaint = new Paint();
private Paint xPaint = new Paint();
CustomObjectAnimator xAnimator = new CustomObjectAnimator(this);
CustomObjectAnimator tickerAnimator = new CustomObjectAnimator(this);
public HaloEffect(Context context) {
super(context);
mContext = context;
setWillNotDraw(false);
setDrawingCacheEnabled(false);
mBigRed = BitmapFactory.decodeResource(mContext.getResources(),
R.drawable.halo_bigred);
mMarker = BitmapFactory.decodeResource(mContext.getResources(),
R.drawable.halo_marker);
mMarkerT = BitmapFactory.decodeResource(mContext.getResources(),
R.drawable.halo_marker_t);
mMarkerB = BitmapFactory.decodeResource(mContext.getResources(),
R.drawable.halo_marker_b);
mMarkerPaint.setAntiAlias(true);
mMarkerPaint.setAlpha(0);
xPaint.setAntiAlias(true);
xPaint.setAlpha(0);
updateResources();
}
@Override
public void onSizeChanged(int w, int h, int oldw, int oldh) {
onConfigurationChanged(null);
}
@Override
public void onConfigurationChanged(Configuration newConfiguration) {
// This will reset the initialization flag
mInitialized = false;
// Generate a new content bubble
updateResources();
}
@Override
protected void onLayout (boolean changed, int left, int top, int right, int bottom) {
super.onLayout (changed, left, top, right, bottom);
// We have our effect-layer, now let's kickstart HALO
initControl();
}
public void killTicker() {
tickerAnimator.animate(ObjectAnimator.ofFloat(this, "haloContentAlpha", 0f).setDuration(250),
new DecelerateInterpolator(), null);
}
public void ticker(String tickerText, int delay, int startDuration) {
if (tickerText == null || tickerText.isEmpty()) {
killTicker();
return;
}
mHaloTextViewR.setText(tickerText);
mHaloTextViewL.setText(tickerText);
float total = TICKER_HIDE_TIME + startDuration + 1000;
PropertyValuesHolder tickerUpFrames = PropertyValuesHolder.ofKeyframe("haloContentAlpha",
Keyframe.ofFloat(0f, mHaloTextViewL.getAlpha()),
Keyframe.ofFloat(startDuration / total, 1f),
Keyframe.ofFloat((TICKER_HIDE_TIME + startDuration) / total, 1f),
Keyframe.ofFloat(1f, 0f));
tickerAnimator.animate(ObjectAnimator.ofPropertyValuesHolder(this, tickerUpFrames).setDuration((int)total),
new DecelerateInterpolator(), null, delay, null);
}
public void ping(final Paint paint, final long delay) {
if ((!mPingAllowed && paint != mPaintHoloRed)
&& mGesture != Gesture.TASK) return;
mHandler.postDelayed(new Runnable() {
public void run() {
mPingAllowed = false;
mPingX = mHaloX + mIconHalfSize;
mPingY = mHaloY + mIconHalfSize;
;
mPingPaint = paint;
CustomObjectAnimator pingAnimator = new CustomObjectAnimator(mEffect);
pingAnimator.animate(ObjectAnimator.ofInt(mPingPaint, "alpha", 200, 0).setDuration(PING_TIME),
new DecelerateInterpolator(), new AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
pingRadius = (int)((pingMaxRadius - pingMinRadius) *
animation.getAnimatedFraction()) + pingMinRadius;
invalidate();
}});
// prevent ping spam
mHandler.postDelayed(new Runnable() {
public void run() {
mPingAllowed = true;
}}, PING_TIME / 2);
}}, delay);
}
public void intro() {
xAnimator.animate(ObjectAnimator.ofInt(xPaint, "alpha", 255).setDuration(PING_TIME / 3),
new DecelerateInterpolator(), null);
}
public void outro() {
xAnimator.animate(ObjectAnimator.ofInt(xPaint, "alpha", 0).setDuration(PING_TIME / 3),
new AccelerateInterpolator(), null);
}
CustomObjectAnimator snapAnimator = new CustomObjectAnimator(this);
public void wake() {
unscheduleSleep();
if (mState == State.HIDDEN || mState == State.SILENT) mState = State.IDLE;
int newPos = mTickerLeft ? 0 : mScreenWidth - mIconSize;
updateTriggerPosition(newPos, mHaloY);
snapAnimator.animate(ObjectAnimator.ofInt(this, "haloX", newPos).setDuration(WAKE_TIME),
new DecelerateInterpolator(), null);
}
public void snap(long delay) {
int newPos = mTickerLeft ? 0 : mScreenWidth - mIconSize;
updateTriggerPosition(newPos, mHaloY);
snapAnimator.animate(ObjectAnimator.ofInt(this, "haloX", newPos).setDuration(SNAP_TIME),
new DecelerateInterpolator(), null, delay, null);
}
public void nap(long delay) {
final int newPos = mTickerLeft ? -mIconHalfSize : mScreenWidth - mIconHalfSize;
snapAnimator.animate(ObjectAnimator.ofInt(this, "haloX", newPos).setDuration(NAP_TIME),
new DecelerateInterpolator(), null, delay, new Runnable() {
public void run() {
updateTriggerPosition(newPos, mHaloY);
}});
}
public void sleep(long delay, int speed, final boolean silent) {
final int newPos = (int)(mTickerLeft ? -mIconSize*0.8f : mScreenWidth - mIconSize*0.2f);
snapAnimator.animate(ObjectAnimator.ofInt(this, "haloX", newPos).setDuration(speed),
new DecelerateInterpolator(), null, delay, new Runnable() {
public void run() {
mState = silent ? State.SILENT : State.HIDDEN;
final int triggerWidth = (int)(mTickerLeft ? -mIconSize*0.7f : mScreenWidth - mIconSize*0.3f);
updateTriggerPosition(triggerWidth, mHaloY);
}});
}
public void unscheduleSleep() {
snapAnimator.cancel(true);
}
@Override
protected void onDraw(Canvas canvas) {
int state;
// Ping
if (mPingPaint != null) {
canvas.drawCircle(mPingX, mPingY, pingRadius, mPingPaint);
}
// Content
state = canvas.save();
int ch = mHaloTickerContent.getMeasuredHeight();
int cw = mHaloTickerContent.getMeasuredWidth();
int y = mHaloY + mIconHalfSize - ch / 2;
if (y < 0) y = 0;
int x = mHaloX + mIconSize;
if (!mTickerLeft) {
x = mHaloX - cw;
}
state = canvas.save();
canvas.translate(x, y);
mHaloContentView.draw(canvas);
canvas.restoreToCount(state);
// X
float fraction = 1 - ((float)xPaint.getAlpha()) / 255;
int killyPos = (int)(mKillY - mBigRed.getWidth() / 2 - mIconSize * fraction);
canvas.drawBitmap(mBigRed, mKillX - mBigRed.getWidth() / 2, killyPos, xPaint);
// Horizontal Marker
if (mGesture == Gesture.TASK) {
if (y > 0 && mNotificationData != null && mNotificationData.size() > 0) {
int pulseY = (int)(mHaloY - mIconSize * 0.1f);
int items = mNotificationData.size();
int indexLength = (mScreenWidth - mIconSize * 2) / items;
for (int i = 0; i < items; i++) {
float pulseX = mTickerLeft ? (mIconSize * 1.15f + indexLength * i)
: (mScreenWidth - mIconSize * 1.15f - indexLength * i - mMarker.getWidth());
boolean markerState = mTickerLeft ? mMarkerIndex >= 0 && i < items-mMarkerIndex : i <= mMarkerIndex;
mMarkerPaint.setAlpha(markerState ? 255 : 100);
canvas.drawBitmap(mMarker, pulseX, pulseY, mMarkerPaint);
}
}
}
// Vertical Markers
if (verticalGesture()) {
int xPos = mHaloX + mIconHalfSize - mMarkerT.getWidth() / 2;
mMarkerPaint.setAlpha(mGesture == Gesture.UP1 ? 255 : 100);
int yTop = (int)(mHaloY + mIconHalfSize - mIconSize - mMarkerT.getHeight() / 2);
canvas.drawBitmap(mMarkerT, xPos, yTop, mMarkerPaint);
mMarkerPaint.setAlpha(mGesture == Gesture.UP2 ? 255 : 100);
yTop = yTop - (int)(mIconSize * 0.6f);
canvas.drawBitmap(mMarkerT, xPos, yTop, mMarkerPaint);
mMarkerPaint.setAlpha(mGesture == Gesture.DOWN1 ? 255 : 100);
int yButtom = (int)(mHaloY + mIconHalfSize + mIconSize - mMarkerT.getHeight() / 2);
canvas.drawBitmap(mMarkerB, xPos, yButtom, mMarkerPaint);
mMarkerPaint.setAlpha(mGesture == Gesture.DOWN2 ? 255 : 100);
yButtom = yButtom + (int)(mIconSize * 0.6f);
canvas.drawBitmap(mMarkerB, xPos, yButtom, mMarkerPaint);
}
// Bubble
state = canvas.save();
canvas.translate(mHaloX, mHaloY);
mHaloBubble.draw(canvas);
canvas.restoreToCount(state);
// Number
if (mState == State.IDLE || mState == State.GESTURES && !verticalGesture()) {
state = canvas.save();
canvas.translate(mTickerLeft ? mHaloX + mIconSize - mHaloNumber.getMeasuredWidth() : mHaloX, mHaloY);
mHaloNumberView.draw(canvas);
canvas.restoreToCount(state);
}
}
}
public WindowManager.LayoutParams getWMParams() {
WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
mIconSize,
mIconSize,
WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
| WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
| WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED
| WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
PixelFormat.TRANSLUCENT);
lp.gravity = Gravity.LEFT|Gravity.TOP;
return lp;
}
void clearTicker() {
mEffect.mHaloIcon.setImageDrawable(null);
mEffect.mHaloNumber.setAlpha(0f);
mContentIntent = null;
mCurrentNotficationEntry = null;
mEffect.killTicker();
mEffect.updateResources();
mEffect.invalidate();
}
void tick(NotificationData.Entry entry, String text, int delay, int duration) {
if (entry == null) {
clearTicker();
return;
}
StatusBarNotification notification = entry.notification;
Notification n = notification.notification;
// Deal with the intent
mContentIntent = entry.getFloatingIntent();
mCurrentNotficationEntry = entry;
// set the avatar
mEffect.mHaloIcon.setImageDrawable(new BitmapDrawable(mContext.getResources(), entry.getRoundIcon()));
// Set Number
if (n.number > 0) {
mEffect.mHaloNumber.setText((n.number < 100) ? String.valueOf(n.number) : "+");
mEffect.mHaloNumber.setAlpha(1f);
} else {
mEffect.mHaloNumber.setAlpha(0f);
}
// Set text
if (mState != State.SILENT) mEffect.ticker(text, delay, duration);
mEffect.updateResources();
mEffect.invalidate();
}
// This is the android ticker callback
public void updateTicker(StatusBarNotification notification, String text) {
boolean allowed = false; // default off
try {
allowed = mNotificationManager.isPackageAllowedForHalo(notification.pkg);
} catch (android.os.RemoteException ex) {
// System is dead
}
for (int i = 0; i < mNotificationData.size(); i++) {
NotificationData.Entry entry = mNotificationData.get(i);
if (entry.notification == notification) {
// No intent, no tick ...
if (entry.notification.notification.contentIntent == null) return;
mIsNotificationNew = true;
if (mLastNotificationEntry != null && notification == mLastNotificationEntry.notification) {
// Ok, this is the same notification
// Let's give it a chance though, if the text has changed we allow it
mIsNotificationNew = !mNotificationText.equals(text);
}
if (mIsNotificationNew) {
mNotificationText = text;
mLastNotificationEntry = entry;
if (allowed) {
tick(entry, text, HaloEffect.WAKE_TIME, 1000);
// Pop while not tasking, only if notification is certified fresh
if (mGesture != Gesture.TASK && mState != State.SILENT) mEffect.ping(mPaintHoloBlue, HaloEffect.WAKE_TIME);
if (mState == State.IDLE || mState == State.HIDDEN) {
mEffect.wake();
mEffect.nap(HaloEffect.NAP_DELAY);
if (mHideTicker) mEffect.sleep(HaloEffect.SLEEP_DELAY, HaloEffect.SLEEP_TIME, false);
}
}
}
break;
}
}
}
}
| false | true | public boolean onTouchEvent(MotionEvent event) {
mGestureDetector.onTouchEvent(event);
final int action = event.getAction();
switch(action) {
case MotionEvent.ACTION_DOWN:
// Stop HALO from moving around, unschedule sleeping patterns
if (mState != State.GESTURES) mEffect.unscheduleSleep();
mMarkerIndex = -1;
oldIconIndex = -1;
mGesture = Gesture.NONE;
hiddenState = (mState == State.HIDDEN || mState == State.SILENT);
if (hiddenState) {
mEffect.wake();
if (mHideTicker) {
mEffect.sleep(2500, HaloEffect.SLEEP_TIME, false);
} else {
mEffect.nap(2500);
}
return true;
}
initialX = event.getRawX();
initialY = event.getRawY();
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
if (hiddenState) break;
resetIcons();
mBar.setHaloTaskerActive(false, true);
mEffect.setHaloOverlay(HaloProperties.Overlay.NONE, 0f);
updateTriggerPosition(mEffect.getHaloX(), mEffect.getHaloY());
mEffect.outro();
mEffect.killTicker();
mEffect.unscheduleSleep();
// Do we erase ourselves?
if (mOverX) {
Settings.System.putInt(mContext.getContentResolver(),
Settings.System.HALO_ACTIVE, 0);
return true;
}
// Halo dock position
float mTmpHaloY = (float) mEffect.mHaloY / mScreenHeight * mScreenWidth;
preferences.edit().putInt(KEY_HALO_POSITION_X, mTickerLeft ?
0 : mScreenWidth - mIconSize).putInt(KEY_HALO_POSITION_Y, isLandscapeMod() ?
mEffect.mHaloY : (int)mTmpHaloY).apply();
if (mGesture == Gesture.TASK) {
// Launch tasks
if (mTaskIntent != null) {
playSoundEffect(SoundEffectConstants.CLICK);
launchTask(mTaskIntent);
}
mEffect.nap(0);
if (mHideTicker) mEffect.sleep(HaloEffect.NAP_TIME + 1500, HaloEffect.SLEEP_TIME, false);
} else if (mGesture == Gesture.DOWN2) {
// Hide & silence
playSoundEffect(SoundEffectConstants.CLICK);
mEffect.sleep(0, HaloEffect.NAP_TIME / 2, true);
} else if (mGesture == Gesture.DOWN1) {
// Hide from sight
playSoundEffect(SoundEffectConstants.CLICK);
mEffect.sleep(0, HaloEffect.NAP_TIME / 2, false);
} else if (mGesture == Gesture.UP2) {
// Clear all notifications
playSoundEffect(SoundEffectConstants.CLICK);
try {
mBar.getService().onClearAllNotifications();
} catch (RemoteException ex) {
// system process is dead if we're here.
}
loadLastNotification(true);
} else if (mGesture == Gesture.UP1) {
// Dismiss notification
playSoundEffect(SoundEffectConstants.CLICK);
if (mContentIntent != null) {
try {
mBar.getService().onNotificationClear(mContentIntent.mPkg, mContentIntent.mTag, mContentIntent.mId);
} catch (RemoteException ex) {
// system process is dead if we're here.
}
}
// Find next entry
NotificationData.Entry entry = null;
if (mNotificationData.size() > 0) {
for (int i = mNotificationData.size() - 1; i >= 0; i--) {
NotificationData.Entry item = mNotificationData.get(i);
if (mCurrentNotficationEntry != null
&& mCurrentNotficationEntry.notification == item.notification) {
continue;
}
boolean cancel = (item.notification.notification.flags &
Notification.FLAG_AUTO_CANCEL) == Notification.FLAG_AUTO_CANCEL;
if (cancel) {
entry = item;
break;
}
}
}
// When no entry was found, take the last one
if (entry == null && mNotificationData.size() > 0) {
loadLastNotification(false);
} else {
tick(entry, "", 0, 0);
}
mEffect.nap(1500);
if (mHideTicker) mEffect.sleep(HaloEffect.NAP_TIME + 3000, HaloEffect.SLEEP_TIME, false);
} else {
// No gesture, just snap HALO
mEffect.snap(0);
mEffect.nap(HaloEffect.SNAP_TIME + 1000);
if (mHideTicker) mEffect.sleep(HaloEffect.SNAP_TIME + HaloEffect.NAP_TIME + 2500, HaloEffect.SLEEP_TIME, false);
}
mState = State.IDLE;
mGesture = Gesture.NONE;
break;
case MotionEvent.ACTION_MOVE:
if (hiddenState) break;
float distanceX = mKillX-event.getRawX();
float distanceY = mKillY-event.getRawY();
float distanceToKill = (float)Math.sqrt(Math.pow(distanceX, 2) + Math.pow(distanceY, 2));
distanceX = initialX-event.getRawX();
distanceY = initialY-event.getRawY();
float initialDistance = (float)Math.sqrt(Math.pow(distanceX, 2) + Math.pow(distanceY, 2));
if (mState != State.GESTURES) {
// Check kill radius
if (distanceToKill < mIconSize) {
// Magnetize X
mEffect.setHaloX((int)mKillX - mIconHalfSize);
mEffect.setHaloY((int)(mKillY - mIconHalfSize));
if (!mOverX) {
if (mHapticFeedback) mVibrator.vibrate(25);
mEffect.ping(mPaintHoloRed, 0);
mEffect.setHaloOverlay(HaloProperties.Overlay.BLACK_X, 1f);
mOverX = true;
}
return false;
} else {
if (mOverX) mEffect.setHaloOverlay(HaloProperties.Overlay.NONE, 0f);
mOverX = false;
}
// Drag
if (mState != State.DRAG) {
if (initialDistance > mIconSize * 0.7f) {
if (mInteractionReversed) {
mState = State.GESTURES;
mEffect.wake();
mBar.setHaloTaskerActive(true, true);
} else {
mState = State.DRAG;
mEffect.intro();
if (mHapticFeedback) mVibrator.vibrate(25);
}
}
} else {
int posX = (int)event.getRawX() - mIconHalfSize;
int posY = (int)event.getRawY() - mIconHalfSize;
if (posX < 0) posX = 0;
if (posY < 0) posY = 0;
if (posX > mScreenWidth-mIconSize) posX = mScreenWidth-mIconSize;
if (posY > mScreenHeight-mIconSize) posY = mScreenHeight-mIconSize;
mEffect.setHaloX(posX);
mEffect.setHaloY(posY);
// Update resources when the side changes
boolean oldTickerPos = mTickerLeft;
mTickerLeft = (posX + mIconHalfSize < mScreenWidth / 2);
if (oldTickerPos != mTickerLeft) {
mEffect.updateResources();
mEffect.mHaloTextViewL.setVisibility(mTickerLeft ? View.VISIBLE : View.GONE);
mEffect.mHaloTextViewR.setVisibility(mTickerLeft ? View.GONE : View.VISIBLE);
}
}
} else {
// We have three basic gestures, one horizontal for switching through tasks and
// two vertical for dismissing tasks or making HALO fall asleep
int deltaX = (int)(mTickerLeft ? event.getRawX() : mScreenWidth - event.getRawX());
int deltaY = (int)(mEffect.getHaloY() - event.getRawY() + mIconSize);
int horizontalThreshold = (int)(mIconSize * 1.5f);
int verticalThreshold = mIconHalfSize;
int verticalSteps = (int)(mIconSize * 0.6f);
String gestureText = mNotificationText;
// Switch icons
if (deltaX > horizontalThreshold) {
if (mGesture != Gesture.TASK) mEffect.setHaloOverlay(HaloProperties.Overlay.NONE, 0f);
mGesture = Gesture.TASK;
deltaX -= horizontalThreshold;
if (mNotificationData != null && mNotificationData.size() > 0) {
int items = mNotificationData.size();
// This will be the lenght we are going to use
int indexLength = (mScreenWidth - mIconSize * 2) / items;
// Calculate index
mMarkerIndex = mTickerLeft ? (items - deltaX / indexLength) - 1 : (deltaX / indexLength);
// Watch out for margins!
if (mMarkerIndex >= items) mMarkerIndex = items - 1;
if (mMarkerIndex < 0) mMarkerIndex = 0;
}
// Up & down gestures
} else if (Math.abs(deltaY) > verticalThreshold) {
mMarkerIndex = -1;
boolean gestureChanged = false;
final int deltaIndex = (Math.abs(deltaY) - verticalThreshold) / verticalSteps;
if (deltaY > 0) {
if (deltaIndex < 2 && mGesture != Gesture.UP1) {
mGesture = Gesture.UP1;
gestureChanged = true;
mEffect.setHaloOverlay(HaloProperties.Overlay.DISMISS, 1f);
gestureText = mContext.getResources().getString(R.string.halo_dismiss);
} else if (deltaIndex > 1 && mGesture != Gesture.UP2) {
mGesture = Gesture.UP2;
gestureChanged = true;
mEffect.setHaloOverlay(HaloProperties.Overlay.CLEAR_ALL, 1f);
gestureText = mContext.getResources().getString(R.string.halo_clear_all);
}
} else {
if (deltaIndex < 2 && mGesture != Gesture.DOWN1) {
mGesture = Gesture.DOWN1;
gestureChanged = true;
mEffect.setHaloOverlay(mTickerLeft ? HaloProperties.Overlay.BACK_LEFT
: HaloProperties.Overlay.BACK_RIGHT, 1f);
gestureText = mContext.getResources().getString(R.string.halo_hide);
} else if (deltaIndex > 1 && mGesture != Gesture.DOWN2) {
mGesture = Gesture.DOWN2;
gestureChanged = true;
mEffect.setHaloOverlay(HaloProperties.Overlay.SILENCE, 1f);
gestureText = mContext.getResources().getString(R.string.halo_silence);
}
}
if (gestureChanged) {
mMarkerIndex = -1;
// Tasking hasn't changed, we can tick the message here
if (mMarkerIndex == oldIconIndex) {
mEffect.ticker(gestureText, 0, 250);
mEffect.updateResources();
mEffect.invalidate();
}
if (mHapticFeedback) mVibrator.vibrate(10);
}
} else {
mMarkerIndex = -1;
if (mGesture != Gesture.NONE) {
mEffect.setHaloOverlay(HaloProperties.Overlay.NONE, 0f);
if (verticalGesture()) mEffect.killTicker();
}
mGesture = Gesture.NONE;
}
// If the marker index changed, tick
if (mMarkerIndex != oldIconIndex) {
oldIconIndex = mMarkerIndex;
// Make a tiny pop if not so many icons are present
if (mHapticFeedback && mNotificationData.size() < 10) mVibrator.vibrate(1);
try {
if (mMarkerIndex == -1) {
mTaskIntent = null;
resetIcons();
tick(mLastNotificationEntry, gestureText, 0, 250);
// Ping to notify the user we're back where we started
mEffect.ping(mPaintHoloBlue, 0);
} else {
setIcon(mMarkerIndex);
NotificationData.Entry entry = mNotificationData.get(mMarkerIndex);
String text = "";
if (entry.notification.notification.tickerText != null) {
text = entry.notification.notification.tickerText.toString();
}
tick(entry, text, 0, 250);
mTaskIntent = entry.getFloatingIntent();
}
} catch (Exception e) {
// IndexOutOfBoundsException
}
}
}
mEffect.invalidate();
break;
}
return false;
}
| public boolean onTouchEvent(MotionEvent event) {
mGestureDetector.onTouchEvent(event);
final int action = event.getAction();
switch(action) {
case MotionEvent.ACTION_DOWN:
// Stop HALO from moving around, unschedule sleeping patterns
if (mState != State.GESTURES) mEffect.unscheduleSleep();
mMarkerIndex = -1;
oldIconIndex = -1;
mGesture = Gesture.NONE;
hiddenState = (mState == State.HIDDEN || mState == State.SILENT);
if (hiddenState) {
mEffect.wake();
if (mHideTicker) {
mEffect.sleep(2500, HaloEffect.SLEEP_TIME, false);
} else {
mEffect.nap(2500);
}
return true;
}
initialX = event.getRawX();
initialY = event.getRawY();
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
if (hiddenState) break;
resetIcons();
mBar.setHaloTaskerActive(false, true);
mEffect.setHaloOverlay(HaloProperties.Overlay.NONE, 0f);
updateTriggerPosition(mEffect.getHaloX(), mEffect.getHaloY());
mEffect.outro();
mEffect.killTicker();
mEffect.unscheduleSleep();
// Do we erase ourselves?
if (mOverX) {
Settings.System.putInt(mContext.getContentResolver(),
Settings.System.HALO_ACTIVE, 0);
return true;
}
// Halo dock position
float mTmpHaloY = (float) mEffect.mHaloY / mScreenHeight * mScreenWidth;
preferences.edit().putInt(KEY_HALO_POSITION_X, mTickerLeft ?
0 : mScreenWidth - mIconSize).putInt(KEY_HALO_POSITION_Y, isLandscapeMod() ?
mEffect.mHaloY : (int)mTmpHaloY).apply();
if (mGesture == Gesture.TASK) {
// Launch tasks
if (mTaskIntent != null) {
playSoundEffect(SoundEffectConstants.CLICK);
launchTask(mTaskIntent);
}
mEffect.nap(0);
if (mHideTicker) mEffect.sleep(HaloEffect.NAP_TIME + 1500, HaloEffect.SLEEP_TIME, false);
} else if (mGesture == Gesture.DOWN2) {
// Hide & silence
playSoundEffect(SoundEffectConstants.CLICK);
mEffect.sleep(0, HaloEffect.NAP_TIME / 2, true);
} else if (mGesture == Gesture.DOWN1) {
// Hide from sight
playSoundEffect(SoundEffectConstants.CLICK);
mEffect.sleep(0, HaloEffect.NAP_TIME / 2, false);
} else if (mGesture == Gesture.UP2) {
// Clear all notifications
playSoundEffect(SoundEffectConstants.CLICK);
try {
mBar.getService().onClearAllNotifications();
} catch (RemoteException ex) {
// system process is dead if we're here.
}
mCurrentNotficationEntry = null;
if (mNotificationData.size() > 0) {
if (mNotificationData.size() > 0) {
for (int i = mNotificationData.size() - 1; i >= 0; i--) {
NotificationData.Entry item = mNotificationData.get(i);
if (!((item.notification.notification.flags &
Notification.FLAG_AUTO_CANCEL) == Notification.FLAG_AUTO_CANCEL)) {
tick(item, "", 0, 0);
break;
}
}
}
}
if (mCurrentNotficationEntry == null) clearTicker();
mLastNotificationEntry = null;
} else if (mGesture == Gesture.UP1) {
// Dismiss notification
playSoundEffect(SoundEffectConstants.CLICK);
if (mContentIntent != null) {
try {
mBar.getService().onNotificationClear(mContentIntent.mPkg, mContentIntent.mTag, mContentIntent.mId);
} catch (RemoteException ex) {
// system process is dead if we're here.
}
}
// Find next entry
NotificationData.Entry entry = null;
if (mNotificationData.size() > 0) {
for (int i = mNotificationData.size() - 1; i >= 0; i--) {
NotificationData.Entry item = mNotificationData.get(i);
if (mCurrentNotficationEntry != null
&& mCurrentNotficationEntry.notification == item.notification) {
continue;
}
boolean cancel = (item.notification.notification.flags &
Notification.FLAG_AUTO_CANCEL) == Notification.FLAG_AUTO_CANCEL;
if (cancel) {
entry = item;
break;
}
}
}
// When no entry was found, take the last one
if (entry == null && mNotificationData.size() > 0) {
loadLastNotification(false);
} else {
tick(entry, "", 0, 0);
}
mEffect.nap(1500);
if (mHideTicker) mEffect.sleep(HaloEffect.NAP_TIME + 3000, HaloEffect.SLEEP_TIME, false);
} else {
// No gesture, just snap HALO
mEffect.snap(0);
mEffect.nap(HaloEffect.SNAP_TIME + 1000);
if (mHideTicker) mEffect.sleep(HaloEffect.SNAP_TIME + HaloEffect.NAP_TIME + 2500, HaloEffect.SLEEP_TIME, false);
}
mState = State.IDLE;
mGesture = Gesture.NONE;
break;
case MotionEvent.ACTION_MOVE:
if (hiddenState) break;
float distanceX = mKillX-event.getRawX();
float distanceY = mKillY-event.getRawY();
float distanceToKill = (float)Math.sqrt(Math.pow(distanceX, 2) + Math.pow(distanceY, 2));
distanceX = initialX-event.getRawX();
distanceY = initialY-event.getRawY();
float initialDistance = (float)Math.sqrt(Math.pow(distanceX, 2) + Math.pow(distanceY, 2));
if (mState != State.GESTURES) {
// Check kill radius
if (distanceToKill < mIconSize) {
// Magnetize X
mEffect.setHaloX((int)mKillX - mIconHalfSize);
mEffect.setHaloY((int)(mKillY - mIconHalfSize));
if (!mOverX) {
if (mHapticFeedback) mVibrator.vibrate(25);
mEffect.ping(mPaintHoloRed, 0);
mEffect.setHaloOverlay(HaloProperties.Overlay.BLACK_X, 1f);
mOverX = true;
}
return false;
} else {
if (mOverX) mEffect.setHaloOverlay(HaloProperties.Overlay.NONE, 0f);
mOverX = false;
}
// Drag
if (mState != State.DRAG) {
if (initialDistance > mIconSize * 0.7f) {
if (mInteractionReversed) {
mState = State.GESTURES;
mEffect.wake();
mBar.setHaloTaskerActive(true, true);
} else {
mState = State.DRAG;
mEffect.intro();
if (mHapticFeedback) mVibrator.vibrate(25);
}
}
} else {
int posX = (int)event.getRawX() - mIconHalfSize;
int posY = (int)event.getRawY() - mIconHalfSize;
if (posX < 0) posX = 0;
if (posY < 0) posY = 0;
if (posX > mScreenWidth-mIconSize) posX = mScreenWidth-mIconSize;
if (posY > mScreenHeight-mIconSize) posY = mScreenHeight-mIconSize;
mEffect.setHaloX(posX);
mEffect.setHaloY(posY);
// Update resources when the side changes
boolean oldTickerPos = mTickerLeft;
mTickerLeft = (posX + mIconHalfSize < mScreenWidth / 2);
if (oldTickerPos != mTickerLeft) {
mEffect.updateResources();
mEffect.mHaloTextViewL.setVisibility(mTickerLeft ? View.VISIBLE : View.GONE);
mEffect.mHaloTextViewR.setVisibility(mTickerLeft ? View.GONE : View.VISIBLE);
}
}
} else {
// We have three basic gestures, one horizontal for switching through tasks and
// two vertical for dismissing tasks or making HALO fall asleep
int deltaX = (int)(mTickerLeft ? event.getRawX() : mScreenWidth - event.getRawX());
int deltaY = (int)(mEffect.getHaloY() - event.getRawY() + mIconSize);
int horizontalThreshold = (int)(mIconSize * 1.5f);
int verticalThreshold = mIconHalfSize;
int verticalSteps = (int)(mIconSize * 0.6f);
String gestureText = mNotificationText;
// Switch icons
if (deltaX > horizontalThreshold) {
if (mGesture != Gesture.TASK) mEffect.setHaloOverlay(HaloProperties.Overlay.NONE, 0f);
mGesture = Gesture.TASK;
deltaX -= horizontalThreshold;
if (mNotificationData != null && mNotificationData.size() > 0) {
int items = mNotificationData.size();
// This will be the lenght we are going to use
int indexLength = (mScreenWidth - mIconSize * 2) / items;
// Calculate index
mMarkerIndex = mTickerLeft ? (items - deltaX / indexLength) - 1 : (deltaX / indexLength);
// Watch out for margins!
if (mMarkerIndex >= items) mMarkerIndex = items - 1;
if (mMarkerIndex < 0) mMarkerIndex = 0;
}
// Up & down gestures
} else if (Math.abs(deltaY) > verticalThreshold) {
mMarkerIndex = -1;
boolean gestureChanged = false;
final int deltaIndex = (Math.abs(deltaY) - verticalThreshold) / verticalSteps;
if (deltaY > 0) {
if (deltaIndex < 2 && mGesture != Gesture.UP1) {
mGesture = Gesture.UP1;
gestureChanged = true;
mEffect.setHaloOverlay(HaloProperties.Overlay.DISMISS, 1f);
gestureText = mContext.getResources().getString(R.string.halo_dismiss);
} else if (deltaIndex > 1 && mGesture != Gesture.UP2) {
mGesture = Gesture.UP2;
gestureChanged = true;
mEffect.setHaloOverlay(HaloProperties.Overlay.CLEAR_ALL, 1f);
gestureText = mContext.getResources().getString(R.string.halo_clear_all);
}
} else {
if (deltaIndex < 2 && mGesture != Gesture.DOWN1) {
mGesture = Gesture.DOWN1;
gestureChanged = true;
mEffect.setHaloOverlay(mTickerLeft ? HaloProperties.Overlay.BACK_LEFT
: HaloProperties.Overlay.BACK_RIGHT, 1f);
gestureText = mContext.getResources().getString(R.string.halo_hide);
} else if (deltaIndex > 1 && mGesture != Gesture.DOWN2) {
mGesture = Gesture.DOWN2;
gestureChanged = true;
mEffect.setHaloOverlay(HaloProperties.Overlay.SILENCE, 1f);
gestureText = mContext.getResources().getString(R.string.halo_silence);
}
}
if (gestureChanged) {
mMarkerIndex = -1;
// Tasking hasn't changed, we can tick the message here
if (mMarkerIndex == oldIconIndex) {
mEffect.ticker(gestureText, 0, 250);
mEffect.updateResources();
mEffect.invalidate();
}
if (mHapticFeedback) mVibrator.vibrate(10);
}
} else {
mMarkerIndex = -1;
if (mGesture != Gesture.NONE) {
mEffect.setHaloOverlay(HaloProperties.Overlay.NONE, 0f);
if (verticalGesture()) mEffect.killTicker();
}
mGesture = Gesture.NONE;
}
// If the marker index changed, tick
if (mMarkerIndex != oldIconIndex) {
oldIconIndex = mMarkerIndex;
// Make a tiny pop if not so many icons are present
if (mHapticFeedback && mNotificationData.size() < 10) mVibrator.vibrate(1);
try {
if (mMarkerIndex == -1) {
mTaskIntent = null;
resetIcons();
tick(mLastNotificationEntry, gestureText, 0, 250);
// Ping to notify the user we're back where we started
mEffect.ping(mPaintHoloBlue, 0);
} else {
setIcon(mMarkerIndex);
NotificationData.Entry entry = mNotificationData.get(mMarkerIndex);
String text = "";
if (entry.notification.notification.tickerText != null) {
text = entry.notification.notification.tickerText.toString();
}
tick(entry, text, 0, 250);
mTaskIntent = entry.getFloatingIntent();
}
} catch (Exception e) {
// IndexOutOfBoundsException
}
}
}
mEffect.invalidate();
break;
}
return false;
}
|
diff --git a/org.mosaic.web/src/main/java/org/mosaic/web/impl/RequestDispatcher.java b/org.mosaic.web/src/main/java/org/mosaic/web/impl/RequestDispatcher.java
index bb6c1424..5a09a0b9 100644
--- a/org.mosaic.web/src/main/java/org/mosaic/web/impl/RequestDispatcher.java
+++ b/org.mosaic.web/src/main/java/org/mosaic/web/impl/RequestDispatcher.java
@@ -1,68 +1,68 @@
package org.mosaic.web.impl;
import com.google.common.net.HttpHeaders;
import java.io.IOException;
import java.util.List;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Request;
import org.mosaic.modules.Component;
import org.mosaic.modules.Module;
import org.mosaic.modules.Service;
import org.mosaic.web.application.Application;
import org.mosaic.web.request.WebRequest;
import org.mosaic.web.request.impl.WebRequestImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author arik
*/
@Component
final class RequestDispatcher extends HttpServlet
{
private static final Logger LOG = LoggerFactory.getLogger( RequestDispatcher.class );
@Nonnull
@Component
private Module module;
@SuppressWarnings( "MismatchedQueryAndUpdateOfCollection" )
@Nonnull
@Service
private List<Application> applications;
@Override
protected void service( HttpServletRequest req, HttpServletResponse resp ) throws ServletException, IOException
{
resp.setHeader( HttpHeaders.SERVER, "Mosaic Web Server / " + this.module.getContext().getServerVersion() );
Application application = findApplication( req );
if( application == null )
{
resp.sendError( HttpServletResponse.SC_NOT_FOUND );
return;
}
WebRequest request = new WebRequestImpl( application, ( Request ) req );
request.dumpToInfoLog( LOG, "The request" );
- // TODO arik: implement org.mosaic.web.impl.RequestDispatcher.doGet([req, resp])
+ // TODO arik: implement org.mosaic.web.impl.RequestDispatcher.service([req, resp])
}
@Nullable
private Application findApplication( @Nonnull HttpServletRequest request )
{
for( Application application : this.applications )
{
if( application.getVirtualHosts().contains( request.getServerName().toLowerCase() ) )
{
return application;
}
}
return null;
}
}
| true | true | protected void service( HttpServletRequest req, HttpServletResponse resp ) throws ServletException, IOException
{
resp.setHeader( HttpHeaders.SERVER, "Mosaic Web Server / " + this.module.getContext().getServerVersion() );
Application application = findApplication( req );
if( application == null )
{
resp.sendError( HttpServletResponse.SC_NOT_FOUND );
return;
}
WebRequest request = new WebRequestImpl( application, ( Request ) req );
request.dumpToInfoLog( LOG, "The request" );
// TODO arik: implement org.mosaic.web.impl.RequestDispatcher.doGet([req, resp])
}
| protected void service( HttpServletRequest req, HttpServletResponse resp ) throws ServletException, IOException
{
resp.setHeader( HttpHeaders.SERVER, "Mosaic Web Server / " + this.module.getContext().getServerVersion() );
Application application = findApplication( req );
if( application == null )
{
resp.sendError( HttpServletResponse.SC_NOT_FOUND );
return;
}
WebRequest request = new WebRequestImpl( application, ( Request ) req );
request.dumpToInfoLog( LOG, "The request" );
// TODO arik: implement org.mosaic.web.impl.RequestDispatcher.service([req, resp])
}
|
diff --git a/java/marytts/server/Mary.java b/java/marytts/server/Mary.java
index 43aee2b1a..8654e279e 100755
--- a/java/marytts/server/Mary.java
+++ b/java/marytts/server/Mary.java
@@ -1,392 +1,411 @@
/**
* Copyright 2000-2006 DFKI GmbH.
* All Rights Reserved. Use is subject to license terms.
*
* Permission is hereby granted, free of charge, to use and distribute
* this software and its documentation without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of this work, and to
* permit persons to whom this work is furnished to do so, subject to
* the following conditions:
*
* 1. The code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* 2. Any modifications must be clearly marked as such.
* 3. Original authors' names are not deleted.
* 4. The authors' names are not used to endorse or promote products
* derived from this software without specific prior written
* permission.
*
* DFKI GMBH AND THE CONTRIBUTORS TO THIS WORK DISCLAIM ALL WARRANTIES WITH
* REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL DFKI GMBH NOR THE
* CONTRIBUTORS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
* PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
* ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
* THIS SOFTWARE.
*/
package marytts.server;
// General Java Classes
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.StringReader;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Locale;
import java.util.SortedSet;
import java.util.StringTokenizer;
import java.util.TreeSet;
import java.util.Map.Entry;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.TransformerFactory;
import marytts.Version;
import marytts.datatypes.MaryDataType;
import marytts.exceptions.NoSuchPropertyException;
import marytts.features.FeatureProcessorManager;
import marytts.features.FeatureRegistry;
import marytts.modules.MaryModule;
import marytts.modules.ModuleRegistry;
import marytts.modules.Synthesis;
import marytts.modules.synthesis.Voice;
import marytts.server.http.MaryHttpServer;
import marytts.util.MaryUtils;
import marytts.util.data.audio.MaryAudioUtils;
import marytts.util.io.FileUtils;
import marytts.util.string.StringUtils;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.WriterAppender;
/**
* The main program for the mary TtS system.
* It can run as a socket server or as a stand-alone program.
* @author Marc Schröder
*/
public class Mary {
public static final int STATE_OFF = 0;
public static final int STATE_STARTING = 1;
public static final int STATE_RUNNING = 2;
public static final int STATE_SHUTTING_DOWN = 3;
private static Logger logger;
private static int currentState = STATE_OFF;
private static boolean jarsAdded = false;
/**
* Inform about system state.
* @return an integer representing the current system state.
* @see #STATE_OFF
* @see #STATE_STARTING
* @see #STATE_RUNNING
* @see #STATE_SHUTTING_DOWN
*/
public static int currentState() {
return currentState;
}
/**
* Add jars to classpath. Normally this is called from startup().
* @throws Exception
*/
protected static void addJarsToClasspath() throws Exception
{
if (jarsAdded) return; // have done this already
File jarDir = new File(MaryProperties.maryBase()+"/java");
File[] jarFiles = jarDir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".jar");
}
});
assert jarFiles != null;
URLClassLoader sysloader = (URLClassLoader)ClassLoader.getSystemClassLoader();
Method method = URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{URL.class});
method.setAccessible(true);
for (int i=0; i<jarFiles.length; i++) {
URL jarURL = new URL("file:"+jarFiles[i].getPath());
method.invoke(sysloader, new Object[] {jarURL});
}
jarsAdded = true;
}
private static void startModules()
throws ClassNotFoundException, InstantiationException, Exception {
for (String moduleClassName : MaryProperties.moduleInitInfo()) {
MaryModule m = ModuleRegistry.instantiateModule(moduleClassName);
// Partially fill module repository here;
// TODO: voice-specific entries will be added when each voice is loaded.
ModuleRegistry.registerModule(m, m.getLocale(), null);
}
ModuleRegistry.setRegistrationComplete();
// Separate loop for startup allows modules to cross-reference to each
// other via Mary.getModule(Class) even if some have not yet been
// started.
for (MaryModule m : ModuleRegistry.getAllModules()) {
// Only start the modules here if in server mode:
if (((MaryProperties.getProperty("server").compareTo("commandline")!=0) || m instanceof Synthesis)
&& m.getState() == MaryModule.MODULE_OFFLINE) {
try {
m.startup();
} catch (Throwable t) {
throw new Exception("Problem starting module "+ m.name(), t);
}
}
if (MaryProperties.getAutoBoolean("modules.poweronselftest", false)) {
m.powerOnSelfTest();
}
}
}
private static void setupFeatureProcessors()
throws Exception
{
String featureProcessorManagers = MaryProperties.getProperty("featuremanager.classes.list");
if (featureProcessorManagers == null) {
throw new NoSuchPropertyException("Expected list property 'featuremanager.classes.list' is missing.");
}
StringTokenizer st = new StringTokenizer(featureProcessorManagers);
while (st.hasMoreTokens()) {
String fpmClassName = st.nextToken();
try {
Class fpmClass = Class.forName(fpmClassName);
FeatureProcessorManager mgr = (FeatureProcessorManager) fpmClass.newInstance();
Locale locale = mgr.getLocale();
if (locale != null) {
FeatureRegistry.setFeatureProcessorManager(locale, mgr);
} else {
logger.debug("Setting fallback feature processor manager to '"+fpmClassName+"'");
FeatureRegistry.setFallbackFeatureProcessorManager(mgr);
}
} catch (Throwable t) {
throw new Exception("Cannot instantiate feature processor manager '"+fpmClassName+"'", t);
}
}
}
/**
* Start the MARY system and all modules. This method must be called
* once before any calls to {@link #process()} are possible.
* @throws IllegalStateException if the system is not offline.
* @throws Exception
*/
public static void startup() throws Exception
{
if (currentState != STATE_OFF) throw new IllegalStateException("Cannot start system: it is not offline");
currentState = STATE_STARTING;
addJarsToClasspath();
MaryProperties.readProperties();
// Configure Logging:
logger = Logger.getLogger("main");
Logger.getRootLogger().setLevel(Level.toLevel(MaryProperties.needProperty("log.level")));
PatternLayout layout = new PatternLayout("%d [%t] %-5p %-10c %m\n");
+ File logFile = null;
if (MaryProperties.needAutoBoolean("log.tofile")) {
String filename = MaryProperties.getFilename("log.filename", "mary.log");
- File logFile = new File(filename);
- if (logFile.exists()) logFile.delete();
- BasicConfigurator.configure(new FileAppender(layout, filename));
+ logFile = new File(filename);
+ if (!(logFile.exists()&&logFile.canWrite() // exists and writable
+ || logFile.getParentFile().exists() && logFile.getParentFile().canWrite())) { // parent exists and writable
+ // cannot write to file
+ System.err.print("\nCannot write to log file '"+filename+"' -- ");
+ File fallbackLogFile = new File(System.getProperty("user.home")+"/mary.log");
+ if (fallbackLogFile.exists()&&fallbackLogFile.canWrite() // exists and writable
+ || fallbackLogFile.exists()&&fallbackLogFile.canWrite()) { // parent exists and writable
+ // fallback log file is OK
+ System.err.println("will log to '"+fallbackLogFile.getAbsolutePath()+"' instead.");
+ logFile = fallbackLogFile;
+ } else {
+ // cannot write to fallback log either
+ System.err.println("will log to standard output instead.");
+ logFile = null;
+ }
+ }
+ if (logFile != null && logFile.exists()) logFile.delete();
+ }
+ if (logFile != null) {
+ BasicConfigurator.configure(new FileAppender(layout, logFile.getAbsolutePath()));
} else {
BasicConfigurator.configure(new WriterAppender(layout, System.err));
}
logger.info("Mary starting up...");
logger.info("Specification version " + Version.specificationVersion());
logger.info("Implementation version " + Version.implementationVersion());
logger.info("Running on a Java " + System.getProperty("java.version")
+ " implementation by " + System.getProperty("java.vendor")
+ ", on a " + System.getProperty("os.name") + " platform ("
+ System.getProperty("os.arch") + ", " + System.getProperty("os.version")
+ ")");
logger.debug("Full dump of system properties:");
for (Object key : new TreeSet<Object>(System.getProperties().keySet())) {
logger.debug(key + " = " + System.getProperties().get(key));
}
logger.debug("XML libraries used:");
try {
Class xercesVersion = Class.forName("org.apache.xerces.impl.Version");
logger.debug(xercesVersion.getMethod("getVersion").invoke(null));
} catch (Exception e) {
logger.debug("XML parser is not Xerces: " + DocumentBuilderFactory.newInstance().getClass());
}
try {
Class xalanVersion = Class.forName("org.apache.xalan.Version");
logger.debug(xalanVersion.getMethod("getVersion").invoke(null));
} catch (Exception e) {
logger.debug("XML transformer is not Xalan: " + TransformerFactory.newInstance().getClass());
}
// Essential environment checks:
EnvironmentChecks.check();
setupFeatureProcessors();
// Instantiate module classes and startup modules:
startModules();
logger.info("Startup complete.");
currentState = STATE_RUNNING;
}
/**
* Orderly shut down the MARY system.
* @throws IllegalStateException if the MARY system is not running.
*/
public static void shutdown()
{
if (currentState != STATE_RUNNING) throw new IllegalStateException("MARY system is not running");
currentState = STATE_SHUTTING_DOWN;
logger.info("Shutting down modules...");
// Shut down modules:
for (MaryModule m : ModuleRegistry.getAllModules()) {
if (m.getState() == MaryModule.MODULE_RUNNING)
m.shutdown();
}
logger.info("Shutdown complete.");
currentState = STATE_OFF;
}
/**
* Process input into output using the MARY system. For inputType TEXT
* and output type AUDIO, this does text-to-speech conversion; for other
* settings, intermediate processing results can be generated or provided
* as input.
* @param input
* @param inputTypeName
* @param outputTypeName
* @param localeString
* @param audioType
* @param voiceName
* @param style
* @param effects
* @param output the output stream into which the processing result will be
* written.
* @throws IllegalStateException if the MARY system is not running.
* @throws Exception
*/
public static void process(String input, String inputTypeName, String outputTypeName,
String localeString, String audioTypeName, String voiceName,
String style, String effects, OutputStream output)
throws Exception
{
if (currentState != STATE_RUNNING) throw new IllegalStateException("MARY system is not running");
MaryDataType inputType = MaryDataType.get(inputTypeName);
MaryDataType outputType = MaryDataType.get(outputTypeName);
Locale locale = MaryUtils.string2locale(localeString);
Voice voice = null;
if (voiceName != null)
voice = Voice.getVoice(voiceName);
AudioFileFormat audioFileFormat = null;
AudioFileFormat.Type audioType = null;
if (audioTypeName != null) {
audioType = MaryAudioUtils.getAudioFileFormatType(audioTypeName);
AudioFormat audioFormat = null;
if (audioTypeName.equals("MP3")) {
audioFormat = MaryAudioUtils.getMP3AudioFormat();
} else if (audioTypeName.equals("Vorbis")) {
audioFormat = MaryAudioUtils.getOggAudioFormat();
} else if (voice != null) {
audioFormat = voice.dbAudioFormat();
} else {
audioFormat = Voice.AF22050;
}
audioFileFormat = new AudioFileFormat(audioType, audioFormat, AudioSystem.NOT_SPECIFIED);
}
Request request = new Request(inputType, outputType, locale, voice, effects, style, 1, audioFileFormat);
request.readInputData(new StringReader(input));
request.process();
request.writeOutputData(System.out);
}
/**
* The starting point of the standalone Mary program.
* If server mode is requested by property settings, starts
* the <code>MaryServer</code>; otherwise, a <code>Request</code>
* is created reading from the file given as first argument and writing
* to System.out.
*
* <p>Usage:<p>
* As a socket server:
* <pre>
* java -Dmary.base=$MARY_BASE -Dserver=true marytts.server.Mary
* </pre><p>
* As a stand-alone program:
* <pre>
* java -Dmary.base=$MARY_BASE marytts.server.Mary myfile.txt
* </pre>
* @see MaryProperties
* @see MaryServer
* @see RequestHandler
* @see Request
*/
public static void main(String[] args) throws Exception {
long startTime = System.currentTimeMillis();
addJarsToClasspath();
MaryProperties.readProperties();
String server = MaryProperties.needProperty("server");
System.err.print("MARY server " + Version.specificationVersion() + " starting as a ");
if (server.equals("socket")) System.err.print("socket server...");
else if (server.equals("http")) System.err.print("HTTP server...");
else System.err.print("command-line application...");
startup();
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
shutdown();
}
});
System.err.println(" started in " + (System.currentTimeMillis()-startTime)/1000. + " s");
if (server.equals("socket")) //socket server mode
new MaryServer().run();
else if (server.equals("http")) //http server mode
new MaryHttpServer().run();
else { // command-line mode
InputStream inputStream;
if (args.length == 0 || args[0].equals("-"))
inputStream = System.in;
else
inputStream = new FileInputStream(args[0]);
String input = FileUtils.getStreamAsString(inputStream, "UTF-8");
process(input,
MaryProperties.getProperty("input.type", "TEXT"),
MaryProperties.getProperty("output.type", "AUDIO"),
MaryProperties.getProperty("locale", "en"),
MaryProperties.getProperty("audio.type", "WAVE"),
MaryProperties.getProperty("voice", null),
MaryProperties.getProperty("style", null),
MaryProperties.getProperty("effect", null),
System.out);
}
shutdown();
}
}
| false | true | public static void startup() throws Exception
{
if (currentState != STATE_OFF) throw new IllegalStateException("Cannot start system: it is not offline");
currentState = STATE_STARTING;
addJarsToClasspath();
MaryProperties.readProperties();
// Configure Logging:
logger = Logger.getLogger("main");
Logger.getRootLogger().setLevel(Level.toLevel(MaryProperties.needProperty("log.level")));
PatternLayout layout = new PatternLayout("%d [%t] %-5p %-10c %m\n");
if (MaryProperties.needAutoBoolean("log.tofile")) {
String filename = MaryProperties.getFilename("log.filename", "mary.log");
File logFile = new File(filename);
if (logFile.exists()) logFile.delete();
BasicConfigurator.configure(new FileAppender(layout, filename));
} else {
BasicConfigurator.configure(new WriterAppender(layout, System.err));
}
logger.info("Mary starting up...");
logger.info("Specification version " + Version.specificationVersion());
logger.info("Implementation version " + Version.implementationVersion());
logger.info("Running on a Java " + System.getProperty("java.version")
+ " implementation by " + System.getProperty("java.vendor")
+ ", on a " + System.getProperty("os.name") + " platform ("
+ System.getProperty("os.arch") + ", " + System.getProperty("os.version")
+ ")");
logger.debug("Full dump of system properties:");
for (Object key : new TreeSet<Object>(System.getProperties().keySet())) {
logger.debug(key + " = " + System.getProperties().get(key));
}
logger.debug("XML libraries used:");
try {
Class xercesVersion = Class.forName("org.apache.xerces.impl.Version");
logger.debug(xercesVersion.getMethod("getVersion").invoke(null));
} catch (Exception e) {
logger.debug("XML parser is not Xerces: " + DocumentBuilderFactory.newInstance().getClass());
}
try {
Class xalanVersion = Class.forName("org.apache.xalan.Version");
logger.debug(xalanVersion.getMethod("getVersion").invoke(null));
} catch (Exception e) {
logger.debug("XML transformer is not Xalan: " + TransformerFactory.newInstance().getClass());
}
// Essential environment checks:
EnvironmentChecks.check();
setupFeatureProcessors();
// Instantiate module classes and startup modules:
startModules();
logger.info("Startup complete.");
currentState = STATE_RUNNING;
}
| public static void startup() throws Exception
{
if (currentState != STATE_OFF) throw new IllegalStateException("Cannot start system: it is not offline");
currentState = STATE_STARTING;
addJarsToClasspath();
MaryProperties.readProperties();
// Configure Logging:
logger = Logger.getLogger("main");
Logger.getRootLogger().setLevel(Level.toLevel(MaryProperties.needProperty("log.level")));
PatternLayout layout = new PatternLayout("%d [%t] %-5p %-10c %m\n");
File logFile = null;
if (MaryProperties.needAutoBoolean("log.tofile")) {
String filename = MaryProperties.getFilename("log.filename", "mary.log");
logFile = new File(filename);
if (!(logFile.exists()&&logFile.canWrite() // exists and writable
|| logFile.getParentFile().exists() && logFile.getParentFile().canWrite())) { // parent exists and writable
// cannot write to file
System.err.print("\nCannot write to log file '"+filename+"' -- ");
File fallbackLogFile = new File(System.getProperty("user.home")+"/mary.log");
if (fallbackLogFile.exists()&&fallbackLogFile.canWrite() // exists and writable
|| fallbackLogFile.exists()&&fallbackLogFile.canWrite()) { // parent exists and writable
// fallback log file is OK
System.err.println("will log to '"+fallbackLogFile.getAbsolutePath()+"' instead.");
logFile = fallbackLogFile;
} else {
// cannot write to fallback log either
System.err.println("will log to standard output instead.");
logFile = null;
}
}
if (logFile != null && logFile.exists()) logFile.delete();
}
if (logFile != null) {
BasicConfigurator.configure(new FileAppender(layout, logFile.getAbsolutePath()));
} else {
BasicConfigurator.configure(new WriterAppender(layout, System.err));
}
logger.info("Mary starting up...");
logger.info("Specification version " + Version.specificationVersion());
logger.info("Implementation version " + Version.implementationVersion());
logger.info("Running on a Java " + System.getProperty("java.version")
+ " implementation by " + System.getProperty("java.vendor")
+ ", on a " + System.getProperty("os.name") + " platform ("
+ System.getProperty("os.arch") + ", " + System.getProperty("os.version")
+ ")");
logger.debug("Full dump of system properties:");
for (Object key : new TreeSet<Object>(System.getProperties().keySet())) {
logger.debug(key + " = " + System.getProperties().get(key));
}
logger.debug("XML libraries used:");
try {
Class xercesVersion = Class.forName("org.apache.xerces.impl.Version");
logger.debug(xercesVersion.getMethod("getVersion").invoke(null));
} catch (Exception e) {
logger.debug("XML parser is not Xerces: " + DocumentBuilderFactory.newInstance().getClass());
}
try {
Class xalanVersion = Class.forName("org.apache.xalan.Version");
logger.debug(xalanVersion.getMethod("getVersion").invoke(null));
} catch (Exception e) {
logger.debug("XML transformer is not Xalan: " + TransformerFactory.newInstance().getClass());
}
// Essential environment checks:
EnvironmentChecks.check();
setupFeatureProcessors();
// Instantiate module classes and startup modules:
startModules();
logger.info("Startup complete.");
currentState = STATE_RUNNING;
}
|
diff --git a/src/main/java/com/bergerkiller/bukkit/common/controller/EntityNetworkController.java b/src/main/java/com/bergerkiller/bukkit/common/controller/EntityNetworkController.java
index 7bd5928..8f4c3eb 100644
--- a/src/main/java/com/bergerkiller/bukkit/common/controller/EntityNetworkController.java
+++ b/src/main/java/com/bergerkiller/bukkit/common/controller/EntityNetworkController.java
@@ -1,723 +1,723 @@
package com.bergerkiller.bukkit.common.controller;
import java.util.Collection;
import java.util.Collections;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.util.Vector;
import net.minecraft.server.v1_5_R2.Entity;
import net.minecraft.server.v1_5_R2.EntityTrackerEntry;
import com.bergerkiller.bukkit.common.bases.IntVector2;
import com.bergerkiller.bukkit.common.bases.IntVector3;
import com.bergerkiller.bukkit.common.conversion.Conversion;
import com.bergerkiller.bukkit.common.entity.CommonEntity;
import com.bergerkiller.bukkit.common.entity.CommonEntityController;
import com.bergerkiller.bukkit.common.entity.nms.NMSEntityTrackerEntry;
import com.bergerkiller.bukkit.common.internal.CommonNMS;
import com.bergerkiller.bukkit.common.protocol.CommonPacket;
import com.bergerkiller.bukkit.common.protocol.PacketFields;
import com.bergerkiller.bukkit.common.reflection.classes.EntityRef;
import com.bergerkiller.bukkit.common.reflection.classes.EntityTrackerEntryRef;
import com.bergerkiller.bukkit.common.utils.EntityUtil;
import com.bergerkiller.bukkit.common.utils.MathUtil;
import com.bergerkiller.bukkit.common.utils.PacketUtil;
import com.bergerkiller.bukkit.common.utils.PlayerUtil;
import com.bergerkiller.bukkit.common.wrappers.DataWatcher;
/**
* A controller that deals with the server to client network synchronization.
*
* @param <T> - type of Common Entity this controller is for
*/
public abstract class EntityNetworkController<T extends CommonEntity<?>> extends CommonEntityController<T> {
/**
* The maximum allowed distance per relative movement update
*/
public static final int MAX_RELATIVE_DISTANCE = 127;
/**
* The minimum value change that is able to trigger an update
*/
public static final int MIN_RELATIVE_CHANGE = 4;
/**
* The minimum velocity change that is able to trigger an update
*/
public static final double MIN_RELATIVE_VELOCITY = 0.02;
/**
* The minimum velocity change that is able to trigger an update (squared)
*/
public static final double MIN_RELATIVE_VELOCITY_SQUARED = MIN_RELATIVE_VELOCITY * MIN_RELATIVE_VELOCITY;
/**
* The tick interval at which the entity is updated absolutely
*/
public static final int ABSOLUTE_UPDATE_INTERVAL = 400;
private Object handle;
/**
* Binds this Entity Network Controller to an Entity.
* This is called from elsewhere, and should be ignored entirely.
*
* @param entity to bind with
* @param entityTrackerEntry to bind with
*/
public final void bind(T entity, Object entityTrackerEntry) {
if (this.entity != null) {
this.onDetached();
}
this.entity = entity;
this.handle = entityTrackerEntry;
if (this.handle instanceof NMSEntityTrackerEntry) {
((NMSEntityTrackerEntry) this.handle).setController(this);
}
if (this.entity.isSpawned()) {
this.onAttached();
}
}
/**
* Obtains the Entity Tracker Entry handle of this Network Controller
*
* @return entry handle
*/
public Object getHandle() {
return handle;
}
/**
* Gets a collection of all Players viewing this Entity
*
* @return viewing players
*/
public final Collection<Player> getViewers() {
return Collections.unmodifiableCollection(EntityTrackerEntryRef.viewers.get(handle));
}
/**
* Adds a new viewer to this Network Controller.
* Calling this method also results in spawn messages being sent to the viewer.
* When overriding, make sure to always check the super-result before continuing!
*
* @param viewer to add
* @return True if the viewer was added, False if the viewer was already added
*/
@SuppressWarnings("unchecked")
public boolean addViewer(Player viewer) {
if (!((EntityTrackerEntry) handle).trackedPlayers.add(Conversion.toEntityHandle.convert(viewer))) {
return false;
}
this.makeVisible(viewer);
return true;
}
/**
* Removes a viewer from this Network Controller.
* Calling this method also results in destroy messages being sent to the viewer.
* When overriding, make sure to always check the super-result before continuing!
*
* @param viewer to remove
* @return True if the viewer was removed, False if the viewer wasn't contained
*/
public boolean removeViewer(Player viewer) {
if (!((EntityTrackerEntry) handle).trackedPlayers.remove(Conversion.toEntityHandle.convert(viewer))) {
return false;
}
this.makeHidden(viewer);
return true;
}
/**
* Adds or removes a viewer based on viewer distance
*
* @param viewer to update
*/
public final void updateViewer(Player viewer) {
final IntVector3 pos = this.getProtocolPositionSynched();
final double dx = Math.abs(EntityUtil.getLocX(viewer) - (double) (pos.x / 32.0));
final double dz = Math.abs(EntityUtil.getLocZ(viewer) - (double) (pos.z / 32.0));
final double view = this.getViewDistance();
// Only add the viewer if it is in view, and if the viewer can actually see the entity (PlayerChunk)
// The ignoreChunkCheck is needed for when a new player spawns (it is not yet added to the PlayerChunk)
if (dx <= view && dz <= view && (EntityRef.ignoreChunkCheck.get(entity.getHandle()) ||
PlayerUtil.isChunkEntered(viewer, entity.getChunkX(), entity.getChunkZ()))) {
addViewer(viewer);
} else {
removeViewer(viewer);
}
}
/**
* Ensures that the Entity is displayed to the viewer
*
* @param viewer to display this Entity for
*/
public void makeVisible(Player viewer) {
CommonNMS.getNative(viewer).removeQueue.remove((Object) entity.getEntityId());
// Spawn packet
PacketUtil.sendPacket(viewer, getSpawnPacket());
// Meta Data
PacketUtil.sendPacket(viewer, PacketFields.ENTITY_METADATA.newInstance(entity.getEntityId(), entity.getMetaData(), true));
// Velocity
PacketUtil.sendPacket(viewer, PacketFields.ENTITY_VELOCITY.newInstance(entity.getEntityId(), this.getProtocolVelocitySynched()));
// Passenger?
if (entity.isInsideVehicle()) {
PacketUtil.sendPacket(viewer, PacketFields.ATTACH_ENTITY.newInstance(entity.getEntity(), entity.getVehicle()));
}
// Special living entity messages
if (entity.getEntity() instanceof LivingEntity) {
// Equipment: TODO (needs NMS because index is lost...)
// Mob effects: TODO (can use Potion effects?)
}
// Human entity sleeping action
if (entity.getEntity() instanceof HumanEntity && ((HumanEntity) entity.getEntity()).isSleeping()) {
PacketUtil.sendPacket(viewer, PacketFields.ENTITY_LOCATION_ACTION.newInstance(entity.getEntity(),
0, entity.loc.x.block(), entity.loc.y.block(), entity.loc.z.block()));
}
// Initial entity head rotation
int headRot = getProtocolHeadRotation();
if (headRot != 0) {
PacketUtil.sendPacket(viewer, PacketFields.ENTITY_HEAD_ROTATION.newInstance(entity.getEntityId(), (byte) headRot));
}
}
/**
* Ensures that the Entity is no longer displayed to any viewers.
* All viewers will see the Entity disappear. This method queues for the next tick.
*/
public void makeHiddenForAll() {
for (Player viewer : getViewers()) {
makeHidden(viewer);
}
}
/**
* Ensures that the Entity is no longer displayed to any viewers.
* All viewers will see the Entity disappear.
*
* @param instant option: True to instantly hide, False to queue it for the next tick
*/
public void makeHiddenForAll(boolean instant) {
for (Player viewer : getViewers()) {
makeHidden(viewer, instant);
}
}
/**
* Ensures that the Entity is no longer displayed to the viewer.
* The entity is not instantly hidden; it is queued for the next tick.
*
* @param viewer to hide this Entity for
*/
public void makeHidden(Player viewer) {
makeHidden(viewer, false);
}
/**
* Ensures that the Entity is no longer displayed to the viewer
*
* @param viewer to hide this Entity for
* @param instant option: True to instantly hide, False to queue it for the next tick
*/
@SuppressWarnings("unchecked")
public void makeHidden(Player viewer, boolean instant) {
if (instant) {
PacketUtil.sendPacket(viewer, PacketFields.DESTROY_ENTITY.newInstance(entity.getEntityId()));
} else {
CommonNMS.getNative(viewer).removeQueue.add((Object) entity.getEntityId());
}
}
/**
* Called at a set interval to synchronize data to clients
*/
public void onSync() {
if (entity.isDead()) {
return;
}
//TODO: Item frame support? Meh. Not for not. Later.
this.syncVehicle();
if (this.isUpdateTick() || entity.isPositionChanged()) {
entity.setPositionChanged(false);
// Update location
if (this.getTicksSinceLocationSync() > ABSOLUTE_UPDATE_INTERVAL) {
this.syncLocationAbsolute();
} else {
this.syncLocation();
}
// Update velocity when position changes
entity.setVelocityChanged(false);
this.syncVelocity();
} else if (entity.isVelocityChanged()) {
// Update velocity when velocity changes
entity.setVelocityChanged(false);
this.syncVelocity();
}
this.syncMeta();
this.syncHeadRotation();
}
/**
* Synchronizes the entity Vehicle.
* Updates when the vehicle changes, or if in a Vehicle at a set interval.
*/
public void syncVehicle() {
org.bukkit.entity.Entity oldVehicle = this.getVehicleSynched();
org.bukkit.entity.Entity newVehicle = entity.getVehicle();
if (oldVehicle != newVehicle) { // || (newVehicle != null && isTick(60))) { << DISABLED UNTIL IT ACTUALLY WORKS
this.syncVehicle(newVehicle);
}
}
/**
* Synchronizes the entity location to all clients.
* Based on the distances, relative or absolute movement is performed.
*/
public void syncLocation() {
// Position
final IntVector3 oldPos = this.getProtocolPositionSynched();
final IntVector3 newPos = this.getProtocolPosition();
final boolean moved = newPos.subtract(oldPos).abs().greaterEqualThan(MIN_RELATIVE_CHANGE);
// Rotation
final IntVector2 oldRot = this.getProtocolRotationSynched();
final IntVector2 newRot = this.getProtocolRotation();
final boolean rotated = newRot.subtract(oldRot).abs().greaterEqualThan(MIN_RELATIVE_CHANGE);
// Synchronize
syncLocation(moved ? newPos : null, rotated ? newRot : null);
}
/**
* Synchronizes the entity head yaw rotation to all Clients.
*/
public void syncHeadRotation() {
final int oldYaw = this.getProtocolHeadRotationSynched();
final int newYaw = this.getProtocolHeadRotation();
if (Math.abs(newYaw - oldYaw) >= MIN_RELATIVE_CHANGE) {
syncHeadRotation(newYaw);
}
}
/**
* Synchronizes the entity metadata to all Clients.
* Metadata changes are read and used.
*/
public void syncMeta() {
DataWatcher meta = entity.getMetaData();
if (meta.isChanged()) {
broadcast(PacketFields.ENTITY_METADATA.newInstance(entity.getEntityId(), meta, false), true);
}
}
/**
* Synchronizes the entity velocity to all Clients.
* Based on a change in Velocity, velocity will be updated.
*/
public void syncVelocity() {
if (!this.isMobile()) {
return;
}
//TODO: For players, there should be an event here!
Vector oldVel = this.getProtocolVelocitySynched();
Vector newVel = this.getProtocolVelocity();
// Synchronize velocity when the entity stopped moving, or when the velocity change is large enough
if ((newVel.lengthSquared() == 0.0 && oldVel.lengthSquared() > 0.0) || oldVel.distanceSquared(newVel) > MIN_RELATIVE_VELOCITY_SQUARED) {
this.syncVelocity(newVel);
}
}
/**
* Sends a packet to all viewers, excluding the entity itself
*
* @param packet to send
*/
public void broadcast(CommonPacket packet) {
broadcast(packet, false);
}
/**
* Sends a packet to all viewers, and if set, to itself
*
* @param packet to send
* @param self option: True to send to self (if a player), False to not send to self
*/
public void broadcast(CommonPacket packet, boolean self) {
if (self && entity.getEntity() instanceof Player) {
PacketUtil.sendPacket((Player) entity.getEntity(), packet);
}
// Viewers
for (Player viewer : this.getViewers()) {
PacketUtil.sendPacket(viewer, packet);
}
}
/**
* Creates a new spawn packet for spawning this Entity.
* To change the spawned entity type, override this method.
* By default, the entity is evaluated and the right packet is created automatically.
*
* @return spawn packet
*/
public CommonPacket getSpawnPacket() {
final CommonPacket packet = EntityTrackerEntryRef.getSpawnPacket(handle);
if (PacketFields.VEHICLE_SPAWN.isInstance(packet)) {
// NMS error: They are not using the position, but the live position
// This has some big issues when new players join...
// Position
final IntVector3 pos = this.getProtocolPositionSynched();
packet.write(PacketFields.VEHICLE_SPAWN.x, pos.x);
packet.write(PacketFields.VEHICLE_SPAWN.y, pos.y);
packet.write(PacketFields.VEHICLE_SPAWN.z, pos.z);
// Rotation
final IntVector2 rot = this.getProtocolRotationSynched();
- packet.write(PacketFields.VEHICLE_SPAWN.yaw, (byte) rot.x);
- packet.write(PacketFields.VEHICLE_SPAWN.pitch, (byte) rot.z);
+ packet.write(PacketFields.VEHICLE_SPAWN.yaw, (byte) rot.z);
+ packet.write(PacketFields.VEHICLE_SPAWN.pitch, (byte) rot.x);
}
return packet;
}
public int getViewDistance() {
return EntityTrackerEntryRef.viewDistance.get(handle);
}
public void setViewDistance(int blockDistance) {
EntityTrackerEntryRef.viewDistance.set(handle, blockDistance);
}
public int getUpdateInterval() {
return EntityTrackerEntryRef.updateInterval.get(handle);
}
public void setUpdateInterval(int tickInterval) {
EntityTrackerEntryRef.updateInterval.set(handle, tickInterval);
}
public boolean isMobile() {
return EntityTrackerEntryRef.isMobile.get(handle);
}
public void setMobile(boolean mobile) {
EntityTrackerEntryRef.isMobile.set(handle, mobile);
}
/**
* Synchronizes everything by first destroying and then respawning this Entity to all viewers
*/
public void syncRespawn() {
// Hide
for (Player viewer : getViewers()) {
this.makeHidden(viewer, true);
}
// Update information
final EntityTrackerEntry handle = (EntityTrackerEntry) this.handle;
final Vector velocity = this.getProtocolVelocity();
handle.j = velocity.getX();
handle.k = velocity.getY();
handle.l = velocity.getZ();
final IntVector3 position = this.getProtocolPosition();
handle.xLoc = position.x;
handle.yLoc = position.y;
handle.zLoc = position.z;
final IntVector2 rotation = this.getProtocolRotation();
handle.yRot = rotation.x;
handle.xRot = rotation.z;
final int headYaw = this.getProtocolHeadRotation();
handle.i = headYaw;
// Spawn
for (Player viewer : getViewers()) {
this.makeVisible(viewer);
}
// Attach messages (because it is not handled by vehicles)
if (entity.hasPassenger()) {
broadcast(PacketFields.ATTACH_ENTITY.newInstance(entity.getPassenger(), entity.getEntity()));
}
}
/**
* Synchronizes the entity Vehicle
*
* @param vehicle to synchronize, NULL for no Vehicle
*/
public void syncVehicle(org.bukkit.entity.Entity vehicle) {
EntityTrackerEntryRef.vehicle.set(handle, vehicle);
broadcast(PacketFields.ATTACH_ENTITY.newInstance(entity.getEntity(), vehicle));
}
/**
* Synchronizes the entity position / rotation absolutely (Teleport packet)
*/
public void syncLocationAbsolute() {
syncLocationAbsolute(getProtocolPosition(), getProtocolRotation());
}
/**
* Synchronizes the entity position / rotation absolutely (Teleport packet)
*
* @param position (new)
* @param rotation (new, x = yaw, z = pitch)
*/
public void syncLocationAbsolute(IntVector3 position, IntVector2 rotation) {
if (position == null) {
position = this.getProtocolPositionSynched();
}
if (rotation == null) {
rotation = this.getProtocolRotationSynched();
}
// Update protocol values
final EntityTrackerEntry handle = (EntityTrackerEntry) this.handle;
handle.xLoc = position.x;
handle.yLoc = position.y;
handle.zLoc = position.z;
handle.yRot = rotation.x;
handle.xRot = rotation.z;
// Update last synchronization time
EntityTrackerEntryRef.timeSinceLocationSync.set(handle, 0);
// Send synchronization messages
broadcast(PacketFields.ENTITY_TELEPORT.newInstance(entity.getEntityId(), position.x, position.y, position.z,
(byte) rotation.x, (byte) rotation.z));
}
/**
* Synchronizes the entity position / rotation relatively.
*
* @param position - whether to sync position
* @param rotation - whether to sync rotation
*/
public void syncLocation(boolean position, boolean rotation) {
syncLocation(position ? getProtocolPosition() : null,
rotation ? getProtocolRotation() : null);
}
/**
* Synchronizes the entity position / rotation relatively.
* If the relative change is too big, an absolute update is performed instead.
* Pass in null values to ignore updating it.
*
* @param position (new)
* @param rotation (new, x = yaw, z = pitch)
*/
public void syncLocation(IntVector3 position, IntVector2 rotation) {
final boolean moved = position != null;
final boolean rotated = rotation != null;
final IntVector3 deltaPos = moved ? position.subtract(this.getProtocolPositionSynched()) : IntVector3.ZERO;
if (deltaPos.abs().greaterThan(MAX_RELATIVE_DISTANCE)) {
// Perform teleport instead
syncLocationAbsolute(position, rotation);
} else {
// Update protocol values
final EntityTrackerEntry handle = (EntityTrackerEntry) this.handle;
if (moved) {
handle.xLoc = position.x;
handle.yLoc = position.y;
handle.zLoc = position.z;
}
if (rotated) {
handle.yRot = rotation.x;
handle.xRot = rotation.z;
}
// Send synchronization messages
// If inside vehicle - there is no use to update the location!
if (entity.isInsideVehicle()) {
if (rotated) {
broadcast(PacketFields.ENTITY_LOOK.newInstance(entity.getEntityId(), (byte) rotation.x, (byte) rotation.z));
}
} else if (moved && rotated) {
broadcast(PacketFields.REL_ENTITY_MOVE_LOOK.newInstance(entity.getEntityId(),
(byte) deltaPos.x, (byte) deltaPos.y, (byte) deltaPos.z, (byte) rotation.x, (byte) rotation.z));
} else if (moved) {
broadcast(PacketFields.REL_ENTITY_MOVE.newInstance(entity.getEntityId(),
(byte) deltaPos.x, (byte) deltaPos.y, (byte) deltaPos.z));
} else if (rotated) {
broadcast(PacketFields.ENTITY_LOOK.newInstance(entity.getEntityId(), (byte) rotation.x, (byte) rotation.z));
}
}
}
/**
* Synchronizes the entity head yaw rotation to all Clients
*
* @param headRotation to set to
*/
public void syncHeadRotation(int headRotation) {
((EntityTrackerEntry) handle).i = headRotation;
this.broadcast(PacketFields.ENTITY_HEAD_ROTATION.newInstance(entity.getEntityId(), (byte) headRotation));
}
/**
* Synchronizes the entity velocity
*
* @param velocity (new)
*/
public void syncVelocity(Vector velocity) {
setProtocolVelocitySynched(velocity);
// If inside a vehicle, there is no use in updating
if (entity.isInsideVehicle()) {
return;
}
this.broadcast(PacketFields.ENTITY_VELOCITY.newInstance(entity.getEntityId(), velocity));
}
/**
* Obtains the current Vehicle entity according to the viewers of this entity
*
* @return Client-synchronized vehicle entity
*/
public org.bukkit.entity.Entity getVehicleSynched() {
return EntityTrackerEntryRef.vehicle.get(handle);
}
/**
* Sets the current synched velocity of the entity according to the viewers of this entity.
* This method can be used instead of syncVelocity to ignore packet sending.
*
* @param velocity to set to
*/
public void setProtocolVelocitySynched(Vector velocity) {
final EntityTrackerEntry handle = (EntityTrackerEntry) this.handle;
handle.j = velocity.getX();
handle.k = velocity.getY();
handle.l = velocity.getZ();
}
/**
* Obtains the current velocity of the entity according to the viewers of this entity
*
* @return Client-synchronized entity velocity
*/
public Vector getProtocolVelocitySynched() {
final EntityTrackerEntry handle = (EntityTrackerEntry) this.handle;
return new Vector(handle.j, handle.k, handle.l);
}
/**
* Obtains the current position of the entity according to the viewers of this entity
*
* @return Client-synchronized entity position
*/
public IntVector3 getProtocolPositionSynched() {
final EntityTrackerEntry handle = (EntityTrackerEntry) this.handle;
return new IntVector3(handle.xLoc, handle.yLoc, handle.zLoc);
}
/**
* Obtains the current rotation of the entity according to the viewers of this entity
*
* @return Client-synchronized entity rotation (x = yaw, z = pitch)
*/
public IntVector2 getProtocolRotationSynched() {
final EntityTrackerEntry handle = (EntityTrackerEntry) this.handle;
return new IntVector2(handle.yRot, handle.xRot);
}
/**
* Obtains the current velocity of the entity, converted to protocol format
*
* @return Entity velocity in protocol format
*/
public Vector getProtocolVelocity() {
return this.entity.getVelocity();
}
/**
* Obtains the current position of the entity, converted to protocol format
*
* @return Entity position in protocol format
*/
public IntVector3 getProtocolPosition() {
final Entity entity = this.entity.getHandle(Entity.class);
return new IntVector3(protLoc(entity.locX), MathUtil.floor(entity.locY * 32.0), protLoc(entity.locZ));
}
/**
* Obtains the current rotation (yaw/pitch) of the entity, converted to protocol format
*
* @return Entity rotation in protocol format (x = yaw, z = pitch)
*/
public IntVector2 getProtocolRotation() {
final Entity entity = this.entity.getHandle(Entity.class);
return new IntVector2(protRot(entity.yaw), protRot(entity.pitch));
}
/**
* Obtains the current head yaw rotation of this entity, according to the viewers
*
* @return Client-synched head-yaw rotation
*/
public int getProtocolHeadRotationSynched() {
return ((EntityTrackerEntry) handle).i;
}
/**
* Gets the amount of ticks that have passed since the last Location synchronization.
* A location synchronization means that an absolute position update is performed.
*
* @return ticks since last location synchronization
*/
public int getTicksSinceLocationSync() {
return EntityTrackerEntryRef.timeSinceLocationSync.get(handle);
}
/**
* Checks whether the current update interval is reached
*
* @return True if the update interval was reached, False if not
*/
public boolean isUpdateTick() {
final EntityTrackerEntry handle = (EntityTrackerEntry) this.handle;
return (handle.m % handle.c) == 0;
}
/**
* Checks whether a certain interval is reached
*
* @param interval in ticks
* @return True if the interval was reached, False if not
*/
public boolean isTick(int interval) {
return (((EntityTrackerEntry) handle).m % interval) == 0;
}
/**
* Obtains the current 'tick' value, which can be used for intervals
*
* @return Tick time
*/
public int getTick() {
return ((EntityTrackerEntry) handle).m;
}
/**
* Obtains the current head rotation of the entity, converted to protocol format
*
* @return Entity head rotation in protocol format
*/
public int getProtocolHeadRotation() {
return protRot(this.entity.getHeadRotation());
}
private int protRot(float rot) {
return MathUtil.floor(rot * 256.0f / 360.0f);
}
private int protLoc(double loc) {
return ((EntityTrackerEntry) handle).tracker.at.a(loc);
}
}
| true | true | public void syncVehicle() {
org.bukkit.entity.Entity oldVehicle = this.getVehicleSynched();
org.bukkit.entity.Entity newVehicle = entity.getVehicle();
if (oldVehicle != newVehicle) { // || (newVehicle != null && isTick(60))) { << DISABLED UNTIL IT ACTUALLY WORKS
this.syncVehicle(newVehicle);
}
}
/**
* Synchronizes the entity location to all clients.
* Based on the distances, relative or absolute movement is performed.
*/
public void syncLocation() {
// Position
final IntVector3 oldPos = this.getProtocolPositionSynched();
final IntVector3 newPos = this.getProtocolPosition();
final boolean moved = newPos.subtract(oldPos).abs().greaterEqualThan(MIN_RELATIVE_CHANGE);
// Rotation
final IntVector2 oldRot = this.getProtocolRotationSynched();
final IntVector2 newRot = this.getProtocolRotation();
final boolean rotated = newRot.subtract(oldRot).abs().greaterEqualThan(MIN_RELATIVE_CHANGE);
// Synchronize
syncLocation(moved ? newPos : null, rotated ? newRot : null);
}
/**
* Synchronizes the entity head yaw rotation to all Clients.
*/
public void syncHeadRotation() {
final int oldYaw = this.getProtocolHeadRotationSynched();
final int newYaw = this.getProtocolHeadRotation();
if (Math.abs(newYaw - oldYaw) >= MIN_RELATIVE_CHANGE) {
syncHeadRotation(newYaw);
}
}
/**
* Synchronizes the entity metadata to all Clients.
* Metadata changes are read and used.
*/
public void syncMeta() {
DataWatcher meta = entity.getMetaData();
if (meta.isChanged()) {
broadcast(PacketFields.ENTITY_METADATA.newInstance(entity.getEntityId(), meta, false), true);
}
}
/**
* Synchronizes the entity velocity to all Clients.
* Based on a change in Velocity, velocity will be updated.
*/
public void syncVelocity() {
if (!this.isMobile()) {
return;
}
//TODO: For players, there should be an event here!
Vector oldVel = this.getProtocolVelocitySynched();
Vector newVel = this.getProtocolVelocity();
// Synchronize velocity when the entity stopped moving, or when the velocity change is large enough
if ((newVel.lengthSquared() == 0.0 && oldVel.lengthSquared() > 0.0) || oldVel.distanceSquared(newVel) > MIN_RELATIVE_VELOCITY_SQUARED) {
this.syncVelocity(newVel);
}
}
/**
* Sends a packet to all viewers, excluding the entity itself
*
* @param packet to send
*/
public void broadcast(CommonPacket packet) {
broadcast(packet, false);
}
/**
* Sends a packet to all viewers, and if set, to itself
*
* @param packet to send
* @param self option: True to send to self (if a player), False to not send to self
*/
public void broadcast(CommonPacket packet, boolean self) {
if (self && entity.getEntity() instanceof Player) {
PacketUtil.sendPacket((Player) entity.getEntity(), packet);
}
// Viewers
for (Player viewer : this.getViewers()) {
PacketUtil.sendPacket(viewer, packet);
}
}
/**
* Creates a new spawn packet for spawning this Entity.
* To change the spawned entity type, override this method.
* By default, the entity is evaluated and the right packet is created automatically.
*
* @return spawn packet
*/
public CommonPacket getSpawnPacket() {
final CommonPacket packet = EntityTrackerEntryRef.getSpawnPacket(handle);
if (PacketFields.VEHICLE_SPAWN.isInstance(packet)) {
// NMS error: They are not using the position, but the live position
// This has some big issues when new players join...
// Position
final IntVector3 pos = this.getProtocolPositionSynched();
packet.write(PacketFields.VEHICLE_SPAWN.x, pos.x);
packet.write(PacketFields.VEHICLE_SPAWN.y, pos.y);
packet.write(PacketFields.VEHICLE_SPAWN.z, pos.z);
// Rotation
final IntVector2 rot = this.getProtocolRotationSynched();
packet.write(PacketFields.VEHICLE_SPAWN.yaw, (byte) rot.x);
packet.write(PacketFields.VEHICLE_SPAWN.pitch, (byte) rot.z);
}
return packet;
}
public int getViewDistance() {
return EntityTrackerEntryRef.viewDistance.get(handle);
}
public void setViewDistance(int blockDistance) {
EntityTrackerEntryRef.viewDistance.set(handle, blockDistance);
}
public int getUpdateInterval() {
return EntityTrackerEntryRef.updateInterval.get(handle);
}
public void setUpdateInterval(int tickInterval) {
EntityTrackerEntryRef.updateInterval.set(handle, tickInterval);
}
public boolean isMobile() {
return EntityTrackerEntryRef.isMobile.get(handle);
}
public void setMobile(boolean mobile) {
EntityTrackerEntryRef.isMobile.set(handle, mobile);
}
/**
* Synchronizes everything by first destroying and then respawning this Entity to all viewers
*/
public void syncRespawn() {
// Hide
for (Player viewer : getViewers()) {
this.makeHidden(viewer, true);
}
// Update information
final EntityTrackerEntry handle = (EntityTrackerEntry) this.handle;
final Vector velocity = this.getProtocolVelocity();
handle.j = velocity.getX();
handle.k = velocity.getY();
handle.l = velocity.getZ();
final IntVector3 position = this.getProtocolPosition();
handle.xLoc = position.x;
handle.yLoc = position.y;
handle.zLoc = position.z;
final IntVector2 rotation = this.getProtocolRotation();
handle.yRot = rotation.x;
handle.xRot = rotation.z;
final int headYaw = this.getProtocolHeadRotation();
handle.i = headYaw;
// Spawn
for (Player viewer : getViewers()) {
this.makeVisible(viewer);
}
// Attach messages (because it is not handled by vehicles)
if (entity.hasPassenger()) {
broadcast(PacketFields.ATTACH_ENTITY.newInstance(entity.getPassenger(), entity.getEntity()));
}
}
/**
* Synchronizes the entity Vehicle
*
* @param vehicle to synchronize, NULL for no Vehicle
*/
public void syncVehicle(org.bukkit.entity.Entity vehicle) {
EntityTrackerEntryRef.vehicle.set(handle, vehicle);
broadcast(PacketFields.ATTACH_ENTITY.newInstance(entity.getEntity(), vehicle));
}
/**
* Synchronizes the entity position / rotation absolutely (Teleport packet)
*/
public void syncLocationAbsolute() {
syncLocationAbsolute(getProtocolPosition(), getProtocolRotation());
}
/**
* Synchronizes the entity position / rotation absolutely (Teleport packet)
*
* @param position (new)
* @param rotation (new, x = yaw, z = pitch)
*/
public void syncLocationAbsolute(IntVector3 position, IntVector2 rotation) {
if (position == null) {
position = this.getProtocolPositionSynched();
}
if (rotation == null) {
rotation = this.getProtocolRotationSynched();
}
// Update protocol values
final EntityTrackerEntry handle = (EntityTrackerEntry) this.handle;
handle.xLoc = position.x;
handle.yLoc = position.y;
handle.zLoc = position.z;
handle.yRot = rotation.x;
handle.xRot = rotation.z;
// Update last synchronization time
EntityTrackerEntryRef.timeSinceLocationSync.set(handle, 0);
// Send synchronization messages
broadcast(PacketFields.ENTITY_TELEPORT.newInstance(entity.getEntityId(), position.x, position.y, position.z,
(byte) rotation.x, (byte) rotation.z));
}
/**
* Synchronizes the entity position / rotation relatively.
*
* @param position - whether to sync position
* @param rotation - whether to sync rotation
*/
public void syncLocation(boolean position, boolean rotation) {
syncLocation(position ? getProtocolPosition() : null,
rotation ? getProtocolRotation() : null);
}
/**
* Synchronizes the entity position / rotation relatively.
* If the relative change is too big, an absolute update is performed instead.
* Pass in null values to ignore updating it.
*
* @param position (new)
* @param rotation (new, x = yaw, z = pitch)
*/
public void syncLocation(IntVector3 position, IntVector2 rotation) {
final boolean moved = position != null;
final boolean rotated = rotation != null;
final IntVector3 deltaPos = moved ? position.subtract(this.getProtocolPositionSynched()) : IntVector3.ZERO;
if (deltaPos.abs().greaterThan(MAX_RELATIVE_DISTANCE)) {
// Perform teleport instead
syncLocationAbsolute(position, rotation);
} else {
// Update protocol values
final EntityTrackerEntry handle = (EntityTrackerEntry) this.handle;
if (moved) {
handle.xLoc = position.x;
handle.yLoc = position.y;
handle.zLoc = position.z;
}
if (rotated) {
handle.yRot = rotation.x;
handle.xRot = rotation.z;
}
// Send synchronization messages
// If inside vehicle - there is no use to update the location!
if (entity.isInsideVehicle()) {
if (rotated) {
broadcast(PacketFields.ENTITY_LOOK.newInstance(entity.getEntityId(), (byte) rotation.x, (byte) rotation.z));
}
} else if (moved && rotated) {
broadcast(PacketFields.REL_ENTITY_MOVE_LOOK.newInstance(entity.getEntityId(),
(byte) deltaPos.x, (byte) deltaPos.y, (byte) deltaPos.z, (byte) rotation.x, (byte) rotation.z));
} else if (moved) {
broadcast(PacketFields.REL_ENTITY_MOVE.newInstance(entity.getEntityId(),
(byte) deltaPos.x, (byte) deltaPos.y, (byte) deltaPos.z));
} else if (rotated) {
broadcast(PacketFields.ENTITY_LOOK.newInstance(entity.getEntityId(), (byte) rotation.x, (byte) rotation.z));
}
}
}
/**
* Synchronizes the entity head yaw rotation to all Clients
*
* @param headRotation to set to
*/
public void syncHeadRotation(int headRotation) {
((EntityTrackerEntry) handle).i = headRotation;
this.broadcast(PacketFields.ENTITY_HEAD_ROTATION.newInstance(entity.getEntityId(), (byte) headRotation));
}
/**
* Synchronizes the entity velocity
*
* @param velocity (new)
*/
public void syncVelocity(Vector velocity) {
setProtocolVelocitySynched(velocity);
// If inside a vehicle, there is no use in updating
if (entity.isInsideVehicle()) {
return;
}
this.broadcast(PacketFields.ENTITY_VELOCITY.newInstance(entity.getEntityId(), velocity));
}
/**
* Obtains the current Vehicle entity according to the viewers of this entity
*
* @return Client-synchronized vehicle entity
*/
public org.bukkit.entity.Entity getVehicleSynched() {
return EntityTrackerEntryRef.vehicle.get(handle);
}
/**
* Sets the current synched velocity of the entity according to the viewers of this entity.
* This method can be used instead of syncVelocity to ignore packet sending.
*
* @param velocity to set to
*/
public void setProtocolVelocitySynched(Vector velocity) {
final EntityTrackerEntry handle = (EntityTrackerEntry) this.handle;
handle.j = velocity.getX();
handle.k = velocity.getY();
handle.l = velocity.getZ();
}
/**
* Obtains the current velocity of the entity according to the viewers of this entity
*
* @return Client-synchronized entity velocity
*/
public Vector getProtocolVelocitySynched() {
final EntityTrackerEntry handle = (EntityTrackerEntry) this.handle;
return new Vector(handle.j, handle.k, handle.l);
}
/**
* Obtains the current position of the entity according to the viewers of this entity
*
* @return Client-synchronized entity position
*/
public IntVector3 getProtocolPositionSynched() {
final EntityTrackerEntry handle = (EntityTrackerEntry) this.handle;
return new IntVector3(handle.xLoc, handle.yLoc, handle.zLoc);
}
/**
* Obtains the current rotation of the entity according to the viewers of this entity
*
* @return Client-synchronized entity rotation (x = yaw, z = pitch)
*/
public IntVector2 getProtocolRotationSynched() {
final EntityTrackerEntry handle = (EntityTrackerEntry) this.handle;
return new IntVector2(handle.yRot, handle.xRot);
}
/**
* Obtains the current velocity of the entity, converted to protocol format
*
* @return Entity velocity in protocol format
*/
public Vector getProtocolVelocity() {
return this.entity.getVelocity();
}
/**
* Obtains the current position of the entity, converted to protocol format
*
* @return Entity position in protocol format
*/
public IntVector3 getProtocolPosition() {
final Entity entity = this.entity.getHandle(Entity.class);
return new IntVector3(protLoc(entity.locX), MathUtil.floor(entity.locY * 32.0), protLoc(entity.locZ));
}
/**
* Obtains the current rotation (yaw/pitch) of the entity, converted to protocol format
*
* @return Entity rotation in protocol format (x = yaw, z = pitch)
*/
public IntVector2 getProtocolRotation() {
final Entity entity = this.entity.getHandle(Entity.class);
return new IntVector2(protRot(entity.yaw), protRot(entity.pitch));
}
/**
* Obtains the current head yaw rotation of this entity, according to the viewers
*
* @return Client-synched head-yaw rotation
*/
public int getProtocolHeadRotationSynched() {
return ((EntityTrackerEntry) handle).i;
}
/**
* Gets the amount of ticks that have passed since the last Location synchronization.
* A location synchronization means that an absolute position update is performed.
*
* @return ticks since last location synchronization
*/
public int getTicksSinceLocationSync() {
return EntityTrackerEntryRef.timeSinceLocationSync.get(handle);
}
/**
* Checks whether the current update interval is reached
*
* @return True if the update interval was reached, False if not
*/
public boolean isUpdateTick() {
final EntityTrackerEntry handle = (EntityTrackerEntry) this.handle;
return (handle.m % handle.c) == 0;
}
/**
* Checks whether a certain interval is reached
*
* @param interval in ticks
* @return True if the interval was reached, False if not
*/
public boolean isTick(int interval) {
return (((EntityTrackerEntry) handle).m % interval) == 0;
}
/**
* Obtains the current 'tick' value, which can be used for intervals
*
* @return Tick time
*/
public int getTick() {
return ((EntityTrackerEntry) handle).m;
}
/**
* Obtains the current head rotation of the entity, converted to protocol format
*
* @return Entity head rotation in protocol format
*/
public int getProtocolHeadRotation() {
return protRot(this.entity.getHeadRotation());
}
private int protRot(float rot) {
return MathUtil.floor(rot * 256.0f / 360.0f);
}
private int protLoc(double loc) {
return ((EntityTrackerEntry) handle).tracker.at.a(loc);
}
}
| public void syncVehicle() {
org.bukkit.entity.Entity oldVehicle = this.getVehicleSynched();
org.bukkit.entity.Entity newVehicle = entity.getVehicle();
if (oldVehicle != newVehicle) { // || (newVehicle != null && isTick(60))) { << DISABLED UNTIL IT ACTUALLY WORKS
this.syncVehicle(newVehicle);
}
}
/**
* Synchronizes the entity location to all clients.
* Based on the distances, relative or absolute movement is performed.
*/
public void syncLocation() {
// Position
final IntVector3 oldPos = this.getProtocolPositionSynched();
final IntVector3 newPos = this.getProtocolPosition();
final boolean moved = newPos.subtract(oldPos).abs().greaterEqualThan(MIN_RELATIVE_CHANGE);
// Rotation
final IntVector2 oldRot = this.getProtocolRotationSynched();
final IntVector2 newRot = this.getProtocolRotation();
final boolean rotated = newRot.subtract(oldRot).abs().greaterEqualThan(MIN_RELATIVE_CHANGE);
// Synchronize
syncLocation(moved ? newPos : null, rotated ? newRot : null);
}
/**
* Synchronizes the entity head yaw rotation to all Clients.
*/
public void syncHeadRotation() {
final int oldYaw = this.getProtocolHeadRotationSynched();
final int newYaw = this.getProtocolHeadRotation();
if (Math.abs(newYaw - oldYaw) >= MIN_RELATIVE_CHANGE) {
syncHeadRotation(newYaw);
}
}
/**
* Synchronizes the entity metadata to all Clients.
* Metadata changes are read and used.
*/
public void syncMeta() {
DataWatcher meta = entity.getMetaData();
if (meta.isChanged()) {
broadcast(PacketFields.ENTITY_METADATA.newInstance(entity.getEntityId(), meta, false), true);
}
}
/**
* Synchronizes the entity velocity to all Clients.
* Based on a change in Velocity, velocity will be updated.
*/
public void syncVelocity() {
if (!this.isMobile()) {
return;
}
//TODO: For players, there should be an event here!
Vector oldVel = this.getProtocolVelocitySynched();
Vector newVel = this.getProtocolVelocity();
// Synchronize velocity when the entity stopped moving, or when the velocity change is large enough
if ((newVel.lengthSquared() == 0.0 && oldVel.lengthSquared() > 0.0) || oldVel.distanceSquared(newVel) > MIN_RELATIVE_VELOCITY_SQUARED) {
this.syncVelocity(newVel);
}
}
/**
* Sends a packet to all viewers, excluding the entity itself
*
* @param packet to send
*/
public void broadcast(CommonPacket packet) {
broadcast(packet, false);
}
/**
* Sends a packet to all viewers, and if set, to itself
*
* @param packet to send
* @param self option: True to send to self (if a player), False to not send to self
*/
public void broadcast(CommonPacket packet, boolean self) {
if (self && entity.getEntity() instanceof Player) {
PacketUtil.sendPacket((Player) entity.getEntity(), packet);
}
// Viewers
for (Player viewer : this.getViewers()) {
PacketUtil.sendPacket(viewer, packet);
}
}
/**
* Creates a new spawn packet for spawning this Entity.
* To change the spawned entity type, override this method.
* By default, the entity is evaluated and the right packet is created automatically.
*
* @return spawn packet
*/
public CommonPacket getSpawnPacket() {
final CommonPacket packet = EntityTrackerEntryRef.getSpawnPacket(handle);
if (PacketFields.VEHICLE_SPAWN.isInstance(packet)) {
// NMS error: They are not using the position, but the live position
// This has some big issues when new players join...
// Position
final IntVector3 pos = this.getProtocolPositionSynched();
packet.write(PacketFields.VEHICLE_SPAWN.x, pos.x);
packet.write(PacketFields.VEHICLE_SPAWN.y, pos.y);
packet.write(PacketFields.VEHICLE_SPAWN.z, pos.z);
// Rotation
final IntVector2 rot = this.getProtocolRotationSynched();
packet.write(PacketFields.VEHICLE_SPAWN.yaw, (byte) rot.z);
packet.write(PacketFields.VEHICLE_SPAWN.pitch, (byte) rot.x);
}
return packet;
}
public int getViewDistance() {
return EntityTrackerEntryRef.viewDistance.get(handle);
}
public void setViewDistance(int blockDistance) {
EntityTrackerEntryRef.viewDistance.set(handle, blockDistance);
}
public int getUpdateInterval() {
return EntityTrackerEntryRef.updateInterval.get(handle);
}
public void setUpdateInterval(int tickInterval) {
EntityTrackerEntryRef.updateInterval.set(handle, tickInterval);
}
public boolean isMobile() {
return EntityTrackerEntryRef.isMobile.get(handle);
}
public void setMobile(boolean mobile) {
EntityTrackerEntryRef.isMobile.set(handle, mobile);
}
/**
* Synchronizes everything by first destroying and then respawning this Entity to all viewers
*/
public void syncRespawn() {
// Hide
for (Player viewer : getViewers()) {
this.makeHidden(viewer, true);
}
// Update information
final EntityTrackerEntry handle = (EntityTrackerEntry) this.handle;
final Vector velocity = this.getProtocolVelocity();
handle.j = velocity.getX();
handle.k = velocity.getY();
handle.l = velocity.getZ();
final IntVector3 position = this.getProtocolPosition();
handle.xLoc = position.x;
handle.yLoc = position.y;
handle.zLoc = position.z;
final IntVector2 rotation = this.getProtocolRotation();
handle.yRot = rotation.x;
handle.xRot = rotation.z;
final int headYaw = this.getProtocolHeadRotation();
handle.i = headYaw;
// Spawn
for (Player viewer : getViewers()) {
this.makeVisible(viewer);
}
// Attach messages (because it is not handled by vehicles)
if (entity.hasPassenger()) {
broadcast(PacketFields.ATTACH_ENTITY.newInstance(entity.getPassenger(), entity.getEntity()));
}
}
/**
* Synchronizes the entity Vehicle
*
* @param vehicle to synchronize, NULL for no Vehicle
*/
public void syncVehicle(org.bukkit.entity.Entity vehicle) {
EntityTrackerEntryRef.vehicle.set(handle, vehicle);
broadcast(PacketFields.ATTACH_ENTITY.newInstance(entity.getEntity(), vehicle));
}
/**
* Synchronizes the entity position / rotation absolutely (Teleport packet)
*/
public void syncLocationAbsolute() {
syncLocationAbsolute(getProtocolPosition(), getProtocolRotation());
}
/**
* Synchronizes the entity position / rotation absolutely (Teleport packet)
*
* @param position (new)
* @param rotation (new, x = yaw, z = pitch)
*/
public void syncLocationAbsolute(IntVector3 position, IntVector2 rotation) {
if (position == null) {
position = this.getProtocolPositionSynched();
}
if (rotation == null) {
rotation = this.getProtocolRotationSynched();
}
// Update protocol values
final EntityTrackerEntry handle = (EntityTrackerEntry) this.handle;
handle.xLoc = position.x;
handle.yLoc = position.y;
handle.zLoc = position.z;
handle.yRot = rotation.x;
handle.xRot = rotation.z;
// Update last synchronization time
EntityTrackerEntryRef.timeSinceLocationSync.set(handle, 0);
// Send synchronization messages
broadcast(PacketFields.ENTITY_TELEPORT.newInstance(entity.getEntityId(), position.x, position.y, position.z,
(byte) rotation.x, (byte) rotation.z));
}
/**
* Synchronizes the entity position / rotation relatively.
*
* @param position - whether to sync position
* @param rotation - whether to sync rotation
*/
public void syncLocation(boolean position, boolean rotation) {
syncLocation(position ? getProtocolPosition() : null,
rotation ? getProtocolRotation() : null);
}
/**
* Synchronizes the entity position / rotation relatively.
* If the relative change is too big, an absolute update is performed instead.
* Pass in null values to ignore updating it.
*
* @param position (new)
* @param rotation (new, x = yaw, z = pitch)
*/
public void syncLocation(IntVector3 position, IntVector2 rotation) {
final boolean moved = position != null;
final boolean rotated = rotation != null;
final IntVector3 deltaPos = moved ? position.subtract(this.getProtocolPositionSynched()) : IntVector3.ZERO;
if (deltaPos.abs().greaterThan(MAX_RELATIVE_DISTANCE)) {
// Perform teleport instead
syncLocationAbsolute(position, rotation);
} else {
// Update protocol values
final EntityTrackerEntry handle = (EntityTrackerEntry) this.handle;
if (moved) {
handle.xLoc = position.x;
handle.yLoc = position.y;
handle.zLoc = position.z;
}
if (rotated) {
handle.yRot = rotation.x;
handle.xRot = rotation.z;
}
// Send synchronization messages
// If inside vehicle - there is no use to update the location!
if (entity.isInsideVehicle()) {
if (rotated) {
broadcast(PacketFields.ENTITY_LOOK.newInstance(entity.getEntityId(), (byte) rotation.x, (byte) rotation.z));
}
} else if (moved && rotated) {
broadcast(PacketFields.REL_ENTITY_MOVE_LOOK.newInstance(entity.getEntityId(),
(byte) deltaPos.x, (byte) deltaPos.y, (byte) deltaPos.z, (byte) rotation.x, (byte) rotation.z));
} else if (moved) {
broadcast(PacketFields.REL_ENTITY_MOVE.newInstance(entity.getEntityId(),
(byte) deltaPos.x, (byte) deltaPos.y, (byte) deltaPos.z));
} else if (rotated) {
broadcast(PacketFields.ENTITY_LOOK.newInstance(entity.getEntityId(), (byte) rotation.x, (byte) rotation.z));
}
}
}
/**
* Synchronizes the entity head yaw rotation to all Clients
*
* @param headRotation to set to
*/
public void syncHeadRotation(int headRotation) {
((EntityTrackerEntry) handle).i = headRotation;
this.broadcast(PacketFields.ENTITY_HEAD_ROTATION.newInstance(entity.getEntityId(), (byte) headRotation));
}
/**
* Synchronizes the entity velocity
*
* @param velocity (new)
*/
public void syncVelocity(Vector velocity) {
setProtocolVelocitySynched(velocity);
// If inside a vehicle, there is no use in updating
if (entity.isInsideVehicle()) {
return;
}
this.broadcast(PacketFields.ENTITY_VELOCITY.newInstance(entity.getEntityId(), velocity));
}
/**
* Obtains the current Vehicle entity according to the viewers of this entity
*
* @return Client-synchronized vehicle entity
*/
public org.bukkit.entity.Entity getVehicleSynched() {
return EntityTrackerEntryRef.vehicle.get(handle);
}
/**
* Sets the current synched velocity of the entity according to the viewers of this entity.
* This method can be used instead of syncVelocity to ignore packet sending.
*
* @param velocity to set to
*/
public void setProtocolVelocitySynched(Vector velocity) {
final EntityTrackerEntry handle = (EntityTrackerEntry) this.handle;
handle.j = velocity.getX();
handle.k = velocity.getY();
handle.l = velocity.getZ();
}
/**
* Obtains the current velocity of the entity according to the viewers of this entity
*
* @return Client-synchronized entity velocity
*/
public Vector getProtocolVelocitySynched() {
final EntityTrackerEntry handle = (EntityTrackerEntry) this.handle;
return new Vector(handle.j, handle.k, handle.l);
}
/**
* Obtains the current position of the entity according to the viewers of this entity
*
* @return Client-synchronized entity position
*/
public IntVector3 getProtocolPositionSynched() {
final EntityTrackerEntry handle = (EntityTrackerEntry) this.handle;
return new IntVector3(handle.xLoc, handle.yLoc, handle.zLoc);
}
/**
* Obtains the current rotation of the entity according to the viewers of this entity
*
* @return Client-synchronized entity rotation (x = yaw, z = pitch)
*/
public IntVector2 getProtocolRotationSynched() {
final EntityTrackerEntry handle = (EntityTrackerEntry) this.handle;
return new IntVector2(handle.yRot, handle.xRot);
}
/**
* Obtains the current velocity of the entity, converted to protocol format
*
* @return Entity velocity in protocol format
*/
public Vector getProtocolVelocity() {
return this.entity.getVelocity();
}
/**
* Obtains the current position of the entity, converted to protocol format
*
* @return Entity position in protocol format
*/
public IntVector3 getProtocolPosition() {
final Entity entity = this.entity.getHandle(Entity.class);
return new IntVector3(protLoc(entity.locX), MathUtil.floor(entity.locY * 32.0), protLoc(entity.locZ));
}
/**
* Obtains the current rotation (yaw/pitch) of the entity, converted to protocol format
*
* @return Entity rotation in protocol format (x = yaw, z = pitch)
*/
public IntVector2 getProtocolRotation() {
final Entity entity = this.entity.getHandle(Entity.class);
return new IntVector2(protRot(entity.yaw), protRot(entity.pitch));
}
/**
* Obtains the current head yaw rotation of this entity, according to the viewers
*
* @return Client-synched head-yaw rotation
*/
public int getProtocolHeadRotationSynched() {
return ((EntityTrackerEntry) handle).i;
}
/**
* Gets the amount of ticks that have passed since the last Location synchronization.
* A location synchronization means that an absolute position update is performed.
*
* @return ticks since last location synchronization
*/
public int getTicksSinceLocationSync() {
return EntityTrackerEntryRef.timeSinceLocationSync.get(handle);
}
/**
* Checks whether the current update interval is reached
*
* @return True if the update interval was reached, False if not
*/
public boolean isUpdateTick() {
final EntityTrackerEntry handle = (EntityTrackerEntry) this.handle;
return (handle.m % handle.c) == 0;
}
/**
* Checks whether a certain interval is reached
*
* @param interval in ticks
* @return True if the interval was reached, False if not
*/
public boolean isTick(int interval) {
return (((EntityTrackerEntry) handle).m % interval) == 0;
}
/**
* Obtains the current 'tick' value, which can be used for intervals
*
* @return Tick time
*/
public int getTick() {
return ((EntityTrackerEntry) handle).m;
}
/**
* Obtains the current head rotation of the entity, converted to protocol format
*
* @return Entity head rotation in protocol format
*/
public int getProtocolHeadRotation() {
return protRot(this.entity.getHeadRotation());
}
private int protRot(float rot) {
return MathUtil.floor(rot * 256.0f / 360.0f);
}
private int protLoc(double loc) {
return ((EntityTrackerEntry) handle).tracker.at.a(loc);
}
}
|
diff --git a/GAE/src/org/waterforpeople/mapping/dao/SurveyInstanceDAO.java b/GAE/src/org/waterforpeople/mapping/dao/SurveyInstanceDAO.java
index 36dc378c2..1f7c31ed2 100644
--- a/GAE/src/org/waterforpeople/mapping/dao/SurveyInstanceDAO.java
+++ b/GAE/src/org/waterforpeople/mapping/dao/SurveyInstanceDAO.java
@@ -1,434 +1,434 @@
package org.waterforpeople.mapping.dao;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import org.waterforpeople.mapping.domain.QuestionAnswerStore;
import org.waterforpeople.mapping.domain.Status.StatusCode;
import org.waterforpeople.mapping.domain.SurveyInstance;
import com.gallatinsystems.device.domain.DeviceFiles;
import com.gallatinsystems.framework.dao.BaseDAO;
import com.gallatinsystems.framework.servlet.PersistenceFilter;
import com.google.appengine.api.datastore.DatastoreTimeoutException;
public class SurveyInstanceDAO extends BaseDAO<SurveyInstance> {
private static final Logger logger = Logger
.getLogger(SurveyInstanceDAO.class.getName());
public SurveyInstance save(Date collectionDate, DeviceFiles deviceFile,
Long userID, List<String> unparsedLines) {
SurveyInstance si = new SurveyInstance();
boolean hasErrors = false;
si.setDeviceFile(deviceFile);
si.setUserID(userID);
String delimiter = "\t";
ArrayList<QuestionAnswerStore> qasList = new ArrayList<QuestionAnswerStore>();
for (String line : unparsedLines) {
String[] parts = line.split(delimiter);
if (parts.length < 5) {
delimiter = ",";
parts = line.split(delimiter);
}
// TODO: this will have to be removed when we use Strength and
// ScoredValue Questions
while (",".equals(delimiter) && parts.length > 9) {
try {
new Date(new Long(parts[7].trim()));
break;
} catch (Exception e) {
logger.log(Level.INFO,
"Removing comma because 7th pos doesn't pass got string: "
+ parts[7] + "instead of date");
}
log.log(Level.INFO, "Has too many commas: " + line);
int startIndex = 0;
int iCount = 0;
while ((startIndex = line.indexOf(",", startIndex + 1)) != -1) {
if (iCount == 4) {
String firstPart = line.substring(0, startIndex);
String secondPart = line.substring(startIndex + 1,
line.length());
line = firstPart + secondPart;
break;
}
iCount++;
}
parts = line.split(",");
}
QuestionAnswerStore qas = new QuestionAnswerStore();
Date collDate = collectionDate;
try {
collDate = new Date(new Long(parts[7].trim()));
} catch (Exception e) {
logger.log(Level.WARNING,
"Could not construct collection date", e);
deviceFile
.addProcessingMessage("Could not construct collection date from: "
+ parts[7]);
hasErrors = true;
}
if (si.getSurveyId() == null) {
try {
if (collDate != null) {
si.setCollectionDate(collDate);
}
si.setSurveyId(Long.parseLong(parts[0].trim()));
if (parts.length >= 12) {
String uuid = parts[parts.length - 1];
if (uuid != null && uuid.trim().length() > 0) {
SurveyInstance existingSi = findByUUID(uuid);
if (existingSi != null) {
return null;
} else {
si.setUuid(uuid);
}
}
}
si = save(si);
} catch (NumberFormatException e) {
logger.log(Level.SEVERE, "Could not parse survey id: "
+ parts[0], e);
deviceFile
.addProcessingMessage("Could not parse survey id: "
+ parts[0] + e.getMessage());
hasErrors = true;
} catch (DatastoreTimeoutException te) {
sleep();
si = save(si);
}
}
qas.setSurveyId(si.getSurveyId());
qas.setSurveyInstanceId(si.getKey().getId());
qas.setArbitratyNumber(new Long(parts[1].trim()));
qas.setQuestionID(parts[2].trim());
qas.setType(parts[3].trim());
qas.setCollectionDate(collDate);
if (parts.length > 4) {
qas.setValue(parts[4].trim());
}
- if (parts.length >= 5) {
+ if (parts.length > 5) {
if (si.getSubmitterName() == null
|| si.getSubmitterName().trim().length() == 0) {
si.setSubmitterName(parts[5].trim());
}
}
if (parts.length >= 9) {
if (si.getDeviceIdentifier() == null) {
si.setDeviceIdentifier(parts[8].trim());
}
}
if (parts.length >= 10) {
qas.setScoredValue(parts[9].trim());
}
if (parts.length >= 11) {
qas.setStrength(parts[10].trim());
}
qasList.add(qas);
}
try {
save(qasList);
} catch (DatastoreTimeoutException te) {
sleep();
save(qasList);
}
deviceFile.setSurveyInstanceId(si.getKey().getId());
if (!hasErrors) {
si.getDeviceFile().setProcessedStatus(
StatusCode.PROCESSED_NO_ERRORS);
} else {
si.getDeviceFile().setProcessedStatus(
StatusCode.PROCESSED_WITH_ERRORS);
}
si.setQuestionAnswersStore(qasList);
return si;
}
public SurveyInstanceDAO() {
super(SurveyInstance.class);
}
@SuppressWarnings("unchecked")
public List<SurveyInstance> listByDateRange(Date beginDate,
String cursorString) {
PersistenceManager pm = PersistenceFilter.getManager();
javax.jdo.Query q = pm.newQuery(SurveyInstance.class);
q.setFilter("collectionDate >= pBeginDate");
q.declareParameters("java.util.Date pBeginDate");
q.setOrdering("collectionDate desc");
prepareCursor(cursorString, q);
return (List<SurveyInstance>) q.execute(beginDate);
}
@SuppressWarnings("unchecked")
public List<SurveyInstance> listByDateRange(Date beginDate, Date endDate,
boolean unapprovedOnlyFlag, Long surveyId, String source,
String cursorString) {
PersistenceManager pm = PersistenceFilter.getManager();
javax.jdo.Query query = pm.newQuery(SurveyInstance.class);
Map<String, Object> paramMap = null;
StringBuilder filterString = new StringBuilder();
StringBuilder paramString = new StringBuilder();
paramMap = new HashMap<String, Object>();
appendNonNullParam("surveyId", filterString, paramString, "Long",
surveyId, paramMap);
appendNonNullParam("deviceIdentifier", filterString, paramString,
"String", source, paramMap);
appendNonNullParam("collectionDate", filterString, paramString, "Date",
beginDate, paramMap, GTE_OP);
appendNonNullParam("collectionDate", filterString, paramString, "Date",
endDate, paramMap, LTE_OP);
if (unapprovedOnlyFlag) {
appendNonNullParam("approvedFlag", filterString, paramString,
"String", "False", paramMap);
}
if (beginDate != null || endDate != null) {
query.declareImports("import java.util.Date");
}
query.setOrdering("collectionDate desc");
query.setFilter(filterString.toString());
query.declareParameters(paramString.toString());
prepareCursor(cursorString, query);
return (List<SurveyInstance>) query.executeWithMap(paramMap);
}
/**
* finds a questionAnswerStore object for the surveyInstance and questionId
* passed in (if it exists)
*
* @param surveyInstanceId
* @param questionId
* @return
*/
@SuppressWarnings("unchecked")
public QuestionAnswerStore findQuestionAnswerStoreForQuestion(
Long surveyInstanceId, String questionId) {
PersistenceManager pm = PersistenceFilter.getManager();
Query q = pm.newQuery(QuestionAnswerStore.class);
q.setFilter("surveyInstanceId == surveyInstanceIdParam && questionID == questionIdParam");
q.declareParameters("Long surveyInstanceIdParam, String questionIdParam");
List<QuestionAnswerStore> result = (List<QuestionAnswerStore>) q
.execute(surveyInstanceId, questionId);
if (result != null && result.size() > 0) {
return result.get(0);
} else {
return null;
}
}
/**
* lists all questionAnswerStore objects for a single surveyInstance,
* optionally filtered by type
*
* @param surveyInstanceId
* - mandatory
* @param type
* - optional
* @return
*/
@SuppressWarnings("unchecked")
public List<QuestionAnswerStore> listQuestionAnswerStoreByType(
Long surveyInstanceId, String type) {
if (surveyInstanceId != null) {
PersistenceManager pm = PersistenceFilter.getManager();
javax.jdo.Query query = pm.newQuery(QuestionAnswerStore.class);
Map<String, Object> paramMap = null;
StringBuilder filterString = new StringBuilder();
StringBuilder paramString = new StringBuilder();
paramMap = new HashMap<String, Object>();
appendNonNullParam("surveyInstanceId", filterString, paramString,
"Long", surveyInstanceId, paramMap);
appendNonNullParam("type", filterString, paramString, "String",
type, paramMap);
query.setFilter(filterString.toString());
query.declareParameters(paramString.toString());
return (List<QuestionAnswerStore>) query.executeWithMap(paramMap);
} else {
throw new IllegalArgumentException(
"surveyInstanceId may not be null");
}
}
/**
* lists all questionAnswerStore objects for a survey instance
*
* @param instanceId
* @return
*/
@SuppressWarnings("unchecked")
public List<QuestionAnswerStore> listQuestionAnswerStore(Long instanceId,
Integer count) {
PersistenceManager pm = PersistenceFilter.getManager();
Query q = pm.newQuery(QuestionAnswerStore.class);
q.setFilter("surveyInstanceId == surveyInstanceIdParam");
q.declareParameters("Long surveyInstanceIdParam");
if (count != null) {
q.setRange(0, count);
}
return (List<QuestionAnswerStore>) q.execute(instanceId);
}
/**
* lists all questionAnswerStore objects for a specific question
*
* @param questionId
* @return
*/
@SuppressWarnings("unchecked")
public List<QuestionAnswerStore> listQuestionAnswerStoreForQuestion(
String questionId, String cursorString) {
PersistenceManager pm = PersistenceFilter.getManager();
javax.jdo.Query q = pm.newQuery(QuestionAnswerStore.class);
q.setFilter("questionID == qidParam");
q.declareParameters("String qidParam");
prepareCursor(cursorString, q);
return (List<QuestionAnswerStore>) q.execute(questionId);
}
/**
* lists all surveyInstance records for a given survey
*
* @param surveyId
* @return
*/
@SuppressWarnings("unchecked")
public List<SurveyInstance> listSurveyInstanceBySurvey(Long surveyId,
Integer count) {
PersistenceManager pm = PersistenceFilter.getManager();
Query q = pm.newQuery(SurveyInstance.class);
q.setFilter("surveyId == surveyIdParam");
q.declareParameters("Long surveyIdParam");
if (count != null) {
q.setRange(0, count);
}
return (List<SurveyInstance>) q.execute(surveyId);
}
@SuppressWarnings("unchecked")
public List<SurveyInstance> listSurveyInstanceBySurveyId(Long surveyId,
String cursorString) {
PersistenceManager pm = PersistenceFilter.getManager();
Query q = pm.newQuery(SurveyInstance.class);
q.setFilter("surveyId == surveyIdParam");
q.declareParameters("Long surveyIdParam");
prepareCursor(cursorString, q);
List<SurveyInstance> siList = (List<SurveyInstance>) q
.execute(surveyId);
return siList;
}
/**
* lists instances for the given surveyedLocale optionally filtered by the
* dates passed in
*
* @param surveyedLocaleId
* @return
*/
public List<SurveyInstance> listInstancesByLocale(Long surveyedLocaleId,
Date dateFrom, Date dateTo, String cursor) {
return listInstancesByLocale(surveyedLocaleId, dateFrom, dateTo,
DEFAULT_RESULT_COUNT, cursor);
}
/**
* lists instances for the given surveyedLocale optionally filtered by the
* dates passed in
*
* @param surveyedLocaleId
* @return
*/
@SuppressWarnings("unchecked")
public List<SurveyInstance> listInstancesByLocale(Long surveyedLocaleId,
Date dateFrom, Date dateTo, Integer pageSize, String cursor) {
PersistenceManager pm = PersistenceFilter.getManager();
javax.jdo.Query query = pm.newQuery(SurveyInstance.class);
Map<String, Object> paramMap = null;
StringBuilder filterString = new StringBuilder();
StringBuilder paramString = new StringBuilder();
paramMap = new HashMap<String, Object>();
appendNonNullParam("surveyedLocaleId", filterString, paramString,
"Long", surveyedLocaleId, paramMap);
if (dateFrom != null || dateTo != null) {
appendNonNullParam("collectionDate", filterString, paramString,
"Date", dateFrom, paramMap, GTE_OP);
appendNonNullParam("collectionDate", filterString, paramString,
"Date", dateTo, paramMap, LTE_OP);
query.declareImports("import java.util.Date");
}
query.setFilter(filterString.toString());
query.declareParameters(paramString.toString());
query.setOrdering("collectionDate desc");
prepareCursor(cursor, pageSize, query);
return (List<SurveyInstance>) query.executeWithMap(paramMap);
}
/**
* lists all survey instances by the submitter passed in
*
* @param submitter
* @return
*/
@SuppressWarnings("unchecked")
public List<SurveyInstance> listInstanceBySubmitter(String submitter) {
if (submitter != null) {
return listByProperty("submitterName", submitter, "String");
} else {
PersistenceManager pm = PersistenceFilter.getManager();
javax.jdo.Query query = pm.newQuery(SurveyInstance.class,
"submitterName == null");
return (List<SurveyInstance>) query.execute();
}
}
/**
* finds a single survey instance by uuid. This method will NOT load all
* QuestionAnswerStore objects.
*
* @param uuid
* @return
*/
public SurveyInstance findByUUID(String uuid) {
return findByProperty("uuid", uuid, "String");
}
}
| true | true | public SurveyInstance save(Date collectionDate, DeviceFiles deviceFile,
Long userID, List<String> unparsedLines) {
SurveyInstance si = new SurveyInstance();
boolean hasErrors = false;
si.setDeviceFile(deviceFile);
si.setUserID(userID);
String delimiter = "\t";
ArrayList<QuestionAnswerStore> qasList = new ArrayList<QuestionAnswerStore>();
for (String line : unparsedLines) {
String[] parts = line.split(delimiter);
if (parts.length < 5) {
delimiter = ",";
parts = line.split(delimiter);
}
// TODO: this will have to be removed when we use Strength and
// ScoredValue Questions
while (",".equals(delimiter) && parts.length > 9) {
try {
new Date(new Long(parts[7].trim()));
break;
} catch (Exception e) {
logger.log(Level.INFO,
"Removing comma because 7th pos doesn't pass got string: "
+ parts[7] + "instead of date");
}
log.log(Level.INFO, "Has too many commas: " + line);
int startIndex = 0;
int iCount = 0;
while ((startIndex = line.indexOf(",", startIndex + 1)) != -1) {
if (iCount == 4) {
String firstPart = line.substring(0, startIndex);
String secondPart = line.substring(startIndex + 1,
line.length());
line = firstPart + secondPart;
break;
}
iCount++;
}
parts = line.split(",");
}
QuestionAnswerStore qas = new QuestionAnswerStore();
Date collDate = collectionDate;
try {
collDate = new Date(new Long(parts[7].trim()));
} catch (Exception e) {
logger.log(Level.WARNING,
"Could not construct collection date", e);
deviceFile
.addProcessingMessage("Could not construct collection date from: "
+ parts[7]);
hasErrors = true;
}
if (si.getSurveyId() == null) {
try {
if (collDate != null) {
si.setCollectionDate(collDate);
}
si.setSurveyId(Long.parseLong(parts[0].trim()));
if (parts.length >= 12) {
String uuid = parts[parts.length - 1];
if (uuid != null && uuid.trim().length() > 0) {
SurveyInstance existingSi = findByUUID(uuid);
if (existingSi != null) {
return null;
} else {
si.setUuid(uuid);
}
}
}
si = save(si);
} catch (NumberFormatException e) {
logger.log(Level.SEVERE, "Could not parse survey id: "
+ parts[0], e);
deviceFile
.addProcessingMessage("Could not parse survey id: "
+ parts[0] + e.getMessage());
hasErrors = true;
} catch (DatastoreTimeoutException te) {
sleep();
si = save(si);
}
}
qas.setSurveyId(si.getSurveyId());
qas.setSurveyInstanceId(si.getKey().getId());
qas.setArbitratyNumber(new Long(parts[1].trim()));
qas.setQuestionID(parts[2].trim());
qas.setType(parts[3].trim());
qas.setCollectionDate(collDate);
if (parts.length > 4) {
qas.setValue(parts[4].trim());
}
if (parts.length >= 5) {
if (si.getSubmitterName() == null
|| si.getSubmitterName().trim().length() == 0) {
si.setSubmitterName(parts[5].trim());
}
}
if (parts.length >= 9) {
if (si.getDeviceIdentifier() == null) {
si.setDeviceIdentifier(parts[8].trim());
}
}
if (parts.length >= 10) {
qas.setScoredValue(parts[9].trim());
}
if (parts.length >= 11) {
qas.setStrength(parts[10].trim());
}
qasList.add(qas);
}
try {
save(qasList);
} catch (DatastoreTimeoutException te) {
sleep();
save(qasList);
}
deviceFile.setSurveyInstanceId(si.getKey().getId());
if (!hasErrors) {
si.getDeviceFile().setProcessedStatus(
StatusCode.PROCESSED_NO_ERRORS);
} else {
si.getDeviceFile().setProcessedStatus(
StatusCode.PROCESSED_WITH_ERRORS);
}
si.setQuestionAnswersStore(qasList);
return si;
}
| public SurveyInstance save(Date collectionDate, DeviceFiles deviceFile,
Long userID, List<String> unparsedLines) {
SurveyInstance si = new SurveyInstance();
boolean hasErrors = false;
si.setDeviceFile(deviceFile);
si.setUserID(userID);
String delimiter = "\t";
ArrayList<QuestionAnswerStore> qasList = new ArrayList<QuestionAnswerStore>();
for (String line : unparsedLines) {
String[] parts = line.split(delimiter);
if (parts.length < 5) {
delimiter = ",";
parts = line.split(delimiter);
}
// TODO: this will have to be removed when we use Strength and
// ScoredValue Questions
while (",".equals(delimiter) && parts.length > 9) {
try {
new Date(new Long(parts[7].trim()));
break;
} catch (Exception e) {
logger.log(Level.INFO,
"Removing comma because 7th pos doesn't pass got string: "
+ parts[7] + "instead of date");
}
log.log(Level.INFO, "Has too many commas: " + line);
int startIndex = 0;
int iCount = 0;
while ((startIndex = line.indexOf(",", startIndex + 1)) != -1) {
if (iCount == 4) {
String firstPart = line.substring(0, startIndex);
String secondPart = line.substring(startIndex + 1,
line.length());
line = firstPart + secondPart;
break;
}
iCount++;
}
parts = line.split(",");
}
QuestionAnswerStore qas = new QuestionAnswerStore();
Date collDate = collectionDate;
try {
collDate = new Date(new Long(parts[7].trim()));
} catch (Exception e) {
logger.log(Level.WARNING,
"Could not construct collection date", e);
deviceFile
.addProcessingMessage("Could not construct collection date from: "
+ parts[7]);
hasErrors = true;
}
if (si.getSurveyId() == null) {
try {
if (collDate != null) {
si.setCollectionDate(collDate);
}
si.setSurveyId(Long.parseLong(parts[0].trim()));
if (parts.length >= 12) {
String uuid = parts[parts.length - 1];
if (uuid != null && uuid.trim().length() > 0) {
SurveyInstance existingSi = findByUUID(uuid);
if (existingSi != null) {
return null;
} else {
si.setUuid(uuid);
}
}
}
si = save(si);
} catch (NumberFormatException e) {
logger.log(Level.SEVERE, "Could not parse survey id: "
+ parts[0], e);
deviceFile
.addProcessingMessage("Could not parse survey id: "
+ parts[0] + e.getMessage());
hasErrors = true;
} catch (DatastoreTimeoutException te) {
sleep();
si = save(si);
}
}
qas.setSurveyId(si.getSurveyId());
qas.setSurveyInstanceId(si.getKey().getId());
qas.setArbitratyNumber(new Long(parts[1].trim()));
qas.setQuestionID(parts[2].trim());
qas.setType(parts[3].trim());
qas.setCollectionDate(collDate);
if (parts.length > 4) {
qas.setValue(parts[4].trim());
}
if (parts.length > 5) {
if (si.getSubmitterName() == null
|| si.getSubmitterName().trim().length() == 0) {
si.setSubmitterName(parts[5].trim());
}
}
if (parts.length >= 9) {
if (si.getDeviceIdentifier() == null) {
si.setDeviceIdentifier(parts[8].trim());
}
}
if (parts.length >= 10) {
qas.setScoredValue(parts[9].trim());
}
if (parts.length >= 11) {
qas.setStrength(parts[10].trim());
}
qasList.add(qas);
}
try {
save(qasList);
} catch (DatastoreTimeoutException te) {
sleep();
save(qasList);
}
deviceFile.setSurveyInstanceId(si.getKey().getId());
if (!hasErrors) {
si.getDeviceFile().setProcessedStatus(
StatusCode.PROCESSED_NO_ERRORS);
} else {
si.getDeviceFile().setProcessedStatus(
StatusCode.PROCESSED_WITH_ERRORS);
}
si.setQuestionAnswersStore(qasList);
return si;
}
|
diff --git a/src/main/java/com/github/ucchyocean/lc/command/InfoCommand.java b/src/main/java/com/github/ucchyocean/lc/command/InfoCommand.java
index 433a665..e36f8fb 100644
--- a/src/main/java/com/github/ucchyocean/lc/command/InfoCommand.java
+++ b/src/main/java/com/github/ucchyocean/lc/command/InfoCommand.java
@@ -1,109 +1,109 @@
/*
* @author ucchy
* @license LGPLv3
* @copyright Copyright ucchy 2013
*/
package com.github.ucchyocean.lc.command;
import java.util.ArrayList;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.github.ucchyocean.lc.Channel;
/**
* infoコマンドの実行クラス
* @author ucchy
*/
public class InfoCommand extends SubCommandAbst {
private static final String COMMAND_NAME = "info";
private static final String PERMISSION_NODE = "lunachat." + COMMAND_NAME;
private static final String USAGE_KEY = "usageInfo";
/**
* コマンドを取得します。
* @return コマンド
* @see com.github.ucchyocean.lc.command.SubCommandAbst#getCommandName()
*/
@Override
public String getCommandName() {
return COMMAND_NAME;
}
/**
* パーミッションノードを取得します。
* @return パーミッションノード
* @see com.github.ucchyocean.lc.command.SubCommandAbst#getPermissionNode()
*/
@Override
public String getPermissionNode() {
return PERMISSION_NODE;
}
/**
* 使用方法に関するメッセージをsenderに送信します。
* @param sender コマンド実行者
* @param label 実行ラベル
* @see com.github.ucchyocean.lc.command.SubCommandAbst#sendUsageMessage()
*/
@Override
public void sendUsageMessage(
CommandSender sender, String label) {
sendResourceMessage(sender, "", USAGE_KEY, label);
}
/**
* コマンドを実行します。
* @param sender コマンド実行者
* @param label 実行ラベル
* @param args 実行時の引数
* @return コマンドが実行されたかどうか
* @see com.github.ucchyocean.lc.command.SubCommandAbst#runCommand(java.lang.String[])
*/
@Override
public boolean runCommand(
CommandSender sender, String label, String[] args) {
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
}
// 引数チェック
// このコマンドは、コンソールでも実行できるが、その場合はチャンネル名を指定する必要がある
String cname = null;
if ( player != null && args.length <= 1 ) {
Channel def = api.getDefaultChannel(player.getName());
if ( def != null ) {
cname = def.getName();
}
} else if ( args.length >= 2 ) {
cname = args[1];
} else {
sendResourceMessage(sender, PREERR, "errmsgCommand");
return true;
}
// チャンネルが存在するかどうか確認する
Channel channel = api.getChannel(cname);
if ( channel == null ) {
sendResourceMessage(sender, PREERR, "errmsgNotExist");
return true;
}
// BANされていないかどうか確認する
- if ( channel.getBanned().contains(player.getName()) ) {
+ if ( player != null && channel.getBanned().contains(player.getName()) ) {
sendResourceMessage(sender, PREERR, "errmsgBanned");
return true;
}
// 情報を取得して表示する
ArrayList<String> list = channel.getInfo();
for (String msg : list) {
sender.sendMessage(msg);
}
return true;
}
}
| true | true | public boolean runCommand(
CommandSender sender, String label, String[] args) {
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
}
// 引数チェック
// このコマンドは、コンソールでも実行できるが、その場合はチャンネル名を指定する必要がある
String cname = null;
if ( player != null && args.length <= 1 ) {
Channel def = api.getDefaultChannel(player.getName());
if ( def != null ) {
cname = def.getName();
}
} else if ( args.length >= 2 ) {
cname = args[1];
} else {
sendResourceMessage(sender, PREERR, "errmsgCommand");
return true;
}
// チャンネルが存在するかどうか確認する
Channel channel = api.getChannel(cname);
if ( channel == null ) {
sendResourceMessage(sender, PREERR, "errmsgNotExist");
return true;
}
// BANされていないかどうか確認する
if ( channel.getBanned().contains(player.getName()) ) {
sendResourceMessage(sender, PREERR, "errmsgBanned");
return true;
}
// 情報を取得して表示する
ArrayList<String> list = channel.getInfo();
for (String msg : list) {
sender.sendMessage(msg);
}
return true;
}
| public boolean runCommand(
CommandSender sender, String label, String[] args) {
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
}
// 引数チェック
// このコマンドは、コンソールでも実行できるが、その場合はチャンネル名を指定する必要がある
String cname = null;
if ( player != null && args.length <= 1 ) {
Channel def = api.getDefaultChannel(player.getName());
if ( def != null ) {
cname = def.getName();
}
} else if ( args.length >= 2 ) {
cname = args[1];
} else {
sendResourceMessage(sender, PREERR, "errmsgCommand");
return true;
}
// チャンネルが存在するかどうか確認する
Channel channel = api.getChannel(cname);
if ( channel == null ) {
sendResourceMessage(sender, PREERR, "errmsgNotExist");
return true;
}
// BANされていないかどうか確認する
if ( player != null && channel.getBanned().contains(player.getName()) ) {
sendResourceMessage(sender, PREERR, "errmsgBanned");
return true;
}
// 情報を取得して表示する
ArrayList<String> list = channel.getInfo();
for (String msg : list) {
sender.sendMessage(msg);
}
return true;
}
|
diff --git a/src/de/uni_koblenz/jgralab/greql2/evaluator/vertexeval/PathExistenceEvaluator.java b/src/de/uni_koblenz/jgralab/greql2/evaluator/vertexeval/PathExistenceEvaluator.java
index ffea22309..22ced1b8b 100644
--- a/src/de/uni_koblenz/jgralab/greql2/evaluator/vertexeval/PathExistenceEvaluator.java
+++ b/src/de/uni_koblenz/jgralab/greql2/evaluator/vertexeval/PathExistenceEvaluator.java
@@ -1,155 +1,156 @@
/*
* JGraLab - The Java graph laboratory
* (c) 2006-2008 Institute for Software Technology
* University of Koblenz-Landau, Germany
*
* [email protected]
*
* Please report bugs to http://serres.uni-koblenz.de/bugzilla
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package de.uni_koblenz.jgralab.greql2.evaluator.vertexeval;
import de.uni_koblenz.jgralab.EdgeDirection;
import de.uni_koblenz.jgralab.Vertex;
import de.uni_koblenz.jgralab.greql2.evaluator.GreqlEvaluator;
import de.uni_koblenz.jgralab.greql2.evaluator.costmodel.GraphSize;
import de.uni_koblenz.jgralab.greql2.evaluator.costmodel.VertexCosts;
import de.uni_koblenz.jgralab.greql2.evaluator.fa.DFA;
import de.uni_koblenz.jgralab.greql2.evaluator.fa.NFA;
import de.uni_koblenz.jgralab.greql2.exception.EvaluateException;
import de.uni_koblenz.jgralab.greql2.exception.JValueInvalidTypeException;
import de.uni_koblenz.jgralab.greql2.funlib.Greql2FunctionLibrary;
import de.uni_koblenz.jgralab.greql2.jvalue.JValue;
import de.uni_koblenz.jgralab.greql2.schema.Expression;
import de.uni_koblenz.jgralab.greql2.schema.PathDescription;
import de.uni_koblenz.jgralab.greql2.schema.PathExistence;
/**
* Evaluates a path existence, that's the question if there is a path of a
* specific regular form form startVertex to targetVertex
*
* @author [email protected]
*
*/
public class PathExistenceEvaluator extends PathSearchEvaluator {
/**
* this is the PathExistence vertex in the GReQL Syntaxgraph this evaluator
* evaluates
*/
private PathExistence vertex;
/**
* returns the vertex this VertexEvaluator evaluates
*/
@Override
public Vertex getVertex() {
return vertex;
}
public PathExistenceEvaluator(PathExistence vertex, GreqlEvaluator eval) {
super(eval);
this.vertex = vertex;
}
@Override
public JValue evaluate() throws EvaluateException {
PathDescription p = (PathDescription) vertex.getFirstIsPathOf(
EdgeDirection.IN).getAlpha();
PathDescriptionEvaluator pathDescEval = (PathDescriptionEvaluator) greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(p);
Expression startExpression = (Expression) vertex.getFirstIsStartExprOf(
EdgeDirection.IN).getAlpha();
VertexEvaluator startEval = greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(startExpression);
JValue res = startEval.getResult(subgraph);
/**
* check if the result is invalid, this may occur because the
* restrictedExpression may return a null-value
*/
- if (!res.isValid())
+ if (!res.isValid()) {
return new JValue();
+ }
Vertex startVertex = null;
try {
startVertex = res.toVertex();
} catch (JValueInvalidTypeException exception) {
throw new EvaluateException(
"Error evaluation ForwardVertexSet, StartExpression doesn't evaluate to a vertex",
exception);
}
if (startVertex == null)
return new JValue();
Expression targetExpression = (Expression) vertex
.getFirstIsTargetExprOf(EdgeDirection.IN).getAlpha();
VertexEvaluator targetEval = greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(targetExpression);
Vertex targetVertex = null;
res = targetEval.getResult(subgraph);
if (!res.isValid()) {
return new JValue();
}
try {
targetVertex = res.toVertex();
} catch (JValueInvalidTypeException exception) {
throw new EvaluateException(
"Error evaluation ForwardVertexSet, TargetExpression doesn't evaluate to a vertex",
exception);
}
if (targetVertex == null) {
return new JValue();
}
// GreqlEvaluator.println("Try to create DFA");
if (searchAutomaton == null) {
NFA createdNFA = pathDescEval.getNFA();
// createdNFA.printAscii();
searchAutomaton = new DFA(createdNFA);
// searchAutomaton.printAscii();
// We log the number of states as the result size of the underlying
// PathDescription.
if (evaluationLogger != null) {
evaluationLogger.logResultSize("PathDescription",
searchAutomaton.stateList.size());
}
}
// GreqlEvaluator.println("Successfull created DFA");
if (function == null) {
function = Greql2FunctionLibrary.instance().getGreqlFunction(
"isReachable");
}
JValue[] arguments = new JValue[3];
arguments[0] = new JValue(startVertex);
arguments[1] = new JValue(targetVertex);
arguments[2] = new JValue(searchAutomaton);
JValue tempResult = function.evaluate(graph, subgraph, arguments);
return tempResult;
}
@Override
public VertexCosts calculateSubtreeEvaluationCosts(GraphSize graphSize) {
return this.greqlEvaluator.getCostModel().calculateCostsPathExistence(
this, graphSize);
}
@Override
public double calculateEstimatedSelectivity(GraphSize graphSize) {
return greqlEvaluator.getCostModel().calculateSelectivityPathExistence(
this, graphSize);
}
}
| false | true | public JValue evaluate() throws EvaluateException {
PathDescription p = (PathDescription) vertex.getFirstIsPathOf(
EdgeDirection.IN).getAlpha();
PathDescriptionEvaluator pathDescEval = (PathDescriptionEvaluator) greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(p);
Expression startExpression = (Expression) vertex.getFirstIsStartExprOf(
EdgeDirection.IN).getAlpha();
VertexEvaluator startEval = greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(startExpression);
JValue res = startEval.getResult(subgraph);
/**
* check if the result is invalid, this may occur because the
* restrictedExpression may return a null-value
*/
if (!res.isValid())
return new JValue();
Vertex startVertex = null;
try {
startVertex = res.toVertex();
} catch (JValueInvalidTypeException exception) {
throw new EvaluateException(
"Error evaluation ForwardVertexSet, StartExpression doesn't evaluate to a vertex",
exception);
}
if (startVertex == null)
return new JValue();
Expression targetExpression = (Expression) vertex
.getFirstIsTargetExprOf(EdgeDirection.IN).getAlpha();
VertexEvaluator targetEval = greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(targetExpression);
Vertex targetVertex = null;
res = targetEval.getResult(subgraph);
if (!res.isValid()) {
return new JValue();
}
try {
targetVertex = res.toVertex();
} catch (JValueInvalidTypeException exception) {
throw new EvaluateException(
"Error evaluation ForwardVertexSet, TargetExpression doesn't evaluate to a vertex",
exception);
}
if (targetVertex == null) {
return new JValue();
}
// GreqlEvaluator.println("Try to create DFA");
if (searchAutomaton == null) {
NFA createdNFA = pathDescEval.getNFA();
// createdNFA.printAscii();
searchAutomaton = new DFA(createdNFA);
// searchAutomaton.printAscii();
// We log the number of states as the result size of the underlying
// PathDescription.
if (evaluationLogger != null) {
evaluationLogger.logResultSize("PathDescription",
searchAutomaton.stateList.size());
}
}
// GreqlEvaluator.println("Successfull created DFA");
if (function == null) {
function = Greql2FunctionLibrary.instance().getGreqlFunction(
"isReachable");
}
JValue[] arguments = new JValue[3];
arguments[0] = new JValue(startVertex);
arguments[1] = new JValue(targetVertex);
arguments[2] = new JValue(searchAutomaton);
JValue tempResult = function.evaluate(graph, subgraph, arguments);
return tempResult;
}
| public JValue evaluate() throws EvaluateException {
PathDescription p = (PathDescription) vertex.getFirstIsPathOf(
EdgeDirection.IN).getAlpha();
PathDescriptionEvaluator pathDescEval = (PathDescriptionEvaluator) greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(p);
Expression startExpression = (Expression) vertex.getFirstIsStartExprOf(
EdgeDirection.IN).getAlpha();
VertexEvaluator startEval = greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(startExpression);
JValue res = startEval.getResult(subgraph);
/**
* check if the result is invalid, this may occur because the
* restrictedExpression may return a null-value
*/
if (!res.isValid()) {
return new JValue();
}
Vertex startVertex = null;
try {
startVertex = res.toVertex();
} catch (JValueInvalidTypeException exception) {
throw new EvaluateException(
"Error evaluation ForwardVertexSet, StartExpression doesn't evaluate to a vertex",
exception);
}
if (startVertex == null)
return new JValue();
Expression targetExpression = (Expression) vertex
.getFirstIsTargetExprOf(EdgeDirection.IN).getAlpha();
VertexEvaluator targetEval = greqlEvaluator
.getVertexEvaluatorGraphMarker().getMark(targetExpression);
Vertex targetVertex = null;
res = targetEval.getResult(subgraph);
if (!res.isValid()) {
return new JValue();
}
try {
targetVertex = res.toVertex();
} catch (JValueInvalidTypeException exception) {
throw new EvaluateException(
"Error evaluation ForwardVertexSet, TargetExpression doesn't evaluate to a vertex",
exception);
}
if (targetVertex == null) {
return new JValue();
}
// GreqlEvaluator.println("Try to create DFA");
if (searchAutomaton == null) {
NFA createdNFA = pathDescEval.getNFA();
// createdNFA.printAscii();
searchAutomaton = new DFA(createdNFA);
// searchAutomaton.printAscii();
// We log the number of states as the result size of the underlying
// PathDescription.
if (evaluationLogger != null) {
evaluationLogger.logResultSize("PathDescription",
searchAutomaton.stateList.size());
}
}
// GreqlEvaluator.println("Successfull created DFA");
if (function == null) {
function = Greql2FunctionLibrary.instance().getGreqlFunction(
"isReachable");
}
JValue[] arguments = new JValue[3];
arguments[0] = new JValue(startVertex);
arguments[1] = new JValue(targetVertex);
arguments[2] = new JValue(searchAutomaton);
JValue tempResult = function.evaluate(graph, subgraph, arguments);
return tempResult;
}
|
diff --git a/com.ggasoftware.indigo.knime.plugin/src/com/ggasoftware/indigo/knime/convert/molloader/IndigoMoleculeLoaderNodeModel.java b/com.ggasoftware.indigo.knime.plugin/src/com/ggasoftware/indigo/knime/convert/molloader/IndigoMoleculeLoaderNodeModel.java
index a593b38..810739d 100644
--- a/com.ggasoftware.indigo.knime.plugin/src/com/ggasoftware/indigo/knime/convert/molloader/IndigoMoleculeLoaderNodeModel.java
+++ b/com.ggasoftware.indigo.knime.plugin/src/com/ggasoftware/indigo/knime/convert/molloader/IndigoMoleculeLoaderNodeModel.java
@@ -1,302 +1,302 @@
/****************************************************************************
* Copyright (C) 2011 GGA Software Services LLC
*
* This file may be distributed and/or modified under the terms of the
* GNU General Public License version 3 as published by the Free Software
* Foundation.
*
* This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
* WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses>.
***************************************************************************/
package com.ggasoftware.indigo.knime.convert.molloader;
import java.io.IOException;
import org.knime.chem.types.SmartsCell;
import org.knime.core.data.*;
import org.knime.core.data.container.*;
import org.knime.core.data.def.*;
import org.knime.core.node.*;
import com.ggasoftware.indigo.*;
import com.ggasoftware.indigo.knime.cell.IndigoMolCell;
import com.ggasoftware.indigo.knime.cell.IndigoQueryMolCell;
import com.ggasoftware.indigo.knime.plugin.IndigoPlugin;
import java.io.File;
public class IndigoMoleculeLoaderNodeModel extends NodeModel
{
private final IndigoMoleculeLoaderSettings _settings = new IndigoMoleculeLoaderSettings();
boolean _query;
protected IndigoMoleculeLoaderNodeModel (boolean query)
{
super(1, 2);
_query = query;
}
protected DataTableSpec[] getDataTableSpecs (DataTableSpec inputTableSpec)
throws InvalidSettingsException
{
if (_settings.colName == null || _settings.colName.length() < 1)
throw new InvalidSettingsException("Column name not specified");
if (!_settings.replaceColumn)
if (_settings.newColName == null || _settings.newColName.length() < 1)
throw new InvalidSettingsException("No new column name specified");
String newColName = _settings.newColName;
int newColIdx = inputTableSpec.getNumColumns();
int colIdx = inputTableSpec.findColumnIndex(_settings.colName);
if (colIdx == -1)
throw new InvalidSettingsException("column not found");
if (_settings.replaceColumn)
{
newColName = _settings.colName;
newColIdx = colIdx;
}
DataType newtype;
if (_query)
newtype = IndigoQueryMolCell.TYPE;
else
newtype = IndigoMolCell.TYPE;
DataColumnSpec validOutputColumnSpec = new DataColumnSpecCreator(newColName, newtype).createSpec();
DataColumnSpec invalidOutputColumnSpec = new DataColumnSpecCreator(newColName, StringCell.TYPE).createSpec();
DataColumnSpec[] validOutputColumnSpecs, invalidOutputColumnSpecs;
if (_settings.replaceColumn)
{
validOutputColumnSpecs = new DataColumnSpec[inputTableSpec.getNumColumns()];
invalidOutputColumnSpecs = new DataColumnSpec[inputTableSpec.getNumColumns()];
}
else
{
validOutputColumnSpecs = new DataColumnSpec[inputTableSpec.getNumColumns() + 1];
invalidOutputColumnSpecs = new DataColumnSpec[inputTableSpec.getNumColumns() + 1];
}
for (int i = 0; i < inputTableSpec.getNumColumns(); i++)
{
DataColumnSpec columnSpec = inputTableSpec.getColumnSpec(i);
if (_settings.replaceColumn && i == newColIdx)
{
validOutputColumnSpecs[i] = validOutputColumnSpec;
invalidOutputColumnSpecs[i] = invalidOutputColumnSpec;
}
else
{
validOutputColumnSpecs[i] = columnSpec;
invalidOutputColumnSpecs[i] = columnSpec;
}
}
if (!_settings.replaceColumn)
{
validOutputColumnSpecs[newColIdx] = validOutputColumnSpec;
invalidOutputColumnSpecs[newColIdx] = invalidOutputColumnSpec;
}
return new DataTableSpec[] { new DataTableSpec(validOutputColumnSpecs),
new DataTableSpec(invalidOutputColumnSpecs) };
}
/**
* {@inheritDoc}
*/
@Override
protected BufferedDataTable[] execute (final BufferedDataTable[] inData,
final ExecutionContext exec) throws Exception
{
DataTableSpec inputTableSpec = inData[0].getDataTableSpec();
DataTableSpec[] outputSpecs = getDataTableSpecs(inputTableSpec);
BufferedDataContainer validOutputContainer = exec
.createDataContainer(outputSpecs[0]);
BufferedDataContainer invalidOutputContainer = exec
.createDataContainer(outputSpecs[1]);
int newColIdx = inputTableSpec.getNumColumns();
int colIdx = inputTableSpec.findColumnIndex(_settings.colName);
if (colIdx == -1)
throw new Exception("column not found");
if (_settings.replaceColumn)
newColIdx = colIdx;
CloseableRowIterator it = inData[0].iterator();
int rowNumber = 1;
Indigo indigo = IndigoPlugin.getIndigo();
while (it.hasNext())
{
DataRow inputRow = it.next();
RowKey key = inputRow.getKey();
DataCell[] cells;
if (_settings.replaceColumn)
cells = new DataCell[inputRow.getNumCells()];
else
cells = new DataCell[inputRow.getNumCells() + 1];
DataCell molcell = inputRow.getCell(colIdx);
DataCell newcell = null;
String message = null;
try
{
IndigoPlugin.lock();
indigo.setOption("ignore-stereochemistry-errors",
_settings.ignoreStereochemistryErrors);
indigo.setOption("treat-x-as-pseudoatom",
_settings.treatXAsPseudoatom);
if (_query)
newcell = new IndigoQueryMolCell(molcell.toString(), (molcell.getType().equals(SmartsCell.TYPE)));
else
newcell = new IndigoMolCell(indigo.loadMolecule(molcell.toString()));
}
catch (IndigoException e)
{
message = e.getMessage();
}
finally
{
IndigoPlugin.unlock();
}
if (newcell != null)
{
for (int i = 0; i < inputRow.getNumCells(); i++)
{
if (_settings.replaceColumn && i == newColIdx)
{
if (_query)
cells[i] = new IndigoQueryMolCell(molcell.toString(), (molcell.getType().equals(SmartsCell.TYPE)));
else
cells[i] = newcell;
}
else
cells[i] = inputRow.getCell(i);
}
if (!_settings.replaceColumn)
{
if (_query)
- cells[newColIdx] = new IndigoQueryMolCell(molcell.toString(), (molcell.getType() == SmartsCell.TYPE));
+ cells[newColIdx] = new IndigoQueryMolCell(molcell.toString(), (molcell.getType().equals(SmartsCell.TYPE)));
else
cells[newColIdx] = newcell;
}
validOutputContainer.addRowToTable(new DefaultRow(key, cells));
}
else
{
for (int i = 0; i < inputRow.getNumCells(); i++)
{
if (_settings.replaceColumn && i == newColIdx)
cells[i] = new StringCell(message);
else
cells[i] = inputRow.getCell(i);
}
if (!_settings.replaceColumn)
cells[newColIdx] = new StringCell(message);
invalidOutputContainer.addRowToTable(new DefaultRow(key, cells));
}
exec.checkCanceled();
exec.setProgress(rowNumber / (double) inData[0].getRowCount(),
"Adding row " + rowNumber);
rowNumber++;
}
validOutputContainer.close();
invalidOutputContainer.close();
return new BufferedDataTable[] { validOutputContainer.getTable(),
invalidOutputContainer.getTable() };
}
/**
* {@inheritDoc}
*/
@Override
protected void reset ()
{
}
/**
* {@inheritDoc}
*/
@Override
protected DataTableSpec[] configure (final DataTableSpec[] inSpecs)
throws InvalidSettingsException
{
DataTableSpec inputTableSpec = inSpecs[0];
return getDataTableSpecs(inputTableSpec);
}
/**
* {@inheritDoc}
*/
@Override
protected void saveSettingsTo (final NodeSettingsWO settings)
{
_settings.saveSettings(settings);
}
/**
* {@inheritDoc}
*/
@Override
protected void loadValidatedSettingsFrom (final NodeSettingsRO settings)
throws InvalidSettingsException
{
_settings.loadSettings(settings);
}
/**
* {@inheritDoc}
*/
@Override
protected void validateSettings (final NodeSettingsRO settings)
throws InvalidSettingsException
{
IndigoMoleculeLoaderSettings s = new IndigoMoleculeLoaderSettings();
s.loadSettings(settings);
if (!s.replaceColumn)
if (s.newColName == null || s.newColName.length() < 1)
throw new InvalidSettingsException("No name for new column given");
}
/**
* {@inheritDoc}
*/
@Override
protected void loadInternals (final File internDir,
final ExecutionMonitor exec) throws IOException,
CanceledExecutionException
{
}
/**
* {@inheritDoc}
*/
@Override
protected void saveInternals (final File internDir,
final ExecutionMonitor exec) throws IOException,
CanceledExecutionException
{
}
}
| true | true | protected BufferedDataTable[] execute (final BufferedDataTable[] inData,
final ExecutionContext exec) throws Exception
{
DataTableSpec inputTableSpec = inData[0].getDataTableSpec();
DataTableSpec[] outputSpecs = getDataTableSpecs(inputTableSpec);
BufferedDataContainer validOutputContainer = exec
.createDataContainer(outputSpecs[0]);
BufferedDataContainer invalidOutputContainer = exec
.createDataContainer(outputSpecs[1]);
int newColIdx = inputTableSpec.getNumColumns();
int colIdx = inputTableSpec.findColumnIndex(_settings.colName);
if (colIdx == -1)
throw new Exception("column not found");
if (_settings.replaceColumn)
newColIdx = colIdx;
CloseableRowIterator it = inData[0].iterator();
int rowNumber = 1;
Indigo indigo = IndigoPlugin.getIndigo();
while (it.hasNext())
{
DataRow inputRow = it.next();
RowKey key = inputRow.getKey();
DataCell[] cells;
if (_settings.replaceColumn)
cells = new DataCell[inputRow.getNumCells()];
else
cells = new DataCell[inputRow.getNumCells() + 1];
DataCell molcell = inputRow.getCell(colIdx);
DataCell newcell = null;
String message = null;
try
{
IndigoPlugin.lock();
indigo.setOption("ignore-stereochemistry-errors",
_settings.ignoreStereochemistryErrors);
indigo.setOption("treat-x-as-pseudoatom",
_settings.treatXAsPseudoatom);
if (_query)
newcell = new IndigoQueryMolCell(molcell.toString(), (molcell.getType().equals(SmartsCell.TYPE)));
else
newcell = new IndigoMolCell(indigo.loadMolecule(molcell.toString()));
}
catch (IndigoException e)
{
message = e.getMessage();
}
finally
{
IndigoPlugin.unlock();
}
if (newcell != null)
{
for (int i = 0; i < inputRow.getNumCells(); i++)
{
if (_settings.replaceColumn && i == newColIdx)
{
if (_query)
cells[i] = new IndigoQueryMolCell(molcell.toString(), (molcell.getType().equals(SmartsCell.TYPE)));
else
cells[i] = newcell;
}
else
cells[i] = inputRow.getCell(i);
}
if (!_settings.replaceColumn)
{
if (_query)
cells[newColIdx] = new IndigoQueryMolCell(molcell.toString(), (molcell.getType() == SmartsCell.TYPE));
else
cells[newColIdx] = newcell;
}
validOutputContainer.addRowToTable(new DefaultRow(key, cells));
}
else
{
for (int i = 0; i < inputRow.getNumCells(); i++)
{
if (_settings.replaceColumn && i == newColIdx)
cells[i] = new StringCell(message);
else
cells[i] = inputRow.getCell(i);
}
if (!_settings.replaceColumn)
cells[newColIdx] = new StringCell(message);
invalidOutputContainer.addRowToTable(new DefaultRow(key, cells));
}
exec.checkCanceled();
exec.setProgress(rowNumber / (double) inData[0].getRowCount(),
"Adding row " + rowNumber);
rowNumber++;
}
validOutputContainer.close();
invalidOutputContainer.close();
return new BufferedDataTable[] { validOutputContainer.getTable(),
invalidOutputContainer.getTable() };
}
| protected BufferedDataTable[] execute (final BufferedDataTable[] inData,
final ExecutionContext exec) throws Exception
{
DataTableSpec inputTableSpec = inData[0].getDataTableSpec();
DataTableSpec[] outputSpecs = getDataTableSpecs(inputTableSpec);
BufferedDataContainer validOutputContainer = exec
.createDataContainer(outputSpecs[0]);
BufferedDataContainer invalidOutputContainer = exec
.createDataContainer(outputSpecs[1]);
int newColIdx = inputTableSpec.getNumColumns();
int colIdx = inputTableSpec.findColumnIndex(_settings.colName);
if (colIdx == -1)
throw new Exception("column not found");
if (_settings.replaceColumn)
newColIdx = colIdx;
CloseableRowIterator it = inData[0].iterator();
int rowNumber = 1;
Indigo indigo = IndigoPlugin.getIndigo();
while (it.hasNext())
{
DataRow inputRow = it.next();
RowKey key = inputRow.getKey();
DataCell[] cells;
if (_settings.replaceColumn)
cells = new DataCell[inputRow.getNumCells()];
else
cells = new DataCell[inputRow.getNumCells() + 1];
DataCell molcell = inputRow.getCell(colIdx);
DataCell newcell = null;
String message = null;
try
{
IndigoPlugin.lock();
indigo.setOption("ignore-stereochemistry-errors",
_settings.ignoreStereochemistryErrors);
indigo.setOption("treat-x-as-pseudoatom",
_settings.treatXAsPseudoatom);
if (_query)
newcell = new IndigoQueryMolCell(molcell.toString(), (molcell.getType().equals(SmartsCell.TYPE)));
else
newcell = new IndigoMolCell(indigo.loadMolecule(molcell.toString()));
}
catch (IndigoException e)
{
message = e.getMessage();
}
finally
{
IndigoPlugin.unlock();
}
if (newcell != null)
{
for (int i = 0; i < inputRow.getNumCells(); i++)
{
if (_settings.replaceColumn && i == newColIdx)
{
if (_query)
cells[i] = new IndigoQueryMolCell(molcell.toString(), (molcell.getType().equals(SmartsCell.TYPE)));
else
cells[i] = newcell;
}
else
cells[i] = inputRow.getCell(i);
}
if (!_settings.replaceColumn)
{
if (_query)
cells[newColIdx] = new IndigoQueryMolCell(molcell.toString(), (molcell.getType().equals(SmartsCell.TYPE)));
else
cells[newColIdx] = newcell;
}
validOutputContainer.addRowToTable(new DefaultRow(key, cells));
}
else
{
for (int i = 0; i < inputRow.getNumCells(); i++)
{
if (_settings.replaceColumn && i == newColIdx)
cells[i] = new StringCell(message);
else
cells[i] = inputRow.getCell(i);
}
if (!_settings.replaceColumn)
cells[newColIdx] = new StringCell(message);
invalidOutputContainer.addRowToTable(new DefaultRow(key, cells));
}
exec.checkCanceled();
exec.setProgress(rowNumber / (double) inData[0].getRowCount(),
"Adding row " + rowNumber);
rowNumber++;
}
validOutputContainer.close();
invalidOutputContainer.close();
return new BufferedDataTable[] { validOutputContainer.getTable(),
invalidOutputContainer.getTable() };
}
|
diff --git a/chunchun/src/jbossas/java/com/jboss/datagrid/chunchun/session/PostBean.java b/chunchun/src/jbossas/java/com/jboss/datagrid/chunchun/session/PostBean.java
index 4a7c7f4..d50ba96 100644
--- a/chunchun/src/jbossas/java/com/jboss/datagrid/chunchun/session/PostBean.java
+++ b/chunchun/src/jbossas/java/com/jboss/datagrid/chunchun/session/PostBean.java
@@ -1,254 +1,258 @@
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package com.jboss.datagrid.chunchun.session;
import java.io.Serializable;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.enterprise.context.SessionScoped;
import javax.enterprise.inject.Instance;
import javax.inject.Inject;
import javax.inject.Named;
import javax.transaction.UserTransaction;
import com.jboss.datagrid.chunchun.model.Post;
import org.infinispan.api.BasicCache;
import com.jboss.datagrid.chunchun.model.PostKey;
import com.jboss.datagrid.chunchun.model.User;
/**
* Handles post operations (sending posts, listing recent posts from all watched people,
* listing own recent posts, ...)
*
* @author Martin Gencur
*
*/
@Named
@SessionScoped
public class PostBean implements Serializable {
private static final long serialVersionUID = -8914061755188086355L;
private static final int INITIAL_POSTS_LIMIT = 30;
private int loadedPosts = INITIAL_POSTS_LIMIT;
private static final int INCREASE_LOADED_BY = 50; //increase loadedPosts by
private static final int INITIAL_SHOWED_POSTS = 10;
private int showedPosts = INITIAL_SHOWED_POSTS;
private static final int INCREASE_SHOWED_BY = 10; //increase showedPosts by
private static final long MINUTE = 60 * 1000;
private static final long TEN_MINUTES = 10 * MINUTE;
private static final long THIRTY_MINUTES = 30 * MINUTE;
private static final long HOUR = 60 * MINUTE;
private static final long TWELVE_HOURS = 12 * HOUR;
private static final long DAY = 24 * HOUR;
private static final long THREE_DAYS = DAY * 3;
private static final long SEVEN_DAYS = DAY * 7;
private static final long LOW_WATCH_LIMIT = 50;
private static final long MEDIUM_WATCH_LIMIT = 300;
private static final long HIGH_WATCH_LIMIT = 1000;
//shorten time steps with increasing number of people that I'm watching
private static long agesByNumOfWatched[][] = {
{ DAY, THREE_DAYS, SEVEN_DAYS },
{ HOUR, TWELVE_HOURS, DAY, THREE_DAYS, SEVEN_DAYS },
{ MINUTE, THIRTY_MINUTES, HOUR, DAY, SEVEN_DAYS },
{ MINUTE, TEN_MINUTES, THIRTY_MINUTES, TWELVE_HOURS, SEVEN_DAYS } };
private String message;
LinkedList<DisplayPost> recentPosts = new LinkedList<DisplayPost>();
@Inject
private Instance<Authenticator> auth;
@Inject
private UserBean userBean;
@Inject
private CacheContainerProvider provider;
@Inject
private UserTransaction utx;
public String sendPost() {
Post t = new Post(auth.get().getUsername(), message);
try {
utx.begin();
User u = auth.get().getUser();
getPostCache().put(t.getKey(), t);
u.getPosts().add(t.getKey());
getUserCache().replace(auth.get().getUsername(), u);
utx.commit();
} catch (Exception e) {
if (utx != null) {
try {
utx.rollback();
} catch (Exception e1) {
}
}
}
return null;
}
public List<DisplayPost> getRecentPosts() {
if (recentPosts.size() <= INITIAL_POSTS_LIMIT) {
reloadPosts(INITIAL_POSTS_LIMIT);
}
if (showedPosts > loadedPosts) {
loadedPosts = showedPosts;
reloadPosts(loadedPosts);
}
return recentPosts.subList(0, showedPosts);
}
/*
* Reload content of recentPosts list
*/
private void reloadPosts(int limit) {
long now = System.currentTimeMillis();
List<String> following = auth.get().getUser().getWatching();
long[] ages = chooseRecentPostsStrategy(following.size());
+ //make sure we have an empty list before reloading, otherwise entries will be contained more than once
+ if (recentPosts.size() > 0) {
+ recentPosts.clear();
+ }
// add initial entry (oldest possible one)
recentPosts.add(new DisplayPost());
// first check only posts newer than 1 hour, then increase maxAge
for (int maxAge = 0; maxAge != ages.length; maxAge++) {
if (recentPosts.size() >= limit) {
break;
}
// get all people that I'm following
for (String username : following) {
User u = (User) getUserCache().get(username);
CopyOnWriteArrayList<PostKey> postKeys = (CopyOnWriteArrayList<PostKey>) u.getPosts();
LinkedList<PostKey> postKeysLinked = new LinkedList<PostKey>();
postKeysLinked.addAll(postKeys);
Iterator<PostKey> it = postKeysLinked.descendingIterator();
// go from newest to oldest post
while (it.hasNext()) {
PostKey key = it.next();
//check only desired sector in the past
if (maxAge > 0 && key.getTimeOfPost() >= (now - ages[maxAge - 1])) {
// if we checked this post in the previous sector, move on
continue;
} else if (key.getTimeOfPost() < (now - ages[maxAge])) {
// if the post is older than what belongs to this sector, move on
break;
}
int position = 0;
//possibly add the post to newest posts
for (DisplayPost recentPost : recentPosts) {
if (key.getTimeOfPost() > recentPost.getTimeOfPost()) {
Post t = (Post) getPostCache().get(key);
if (t != null) {
DisplayPost tw = new DisplayPost(u.getName(), u.getUsername(), t.getMessage(), t.getTimeOfPost());
recentPosts.add(position, tw);
if (recentPosts.size() > limit) {
recentPosts.removeLast();
}
}
break;
}
position++;
}
}
}
}
}
public void morePosts() {
showedPosts += INCREASE_SHOWED_BY;
}
public void setDisplayedPostsLimit(int limit) {
showedPosts = limit;
}
public int getDisplayedPostsLimit() {
return showedPosts;
}
private long[] chooseRecentPostsStrategy(int size) {
if (size < LOW_WATCH_LIMIT) {
return agesByNumOfWatched[0];
} else if (size < MEDIUM_WATCH_LIMIT) {
return agesByNumOfWatched[1];
} else if (size < HIGH_WATCH_LIMIT) {
return agesByNumOfWatched[2];
} else {
return agesByNumOfWatched[3];
}
}
public List<DisplayPost> getMyPosts() {
LinkedList<DisplayPost> myPosts = new LinkedList<DisplayPost>();
List<PostKey> myPostKeys = auth.get().getUser().getPosts();
for (PostKey key : myPostKeys) {
Post t = (Post) getPostCache().get(key);
if (t != null) {
DisplayPost dispPost = new DisplayPost(auth.get().getUser().getName(), auth.get()
.getUser().getUsername(), t.getMessage(), t.getTimeOfPost());
myPosts.addFirst(dispPost);
}
}
return myPosts;
}
public List<DisplayPost> getWatchedUserPosts() {
LinkedList<DisplayPost> userPosts = new LinkedList<DisplayPost>();
List<PostKey> myPostKeys = userBean.getWatchedUser().getPosts();
for (PostKey key : myPostKeys) {
Post t = (Post) getPostCache().get(key);
if (t != null) {
DisplayPost dispPost = new DisplayPost(userBean.getWatchedUser().getName(), userBean
.getWatchedUser().getUsername(), t.getMessage(), t.getTimeOfPost());
userPosts.addFirst(dispPost);
}
}
return userPosts;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
private BasicCache<String, Object> getUserCache() {
return provider.getCacheContainer().getCache("userCache");
}
private BasicCache<PostKey, Object> getPostCache() {
return provider.getCacheContainer().getCache("postCache");
}
public void resetRecentPosts() {
recentPosts = new LinkedList<DisplayPost>();
showedPosts = INITIAL_SHOWED_POSTS;
loadedPosts = INITIAL_POSTS_LIMIT;
}
}
| true | true | private void reloadPosts(int limit) {
long now = System.currentTimeMillis();
List<String> following = auth.get().getUser().getWatching();
long[] ages = chooseRecentPostsStrategy(following.size());
// add initial entry (oldest possible one)
recentPosts.add(new DisplayPost());
// first check only posts newer than 1 hour, then increase maxAge
for (int maxAge = 0; maxAge != ages.length; maxAge++) {
if (recentPosts.size() >= limit) {
break;
}
// get all people that I'm following
for (String username : following) {
User u = (User) getUserCache().get(username);
CopyOnWriteArrayList<PostKey> postKeys = (CopyOnWriteArrayList<PostKey>) u.getPosts();
LinkedList<PostKey> postKeysLinked = new LinkedList<PostKey>();
postKeysLinked.addAll(postKeys);
Iterator<PostKey> it = postKeysLinked.descendingIterator();
// go from newest to oldest post
while (it.hasNext()) {
PostKey key = it.next();
//check only desired sector in the past
if (maxAge > 0 && key.getTimeOfPost() >= (now - ages[maxAge - 1])) {
// if we checked this post in the previous sector, move on
continue;
} else if (key.getTimeOfPost() < (now - ages[maxAge])) {
// if the post is older than what belongs to this sector, move on
break;
}
int position = 0;
//possibly add the post to newest posts
for (DisplayPost recentPost : recentPosts) {
if (key.getTimeOfPost() > recentPost.getTimeOfPost()) {
Post t = (Post) getPostCache().get(key);
if (t != null) {
DisplayPost tw = new DisplayPost(u.getName(), u.getUsername(), t.getMessage(), t.getTimeOfPost());
recentPosts.add(position, tw);
if (recentPosts.size() > limit) {
recentPosts.removeLast();
}
}
break;
}
position++;
}
}
}
}
}
| private void reloadPosts(int limit) {
long now = System.currentTimeMillis();
List<String> following = auth.get().getUser().getWatching();
long[] ages = chooseRecentPostsStrategy(following.size());
//make sure we have an empty list before reloading, otherwise entries will be contained more than once
if (recentPosts.size() > 0) {
recentPosts.clear();
}
// add initial entry (oldest possible one)
recentPosts.add(new DisplayPost());
// first check only posts newer than 1 hour, then increase maxAge
for (int maxAge = 0; maxAge != ages.length; maxAge++) {
if (recentPosts.size() >= limit) {
break;
}
// get all people that I'm following
for (String username : following) {
User u = (User) getUserCache().get(username);
CopyOnWriteArrayList<PostKey> postKeys = (CopyOnWriteArrayList<PostKey>) u.getPosts();
LinkedList<PostKey> postKeysLinked = new LinkedList<PostKey>();
postKeysLinked.addAll(postKeys);
Iterator<PostKey> it = postKeysLinked.descendingIterator();
// go from newest to oldest post
while (it.hasNext()) {
PostKey key = it.next();
//check only desired sector in the past
if (maxAge > 0 && key.getTimeOfPost() >= (now - ages[maxAge - 1])) {
// if we checked this post in the previous sector, move on
continue;
} else if (key.getTimeOfPost() < (now - ages[maxAge])) {
// if the post is older than what belongs to this sector, move on
break;
}
int position = 0;
//possibly add the post to newest posts
for (DisplayPost recentPost : recentPosts) {
if (key.getTimeOfPost() > recentPost.getTimeOfPost()) {
Post t = (Post) getPostCache().get(key);
if (t != null) {
DisplayPost tw = new DisplayPost(u.getName(), u.getUsername(), t.getMessage(), t.getTimeOfPost());
recentPosts.add(position, tw);
if (recentPosts.size() > limit) {
recentPosts.removeLast();
}
}
break;
}
position++;
}
}
}
}
}
|
diff --git a/src/jp/tsuttsu305/onPlayerDeathEvent.java b/src/jp/tsuttsu305/onPlayerDeathEvent.java
index 8d4cd58..3d84182 100644
--- a/src/jp/tsuttsu305/onPlayerDeathEvent.java
+++ b/src/jp/tsuttsu305/onPlayerDeathEvent.java
@@ -1,169 +1,168 @@
package jp.tsuttsu305;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.entity.Wolf;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.inventory.ItemStack;
public class onPlayerDeathEvent implements Listener {
// * メインクラスのインスタンス
// このクラスのインスタンスが生成される際に、メインクラスのインスタンスを設定する
// メインクラスの動的フィールド・メソッドにアクセスする時は main.hogehoge のように使う
private PlayerDeathMsgJp main = null;
/**
* onPlayerDeathEventクラスのコンストラクタ
* @param main メインクラスのインスタンス
*/
public onPlayerDeathEvent(PlayerDeathMsgJp main){
this.main = main;
}
//TODO:main.getMessage() これを何とかする必要あり
//Main Main = jp.tsuttsu305.Main.plugin;
@EventHandler
public void onPlayerDeath(PlayerDeathEvent event){
// プレイヤーとプレイヤーが最後に受けたダメージイベントを取得
Player deader = event.getEntity();
final EntityDamageEvent cause = event.getEntity().getLastDamageCause();
// 死亡メッセージ
String deathMessage = event.getDeathMessage();
String name = deader.getName();
// ダメージイベントを受けずに死んだ 死因不明
if (cause == null){
deathMessage = main.getMessage("unknown"); // Unknown
}
// ダメージイベントあり 原因によってメッセージ変更
else{
// ダメージイベントがEntityDamageByEntityEvent(エンティティが原因のダメージイベント)かどうかチェック
if (cause instanceof EntityDamageByEntityEvent) {
Entity killer = ((EntityDamageByEntityEvent) cause).getDamager(); // EntityDamageByEventのgetDamagerメソッドから原因となったエンティティを取得
// エンティティの型チェック 特殊な表示の仕方が必要
if (killer instanceof Player){
// この辺に倒したプレイヤー名取得
Player killerP = deader.getKiller();
//killerが持ってたアイテム
ItemStack hand = killerP.getItemInHand();
deathMessage = main.getMessage("pvp");
deathMessage = deathMessage.replace("%k", killerP.getName());
deathMessage = deathMessage.replace("%i", hand.getType().toString());
}
// 飼われている狼
else if (killer instanceof Wolf && ((Wolf) killer).isTamed()){
// 飼い主取得
String tamer = ((Wolf)killer).getOwner().getName();
deathMessage = main.getMessage("tamewolf");
deathMessage = deathMessage.replace("%o", tamer);
}
// プレイヤーが投げた弓や雪玉など
else if (killer instanceof Projectile && ((Projectile) killer).getShooter() instanceof Player) {
// 投げたプレイヤー取得
Player sh = (Player) ((Projectile)killer).getShooter();
//仕様です。こんなものなかった
//ItemStack pass = deader.getKiller().getItemInHand();
deathMessage = main.getMessage("throw");
//仕様です。こんなものなかった
//deathMessage = deathMessage.replace("%i", pass.getType().toString());
deathMessage = deathMessage.replace("%k", sh.getName());
}
// そのほかのMOBは直接設定ファイルから取得
else{
//Mainクラスの main.plugin.Main.getMessage メソッドを呼ぶ
- //deader.sendMessage(killer.getType().getName().toLowerCase());
deathMessage = main.getMessage(killer.getType().getName().toLowerCase());
}
}
// エンティティ以外に倒されたメッセージは別に設定
else{
switch (cause.getCause()){
case CONTACT:
deathMessage = main.getMessage(cause.getCause().toString());
break;
case DROWNING:
deathMessage = main.getMessage(cause.getCause().toString());
break;
case FALL:
deathMessage = main.getMessage(cause.getCause().toString());
break;
case FIRE:
case FIRE_TICK:
deathMessage = main.getMessage("fire");
break;
case LAVA:
deathMessage = main.getMessage(cause.getCause().toString());
break;
case LIGHTNING:
deathMessage = main.getMessage(cause.getCause().toString());
break;
case POISON:
deathMessage = main.getMessage(cause.getCause().toString());
break;
case STARVATION:
deathMessage = main.getMessage(cause.getCause().toString());
break;
case SUFFOCATION:
deathMessage = main.getMessage(cause.getCause().toString());
break;
case SUICIDE:
deathMessage = main.getMessage(cause.getCause().toString());
break;
case VOID:
deathMessage = main.getMessage(cause.getCause().toString());
break;
// それ以外は不明
default:
deathMessage = main.getMessage("unknown"); // Unknown
break;
}
}
}
// 設定ファイルから読み込むなら最後に一括変換したほうがスマートかも
deathMessage = deathMessage.replace("%p", name);
event.setDeathMessage(deathMessage);
return;
}
}
| true | true | public void onPlayerDeath(PlayerDeathEvent event){
// プレイヤーとプレイヤーが最後に受けたダメージイベントを取得
Player deader = event.getEntity();
final EntityDamageEvent cause = event.getEntity().getLastDamageCause();
// 死亡メッセージ
String deathMessage = event.getDeathMessage();
String name = deader.getName();
// ダメージイベントを受けずに死んだ 死因不明
if (cause == null){
deathMessage = main.getMessage("unknown"); // Unknown
}
// ダメージイベントあり 原因によってメッセージ変更
else{
// ダメージイベントがEntityDamageByEntityEvent(エンティティが原因のダメージイベント)かどうかチェック
if (cause instanceof EntityDamageByEntityEvent) {
Entity killer = ((EntityDamageByEntityEvent) cause).getDamager(); // EntityDamageByEventのgetDamagerメソッドから原因となったエンティティを取得
// エンティティの型チェック 特殊な表示の仕方が必要
if (killer instanceof Player){
// この辺に倒したプレイヤー名取得
Player killerP = deader.getKiller();
//killerが持ってたアイテム
ItemStack hand = killerP.getItemInHand();
deathMessage = main.getMessage("pvp");
deathMessage = deathMessage.replace("%k", killerP.getName());
deathMessage = deathMessage.replace("%i", hand.getType().toString());
}
// 飼われている狼
else if (killer instanceof Wolf && ((Wolf) killer).isTamed()){
// 飼い主取得
String tamer = ((Wolf)killer).getOwner().getName();
deathMessage = main.getMessage("tamewolf");
deathMessage = deathMessage.replace("%o", tamer);
}
// プレイヤーが投げた弓や雪玉など
else if (killer instanceof Projectile && ((Projectile) killer).getShooter() instanceof Player) {
// 投げたプレイヤー取得
Player sh = (Player) ((Projectile)killer).getShooter();
//仕様です。こんなものなかった
//ItemStack pass = deader.getKiller().getItemInHand();
deathMessage = main.getMessage("throw");
//仕様です。こんなものなかった
//deathMessage = deathMessage.replace("%i", pass.getType().toString());
deathMessage = deathMessage.replace("%k", sh.getName());
}
// そのほかのMOBは直接設定ファイルから取得
else{
//Mainクラスの main.plugin.Main.getMessage メソッドを呼ぶ
//deader.sendMessage(killer.getType().getName().toLowerCase());
deathMessage = main.getMessage(killer.getType().getName().toLowerCase());
}
}
// エンティティ以外に倒されたメッセージは別に設定
else{
switch (cause.getCause()){
case CONTACT:
deathMessage = main.getMessage(cause.getCause().toString());
break;
case DROWNING:
deathMessage = main.getMessage(cause.getCause().toString());
break;
case FALL:
deathMessage = main.getMessage(cause.getCause().toString());
break;
case FIRE:
case FIRE_TICK:
deathMessage = main.getMessage("fire");
break;
case LAVA:
deathMessage = main.getMessage(cause.getCause().toString());
break;
case LIGHTNING:
deathMessage = main.getMessage(cause.getCause().toString());
break;
case POISON:
deathMessage = main.getMessage(cause.getCause().toString());
break;
case STARVATION:
deathMessage = main.getMessage(cause.getCause().toString());
break;
case SUFFOCATION:
deathMessage = main.getMessage(cause.getCause().toString());
break;
case SUICIDE:
deathMessage = main.getMessage(cause.getCause().toString());
break;
case VOID:
deathMessage = main.getMessage(cause.getCause().toString());
break;
// それ以外は不明
default:
deathMessage = main.getMessage("unknown"); // Unknown
break;
}
}
}
// 設定ファイルから読み込むなら最後に一括変換したほうがスマートかも
deathMessage = deathMessage.replace("%p", name);
event.setDeathMessage(deathMessage);
return;
}
| public void onPlayerDeath(PlayerDeathEvent event){
// プレイヤーとプレイヤーが最後に受けたダメージイベントを取得
Player deader = event.getEntity();
final EntityDamageEvent cause = event.getEntity().getLastDamageCause();
// 死亡メッセージ
String deathMessage = event.getDeathMessage();
String name = deader.getName();
// ダメージイベントを受けずに死んだ 死因不明
if (cause == null){
deathMessage = main.getMessage("unknown"); // Unknown
}
// ダメージイベントあり 原因によってメッセージ変更
else{
// ダメージイベントがEntityDamageByEntityEvent(エンティティが原因のダメージイベント)かどうかチェック
if (cause instanceof EntityDamageByEntityEvent) {
Entity killer = ((EntityDamageByEntityEvent) cause).getDamager(); // EntityDamageByEventのgetDamagerメソッドから原因となったエンティティを取得
// エンティティの型チェック 特殊な表示の仕方が必要
if (killer instanceof Player){
// この辺に倒したプレイヤー名取得
Player killerP = deader.getKiller();
//killerが持ってたアイテム
ItemStack hand = killerP.getItemInHand();
deathMessage = main.getMessage("pvp");
deathMessage = deathMessage.replace("%k", killerP.getName());
deathMessage = deathMessage.replace("%i", hand.getType().toString());
}
// 飼われている狼
else if (killer instanceof Wolf && ((Wolf) killer).isTamed()){
// 飼い主取得
String tamer = ((Wolf)killer).getOwner().getName();
deathMessage = main.getMessage("tamewolf");
deathMessage = deathMessage.replace("%o", tamer);
}
// プレイヤーが投げた弓や雪玉など
else if (killer instanceof Projectile && ((Projectile) killer).getShooter() instanceof Player) {
// 投げたプレイヤー取得
Player sh = (Player) ((Projectile)killer).getShooter();
//仕様です。こんなものなかった
//ItemStack pass = deader.getKiller().getItemInHand();
deathMessage = main.getMessage("throw");
//仕様です。こんなものなかった
//deathMessage = deathMessage.replace("%i", pass.getType().toString());
deathMessage = deathMessage.replace("%k", sh.getName());
}
// そのほかのMOBは直接設定ファイルから取得
else{
//Mainクラスの main.plugin.Main.getMessage メソッドを呼ぶ
deathMessage = main.getMessage(killer.getType().getName().toLowerCase());
}
}
// エンティティ以外に倒されたメッセージは別に設定
else{
switch (cause.getCause()){
case CONTACT:
deathMessage = main.getMessage(cause.getCause().toString());
break;
case DROWNING:
deathMessage = main.getMessage(cause.getCause().toString());
break;
case FALL:
deathMessage = main.getMessage(cause.getCause().toString());
break;
case FIRE:
case FIRE_TICK:
deathMessage = main.getMessage("fire");
break;
case LAVA:
deathMessage = main.getMessage(cause.getCause().toString());
break;
case LIGHTNING:
deathMessage = main.getMessage(cause.getCause().toString());
break;
case POISON:
deathMessage = main.getMessage(cause.getCause().toString());
break;
case STARVATION:
deathMessage = main.getMessage(cause.getCause().toString());
break;
case SUFFOCATION:
deathMessage = main.getMessage(cause.getCause().toString());
break;
case SUICIDE:
deathMessage = main.getMessage(cause.getCause().toString());
break;
case VOID:
deathMessage = main.getMessage(cause.getCause().toString());
break;
// それ以外は不明
default:
deathMessage = main.getMessage("unknown"); // Unknown
break;
}
}
}
// 設定ファイルから読み込むなら最後に一括変換したほうがスマートかも
deathMessage = deathMessage.replace("%p", name);
event.setDeathMessage(deathMessage);
return;
}
|
diff --git a/src/PrimerDesign/src/view/Splash.java b/src/PrimerDesign/src/view/Splash.java
index cffd5a1..8fc389c 100644
--- a/src/PrimerDesign/src/view/Splash.java
+++ b/src/PrimerDesign/src/view/Splash.java
@@ -1,169 +1,169 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package view;
import controller.PrimerDesign;
/**
*
* @author 0901758b
*/
public class Splash extends javax.swing.JPanel {
/**
* Creates new form Splash
*/
public Splash() {
initComponents();
}
/**
* This method is called from within the constructor to initialise the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
titleLabel = new javax.swing.JLabel();
leftLabel = new javax.swing.JLabel();
bottomLabel = new javax.swing.JLabel();
rightLabel = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
bottomTextArea = new javax.swing.JTextArea();
jScrollPane2 = new javax.swing.JScrollPane();
leftTextArea = new javax.swing.JTextArea();
jScrollPane3 = new javax.swing.JScrollPane();
rightTextArea = new javax.swing.JTextArea();
startButton = new javax.swing.JButton();
setPreferredSize(new java.awt.Dimension(800, 600));
titleLabel.setFont(new java.awt.Font("DejaVu Sans", 0, 24)); // NOI18N
titleLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
titleLabel.setText("Polymerase Chain Reaction Tutorial");
leftLabel.setFont(new java.awt.Font("DejaVu Sans", 0, 14)); // NOI18N
leftLabel.setText("Overview");
bottomLabel.setFont(new java.awt.Font("DejaVu Sans", 0, 14)); // NOI18N
bottomLabel.setText("Further Reading");
rightLabel.setFont(new java.awt.Font("DejaVu Sans", 0, 14)); // NOI18N
rightLabel.setText("Primer Design Rules");
bottomTextArea.setEditable(false);
bottomTextArea.setColumns(20);
bottomTextArea.setRows(5);
bottomTextArea.setText("NCBI Website: \t\t\thttp://www.ncbi.nlm.nih.gov/\nMolecular Methods Moodle Site:\t\thttp://ibls.moodle.gla.ac.uk/course/view.php?id=104");
jScrollPane1.setViewportView(bottomTextArea);
leftTextArea.setEditable(false);
leftTextArea.setColumns(20);
leftTextArea.setLineWrap(true);
leftTextArea.setRows(5);
- leftTextArea.setText("Hello, and welcome to the Polymerase Chain Reaction (PCR) Tutorial.\n\nThis application will guide you through the process of PCR, particularly on primer design. You can use any sequence and any primers you like, we will make sure they are correct.\n\nIf this application crashes, or does something you don't expect, please e-mail [email protected] with details of what you were doing immediately before the incident and details of the incident itself. This will hopefully allow us to fix the problem.\n\n\n\n\n\nCreated by Ross Barnie, Dmitrijs Jonins, Daniel McElroy, Murray Ross and Ross Taylor.");
+ leftTextArea.setText("Hello, and welcome to the Polymerase Chain Reaction (PCR) Tutorial.\n\nThis application will guide you through the process of PCR, particularly helping with primer design. You can use any sequence and you will have to design the primers for the process, we will make sure they are correct.\n\nIf this application crashes, or does something you don't expect, please e-mail [email protected] with details of what you were doing immediately before the incident and details of the incident itself. This will hopefully allow us to fix the problem.\n\n\n\n\n\nCreated by Ross Barnie, Dmitrijs Jonins, Daniel McElroy, Murray Ross and Ross Taylor.");
leftTextArea.setWrapStyleWord(true);
jScrollPane2.setViewportView(leftTextArea);
rightTextArea.setEditable(false);
rightTextArea.setColumns(20);
rightTextArea.setLineWrap(true);
rightTextArea.setRows(5);
rightTextArea.setText("Generally, primers should be 20 to 30 bases in length. \n\nThe sequence you use should avoid long repetitions of a single base. \n\nThe last base of the primer should be a 'c' or a 'g'. You should avoid sequences which could self-anneal. \n\nThe primers you choose should be unique to the sequence. \n\nBetween 40% and 60% of each primer sequence should consist of 'g' or 'c' bases. \n\nAlso keep in mind that the melting temperature should be between 50 and 60°C (Tm = 2(A + T) + 4(C + G), where A, T, C and G are the number of times each of those bases appear in a primer).");
rightTextArea.setWrapStyleWord(true);
jScrollPane3.setViewportView(rightTextArea);
startButton.setText("Start");
startButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
startButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(bottomLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(titleLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane1))
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(leftLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 375, Short.MAX_VALUE))
.addGap(26, 26, 26)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(rightLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 217, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 12, Short.MAX_VALUE))))))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(startButton, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jScrollPane2, jScrollPane3});
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(titleLabel)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(leftLabel)
.addComponent(rightLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 350, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 350, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(bottomLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 11, Short.MAX_VALUE)
.addComponent(startButton)
.addContainerGap())
);
layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {jScrollPane2, jScrollPane3});
}// </editor-fold>//GEN-END:initComponents
private void startButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startButtonActionPerformed
// remove current panel from window
PrimerDesign.window.getContentPane().remove(PrimerDesign.splash);
PrimerDesign.window.setVisible(false);
// add next panel to window and display
PrimerDesign.start = new StartPanel();
PrimerDesign.window.getContentPane().add(PrimerDesign.start);
PrimerDesign.window.pack();
PrimerDesign.window.setVisible(true);
}//GEN-LAST:event_startButtonActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel bottomLabel;
private javax.swing.JTextArea bottomTextArea;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JLabel leftLabel;
private javax.swing.JTextArea leftTextArea;
private javax.swing.JLabel rightLabel;
private javax.swing.JTextArea rightTextArea;
private javax.swing.JButton startButton;
private javax.swing.JLabel titleLabel;
// End of variables declaration//GEN-END:variables
}
| true | true | private void initComponents() {
titleLabel = new javax.swing.JLabel();
leftLabel = new javax.swing.JLabel();
bottomLabel = new javax.swing.JLabel();
rightLabel = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
bottomTextArea = new javax.swing.JTextArea();
jScrollPane2 = new javax.swing.JScrollPane();
leftTextArea = new javax.swing.JTextArea();
jScrollPane3 = new javax.swing.JScrollPane();
rightTextArea = new javax.swing.JTextArea();
startButton = new javax.swing.JButton();
setPreferredSize(new java.awt.Dimension(800, 600));
titleLabel.setFont(new java.awt.Font("DejaVu Sans", 0, 24)); // NOI18N
titleLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
titleLabel.setText("Polymerase Chain Reaction Tutorial");
leftLabel.setFont(new java.awt.Font("DejaVu Sans", 0, 14)); // NOI18N
leftLabel.setText("Overview");
bottomLabel.setFont(new java.awt.Font("DejaVu Sans", 0, 14)); // NOI18N
bottomLabel.setText("Further Reading");
rightLabel.setFont(new java.awt.Font("DejaVu Sans", 0, 14)); // NOI18N
rightLabel.setText("Primer Design Rules");
bottomTextArea.setEditable(false);
bottomTextArea.setColumns(20);
bottomTextArea.setRows(5);
bottomTextArea.setText("NCBI Website: \t\t\thttp://www.ncbi.nlm.nih.gov/\nMolecular Methods Moodle Site:\t\thttp://ibls.moodle.gla.ac.uk/course/view.php?id=104");
jScrollPane1.setViewportView(bottomTextArea);
leftTextArea.setEditable(false);
leftTextArea.setColumns(20);
leftTextArea.setLineWrap(true);
leftTextArea.setRows(5);
leftTextArea.setText("Hello, and welcome to the Polymerase Chain Reaction (PCR) Tutorial.\n\nThis application will guide you through the process of PCR, particularly on primer design. You can use any sequence and any primers you like, we will make sure they are correct.\n\nIf this application crashes, or does something you don't expect, please e-mail [email protected] with details of what you were doing immediately before the incident and details of the incident itself. This will hopefully allow us to fix the problem.\n\n\n\n\n\nCreated by Ross Barnie, Dmitrijs Jonins, Daniel McElroy, Murray Ross and Ross Taylor.");
leftTextArea.setWrapStyleWord(true);
jScrollPane2.setViewportView(leftTextArea);
rightTextArea.setEditable(false);
rightTextArea.setColumns(20);
rightTextArea.setLineWrap(true);
rightTextArea.setRows(5);
rightTextArea.setText("Generally, primers should be 20 to 30 bases in length. \n\nThe sequence you use should avoid long repetitions of a single base. \n\nThe last base of the primer should be a 'c' or a 'g'. You should avoid sequences which could self-anneal. \n\nThe primers you choose should be unique to the sequence. \n\nBetween 40% and 60% of each primer sequence should consist of 'g' or 'c' bases. \n\nAlso keep in mind that the melting temperature should be between 50 and 60°C (Tm = 2(A + T) + 4(C + G), where A, T, C and G are the number of times each of those bases appear in a primer).");
rightTextArea.setWrapStyleWord(true);
jScrollPane3.setViewportView(rightTextArea);
startButton.setText("Start");
startButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
startButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(bottomLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(titleLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane1))
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(leftLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 375, Short.MAX_VALUE))
.addGap(26, 26, 26)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(rightLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 217, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 12, Short.MAX_VALUE))))))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(startButton, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jScrollPane2, jScrollPane3});
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(titleLabel)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(leftLabel)
.addComponent(rightLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 350, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 350, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(bottomLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 11, Short.MAX_VALUE)
.addComponent(startButton)
.addContainerGap())
);
layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {jScrollPane2, jScrollPane3});
}// </editor-fold>//GEN-END:initComponents
| private void initComponents() {
titleLabel = new javax.swing.JLabel();
leftLabel = new javax.swing.JLabel();
bottomLabel = new javax.swing.JLabel();
rightLabel = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
bottomTextArea = new javax.swing.JTextArea();
jScrollPane2 = new javax.swing.JScrollPane();
leftTextArea = new javax.swing.JTextArea();
jScrollPane3 = new javax.swing.JScrollPane();
rightTextArea = new javax.swing.JTextArea();
startButton = new javax.swing.JButton();
setPreferredSize(new java.awt.Dimension(800, 600));
titleLabel.setFont(new java.awt.Font("DejaVu Sans", 0, 24)); // NOI18N
titleLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
titleLabel.setText("Polymerase Chain Reaction Tutorial");
leftLabel.setFont(new java.awt.Font("DejaVu Sans", 0, 14)); // NOI18N
leftLabel.setText("Overview");
bottomLabel.setFont(new java.awt.Font("DejaVu Sans", 0, 14)); // NOI18N
bottomLabel.setText("Further Reading");
rightLabel.setFont(new java.awt.Font("DejaVu Sans", 0, 14)); // NOI18N
rightLabel.setText("Primer Design Rules");
bottomTextArea.setEditable(false);
bottomTextArea.setColumns(20);
bottomTextArea.setRows(5);
bottomTextArea.setText("NCBI Website: \t\t\thttp://www.ncbi.nlm.nih.gov/\nMolecular Methods Moodle Site:\t\thttp://ibls.moodle.gla.ac.uk/course/view.php?id=104");
jScrollPane1.setViewportView(bottomTextArea);
leftTextArea.setEditable(false);
leftTextArea.setColumns(20);
leftTextArea.setLineWrap(true);
leftTextArea.setRows(5);
leftTextArea.setText("Hello, and welcome to the Polymerase Chain Reaction (PCR) Tutorial.\n\nThis application will guide you through the process of PCR, particularly helping with primer design. You can use any sequence and you will have to design the primers for the process, we will make sure they are correct.\n\nIf this application crashes, or does something you don't expect, please e-mail [email protected] with details of what you were doing immediately before the incident and details of the incident itself. This will hopefully allow us to fix the problem.\n\n\n\n\n\nCreated by Ross Barnie, Dmitrijs Jonins, Daniel McElroy, Murray Ross and Ross Taylor.");
leftTextArea.setWrapStyleWord(true);
jScrollPane2.setViewportView(leftTextArea);
rightTextArea.setEditable(false);
rightTextArea.setColumns(20);
rightTextArea.setLineWrap(true);
rightTextArea.setRows(5);
rightTextArea.setText("Generally, primers should be 20 to 30 bases in length. \n\nThe sequence you use should avoid long repetitions of a single base. \n\nThe last base of the primer should be a 'c' or a 'g'. You should avoid sequences which could self-anneal. \n\nThe primers you choose should be unique to the sequence. \n\nBetween 40% and 60% of each primer sequence should consist of 'g' or 'c' bases. \n\nAlso keep in mind that the melting temperature should be between 50 and 60°C (Tm = 2(A + T) + 4(C + G), where A, T, C and G are the number of times each of those bases appear in a primer).");
rightTextArea.setWrapStyleWord(true);
jScrollPane3.setViewportView(rightTextArea);
startButton.setText("Start");
startButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
startButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(bottomLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(titleLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane1))
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(leftLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 375, Short.MAX_VALUE))
.addGap(26, 26, 26)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(rightLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 217, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 12, Short.MAX_VALUE))))))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(startButton, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jScrollPane2, jScrollPane3});
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(titleLabel)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(leftLabel)
.addComponent(rightLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 350, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 350, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(bottomLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 11, Short.MAX_VALUE)
.addComponent(startButton)
.addContainerGap())
);
layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {jScrollPane2, jScrollPane3});
}// </editor-fold>//GEN-END:initComponents
|
diff --git a/src/org/openjump/core/ui/plugin/mousemenu/SaveDatasetsPlugIn.java b/src/org/openjump/core/ui/plugin/mousemenu/SaveDatasetsPlugIn.java
index a16f0cfe..bb90a3d1 100644
--- a/src/org/openjump/core/ui/plugin/mousemenu/SaveDatasetsPlugIn.java
+++ b/src/org/openjump/core/ui/plugin/mousemenu/SaveDatasetsPlugIn.java
@@ -1,872 +1,872 @@
/*
* The Unified Mapping Platform (JUMP) is an extensible, interactive GUI
* for visualizing and manipulating spatial features with geometry and attributes.
*
* JUMP is Copyright (C) 2003 Vivid Solutions
*
* This program implements extensions to JUMP and is
* Copyright (C) 2004 Integrated Systems Analysts, Inc.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* For more information, contact:
*
* Integrated Systems Analysts, Inc.
* 630C Anchors St., Suite 101
* Fort Walton Beach, Florida
* USA
*
* (850)862-7321
* www.ashs.isa.com
*/
package org.openjump.core.ui.plugin.mousemenu;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.filechooser.FileFilter;
import org.openjump.core.geomutils.GeoUtils;
import org.openjump.core.ui.images.IconLoader;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryCollection;
import com.vividsolutions.jts.geom.MultiLineString;
import com.vividsolutions.jts.geom.MultiPoint;
import com.vividsolutions.jts.geom.MultiPolygon;
import com.vividsolutions.jump.I18N;
import com.vividsolutions.jump.feature.Feature;
import com.vividsolutions.jump.feature.FeatureCollectionWrapper;
import com.vividsolutions.jump.feature.FeatureDataset;
import com.vividsolutions.jump.feature.FeatureSchema;
import com.vividsolutions.jump.io.DriverProperties;
import com.vividsolutions.jump.io.FMEGMLWriter;
import com.vividsolutions.jump.io.GMLWriter;
import com.vividsolutions.jump.io.JMLWriter;
import com.vividsolutions.jump.io.ShapefileWriter;
import com.vividsolutions.jump.io.WKTWriter;
import com.vividsolutions.jump.io.datasource.DataSource;
import com.vividsolutions.jump.io.datasource.DataSourceQuery;
import com.vividsolutions.jump.io.datasource.StandardReaderWriterFileDataSource;
import com.vividsolutions.jump.util.FileUtil;
import com.vividsolutions.jump.workbench.WorkbenchContext;
import com.vividsolutions.jump.workbench.model.Layer;
import com.vividsolutions.jump.workbench.model.LayerManager;
import com.vividsolutions.jump.workbench.model.StandardCategoryNames;
import com.vividsolutions.jump.workbench.plugin.AbstractPlugIn;
import com.vividsolutions.jump.workbench.plugin.EnableCheckFactory;
import com.vividsolutions.jump.workbench.plugin.MultiEnableCheck;
import com.vividsolutions.jump.workbench.plugin.PlugInContext;
import com.vividsolutions.jump.workbench.ui.GUIUtil;
import com.vividsolutions.jump.workbench.ui.plugin.FeatureInstaller;
import com.vividsolutions.jump.workbench.ui.plugin.SaveProjectAsPlugIn;
import com.vividsolutions.jump.workbench.ui.plugin.SaveProjectPlugIn;
public class SaveDatasetsPlugIn extends AbstractPlugIn
{
private static final String sSaveSelectedDatasets = I18N.get("org.openjump.core.ui.plugin.mousemenu.SaveDatasetsPlugIn.Save-Selected-Datasets");
private static final String sUseSaveDatasetAsToSaveLayer= I18N.get("org.openjump.core.ui.plugin.mousemenu.SaveDatasetsPlugIn.Use***Save-Dataset-As***to-Save-Layer");
private static final String sSavedLayer= I18N.get("org.openjump.core.ui.plugin.mousemenu.SaveDatasetsPlugIn.Saved-Layer");
private static final String sErrorSeeOutputWindow=I18N.get("org.openjump.core.ui.plugin.mousemenu.SaveDatasetsPlugIn.Error-See-Output-Window");
private static final String sWarningSeeOutputWindow=I18N.get("org.openjump.core.ui.plugin.mousemenu.SaveDatasetsPlugIn.Warning-See-Output-Window");
private static final String sCouldNotSaveLayer=I18N.get("org.openjump.core.ui.plugin.mousemenu.SaveDatasetsPlugIn.Could-not-save-layer");
private static final String sCouldNotSave=I18N.get("org.openjump.core.ui.plugin.mousemenu.SaveDatasetsPlugIn.Could-not-save");
private static final String sLayer=I18N.get("org.openjump.core.ui.plugin.mousemenu.SaveDatasetsPlugIn.layer");
private static final String sWithEmptyGeometry=I18N.get("org.openjump.core.ui.plugin.mousemenu.SaveDatasetsPlugIn.with-empty-geometry");
private static final String sWithMixedGeometryTypes=I18N.get("org.openjump.core.ui.plugin.mousemenu.SaveDatasetsPlugIn.with-mixed-geometry-types");
private static final String sCanNotSaveReadOnly=I18N.get("org.openjump.core.ui.plugin.mousemenu.SaveDatasetsPlugIn.Cannot-save-to-read-only-source-for-layer");
private static final String sDidNotSaveSameFile=I18N.get("org.openjump.core.ui.plugin.mousemenu.SaveDatasetsPlugIn.Did-not-save-these-layers-since-they-would-have-to-be-saved-to-the-same-file");
private static final String sSavedTask=I18N.get("org.openjump.core.ui.plugin.mousemenu.SaveDatasetsPlugIn.Saved-task");
private static final String sFileName=I18N.get("org.openjump.core.ui.plugin.mousemenu.SaveDatasetsPlugIn.File-Name");
private static final String sLayerName=I18N.get("org.openjump.core.ui.plugin.mousemenu.SaveDatasetsPlugIn.Layer-Name");
private static final String sUnrecognizedFileType=I18N.get("org.openjump.core.ui.plugin.mousemenu.SaveDatasetsPlugIn.Unrecognized-file-type");
private static final String sNewLayerCreated=I18N.get("org.openjump.core.ui.plugin.mousemenu.SaveDatasetsPlugIn.New-layer-created");
private static final String sCouldNotWrite=I18N.get("org.openjump.core.ui.plugin.mousemenu.SaveDatasetsPlugIn.Could-not-write");
private static final String sEmptyLayerNotSaved = I18N.get("org.openjump.core.ui.plugin.mousemenu.SaveDatasetsPlugIn.Empty-layer-not-saved");
private static final String sSaveFilesFromReadOnlySources = I18N.get("org.openjump.core.ui.plugin.mousemenu.SaveDatasetsPlugIn.Save-files-from-read-only-sources");
private static final String sFiles = I18N.get("org.openjump.core.ui.plugin.mousemenu.SaveDatasetsPlugIn.Files");
private static final String sWantToSaveReadonly = I18N.get("org.openjump.core.ui.plugin.mousemenu.SaveDatasetsPlugIn.Do-you-want-to-save-the-read-only-layers");
private static final String sNoteLayerNameWillBeFileName = I18N.get("org.openjump.core.ui.plugin.mousemenu.SaveDatasetsPlugIn.Note-layer-name-will-be-filename");
private static final String sReadOnlyLayer = I18N.get("org.openjump.core.ui.plugin.mousemenu.SaveDatasetsPlugIn.read-only-layer");
private static final String sReplacesFile = I18N.get("org.openjump.core.ui.plugin.mousemenu.SaveDatasetsPlugIn.replaces-file");
private static final String sReadOnlyWillReplace = I18N.get("org.openjump.core.ui.plugin.mousemenu.SaveDatasetsPlugIn.read-only-source-will-replace-an-existing-file");
private static final String sNoteOutputWindow = I18N.get("org.openjump.core.ui.plugin.mousemenu.SaveDatasetsPlugIn.Note-Output-window-will-display-the-results-of-this-command");
private static final String sWouldHaveReplaced = I18N.get("org.openjump.core.ui.plugin.mousemenu.SaveDatasetsPlugIn.The-read-only-layer-would-have-replaced-the-following-file(s)");
private static final String sHasReplaced = I18N.get("org.openjump.core.ui.plugin.mousemenu.SaveDatasetsPlugIn.The-read-only-layer-has-replaced-the-following-file(s)");
private static final String sNoOutputDir = I18N.get("org.openjump.core.ui.plugin.mousemenu.SaveDatasetsPlugIn.No-output-directory-designated-for-read-only-source-could-not-save-layer");
private static final String sNoOutputFileExt = I18N.get("org.openjump.core.ui.plugin.mousemenu.SaveDatasetsPlugIn.No-output-file-extension-designated-for-read-only-source-could-not-save-layer");
private boolean saveAll = false;
private int saveReadOnlySources = -1; //-1 - ask; 0 - don't save; 1 - save;
private String pathToSaveReadOnlySources = "";
private String extToSaveReadOnlySources = "";
private JFileChooser fileChooser;
public void initialize(PlugInContext context) throws Exception
{
WorkbenchContext workbenchContext = context.getWorkbenchContext();
FeatureInstaller featureInstaller = new FeatureInstaller(workbenchContext);
JPopupMenu layerNamePopupMenu = workbenchContext.getWorkbench()
.getFrame()
.getLayerNamePopupMenu();
featureInstaller.addPopupMenuItem(layerNamePopupMenu,
this, sSaveSelectedDatasets +"{pos:12}",
false, ICON,
SaveDatasetsPlugIn.createEnableCheck(workbenchContext));
}
public static final ImageIcon ICON = IconLoader.icon("disk_multiple.png");
public boolean execute(PlugInContext context) throws Exception
{
try
{
WorkbenchContext workbenchContext = context.getWorkbenchContext();
fileChooser = new JFileChooser();
//fileChooser = GUIUtil.createJFileChooserWithOverwritePrompting();
fileChooser.setDialogTitle(sSaveFilesFromReadOnlySources);
fileChooser.setDialogType(JFileChooser.SAVE_DIALOG);
fileChooser.setMultiSelectionEnabled(false);
GUIUtil.removeChoosableFileFilters(fileChooser);
FileFilter fileFilter1 = GUIUtil.createFileFilter("SHP " + sFiles, new String[]{"shp"});
fileChooser.addChoosableFileFilter(fileFilter1);
FileFilter fileFilter2 = GUIUtil.createFileFilter("GML " + sFiles, new String[]{"gml"});
fileChooser.addChoosableFileFilter(fileFilter2);
FileFilter fileFilter3 = GUIUtil.createFileFilter("JML " + sFiles, new String[]{"jml"});
fileChooser.addChoosableFileFilter(fileFilter3);
FileFilter fileFilter4 = GUIUtil.createFileFilter("FME " + sFiles, new String[]{"fme"});
fileChooser.addChoosableFileFilter(fileFilter4);
FileFilter fileFilter5 = GUIUtil.createFileFilter("WKT " + sFiles, new String[]{"wkt"});
fileChooser.addChoosableFileFilter(fileFilter5);
fileChooser.setFileFilter(fileFilter1);
boolean writeWarning = false;
String newLine = "";
context.getWorkbenchFrame().getOutputFrame().createNewDocument();
LayerManager layerManager = context.getLayerManager();
Collection layerCollection = layerManager.getLayers();
//ensure all appropriate layers get projection files
for (Iterator i = layerCollection.iterator(); i.hasNext();)
{
writeProjectionFile(context, (Layer) i.next());
}
List layerList = new ArrayList();
if (saveAll)
{
layerCollection = layerManager.getLayersWithModifiedFeatureCollections();
for (Iterator i = layerCollection.iterator(); i.hasNext();)
layerList.add((Layer) i.next());
}
else
{
layerCollection = (Collection) context.getWorkbenchContext().getLayerNamePanel().selectedNodes(Layer.class);
for (Iterator i = layerCollection.iterator(); i.hasNext();)
{
Layer layer = (Layer) i.next();
boolean addIt = false;
DataSourceQuery dsq = layer.getDataSourceQuery();
if (dsq != null)
if (!dsq.getDataSource().isWritable())
addIt = true;
if (layer.isFeatureCollectionModified() || addIt) //just add modified or read-only layers
layerList.add(layer);
}
}
//remove empty layers
for (int i = layerList.size() - 1; i >= 0; i--)
{
Layer layer = (Layer) layerList.get(i);
if (layer.getFeatureCollectionWrapper().getFeatures().size() == 0) //layer is empty
{
context.getWorkbenchFrame().getOutputFrame().addText( sEmptyLayerNotSaved + ": " + layer.getName());
writeWarning = true;
layerList.remove(i);
newLine = "\n";
}
}
//remove any layers which have no data sources, ie,
//those that have not been previously saved
for (int i = layerList.size() - 1; i >= 0; i--)
{
Layer layer = (Layer) layerList.get(i);
DataSourceQuery dsq = layer.getDataSourceQuery();
boolean writeSaveMsg = false;
if (dsq == null) //layer does not have a data source
{
writeSaveMsg = true;
}
else
{
DataSource ds = dsq.getDataSource();
if (ds == null)
{
writeSaveMsg = true;
}
else
{
if (ds.getProperties().get("File") == null)
{
writeSaveMsg = true;
}
}
}
if (writeSaveMsg)
{
context.getWorkbenchFrame().getOutputFrame().addText(sUseSaveDatasetAsToSaveLayer + layer.getName());
writeWarning = true;
layerList.remove(i);
newLine = "\n";
}
}
//remove any layers which have read-only sources, ie, SdeDataSources
saveReadOnlySources = -1; //initialize so that we ask user if these are to be saved
pathToSaveReadOnlySources = ""; //initialize to that WriteLayer will ask the first time
String chosenSaveFile = "";
for (int i = layerList.size() - 1; i >= 0; i--)
{
Layer layer = (Layer) layerList.get(i);
DataSourceQuery dsq = layer.getDataSourceQuery();
if (!dsq.getDataSource().isWritable()) //data source is read-only
{
if (saveReadOnlySources == -1)
{
int response = JOptionPane.showConfirmDialog(workbenchContext.getLayerViewPanel(),
sWantToSaveReadonly + "\n" + "(" + sNoteLayerNameWillBeFileName + ")",
"JUMP", JOptionPane.YES_NO_OPTION);
saveReadOnlySources = 0;
if (response == JOptionPane.YES_OPTION)
{
if (JFileChooser.APPROVE_OPTION == fileChooser.showSaveDialog(workbenchContext.getLayerViewPanel()))
{
File file = fileChooser.getSelectedFile();
pathToSaveReadOnlySources = file.getParent() + "\\";
extToSaveReadOnlySources = "." + FileUtil.getExtension(file);
saveReadOnlySources = 1;
chosenSaveFile = file.getPath();
}
}
}
if (saveReadOnlySources == 0)
{
context.getWorkbenchFrame().getOutputFrame().addText(newLine + sCanNotSaveReadOnly + ": " + layer.getName());
writeWarning = true;
layerList.remove(i);
}
}
}
//remove any layers which have the same data source
//since we don't want to overwrite earlier layers with later layers
int currRec = 0;
int lastRec = layerList.size() - 1;
boolean writeHeader = true;
while (currRec < lastRec)
{
Layer currLayer = (Layer) layerList.get(currRec);
String currDestination = currLayer.getDataSourceQuery().getDataSource().getProperties().get("File").toString();
if (!currLayer.getDataSourceQuery().getDataSource().isWritable()) //read-only source
currDestination = pathToSaveReadOnlySources + currLayer.getName() + extToSaveReadOnlySources;
String dupLayers = "\n" + sFileName + ": " + currDestination + "\n" + sLayerName + ": " + currLayer.getName();
int numDups = 0;
int checkRec = currRec + 1;
while (checkRec <= lastRec)
{
Layer checkLayer = (Layer) layerList.get(checkRec);
String checkDestination = checkLayer.getDataSourceQuery().getDataSource().getProperties().get("File").toString();
if (!checkLayer.getDataSourceQuery().getDataSource().isWritable())
checkDestination = pathToSaveReadOnlySources + checkLayer.getName() + extToSaveReadOnlySources;
if (currDestination.equals(checkDestination)) //found duplicate source
{
dupLayers = dupLayers + "\n" + sLayerName + ": " + checkLayer.getName();
layerList.remove(checkRec);
lastRec--;
numDups++;
}
else
{
checkRec++;
}
}
if (numDups > 0)
{
if (writeHeader)
{
writeHeader = false;
writeWarning = true;
context.getWorkbenchFrame().getOutputFrame().addText(
"\n" + sDidNotSaveSameFile + ":");
newLine = "\n";
}
context.getWorkbenchFrame().getOutputFrame().addText(dupLayers);
layerList.remove(currRec);
lastRec--;
}
else
{
currRec++;
}
}
//check to see if we need to warn user that files are about to be replaced
String replacedFiles = "";
int numReplaced = 0;
boolean fileMatches = false;
for (int i = 0; i < layerList.size(); i++)
{
String destinationFile = "";
Layer layer = (Layer) layerList.get(i);
DataSourceQuery dsq = layer.getDataSourceQuery();
if (!dsq.getDataSource().isWritable())
{
destinationFile = pathToSaveReadOnlySources + layer.getName() + extToSaveReadOnlySources;
if (new File(destinationFile).exists())
{
numReplaced++;
replacedFiles = replacedFiles + sReadOnlyLayer + ": " + layer.getName() + " " + sReplacesFile + ": " + destinationFile + "\n";
if (destinationFile.equalsIgnoreCase(chosenSaveFile))
fileMatches = true;
}
}
}
if ((numReplaced > 1) || ((numReplaced == 1) && (!fileMatches))) //need to ask user if it is OK to replace files
{
String prompt = numReplaced + " " + sReadOnlyWillReplace + "\n (" + sNoteOutputWindow + ")";
if (numReplaced > 1)
prompt = numReplaced + " " + sReadOnlyWillReplace + "\n (" + sNoteOutputWindow + ")";
int response = JOptionPane.showConfirmDialog(workbenchContext.getLayerViewPanel(),
prompt, "JUMP", JOptionPane.OK_CANCEL_OPTION);
if (response == JOptionPane.CANCEL_OPTION)
{
if (numReplaced == 1)
context.getWorkbenchFrame().getOutputFrame().addText(sWouldHaveReplaced + ":");
else
context.getWorkbenchFrame().getOutputFrame().addText(sWouldHaveReplaced + ":");
context.getWorkbenchFrame().getOutputFrame().addText(replacedFiles);
writeWarning = true;
return true;
}
if (numReplaced == 1)
context.getWorkbenchFrame().getOutputFrame().addText(sHasReplaced + ":");
else
context.getWorkbenchFrame().getOutputFrame().addText(sHasReplaced + ":");
context.getWorkbenchFrame().getOutputFrame().addText(replacedFiles);
}
//save the files
//won't get here if user did not want files replaced
for (int i = 0; i < layerList.size(); i++)
{
Layer layer = (Layer) layerList.get(i);
if (WriteLayer(context, layer))
{
layer.setFeatureCollectionModified(false);
context.getWorkbenchFrame().getOutputFrame().addText(sSavedLayer + ": " + layer.getName());
}
else
{
context.getWorkbenchFrame().getOutputFrame().addText(sCouldNotSaveLayer + ": " + layer.getName());
}
}
if (saveAll)
{
if (context.getTask().getProjectFile() != null)
{
new SaveProjectPlugIn(new SaveProjectAsPlugIn()).execute(context);
context.getWorkbenchFrame().getOutputFrame().addText("\n " + sSavedTask +": " + context.getTask().getProjectFile().getName());
}
}
if (writeWarning)
context.getWorkbenchFrame().warnUser(sCouldNotSaveLayer + " --- " + sErrorSeeOutputWindow);
return true;
}
catch (Exception e)
{
context.getWorkbenchFrame().warnUser(sErrorSeeOutputWindow);
context.getWorkbenchFrame().getOutputFrame().addText("SaveDatasetsPlugIn Exception:" + e.toString());
return false;
}
}
public static MultiEnableCheck createEnableCheck(WorkbenchContext workbenchContext)
{
EnableCheckFactory checkFactory = new EnableCheckFactory(workbenchContext);
return new MultiEnableCheck()
.add(checkFactory.createWindowWithSelectionManagerMustBeActiveCheck())
.add(checkFactory.createAtLeastNLayersMustBeSelectedCheck(1));
}
public void setSaveAll()
{
saveAll = true;
}
private boolean WriteLayer(PlugInContext context, Layer layer)
{
String filename = "";
DataSourceQuery dsq = layer.getDataSourceQuery();
if (dsq.getDataSource().isWritable())
{
filename = dsq.getDataSource().getProperties().get("File").toString();
}
else //read-only source
{
filename = pathToSaveReadOnlySources + layer.getName() + extToSaveReadOnlySources;
//the following shouldn't happen
if (pathToSaveReadOnlySources.equals(""))
{
context.getWorkbenchFrame().getOutputFrame().addText(sNoOutputDir + ": " + layer.getName());
context.getWorkbenchFrame().warnUser(sWarningSeeOutputWindow);
return false;
}
if (extToSaveReadOnlySources.equals(""))
{
context.getWorkbenchFrame().getOutputFrame().addText(sNoOutputFileExt + ": " + layer.getName());
context.getWorkbenchFrame().warnUser(sWarningSeeOutputWindow);
return false;
}
}
DriverProperties dp = new DriverProperties();
dp.set("File", filename);
try
{
if ((filename.toLowerCase()).endsWith(".shp"))
{
String path = new File(filename).getParent() + "\\";
List newLayers = new ArrayList();
if (!CompatibleFeatures(layer))
newLayers = splitLayer(context, layer);
(new ShapefileWriter()).write(layer.getFeatureCollectionWrapper(), dp);
for (int i = 0; i < newLayers.size(); i++)
{
Layer newLayer = (Layer) newLayers.get(i);
String newFileName = path + newLayer.getName() + ".shp";
HashMap properties = new HashMap();
properties.put(DataSource.COORDINATE_SYSTEM_KEY, "Unspecified");
properties.put(DataSource.FILE_KEY, newFileName);
DataSource dataSource = (DataSource) StandardReaderWriterFileDataSource.Shapefile.class.newInstance();
dataSource.setProperties(properties);
DataSourceQuery dataSourceQuery = new DataSourceQuery(dataSource, newLayer.getName(), null);
newLayer.setDataSourceQuery(dataSourceQuery).setFeatureCollectionModified(false);
dp.set("File", newFileName);
(new ShapefileWriter()).write(newLayer.getFeatureCollectionWrapper(), dp);
context.getWorkbenchFrame().getOutputFrame().addText(sSavedLayer + ": " + newLayer.getName());
}
return true;
}
if ((filename.toLowerCase()).endsWith(".jml"))
{
(new JMLWriter()).write(layer.getFeatureCollectionWrapper(), dp);
return true;
}
if ((filename.toLowerCase()).endsWith(".gml"))
{
(new GMLWriter()).write(layer.getFeatureCollectionWrapper(), dp);
return true;
}
if ((filename.toLowerCase()).endsWith(".fme"))
{
(new FMEGMLWriter()).write(layer.getFeatureCollectionWrapper(), dp);
return true;
}
if ((filename.toLowerCase()).endsWith(".wkt"))
{
(new WKTWriter()).write(layer.getFeatureCollectionWrapper(), dp);
return true;
}
context.getWorkbenchFrame().getOutputFrame().addText( sUnrecognizedFileType + " --- " + sCouldNotSaveLayer + ": " + layer.getName());
context.getWorkbenchFrame().warnUser(sErrorSeeOutputWindow);
return false;
}
catch (Exception e)
{
context.getWorkbenchFrame().warnUser(sErrorSeeOutputWindow);
context.getWorkbenchFrame().getOutputFrame().createNewDocument();
context.getWorkbenchFrame().getOutputFrame().addText("SaveDatasetsPlugIn:WriteLayer Exception:" + e.toString());
return false;
}
}
private boolean CompatibleFeatures(Layer layer)
{
BitSet bitSet = new BitSet();
FeatureCollectionWrapper featureCollection = layer.getFeatureCollectionWrapper();
List featureList = featureCollection.getFeatures();
for (Iterator i = featureList.iterator(); i.hasNext();)
bitSet = GeoUtils.setBit(bitSet, ((Feature) i.next()).getGeometry());
return (bitSet.cardinality() < 2);
}
private List splitLayer(PlugInContext context, Layer layer)
{
ArrayList newLayers = new ArrayList();
if (!CompatibleFeatures(layer))
{
ArrayList emptyFeatures = new ArrayList();
ArrayList pointFeatures = new ArrayList();
ArrayList lineFeatures = new ArrayList();
ArrayList polyFeatures = new ArrayList();
ArrayList groupFeatures = new ArrayList();
FeatureCollectionWrapper featureCollection = layer.getFeatureCollectionWrapper();
List featureList = featureCollection.getFeatures();
FeatureSchema featureSchema = layer.getFeatureCollectionWrapper().getFeatureSchema();
//first find and handle all empty geometries and GeometryCollections
for (Iterator i = featureList.iterator(); i.hasNext();)
{
Feature feature = (Feature) i.next();
Geometry geometry = feature.getGeometry();
if (geometry.isEmpty()) //going to delete it
emptyFeatures.add(feature);
else if ((geometry instanceof GeometryCollection) &&
(!(geometry instanceof MultiPoint)) &&
(!(geometry instanceof MultiLineString)) &&
(!(geometry instanceof MultiPolygon))) //mixed geometry; going to explode it
groupFeatures.add(feature);
}
for (int i = 0; i < emptyFeatures.size(); i++) //delete empty geometries
{
featureCollection.remove((Feature) emptyFeatures.get(i));
}
for (int i = 0; i < groupFeatures.size(); i++) //delete GeometryCollections
{
Feature feature = (Feature) groupFeatures.get(i);
GeometryCollection geometry = (GeometryCollection) feature.getGeometry();
explodeGeometryCollection(featureSchema, pointFeatures, lineFeatures, polyFeatures, geometry, feature);
featureCollection.remove(feature);
}
//now get new list of remaining features
featureCollection = layer.getFeatureCollectionWrapper();
featureList = layer.getFeatureCollectionWrapper().getFeatures();
BitSet layerBit = new BitSet();
if (featureList.size() > 0)
{
Geometry firstGeo = ((Feature) featureList.iterator().next()).getGeometry();
layerBit = GeoUtils.setBit(layerBit, firstGeo); //this is the layer type
}
//now add just the exploded features that belong on the the original layer
if (layerBit.get(GeoUtils.polyBit))
{
if (polyFeatures.size() > 0)
{
for (int i = 0; i < polyFeatures.size(); i++)
{
Feature feature = (Feature) polyFeatures.get(i);
featureCollection.add(feature);
}
polyFeatures.clear();
}
}
else if (layerBit.get(GeoUtils.lineBit))
{
if (lineFeatures.size() > 0)
{
for (int i = 0; i < lineFeatures.size(); i++)
{
Feature feature = (Feature) lineFeatures.get(i);
featureCollection.add(feature);
}
lineFeatures.clear();
}
}
else if (layerBit.get(GeoUtils.pointBit))
{
if (pointFeatures.size() > 0)
{
for (int i = 0; i < pointFeatures.size(); i++)
{
Feature feature = (Feature) pointFeatures.get(i);
featureCollection.add(feature);
}
pointFeatures.clear();
}
}
else //nothing left on layer; just pick a type for the layer
{
if (polyFeatures.size() > 0)
{
for (int i = 0; i < polyFeatures.size(); i++)
{
Feature feature = (Feature) polyFeatures.get(i);
featureCollection.add(feature);
}
polyFeatures.clear();
}
else if (lineFeatures.size() > 0)
{
for (int i = 0; i < lineFeatures.size(); i++)
{
Feature feature = (Feature) lineFeatures.get(i);
featureCollection.add(feature);
}
lineFeatures.clear();
}
else if (pointFeatures.size() > 0)
{
for (int i = 0; i < pointFeatures.size(); i++)
{
Feature feature = (Feature) pointFeatures.get(i);
featureCollection.add(feature);
}
pointFeatures.clear();
}
}
//at this point we have taken care of the GeometryCollections
//some part of them have been added to the original layer
//the rest of the features are in the array lists waiting
//to be added to the appropriate layers
featureCollection = layer.getFeatureCollectionWrapper();
featureList = layer.getFeatureCollectionWrapper().getFeatures();
layerBit = new BitSet();
if (featureList.size() > 0)
{
Geometry firstGeo = ((Feature) featureList.iterator().next()).getGeometry();
layerBit = GeoUtils.setBit(layerBit, firstGeo); //this is the layer type
}
Collection selectedCategories = context.getLayerNamePanel().getSelectedCategories();
for (Iterator i = featureList.iterator(); i.hasNext();)
{
Feature feature = (Feature) i.next();
Geometry geo = feature.getGeometry();
BitSet currFeatureBit = new BitSet();
currFeatureBit = GeoUtils.setBit(currFeatureBit, geo);
if (!layerBit.get(GeoUtils.pointBit) && currFeatureBit.get(GeoUtils.pointBit))
pointFeatures.add(feature);
if (!layerBit.get(GeoUtils.lineBit) && currFeatureBit.get(GeoUtils.lineBit))
lineFeatures.add(feature);
if (!layerBit.get(GeoUtils.polyBit) && currFeatureBit.get(GeoUtils.polyBit))
polyFeatures.add(feature);
}
if (pointFeatures.size() > 0)
{
Layer pointLayer = context.addLayer(selectedCategories.isEmpty()
? StandardCategoryNames.WORKING
: selectedCategories.iterator().next().toString(), layer.getName() + "_point",
new FeatureDataset(featureSchema));
FeatureCollectionWrapper pointFeatureCollection = pointLayer.getFeatureCollectionWrapper();
newLayers.add(pointLayer);
context.getWorkbenchFrame().getOutputFrame().addText(sNewLayerCreated + ": " + pointLayer.getName());
- context.getWorkbenchFrame().warnUser(sNewLayerCreated + " - " + sErrorSeeOutputWindow);
+ context.getWorkbenchFrame().warnUser(sNewLayerCreated + " - " + sWarningSeeOutputWindow);
for (int i = 0; i < pointFeatures.size(); i++)
{
Feature feature = (Feature) pointFeatures.get(i);
featureCollection.remove(feature);
pointFeatureCollection.add(feature);
}
}
if (lineFeatures.size() > 0)
{
Layer lineLayer = context.addLayer(selectedCategories.isEmpty()
? StandardCategoryNames.WORKING
: selectedCategories.iterator().next().toString(), layer.getName() + "_line",
new FeatureDataset(featureSchema));
FeatureCollectionWrapper lineFeatureCollection = lineLayer.getFeatureCollectionWrapper();
newLayers.add(lineLayer);
context.getWorkbenchFrame().getOutputFrame().addText(sNewLayerCreated + ": " + lineLayer.getName());
context.getWorkbenchFrame().warnUser(sNewLayerCreated + " - " + sErrorSeeOutputWindow);
for (int i = 0; i < lineFeatures.size(); i++)
{
Feature feature = (Feature) lineFeatures.get(i);
featureCollection.remove(feature);
lineFeatureCollection.add(feature);
}
}
if (polyFeatures.size() > 0)
{
Layer polyLayer = context.addLayer(selectedCategories.isEmpty()
? StandardCategoryNames.WORKING
: selectedCategories.iterator().next().toString(), layer.getName() + "_area",
new FeatureDataset(featureSchema));
FeatureCollectionWrapper polyFeatureCollection = polyLayer.getFeatureCollectionWrapper();
newLayers.add(polyLayer);
context.getWorkbenchFrame().getOutputFrame().addText(sNewLayerCreated + ": " + polyLayer.getName());
context.getWorkbenchFrame().warnUser(sNewLayerCreated + " - " + sErrorSeeOutputWindow);
for (int i = 0; i < polyFeatures.size(); i++)
{
Feature feature = (Feature) polyFeatures.get(i);
featureCollection.remove(feature);
polyFeatureCollection.add(feature);
}
}
}
return newLayers;
}
private void explodeGeometryCollection(FeatureSchema fs, ArrayList pointFeatures, ArrayList lineFeatures, ArrayList polyFeatures, GeometryCollection geometryCollection, Feature feature)
{
for (int i = 0; i < geometryCollection.getNumGeometries(); i++)
{
Geometry geometry = geometryCollection.getGeometryN(i);
if (geometry instanceof GeometryCollection)
{
explodeGeometryCollection(fs, pointFeatures, lineFeatures, polyFeatures, (GeometryCollection) geometry, feature);
}
else
{
//Feature newFeature = new BasicFeature(fs);
Feature newFeature = feature.clone(true);
newFeature.setGeometry(geometry);
BitSet featureBit = new BitSet();
featureBit = GeoUtils.setBit(featureBit, geometry);
if (featureBit.get(GeoUtils.pointBit)) pointFeatures.add(newFeature);
if (featureBit.get(GeoUtils.lineBit)) lineFeatures.add(newFeature);
if (featureBit.get(GeoUtils.polyBit)) polyFeatures.add(newFeature);
}
}
}
private void writeProjectionFile(PlugInContext context, Layer outputLayer)throws IOException, FileNotFoundException
{ //per LDB projection files only associated with .shp files; confirmed 8/16/05
DataSourceQuery dsqOut = outputLayer.getDataSourceQuery();
if (dsqOut != null) //file exists; not a new layer
{
String outputFileName = dsqOut.getDataSource().getProperties().get("File").toString();
if ((outputFileName.toLowerCase()).endsWith(".shp"))
{
String outputPrjFileName = "";
int pos = outputFileName.lastIndexOf('.');
outputPrjFileName = outputFileName.substring(0, pos) + ".prj";
if (!(new File(outputPrjFileName).exists()))
{ //loop through all layers to find a project file; then copy contents
List layerList = context.getLayerManager().getLayers();
for (Iterator i = layerList.iterator(); i.hasNext();)
{
Layer layer = (Layer) i.next();
DataSourceQuery dsq = layer.getDataSourceQuery();
if (dsq != null)
{
String inputFileName = dsq.getDataSource().getProperties().get("File").toString();
if ((inputFileName.toLowerCase()).endsWith(".shp"))
{
String inputPrjFileName = "";
pos = inputFileName.lastIndexOf('.');
inputPrjFileName = inputFileName.substring(0, pos) + ".prj";
if (new File(inputPrjFileName).exists())
{
List prjStr = FileUtil.getContents(inputPrjFileName);
try
{
FileUtil.setContents(outputPrjFileName, prjStr);
}
catch (IOException ex)
{
context.getWorkbenchFrame().getOutputFrame().addText(sCouldNotWrite + ": " + outputPrjFileName + " --- " + ex.getMessage());
}
break;
}
}
}
}
}
}
}
}
}
| true | true | private List splitLayer(PlugInContext context, Layer layer)
{
ArrayList newLayers = new ArrayList();
if (!CompatibleFeatures(layer))
{
ArrayList emptyFeatures = new ArrayList();
ArrayList pointFeatures = new ArrayList();
ArrayList lineFeatures = new ArrayList();
ArrayList polyFeatures = new ArrayList();
ArrayList groupFeatures = new ArrayList();
FeatureCollectionWrapper featureCollection = layer.getFeatureCollectionWrapper();
List featureList = featureCollection.getFeatures();
FeatureSchema featureSchema = layer.getFeatureCollectionWrapper().getFeatureSchema();
//first find and handle all empty geometries and GeometryCollections
for (Iterator i = featureList.iterator(); i.hasNext();)
{
Feature feature = (Feature) i.next();
Geometry geometry = feature.getGeometry();
if (geometry.isEmpty()) //going to delete it
emptyFeatures.add(feature);
else if ((geometry instanceof GeometryCollection) &&
(!(geometry instanceof MultiPoint)) &&
(!(geometry instanceof MultiLineString)) &&
(!(geometry instanceof MultiPolygon))) //mixed geometry; going to explode it
groupFeatures.add(feature);
}
for (int i = 0; i < emptyFeatures.size(); i++) //delete empty geometries
{
featureCollection.remove((Feature) emptyFeatures.get(i));
}
for (int i = 0; i < groupFeatures.size(); i++) //delete GeometryCollections
{
Feature feature = (Feature) groupFeatures.get(i);
GeometryCollection geometry = (GeometryCollection) feature.getGeometry();
explodeGeometryCollection(featureSchema, pointFeatures, lineFeatures, polyFeatures, geometry, feature);
featureCollection.remove(feature);
}
//now get new list of remaining features
featureCollection = layer.getFeatureCollectionWrapper();
featureList = layer.getFeatureCollectionWrapper().getFeatures();
BitSet layerBit = new BitSet();
if (featureList.size() > 0)
{
Geometry firstGeo = ((Feature) featureList.iterator().next()).getGeometry();
layerBit = GeoUtils.setBit(layerBit, firstGeo); //this is the layer type
}
//now add just the exploded features that belong on the the original layer
if (layerBit.get(GeoUtils.polyBit))
{
if (polyFeatures.size() > 0)
{
for (int i = 0; i < polyFeatures.size(); i++)
{
Feature feature = (Feature) polyFeatures.get(i);
featureCollection.add(feature);
}
polyFeatures.clear();
}
}
else if (layerBit.get(GeoUtils.lineBit))
{
if (lineFeatures.size() > 0)
{
for (int i = 0; i < lineFeatures.size(); i++)
{
Feature feature = (Feature) lineFeatures.get(i);
featureCollection.add(feature);
}
lineFeatures.clear();
}
}
else if (layerBit.get(GeoUtils.pointBit))
{
if (pointFeatures.size() > 0)
{
for (int i = 0; i < pointFeatures.size(); i++)
{
Feature feature = (Feature) pointFeatures.get(i);
featureCollection.add(feature);
}
pointFeatures.clear();
}
}
else //nothing left on layer; just pick a type for the layer
{
if (polyFeatures.size() > 0)
{
for (int i = 0; i < polyFeatures.size(); i++)
{
Feature feature = (Feature) polyFeatures.get(i);
featureCollection.add(feature);
}
polyFeatures.clear();
}
else if (lineFeatures.size() > 0)
{
for (int i = 0; i < lineFeatures.size(); i++)
{
Feature feature = (Feature) lineFeatures.get(i);
featureCollection.add(feature);
}
lineFeatures.clear();
}
else if (pointFeatures.size() > 0)
{
for (int i = 0; i < pointFeatures.size(); i++)
{
Feature feature = (Feature) pointFeatures.get(i);
featureCollection.add(feature);
}
pointFeatures.clear();
}
}
//at this point we have taken care of the GeometryCollections
//some part of them have been added to the original layer
//the rest of the features are in the array lists waiting
//to be added to the appropriate layers
featureCollection = layer.getFeatureCollectionWrapper();
featureList = layer.getFeatureCollectionWrapper().getFeatures();
layerBit = new BitSet();
if (featureList.size() > 0)
{
Geometry firstGeo = ((Feature) featureList.iterator().next()).getGeometry();
layerBit = GeoUtils.setBit(layerBit, firstGeo); //this is the layer type
}
Collection selectedCategories = context.getLayerNamePanel().getSelectedCategories();
for (Iterator i = featureList.iterator(); i.hasNext();)
{
Feature feature = (Feature) i.next();
Geometry geo = feature.getGeometry();
BitSet currFeatureBit = new BitSet();
currFeatureBit = GeoUtils.setBit(currFeatureBit, geo);
if (!layerBit.get(GeoUtils.pointBit) && currFeatureBit.get(GeoUtils.pointBit))
pointFeatures.add(feature);
if (!layerBit.get(GeoUtils.lineBit) && currFeatureBit.get(GeoUtils.lineBit))
lineFeatures.add(feature);
if (!layerBit.get(GeoUtils.polyBit) && currFeatureBit.get(GeoUtils.polyBit))
polyFeatures.add(feature);
}
if (pointFeatures.size() > 0)
{
Layer pointLayer = context.addLayer(selectedCategories.isEmpty()
? StandardCategoryNames.WORKING
: selectedCategories.iterator().next().toString(), layer.getName() + "_point",
new FeatureDataset(featureSchema));
FeatureCollectionWrapper pointFeatureCollection = pointLayer.getFeatureCollectionWrapper();
newLayers.add(pointLayer);
context.getWorkbenchFrame().getOutputFrame().addText(sNewLayerCreated + ": " + pointLayer.getName());
context.getWorkbenchFrame().warnUser(sNewLayerCreated + " - " + sErrorSeeOutputWindow);
for (int i = 0; i < pointFeatures.size(); i++)
{
Feature feature = (Feature) pointFeatures.get(i);
featureCollection.remove(feature);
pointFeatureCollection.add(feature);
}
}
if (lineFeatures.size() > 0)
{
Layer lineLayer = context.addLayer(selectedCategories.isEmpty()
? StandardCategoryNames.WORKING
: selectedCategories.iterator().next().toString(), layer.getName() + "_line",
new FeatureDataset(featureSchema));
FeatureCollectionWrapper lineFeatureCollection = lineLayer.getFeatureCollectionWrapper();
newLayers.add(lineLayer);
context.getWorkbenchFrame().getOutputFrame().addText(sNewLayerCreated + ": " + lineLayer.getName());
context.getWorkbenchFrame().warnUser(sNewLayerCreated + " - " + sErrorSeeOutputWindow);
for (int i = 0; i < lineFeatures.size(); i++)
{
Feature feature = (Feature) lineFeatures.get(i);
featureCollection.remove(feature);
lineFeatureCollection.add(feature);
}
}
if (polyFeatures.size() > 0)
{
Layer polyLayer = context.addLayer(selectedCategories.isEmpty()
? StandardCategoryNames.WORKING
: selectedCategories.iterator().next().toString(), layer.getName() + "_area",
new FeatureDataset(featureSchema));
FeatureCollectionWrapper polyFeatureCollection = polyLayer.getFeatureCollectionWrapper();
newLayers.add(polyLayer);
context.getWorkbenchFrame().getOutputFrame().addText(sNewLayerCreated + ": " + polyLayer.getName());
context.getWorkbenchFrame().warnUser(sNewLayerCreated + " - " + sErrorSeeOutputWindow);
for (int i = 0; i < polyFeatures.size(); i++)
{
Feature feature = (Feature) polyFeatures.get(i);
featureCollection.remove(feature);
polyFeatureCollection.add(feature);
}
}
}
return newLayers;
}
| private List splitLayer(PlugInContext context, Layer layer)
{
ArrayList newLayers = new ArrayList();
if (!CompatibleFeatures(layer))
{
ArrayList emptyFeatures = new ArrayList();
ArrayList pointFeatures = new ArrayList();
ArrayList lineFeatures = new ArrayList();
ArrayList polyFeatures = new ArrayList();
ArrayList groupFeatures = new ArrayList();
FeatureCollectionWrapper featureCollection = layer.getFeatureCollectionWrapper();
List featureList = featureCollection.getFeatures();
FeatureSchema featureSchema = layer.getFeatureCollectionWrapper().getFeatureSchema();
//first find and handle all empty geometries and GeometryCollections
for (Iterator i = featureList.iterator(); i.hasNext();)
{
Feature feature = (Feature) i.next();
Geometry geometry = feature.getGeometry();
if (geometry.isEmpty()) //going to delete it
emptyFeatures.add(feature);
else if ((geometry instanceof GeometryCollection) &&
(!(geometry instanceof MultiPoint)) &&
(!(geometry instanceof MultiLineString)) &&
(!(geometry instanceof MultiPolygon))) //mixed geometry; going to explode it
groupFeatures.add(feature);
}
for (int i = 0; i < emptyFeatures.size(); i++) //delete empty geometries
{
featureCollection.remove((Feature) emptyFeatures.get(i));
}
for (int i = 0; i < groupFeatures.size(); i++) //delete GeometryCollections
{
Feature feature = (Feature) groupFeatures.get(i);
GeometryCollection geometry = (GeometryCollection) feature.getGeometry();
explodeGeometryCollection(featureSchema, pointFeatures, lineFeatures, polyFeatures, geometry, feature);
featureCollection.remove(feature);
}
//now get new list of remaining features
featureCollection = layer.getFeatureCollectionWrapper();
featureList = layer.getFeatureCollectionWrapper().getFeatures();
BitSet layerBit = new BitSet();
if (featureList.size() > 0)
{
Geometry firstGeo = ((Feature) featureList.iterator().next()).getGeometry();
layerBit = GeoUtils.setBit(layerBit, firstGeo); //this is the layer type
}
//now add just the exploded features that belong on the the original layer
if (layerBit.get(GeoUtils.polyBit))
{
if (polyFeatures.size() > 0)
{
for (int i = 0; i < polyFeatures.size(); i++)
{
Feature feature = (Feature) polyFeatures.get(i);
featureCollection.add(feature);
}
polyFeatures.clear();
}
}
else if (layerBit.get(GeoUtils.lineBit))
{
if (lineFeatures.size() > 0)
{
for (int i = 0; i < lineFeatures.size(); i++)
{
Feature feature = (Feature) lineFeatures.get(i);
featureCollection.add(feature);
}
lineFeatures.clear();
}
}
else if (layerBit.get(GeoUtils.pointBit))
{
if (pointFeatures.size() > 0)
{
for (int i = 0; i < pointFeatures.size(); i++)
{
Feature feature = (Feature) pointFeatures.get(i);
featureCollection.add(feature);
}
pointFeatures.clear();
}
}
else //nothing left on layer; just pick a type for the layer
{
if (polyFeatures.size() > 0)
{
for (int i = 0; i < polyFeatures.size(); i++)
{
Feature feature = (Feature) polyFeatures.get(i);
featureCollection.add(feature);
}
polyFeatures.clear();
}
else if (lineFeatures.size() > 0)
{
for (int i = 0; i < lineFeatures.size(); i++)
{
Feature feature = (Feature) lineFeatures.get(i);
featureCollection.add(feature);
}
lineFeatures.clear();
}
else if (pointFeatures.size() > 0)
{
for (int i = 0; i < pointFeatures.size(); i++)
{
Feature feature = (Feature) pointFeatures.get(i);
featureCollection.add(feature);
}
pointFeatures.clear();
}
}
//at this point we have taken care of the GeometryCollections
//some part of them have been added to the original layer
//the rest of the features are in the array lists waiting
//to be added to the appropriate layers
featureCollection = layer.getFeatureCollectionWrapper();
featureList = layer.getFeatureCollectionWrapper().getFeatures();
layerBit = new BitSet();
if (featureList.size() > 0)
{
Geometry firstGeo = ((Feature) featureList.iterator().next()).getGeometry();
layerBit = GeoUtils.setBit(layerBit, firstGeo); //this is the layer type
}
Collection selectedCategories = context.getLayerNamePanel().getSelectedCategories();
for (Iterator i = featureList.iterator(); i.hasNext();)
{
Feature feature = (Feature) i.next();
Geometry geo = feature.getGeometry();
BitSet currFeatureBit = new BitSet();
currFeatureBit = GeoUtils.setBit(currFeatureBit, geo);
if (!layerBit.get(GeoUtils.pointBit) && currFeatureBit.get(GeoUtils.pointBit))
pointFeatures.add(feature);
if (!layerBit.get(GeoUtils.lineBit) && currFeatureBit.get(GeoUtils.lineBit))
lineFeatures.add(feature);
if (!layerBit.get(GeoUtils.polyBit) && currFeatureBit.get(GeoUtils.polyBit))
polyFeatures.add(feature);
}
if (pointFeatures.size() > 0)
{
Layer pointLayer = context.addLayer(selectedCategories.isEmpty()
? StandardCategoryNames.WORKING
: selectedCategories.iterator().next().toString(), layer.getName() + "_point",
new FeatureDataset(featureSchema));
FeatureCollectionWrapper pointFeatureCollection = pointLayer.getFeatureCollectionWrapper();
newLayers.add(pointLayer);
context.getWorkbenchFrame().getOutputFrame().addText(sNewLayerCreated + ": " + pointLayer.getName());
context.getWorkbenchFrame().warnUser(sNewLayerCreated + " - " + sWarningSeeOutputWindow);
for (int i = 0; i < pointFeatures.size(); i++)
{
Feature feature = (Feature) pointFeatures.get(i);
featureCollection.remove(feature);
pointFeatureCollection.add(feature);
}
}
if (lineFeatures.size() > 0)
{
Layer lineLayer = context.addLayer(selectedCategories.isEmpty()
? StandardCategoryNames.WORKING
: selectedCategories.iterator().next().toString(), layer.getName() + "_line",
new FeatureDataset(featureSchema));
FeatureCollectionWrapper lineFeatureCollection = lineLayer.getFeatureCollectionWrapper();
newLayers.add(lineLayer);
context.getWorkbenchFrame().getOutputFrame().addText(sNewLayerCreated + ": " + lineLayer.getName());
context.getWorkbenchFrame().warnUser(sNewLayerCreated + " - " + sErrorSeeOutputWindow);
for (int i = 0; i < lineFeatures.size(); i++)
{
Feature feature = (Feature) lineFeatures.get(i);
featureCollection.remove(feature);
lineFeatureCollection.add(feature);
}
}
if (polyFeatures.size() > 0)
{
Layer polyLayer = context.addLayer(selectedCategories.isEmpty()
? StandardCategoryNames.WORKING
: selectedCategories.iterator().next().toString(), layer.getName() + "_area",
new FeatureDataset(featureSchema));
FeatureCollectionWrapper polyFeatureCollection = polyLayer.getFeatureCollectionWrapper();
newLayers.add(polyLayer);
context.getWorkbenchFrame().getOutputFrame().addText(sNewLayerCreated + ": " + polyLayer.getName());
context.getWorkbenchFrame().warnUser(sNewLayerCreated + " - " + sErrorSeeOutputWindow);
for (int i = 0; i < polyFeatures.size(); i++)
{
Feature feature = (Feature) polyFeatures.get(i);
featureCollection.remove(feature);
polyFeatureCollection.add(feature);
}
}
}
return newLayers;
}
|
diff --git a/parser/org/eclipse/cdt/core/dom/parser/GNUScannerExtensionConfiguration.java b/parser/org/eclipse/cdt/core/dom/parser/GNUScannerExtensionConfiguration.java
index 9a97e0da0..f1b0757f6 100644
--- a/parser/org/eclipse/cdt/core/dom/parser/GNUScannerExtensionConfiguration.java
+++ b/parser/org/eclipse/cdt/core/dom/parser/GNUScannerExtensionConfiguration.java
@@ -1,108 +1,108 @@
/*******************************************************************************
* Copyright (c) 2004, 2009 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM - Initial API and implementation
* Anton Leherbauer (Wind River Systems)
* Markus Schorn (Wind River Systems)
* Sergey Prigogin (Google)
*******************************************************************************/
package org.eclipse.cdt.core.dom.parser;
import org.eclipse.cdt.core.parser.GCCKeywords;
import org.eclipse.cdt.core.parser.IGCCToken;
import org.eclipse.cdt.core.parser.IMacro;
import org.eclipse.cdt.core.parser.IPreprocessorDirective;
import org.eclipse.cdt.core.parser.IToken;
import org.eclipse.cdt.core.parser.Keywords;
import org.eclipse.cdt.core.parser.util.CharArrayIntMap;
/**
* Base class for all gnu scanner configurations. Provides gnu-specific macros and keywords.
* @since 5.0
*/
public abstract class GNUScannerExtensionConfiguration extends AbstractScannerExtensionConfiguration {
private static GNUScannerExtensionConfiguration sInstance;
@SuppressWarnings("nls")
public GNUScannerExtensionConfiguration() {
addMacro("__complex__", "_Complex");
addMacro("__extension__", "");
addMacro("__imag__", "(int)");
addMacro("__real__", "(int)");
addMacro("__stdcall", "");
addMacro("__thread", "");
addMacro("__builtin_va_arg(ap,type)", "*(typeof(type) *)ap");
addMacro("__builtin_constant_p(exp)", "0");
addMacro("__builtin_types_compatible_p(x,y)", "__builtin_types_compatible_p(sizeof(x),sizeof(y))");
addMacro("__offsetof__(x)", "(x)");
addPreprocessorKeyword(Keywords.cINCLUDE_NEXT, IPreprocessorDirective.ppInclude_next);
addPreprocessorKeyword(Keywords.cIMPORT, IPreprocessorDirective.ppImport);
addPreprocessorKeyword(Keywords.cWARNING, IPreprocessorDirective.ppWarning);
addPreprocessorKeyword(Keywords.cIDENT, IPreprocessorDirective.ppIgnore);
addPreprocessorKeyword(Keywords.cSCCS, IPreprocessorDirective.ppIgnore);
addPreprocessorKeyword(Keywords.cASSERT, IPreprocessorDirective.ppIgnore);
addPreprocessorKeyword(Keywords.cUNASSERT, IPreprocessorDirective.ppIgnore);
- addKeyword(GCCKeywords.cp__ALIGNOF__, IGCCToken.t___alignof__ );
+ addKeyword(GCCKeywords.cp__ALIGNOF, IGCCToken.t___alignof__ );
addKeyword(GCCKeywords.cp__ALIGNOF__, IGCCToken.t___alignof__ );
addKeyword(GCCKeywords.cp__ASM, IToken.t_asm);
addKeyword(GCCKeywords.cp__ASM__, IToken.t_asm);
addKeyword(GCCKeywords.cp__ATTRIBUTE, IGCCToken.t__attribute__ );
addKeyword(GCCKeywords.cp__ATTRIBUTE__, IGCCToken.t__attribute__ );
addKeyword(GCCKeywords.cp__CONST, IToken.t_const);
addKeyword(GCCKeywords.cp__CONST__, IToken.t_const);
addKeyword(GCCKeywords.cp__DECLSPEC, IGCCToken.t__declspec );
addKeyword(GCCKeywords.cp__INLINE, IToken.t_inline);
addKeyword(GCCKeywords.cp__INLINE__, IToken.t_inline);
addKeyword(GCCKeywords.cp__RESTRICT, IToken.t_restrict);
addKeyword(GCCKeywords.cp__RESTRICT__, IToken.t_restrict);
addKeyword(GCCKeywords.cp__VOLATILE, IToken.t_volatile);
addKeyword(GCCKeywords.cp__VOLATILE__, IToken.t_volatile);
addKeyword(GCCKeywords.cp__SIGNED, IToken.t_signed);
addKeyword(GCCKeywords.cp__SIGNED__, IToken.t_signed);
addKeyword(GCCKeywords.cp__TYPEOF, IGCCToken.t_typeof);
addKeyword(GCCKeywords.cp__TYPEOF__, IGCCToken.t_typeof);
addKeyword(GCCKeywords.cpTYPEOF, IGCCToken.t_typeof );
}
@Override
public boolean support$InIdentifiers() {
return true;
}
@Override
public char[] supportAdditionalNumericLiteralSuffixes() {
return "ij".toCharArray(); //$NON-NLS-1$
}
/**
* @deprecated simply derive from this class and use {@link #addMacro(String, String)} to
* add additional macros.
*/
@Deprecated
public static IMacro[] getAdditionalGNUMacros() {
if (sInstance == null) {
sInstance= new GNUScannerExtensionConfiguration() {};
}
return sInstance.getAdditionalMacros();
}
/**
* @deprecated simply derive from this class and use {@link #addKeyword(char[], int)} to
* add additional keywords.
*/
@Deprecated
public static void addAdditionalGNUKeywords(CharArrayIntMap target) {
if (sInstance == null) {
sInstance= new GNUScannerExtensionConfiguration() {};
}
target.putAll(sInstance.getAdditionalKeywords());
}
}
| true | true | public GNUScannerExtensionConfiguration() {
addMacro("__complex__", "_Complex");
addMacro("__extension__", "");
addMacro("__imag__", "(int)");
addMacro("__real__", "(int)");
addMacro("__stdcall", "");
addMacro("__thread", "");
addMacro("__builtin_va_arg(ap,type)", "*(typeof(type) *)ap");
addMacro("__builtin_constant_p(exp)", "0");
addMacro("__builtin_types_compatible_p(x,y)", "__builtin_types_compatible_p(sizeof(x),sizeof(y))");
addMacro("__offsetof__(x)", "(x)");
addPreprocessorKeyword(Keywords.cINCLUDE_NEXT, IPreprocessorDirective.ppInclude_next);
addPreprocessorKeyword(Keywords.cIMPORT, IPreprocessorDirective.ppImport);
addPreprocessorKeyword(Keywords.cWARNING, IPreprocessorDirective.ppWarning);
addPreprocessorKeyword(Keywords.cIDENT, IPreprocessorDirective.ppIgnore);
addPreprocessorKeyword(Keywords.cSCCS, IPreprocessorDirective.ppIgnore);
addPreprocessorKeyword(Keywords.cASSERT, IPreprocessorDirective.ppIgnore);
addPreprocessorKeyword(Keywords.cUNASSERT, IPreprocessorDirective.ppIgnore);
addKeyword(GCCKeywords.cp__ALIGNOF__, IGCCToken.t___alignof__ );
addKeyword(GCCKeywords.cp__ALIGNOF__, IGCCToken.t___alignof__ );
addKeyword(GCCKeywords.cp__ASM, IToken.t_asm);
addKeyword(GCCKeywords.cp__ASM__, IToken.t_asm);
addKeyword(GCCKeywords.cp__ATTRIBUTE, IGCCToken.t__attribute__ );
addKeyword(GCCKeywords.cp__ATTRIBUTE__, IGCCToken.t__attribute__ );
addKeyword(GCCKeywords.cp__CONST, IToken.t_const);
addKeyword(GCCKeywords.cp__CONST__, IToken.t_const);
addKeyword(GCCKeywords.cp__DECLSPEC, IGCCToken.t__declspec );
addKeyword(GCCKeywords.cp__INLINE, IToken.t_inline);
addKeyword(GCCKeywords.cp__INLINE__, IToken.t_inline);
addKeyword(GCCKeywords.cp__RESTRICT, IToken.t_restrict);
addKeyword(GCCKeywords.cp__RESTRICT__, IToken.t_restrict);
addKeyword(GCCKeywords.cp__VOLATILE, IToken.t_volatile);
addKeyword(GCCKeywords.cp__VOLATILE__, IToken.t_volatile);
addKeyword(GCCKeywords.cp__SIGNED, IToken.t_signed);
addKeyword(GCCKeywords.cp__SIGNED__, IToken.t_signed);
addKeyword(GCCKeywords.cp__TYPEOF, IGCCToken.t_typeof);
addKeyword(GCCKeywords.cp__TYPEOF__, IGCCToken.t_typeof);
addKeyword(GCCKeywords.cpTYPEOF, IGCCToken.t_typeof );
}
| public GNUScannerExtensionConfiguration() {
addMacro("__complex__", "_Complex");
addMacro("__extension__", "");
addMacro("__imag__", "(int)");
addMacro("__real__", "(int)");
addMacro("__stdcall", "");
addMacro("__thread", "");
addMacro("__builtin_va_arg(ap,type)", "*(typeof(type) *)ap");
addMacro("__builtin_constant_p(exp)", "0");
addMacro("__builtin_types_compatible_p(x,y)", "__builtin_types_compatible_p(sizeof(x),sizeof(y))");
addMacro("__offsetof__(x)", "(x)");
addPreprocessorKeyword(Keywords.cINCLUDE_NEXT, IPreprocessorDirective.ppInclude_next);
addPreprocessorKeyword(Keywords.cIMPORT, IPreprocessorDirective.ppImport);
addPreprocessorKeyword(Keywords.cWARNING, IPreprocessorDirective.ppWarning);
addPreprocessorKeyword(Keywords.cIDENT, IPreprocessorDirective.ppIgnore);
addPreprocessorKeyword(Keywords.cSCCS, IPreprocessorDirective.ppIgnore);
addPreprocessorKeyword(Keywords.cASSERT, IPreprocessorDirective.ppIgnore);
addPreprocessorKeyword(Keywords.cUNASSERT, IPreprocessorDirective.ppIgnore);
addKeyword(GCCKeywords.cp__ALIGNOF, IGCCToken.t___alignof__ );
addKeyword(GCCKeywords.cp__ALIGNOF__, IGCCToken.t___alignof__ );
addKeyword(GCCKeywords.cp__ASM, IToken.t_asm);
addKeyword(GCCKeywords.cp__ASM__, IToken.t_asm);
addKeyword(GCCKeywords.cp__ATTRIBUTE, IGCCToken.t__attribute__ );
addKeyword(GCCKeywords.cp__ATTRIBUTE__, IGCCToken.t__attribute__ );
addKeyword(GCCKeywords.cp__CONST, IToken.t_const);
addKeyword(GCCKeywords.cp__CONST__, IToken.t_const);
addKeyword(GCCKeywords.cp__DECLSPEC, IGCCToken.t__declspec );
addKeyword(GCCKeywords.cp__INLINE, IToken.t_inline);
addKeyword(GCCKeywords.cp__INLINE__, IToken.t_inline);
addKeyword(GCCKeywords.cp__RESTRICT, IToken.t_restrict);
addKeyword(GCCKeywords.cp__RESTRICT__, IToken.t_restrict);
addKeyword(GCCKeywords.cp__VOLATILE, IToken.t_volatile);
addKeyword(GCCKeywords.cp__VOLATILE__, IToken.t_volatile);
addKeyword(GCCKeywords.cp__SIGNED, IToken.t_signed);
addKeyword(GCCKeywords.cp__SIGNED__, IToken.t_signed);
addKeyword(GCCKeywords.cp__TYPEOF, IGCCToken.t_typeof);
addKeyword(GCCKeywords.cp__TYPEOF__, IGCCToken.t_typeof);
addKeyword(GCCKeywords.cpTYPEOF, IGCCToken.t_typeof );
}
|
diff --git a/htroot/ConfigBasic.java b/htroot/ConfigBasic.java
index 7f6a20492..b1d3cca1e 100644
--- a/htroot/ConfigBasic.java
+++ b/htroot/ConfigBasic.java
@@ -1,278 +1,278 @@
// ConfigBasic.java
// -----------------------
// part of YaCy
// (C) by Michael Peter Christen; [email protected]
// first published on http://www.anomic.de
// Frankfurt, Germany, 2006
// Created 28.02.2006
//
// $LastChangedDate$
// $LastChangedRevision$
// $LastChangedBy$
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// You must compile this file with
// javac -classpath .:../classes ConfigBasic_p.java
// if the shell's current path is HTROOT
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.regex.Pattern;
import net.yacy.cora.protocol.Domains;
import net.yacy.cora.protocol.HeaderFramework;
import net.yacy.cora.protocol.RequestHeader;
import net.yacy.kelondro.workflow.InstantBusyThread;
import de.anomic.data.WorkTables;
import de.anomic.data.Translator;
import de.anomic.http.server.HTTPDemon;
import de.anomic.http.server.HTTPDFileHandler;
import de.anomic.net.UPnP;
import de.anomic.search.Switchboard;
import de.anomic.search.SwitchboardConstants;
import de.anomic.server.serverCore;
import de.anomic.server.serverObjects;
import de.anomic.server.serverSwitch;
import de.anomic.yacy.yacySeed;
public class ConfigBasic {
private static final int NEXTSTEP_FINISHED = 0;
private static final int NEXTSTEP_PWD = 1;
private static final int NEXTSTEP_PEERNAME = 2;
private static final int NEXTSTEP_PEERPORT = 3;
private static final int NEXTSTEP_RECONNECT = 4;
public static serverObjects respond(final RequestHeader header, final serverObjects post, final serverSwitch env) throws FileNotFoundException, IOException {
// return variable that accumulates replacements
final Switchboard sb = (Switchboard) env;
final serverObjects prop = new serverObjects();
final String langPath = env.getDataPath("locale.work", "DATA/LOCALE/locales").getAbsolutePath();
String lang = env.getConfig("locale.language", "default");
final int authentication = sb.adminAuthenticated(header);
if (authentication < 2) {
// must authenticate
prop.put("AUTHENTICATE", "admin log-in");
return prop;
}
// store this call as api call
if (post != null && post.containsKey("set")) {
sb.tables.recordAPICall(post, "ConfigBasic.html", WorkTables.TABLE_API_TYPE_CONFIGURATION, "basic settings");
}
//boolean doPeerPing = false;
if ((sb.peers.mySeed().isVirgin()) || (sb.peers.mySeed().isJunior())) {
InstantBusyThread.oneTimeJob(sb.yc, "peerPing", null, 0);
//doPeerPing = true;
}
// language settings
if (post != null && post.containsKey("language") && !lang.equals(post.get("language", "default")) &&
(Translator.changeLang(env, langPath, post.get("language", "default") + ".lng"))) {
prop.put("changedLanguage", "1");
}
// peer name settings
final String peerName = (post == null) ? sb.peers.mySeed().getName() : post.get("peername", "");
// port settings
final long port;
if (post != null && post.containsKey("port") && Integer.parseInt(post.get("port")) > 1023) {
port = post.getLong("port", 8090);
} else {
port = env.getConfigLong("port", 8090); //this allows a low port, but it will only get one, if the user edits the config himself.
}
// check if peer name already exists
final yacySeed oldSeed = sb.peers.lookupByName(peerName);
if (oldSeed == null && !sb.peers.mySeed().getName().equals(peerName)) {
// the name is new
if (Pattern.compile("[A-Za-z0-9\\-_]{3,80}").matcher(peerName).matches()) {
sb.peers.mySeed().setName(peerName);
}
}
// UPnP config
final boolean upnp;
if(post != null && post.containsKey("port")) { // hack to allow checkbox
upnp = post.containsKey("enableUpnp");
if (upnp && !sb.getConfigBool(SwitchboardConstants.UPNP_ENABLED, false)) {
UPnP.addPortMapping();
}
sb.setConfig(SwitchboardConstants.UPNP_ENABLED, upnp);
if (!upnp) {
UPnP.deletePortMapping();
}
} else {
upnp = false;
}
// check port
final boolean reconnect;
if (!(env.getConfigLong("port", port) == port)) {
// validate port
final serverCore theServerCore = (serverCore) env.getThread("10_httpd");
env.setConfig("port", port);
// redirect the browser to the new port
reconnect = true;
// renew upnp port mapping
if (upnp) {
UPnP.addPortMapping();
}
String host = null;
if (header.containsKey(HeaderFramework.HOST)) {
host = header.get(HeaderFramework.HOST);
final int idx = host.indexOf(':');
if (idx != -1) host = host.substring(0,idx);
} else {
host = Domains.myPublicLocalIP().getHostAddress();
}
prop.put("reconnect", "1");
prop.put("reconnect_host", host);
prop.put("nextStep_host", host);
prop.put("reconnect_port", port);
prop.put("nextStep_port", port);
prop.put("reconnect_sslSupport", theServerCore.withSSL() ? "1" : "0");
prop.put("nextStep_sslSupport", theServerCore.withSSL() ? "1" : "0");
// generate new shortcut (used for Windows)
//yacyAccessible.setNewPortBat(Integer.parseInt(port));
//yacyAccessible.setNewPortLink(Integer.parseInt(port));
// force reconnection in 7 seconds
theServerCore.reconnect(7000);
} else {
reconnect = false;
prop.put("reconnect", "0");
}
// set a use case
String networkName = sb.getConfig(SwitchboardConstants.NETWORK_NAME, "");
if (post != null && post.containsKey("usecase")) {
if ("freeworld".equals(post.get("usecase", "")) && !"freeworld".equals(networkName)) {
// switch to freeworld network
sb.switchNetwork("defaults/yacy.network.freeworld.unit");
// switch to p2p mode
sb.setConfig(SwitchboardConstants.INDEX_DIST_ALLOW, true);
sb.setConfig(SwitchboardConstants.INDEX_RECEIVE_ALLOW, true);
}
- if ("portal".equals(post.get("usecase", "")) && !"webprotal".equals(networkName)) {
+ if ("portal".equals(post.get("usecase", "")) && !"webportal".equals(networkName)) {
// switch to webportal network
sb.switchNetwork("defaults/yacy.network.webportal.unit");
// switch to robinson mode
sb.setConfig(SwitchboardConstants.INDEX_DIST_ALLOW, false);
sb.setConfig(SwitchboardConstants.INDEX_RECEIVE_ALLOW, false);
}
if ("intranet".equals(post.get("usecase", "")) && !"intranet".equals(networkName)) {
// switch to intranet network
sb.switchNetwork("defaults/yacy.network.intranet.unit");
// switch to p2p mode: enable ad-hoc networks between intranet users
sb.setConfig(SwitchboardConstants.INDEX_DIST_ALLOW, false);
sb.setConfig(SwitchboardConstants.INDEX_RECEIVE_ALLOW, false);
}
if ("intranet".equals(post.get("usecase", ""))) {
final String repositoryPath = post.get("repositoryPath", "/DATA/HTROOT/repository");
final File repository = ((repositoryPath.length() > 0 && repositoryPath.charAt(0) == '/') || (repositoryPath.length() > 1 && repositoryPath.charAt(1) == ':')) ? new File(repositoryPath) : new File(sb.getDataPath(), repositoryPath);
if (repository.exists() && repository.isDirectory()) {
sb.setConfig("repositoryPath", repositoryPath);
}
}
}
networkName = sb.getConfig(SwitchboardConstants.NETWORK_NAME, "");
if ("freeworld".equals(networkName)) {
prop.put("setUseCase", 1);
prop.put("setUseCase_freeworldChecked", 1);
} else if ("webportal".equals(networkName)) {
prop.put("setUseCase", 1);
prop.put("setUseCase_portalChecked", 1);
} else if ("intranet".equals(networkName)) {
prop.put("setUseCase", 1);
prop.put("setUseCase_intranetChecked", 1);
} else {
prop.put("setUseCase", 0);
}
prop.put("setUseCase_port", port);
prop.put("setUseCase_repositoryPath", sb.getConfig("repositoryPath", "/DATA/HTROOT/repository"));
// check if values are proper
final boolean properPassword = (sb.getConfig(HTTPDemon.ADMIN_ACCOUNT_B64MD5, "").length() > 0) || sb.getConfigBool("adminAccountForLocalhost", false);
final boolean properName = (sb.peers.mySeed().getName().length() >= 3) && (!(yacySeed.isDefaultPeerName(sb.peers.mySeed().getName())));
final boolean properPort = (sb.peers.mySeed().isSenior()) || (sb.peers.mySeed().isPrincipal());
if ((env.getConfig("defaultFiles", "").startsWith("ConfigBasic.html,"))) {
env.setConfig("defaultFiles", env.getConfig("defaultFiles", "").substring(17));
env.setConfig("browserPopUpPage", "Status.html");
HTTPDFileHandler.initDefaultPath();
}
prop.put("statusName", properName ? "1" : "0");
prop.put("statusPort", properPort ? "1" : "0");
if (reconnect) {
prop.put("nextStep", NEXTSTEP_RECONNECT);
} else if (!properName) {
prop.put("nextStep", NEXTSTEP_PEERNAME);
} else if (!properPassword) {
prop.put("nextStep", NEXTSTEP_PWD);
} else if (!properPort) {
prop.put("nextStep", NEXTSTEP_PEERPORT);
} else {
prop.put("nextStep", NEXTSTEP_FINISHED);
}
final boolean upnp_enabled = env.getConfigBool(SwitchboardConstants.UPNP_ENABLED, false);
prop.put("upnp", "1");
prop.put("upnp_enabled", upnp_enabled ? "1" : "0");
if (upnp_enabled) {
prop.put("upnp_success", (UPnP.getMappedPort() > 0) ? "2" : "1");
}
else {
prop.put("upnp_success", "0");
}
// set default values
prop.putHTML("defaultName", sb.peers.mySeed().getName());
prop.putHTML("defaultPort", env.getConfig("port", "8090"));
lang = env.getConfig("locale.language", "default"); // re-assign lang, may have changed
if ("default".equals(lang)) {
prop.put("langDeutsch", "0");
prop.put("langFrancais", "0");
prop.put("langEnglish", "1");
} else if ("fr".equals(lang)) {
prop.put("langDeutsch", "0");
prop.put("langFrancais", "1");
prop.put("langEnglish", "0");
} else if ("de".equals(lang)) {
prop.put("langDeutsch", "1");
prop.put("langFrancais", "0");
prop.put("langEnglish", "0");
} else {
prop.put("langDeutsch", "0");
prop.put("langFrancais", "0");
prop.put("langEnglish", "0");
}
return prop;
}
}
| true | true | public static serverObjects respond(final RequestHeader header, final serverObjects post, final serverSwitch env) throws FileNotFoundException, IOException {
// return variable that accumulates replacements
final Switchboard sb = (Switchboard) env;
final serverObjects prop = new serverObjects();
final String langPath = env.getDataPath("locale.work", "DATA/LOCALE/locales").getAbsolutePath();
String lang = env.getConfig("locale.language", "default");
final int authentication = sb.adminAuthenticated(header);
if (authentication < 2) {
// must authenticate
prop.put("AUTHENTICATE", "admin log-in");
return prop;
}
// store this call as api call
if (post != null && post.containsKey("set")) {
sb.tables.recordAPICall(post, "ConfigBasic.html", WorkTables.TABLE_API_TYPE_CONFIGURATION, "basic settings");
}
//boolean doPeerPing = false;
if ((sb.peers.mySeed().isVirgin()) || (sb.peers.mySeed().isJunior())) {
InstantBusyThread.oneTimeJob(sb.yc, "peerPing", null, 0);
//doPeerPing = true;
}
// language settings
if (post != null && post.containsKey("language") && !lang.equals(post.get("language", "default")) &&
(Translator.changeLang(env, langPath, post.get("language", "default") + ".lng"))) {
prop.put("changedLanguage", "1");
}
// peer name settings
final String peerName = (post == null) ? sb.peers.mySeed().getName() : post.get("peername", "");
// port settings
final long port;
if (post != null && post.containsKey("port") && Integer.parseInt(post.get("port")) > 1023) {
port = post.getLong("port", 8090);
} else {
port = env.getConfigLong("port", 8090); //this allows a low port, but it will only get one, if the user edits the config himself.
}
// check if peer name already exists
final yacySeed oldSeed = sb.peers.lookupByName(peerName);
if (oldSeed == null && !sb.peers.mySeed().getName().equals(peerName)) {
// the name is new
if (Pattern.compile("[A-Za-z0-9\\-_]{3,80}").matcher(peerName).matches()) {
sb.peers.mySeed().setName(peerName);
}
}
// UPnP config
final boolean upnp;
if(post != null && post.containsKey("port")) { // hack to allow checkbox
upnp = post.containsKey("enableUpnp");
if (upnp && !sb.getConfigBool(SwitchboardConstants.UPNP_ENABLED, false)) {
UPnP.addPortMapping();
}
sb.setConfig(SwitchboardConstants.UPNP_ENABLED, upnp);
if (!upnp) {
UPnP.deletePortMapping();
}
} else {
upnp = false;
}
// check port
final boolean reconnect;
if (!(env.getConfigLong("port", port) == port)) {
// validate port
final serverCore theServerCore = (serverCore) env.getThread("10_httpd");
env.setConfig("port", port);
// redirect the browser to the new port
reconnect = true;
// renew upnp port mapping
if (upnp) {
UPnP.addPortMapping();
}
String host = null;
if (header.containsKey(HeaderFramework.HOST)) {
host = header.get(HeaderFramework.HOST);
final int idx = host.indexOf(':');
if (idx != -1) host = host.substring(0,idx);
} else {
host = Domains.myPublicLocalIP().getHostAddress();
}
prop.put("reconnect", "1");
prop.put("reconnect_host", host);
prop.put("nextStep_host", host);
prop.put("reconnect_port", port);
prop.put("nextStep_port", port);
prop.put("reconnect_sslSupport", theServerCore.withSSL() ? "1" : "0");
prop.put("nextStep_sslSupport", theServerCore.withSSL() ? "1" : "0");
// generate new shortcut (used for Windows)
//yacyAccessible.setNewPortBat(Integer.parseInt(port));
//yacyAccessible.setNewPortLink(Integer.parseInt(port));
// force reconnection in 7 seconds
theServerCore.reconnect(7000);
} else {
reconnect = false;
prop.put("reconnect", "0");
}
// set a use case
String networkName = sb.getConfig(SwitchboardConstants.NETWORK_NAME, "");
if (post != null && post.containsKey("usecase")) {
if ("freeworld".equals(post.get("usecase", "")) && !"freeworld".equals(networkName)) {
// switch to freeworld network
sb.switchNetwork("defaults/yacy.network.freeworld.unit");
// switch to p2p mode
sb.setConfig(SwitchboardConstants.INDEX_DIST_ALLOW, true);
sb.setConfig(SwitchboardConstants.INDEX_RECEIVE_ALLOW, true);
}
if ("portal".equals(post.get("usecase", "")) && !"webprotal".equals(networkName)) {
// switch to webportal network
sb.switchNetwork("defaults/yacy.network.webportal.unit");
// switch to robinson mode
sb.setConfig(SwitchboardConstants.INDEX_DIST_ALLOW, false);
sb.setConfig(SwitchboardConstants.INDEX_RECEIVE_ALLOW, false);
}
if ("intranet".equals(post.get("usecase", "")) && !"intranet".equals(networkName)) {
// switch to intranet network
sb.switchNetwork("defaults/yacy.network.intranet.unit");
// switch to p2p mode: enable ad-hoc networks between intranet users
sb.setConfig(SwitchboardConstants.INDEX_DIST_ALLOW, false);
sb.setConfig(SwitchboardConstants.INDEX_RECEIVE_ALLOW, false);
}
if ("intranet".equals(post.get("usecase", ""))) {
final String repositoryPath = post.get("repositoryPath", "/DATA/HTROOT/repository");
final File repository = ((repositoryPath.length() > 0 && repositoryPath.charAt(0) == '/') || (repositoryPath.length() > 1 && repositoryPath.charAt(1) == ':')) ? new File(repositoryPath) : new File(sb.getDataPath(), repositoryPath);
if (repository.exists() && repository.isDirectory()) {
sb.setConfig("repositoryPath", repositoryPath);
}
}
}
networkName = sb.getConfig(SwitchboardConstants.NETWORK_NAME, "");
if ("freeworld".equals(networkName)) {
prop.put("setUseCase", 1);
prop.put("setUseCase_freeworldChecked", 1);
} else if ("webportal".equals(networkName)) {
prop.put("setUseCase", 1);
prop.put("setUseCase_portalChecked", 1);
} else if ("intranet".equals(networkName)) {
prop.put("setUseCase", 1);
prop.put("setUseCase_intranetChecked", 1);
} else {
prop.put("setUseCase", 0);
}
prop.put("setUseCase_port", port);
prop.put("setUseCase_repositoryPath", sb.getConfig("repositoryPath", "/DATA/HTROOT/repository"));
// check if values are proper
final boolean properPassword = (sb.getConfig(HTTPDemon.ADMIN_ACCOUNT_B64MD5, "").length() > 0) || sb.getConfigBool("adminAccountForLocalhost", false);
final boolean properName = (sb.peers.mySeed().getName().length() >= 3) && (!(yacySeed.isDefaultPeerName(sb.peers.mySeed().getName())));
final boolean properPort = (sb.peers.mySeed().isSenior()) || (sb.peers.mySeed().isPrincipal());
if ((env.getConfig("defaultFiles", "").startsWith("ConfigBasic.html,"))) {
env.setConfig("defaultFiles", env.getConfig("defaultFiles", "").substring(17));
env.setConfig("browserPopUpPage", "Status.html");
HTTPDFileHandler.initDefaultPath();
}
prop.put("statusName", properName ? "1" : "0");
prop.put("statusPort", properPort ? "1" : "0");
if (reconnect) {
prop.put("nextStep", NEXTSTEP_RECONNECT);
} else if (!properName) {
prop.put("nextStep", NEXTSTEP_PEERNAME);
} else if (!properPassword) {
prop.put("nextStep", NEXTSTEP_PWD);
} else if (!properPort) {
prop.put("nextStep", NEXTSTEP_PEERPORT);
} else {
prop.put("nextStep", NEXTSTEP_FINISHED);
}
final boolean upnp_enabled = env.getConfigBool(SwitchboardConstants.UPNP_ENABLED, false);
prop.put("upnp", "1");
prop.put("upnp_enabled", upnp_enabled ? "1" : "0");
if (upnp_enabled) {
prop.put("upnp_success", (UPnP.getMappedPort() > 0) ? "2" : "1");
}
else {
prop.put("upnp_success", "0");
}
// set default values
prop.putHTML("defaultName", sb.peers.mySeed().getName());
prop.putHTML("defaultPort", env.getConfig("port", "8090"));
lang = env.getConfig("locale.language", "default"); // re-assign lang, may have changed
if ("default".equals(lang)) {
prop.put("langDeutsch", "0");
prop.put("langFrancais", "0");
prop.put("langEnglish", "1");
} else if ("fr".equals(lang)) {
prop.put("langDeutsch", "0");
prop.put("langFrancais", "1");
prop.put("langEnglish", "0");
} else if ("de".equals(lang)) {
prop.put("langDeutsch", "1");
prop.put("langFrancais", "0");
prop.put("langEnglish", "0");
} else {
prop.put("langDeutsch", "0");
prop.put("langFrancais", "0");
prop.put("langEnglish", "0");
}
return prop;
}
| public static serverObjects respond(final RequestHeader header, final serverObjects post, final serverSwitch env) throws FileNotFoundException, IOException {
// return variable that accumulates replacements
final Switchboard sb = (Switchboard) env;
final serverObjects prop = new serverObjects();
final String langPath = env.getDataPath("locale.work", "DATA/LOCALE/locales").getAbsolutePath();
String lang = env.getConfig("locale.language", "default");
final int authentication = sb.adminAuthenticated(header);
if (authentication < 2) {
// must authenticate
prop.put("AUTHENTICATE", "admin log-in");
return prop;
}
// store this call as api call
if (post != null && post.containsKey("set")) {
sb.tables.recordAPICall(post, "ConfigBasic.html", WorkTables.TABLE_API_TYPE_CONFIGURATION, "basic settings");
}
//boolean doPeerPing = false;
if ((sb.peers.mySeed().isVirgin()) || (sb.peers.mySeed().isJunior())) {
InstantBusyThread.oneTimeJob(sb.yc, "peerPing", null, 0);
//doPeerPing = true;
}
// language settings
if (post != null && post.containsKey("language") && !lang.equals(post.get("language", "default")) &&
(Translator.changeLang(env, langPath, post.get("language", "default") + ".lng"))) {
prop.put("changedLanguage", "1");
}
// peer name settings
final String peerName = (post == null) ? sb.peers.mySeed().getName() : post.get("peername", "");
// port settings
final long port;
if (post != null && post.containsKey("port") && Integer.parseInt(post.get("port")) > 1023) {
port = post.getLong("port", 8090);
} else {
port = env.getConfigLong("port", 8090); //this allows a low port, but it will only get one, if the user edits the config himself.
}
// check if peer name already exists
final yacySeed oldSeed = sb.peers.lookupByName(peerName);
if (oldSeed == null && !sb.peers.mySeed().getName().equals(peerName)) {
// the name is new
if (Pattern.compile("[A-Za-z0-9\\-_]{3,80}").matcher(peerName).matches()) {
sb.peers.mySeed().setName(peerName);
}
}
// UPnP config
final boolean upnp;
if(post != null && post.containsKey("port")) { // hack to allow checkbox
upnp = post.containsKey("enableUpnp");
if (upnp && !sb.getConfigBool(SwitchboardConstants.UPNP_ENABLED, false)) {
UPnP.addPortMapping();
}
sb.setConfig(SwitchboardConstants.UPNP_ENABLED, upnp);
if (!upnp) {
UPnP.deletePortMapping();
}
} else {
upnp = false;
}
// check port
final boolean reconnect;
if (!(env.getConfigLong("port", port) == port)) {
// validate port
final serverCore theServerCore = (serverCore) env.getThread("10_httpd");
env.setConfig("port", port);
// redirect the browser to the new port
reconnect = true;
// renew upnp port mapping
if (upnp) {
UPnP.addPortMapping();
}
String host = null;
if (header.containsKey(HeaderFramework.HOST)) {
host = header.get(HeaderFramework.HOST);
final int idx = host.indexOf(':');
if (idx != -1) host = host.substring(0,idx);
} else {
host = Domains.myPublicLocalIP().getHostAddress();
}
prop.put("reconnect", "1");
prop.put("reconnect_host", host);
prop.put("nextStep_host", host);
prop.put("reconnect_port", port);
prop.put("nextStep_port", port);
prop.put("reconnect_sslSupport", theServerCore.withSSL() ? "1" : "0");
prop.put("nextStep_sslSupport", theServerCore.withSSL() ? "1" : "0");
// generate new shortcut (used for Windows)
//yacyAccessible.setNewPortBat(Integer.parseInt(port));
//yacyAccessible.setNewPortLink(Integer.parseInt(port));
// force reconnection in 7 seconds
theServerCore.reconnect(7000);
} else {
reconnect = false;
prop.put("reconnect", "0");
}
// set a use case
String networkName = sb.getConfig(SwitchboardConstants.NETWORK_NAME, "");
if (post != null && post.containsKey("usecase")) {
if ("freeworld".equals(post.get("usecase", "")) && !"freeworld".equals(networkName)) {
// switch to freeworld network
sb.switchNetwork("defaults/yacy.network.freeworld.unit");
// switch to p2p mode
sb.setConfig(SwitchboardConstants.INDEX_DIST_ALLOW, true);
sb.setConfig(SwitchboardConstants.INDEX_RECEIVE_ALLOW, true);
}
if ("portal".equals(post.get("usecase", "")) && !"webportal".equals(networkName)) {
// switch to webportal network
sb.switchNetwork("defaults/yacy.network.webportal.unit");
// switch to robinson mode
sb.setConfig(SwitchboardConstants.INDEX_DIST_ALLOW, false);
sb.setConfig(SwitchboardConstants.INDEX_RECEIVE_ALLOW, false);
}
if ("intranet".equals(post.get("usecase", "")) && !"intranet".equals(networkName)) {
// switch to intranet network
sb.switchNetwork("defaults/yacy.network.intranet.unit");
// switch to p2p mode: enable ad-hoc networks between intranet users
sb.setConfig(SwitchboardConstants.INDEX_DIST_ALLOW, false);
sb.setConfig(SwitchboardConstants.INDEX_RECEIVE_ALLOW, false);
}
if ("intranet".equals(post.get("usecase", ""))) {
final String repositoryPath = post.get("repositoryPath", "/DATA/HTROOT/repository");
final File repository = ((repositoryPath.length() > 0 && repositoryPath.charAt(0) == '/') || (repositoryPath.length() > 1 && repositoryPath.charAt(1) == ':')) ? new File(repositoryPath) : new File(sb.getDataPath(), repositoryPath);
if (repository.exists() && repository.isDirectory()) {
sb.setConfig("repositoryPath", repositoryPath);
}
}
}
networkName = sb.getConfig(SwitchboardConstants.NETWORK_NAME, "");
if ("freeworld".equals(networkName)) {
prop.put("setUseCase", 1);
prop.put("setUseCase_freeworldChecked", 1);
} else if ("webportal".equals(networkName)) {
prop.put("setUseCase", 1);
prop.put("setUseCase_portalChecked", 1);
} else if ("intranet".equals(networkName)) {
prop.put("setUseCase", 1);
prop.put("setUseCase_intranetChecked", 1);
} else {
prop.put("setUseCase", 0);
}
prop.put("setUseCase_port", port);
prop.put("setUseCase_repositoryPath", sb.getConfig("repositoryPath", "/DATA/HTROOT/repository"));
// check if values are proper
final boolean properPassword = (sb.getConfig(HTTPDemon.ADMIN_ACCOUNT_B64MD5, "").length() > 0) || sb.getConfigBool("adminAccountForLocalhost", false);
final boolean properName = (sb.peers.mySeed().getName().length() >= 3) && (!(yacySeed.isDefaultPeerName(sb.peers.mySeed().getName())));
final boolean properPort = (sb.peers.mySeed().isSenior()) || (sb.peers.mySeed().isPrincipal());
if ((env.getConfig("defaultFiles", "").startsWith("ConfigBasic.html,"))) {
env.setConfig("defaultFiles", env.getConfig("defaultFiles", "").substring(17));
env.setConfig("browserPopUpPage", "Status.html");
HTTPDFileHandler.initDefaultPath();
}
prop.put("statusName", properName ? "1" : "0");
prop.put("statusPort", properPort ? "1" : "0");
if (reconnect) {
prop.put("nextStep", NEXTSTEP_RECONNECT);
} else if (!properName) {
prop.put("nextStep", NEXTSTEP_PEERNAME);
} else if (!properPassword) {
prop.put("nextStep", NEXTSTEP_PWD);
} else if (!properPort) {
prop.put("nextStep", NEXTSTEP_PEERPORT);
} else {
prop.put("nextStep", NEXTSTEP_FINISHED);
}
final boolean upnp_enabled = env.getConfigBool(SwitchboardConstants.UPNP_ENABLED, false);
prop.put("upnp", "1");
prop.put("upnp_enabled", upnp_enabled ? "1" : "0");
if (upnp_enabled) {
prop.put("upnp_success", (UPnP.getMappedPort() > 0) ? "2" : "1");
}
else {
prop.put("upnp_success", "0");
}
// set default values
prop.putHTML("defaultName", sb.peers.mySeed().getName());
prop.putHTML("defaultPort", env.getConfig("port", "8090"));
lang = env.getConfig("locale.language", "default"); // re-assign lang, may have changed
if ("default".equals(lang)) {
prop.put("langDeutsch", "0");
prop.put("langFrancais", "0");
prop.put("langEnglish", "1");
} else if ("fr".equals(lang)) {
prop.put("langDeutsch", "0");
prop.put("langFrancais", "1");
prop.put("langEnglish", "0");
} else if ("de".equals(lang)) {
prop.put("langDeutsch", "1");
prop.put("langFrancais", "0");
prop.put("langEnglish", "0");
} else {
prop.put("langDeutsch", "0");
prop.put("langFrancais", "0");
prop.put("langEnglish", "0");
}
return prop;
}
|
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/StatusBarService.java b/packages/SystemUI/src/com/android/systemui/statusbar/StatusBarService.java
index 74300532..b9116e27 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/StatusBarService.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/StatusBarService.java
@@ -1,3333 +1,3333 @@
/*
* Copyright (C) 2010 The Android Open Source Project
* Patched by Sven Dawitz; Copyright (C) 2011 CyanogenMod Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.systemui.statusbar;
import com.android.internal.statusbar.IStatusBarService;
import com.android.internal.statusbar.StatusBarIcon;
import com.android.internal.statusbar.StatusBarIconList;
import com.android.internal.statusbar.StatusBarNotification;
import com.android.systemui.statusbar.batteries.CmBatteryMiniIcon;
import com.android.systemui.statusbar.batteries.CmBatterySideBar;
import com.android.systemui.statusbar.batteries.CmBatteryStatusBar;
import com.android.systemui.statusbar.carrierlabels.CarrierLabel;
import com.android.systemui.statusbar.carrierlabels.CarrierLabelBottom;
import com.android.systemui.statusbar.carrierlabels.CarrierLabelExp;
import com.android.systemui.statusbar.carrierlabels.CarrierLabelStatusBar;
import com.android.systemui.statusbar.carrierlabels.CarrierLogo;
import com.android.systemui.statusbar.carrierlabels.CenterCarrierLabelStatusBar;
import com.android.systemui.statusbar.carrierlabels.CenterCarrierLogo;
import com.android.systemui.statusbar.carrierlabels.LeftCarrierLabelStatusBar;
import com.android.systemui.statusbar.carrierlabels.LeftCarrierLogo;
import com.android.systemui.statusbar.clocks.CenterClock;
import com.android.systemui.statusbar.clocks.Clock;
import com.android.systemui.statusbar.clocks.LeftClock;
import com.android.systemui.statusbar.clocks.PowerClock;
import com.android.systemui.statusbar.clocks.ClockExpand;
import com.android.systemui.statusbar.cmcustom.BackLogo;
import com.android.systemui.statusbar.dates.DateView;
import com.android.systemui.statusbar.dates.PowerDateView;
import com.android.systemui.statusbar.popups.BrightnessPanel;
import com.android.systemui.statusbar.popups.QuickSettingsPopupWindow;
import com.android.systemui.statusbar.popups.ShortcutPopupWindow;
import com.android.systemui.statusbar.popups.WeatherPopup;
import com.android.systemui.statusbar.powerwidget.PowerWidget;
import com.android.systemui.statusbar.powerwidget.PowerWidgetBottom;
import com.android.systemui.statusbar.powerwidget.PowerWidgetOne;
import com.android.systemui.statusbar.powerwidget.PowerWidgetTwo;
import com.android.systemui.statusbar.powerwidget.PowerWidgetThree;
import com.android.systemui.statusbar.powerwidget.PowerWidgetFour;
import com.android.systemui.statusbar.powerwidget.MusicControls;
import com.android.systemui.statusbar.quicksettings.QuickSettingsContainerView;
import com.android.systemui.statusbar.quicksettings.QuickSettingsController;
import com.android.systemui.statusbar.policy.NetworkController;
import com.android.systemui.R;
import android.os.IPowerManager;
import android.provider.Settings.SettingNotFoundException;
import android.app.ActivityManagerNative;
import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.app.Dialog;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.app.StatusBarManager;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.CustomTheme;
import android.content.res.Resources;
import android.database.ContentObserver;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.NinePatchDrawable;
import android.graphics.PorterDuff.Mode;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.os.SystemClock;
import android.provider.CmSystem;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Pair;
import android.util.Log;
import android.util.Slog;
import android.util.TypedValue;
import android.view.Display;
import android.view.Gravity;
import android.view.HapticFeedbackConstants;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.VelocityTracker;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.WindowManagerImpl;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RemoteViews;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.ProgressBar;
import android.net.Uri;
import java.io.File;
import java.io.FileDescriptor;
import java.io.RandomAccessFile;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;
//import com.android.systemui.statusbar.RecentApps;
public class StatusBarService extends Service implements CommandQueue.Callbacks {
static final String TAG = "StatusBarService";
static final boolean SPEW_ICONS = false;
static final boolean SPEW = false;
public static final String ACTION_STATUSBAR_START
= "com.android.internal.policy.statusbar.START";
// values changed onCreate if its a bottomBar
static int EXPANDED_LEAVE_ALONE = -10000;
static int EXPANDED_FULL_OPEN = -10001;
private static final float BRIGHTNESS_CONTROL_PADDING = 0.15f;
private static final int BRIGHTNESS_CONTROL_LONG_PRESS_TIMEOUT = 750; // ms
private static final int BRIGHTNESS_CONTROL_LINGER_THRESHOLD = 20;
private boolean mBrightnessControl;
private static final int MSG_ANIMATE = 1000;
private static final int MSG_ANIMATE_REVEAL = 1001;
private int mClockColor;
private static final int MSG_SHOW_INTRUDER = 1002;
private static final int MSG_HIDE_INTRUDER = 1003;
// will likely move to a resource or other tunable param at some point
private static final int INTRUDER_ALERT_DECAY_MS = 3000;
StatusBarPolicy mIconPolicy;
NetworkController mNetworkPolicy;
CommandQueue mCommandQueue;
IStatusBarService mBarService;
/**
* Shallow container for {@link #mStatusBarView} which is added to the
* window manager impl as the actual status bar root view. This is done so
* that the original status_bar layout can be reinflated into this container
* on skin change.
*/
FrameLayout mStatusBarContainer;
int mIconSize;
Display mDisplay;
CmStatusBarView mStatusBarView;
int mPixelFormat;
H mHandler = new H();
Object mQueueLock = new Object();
// last theme that was applied in order to detect theme change (as opposed
// to some other configuration change).
CustomTheme mCurrentTheme;
private DoNotDisturb mDoNotDisturb;
// icons
LinearLayout mIcons;
LinearLayout mCenterClock;
LinearLayout mCenterClockex;
SignalClusterView mCenterIconex;
LinearLayout mLeftClock;
IconMerger mNotificationIcons;
LinearLayout mStatusIcons;
LinearLayout mStatusIconsExp;
ImageView mSettingsIconButton;
// expanded notifications
Dialog mExpandedDialog;
ExpandedView mExpandedView;
WindowManager.LayoutParams mExpandedParams;
ScrollView mScrollView;
ScrollView mBottomScrollView;
LinearLayout mNotificationLinearLayout;
LinearLayout mBottomNotificationLinearLayout;
View mExpandedContents;
View mExpandededContents;
// top bar
TextView mNoNotificationsTitle;
TextView mNoNotificationsTitles;
ImageView mClearButton;
TextView mClearOldButton;
TextView mCompactClearButton;
CmBatteryMiniIcon mCmBatteryMiniIcon;
// drag bar
CloseDragHandle mCloseView;
// ongoing
NotificationData mOngoing = new NotificationData();
TextView mOngoingTitle;
LinearLayout mOngoingItems;
// latest
NotificationData mLatest = new NotificationData();
TextView mLatestTitle;
TextView mLatestTitles;
LinearLayout mLatestItems;
QuickSettingsController mQS;
QuickSettingsContainerView mQuickContainer;
ItemTouchDispatcher mTouchDispatcher;
// position
int[] mPositionTmp = new int[2];
boolean mExpanded;
boolean mExpandedVisible;
// the date view
DateView mDateView;
// on-screen navigation buttons
private NavigationBarView mNavigationBarView;
// the tracker view
TrackingView mTrackingView;
View mNotificationBackgroundView;
ImageView mSettingsButton;
WindowManager.LayoutParams mTrackingParams;
int mTrackingPosition; // the position of the top of the tracking view.
private boolean mPanelSlightlyVisible;
// the power widget
PowerWidget mPowerWidget;
PowerWidgetBottom mPowerWidgetBottom;
PowerWidgetOne mPowerWidgetOne;
PowerWidgetTwo mPowerWidgetTwo;
PowerWidgetThree mPowerWidgetThree;
PowerWidgetFour mPowerWidgetFour;
MusicControls mMusicControls;
//Carrier label stuff
LinearLayout mCarrierLabelLayout;
CarrierLabelStatusBar mCarrierLabelStatusBarLayout;
CarrierLabelBottom mCarrierLabelBottomLayout;
CenterCarrierLabelStatusBar mCenterCarrierLabelStatusBarLayout;
LeftCarrierLabelStatusBar mLeftCarrierLabelStatusBarLayout;
CarrierLogo mCarrierLogoLayout;
CenterCarrierLogo mCarrierLogoCenterLayout;
LeftCarrierLogo mCarrierLogoLeftLayout;
BackLogo mBackLogoLayout;
CmBatteryStatusBar mCmBatteryStatusBar;
LinearLayout mCompactCarrierLayout;
LinearLayout mPowerAndCarrier;
FrameLayout mNaviBarContainer;
CarrierLabelExp mCarrierLabelExpLayout;
// ticker
private Ticker mTicker;
private View mTickerView;
private boolean mTicking;
private TickerView mTickerText;
private TextView mNotificationsToggle;
private TextView mButtonsToggle;
private LinearLayout mNotifications;
private LinearLayout mPowerCarrier;
private LinearLayout mButtons;
public static ImageView mMusicToggleButton;
private BrightnessPanel mBrightnessPanel = null;
// notification color default variables
int mBlackColor = 0xFF000000;
int mWhiteColor = 0xFFFFFFFF;
// notfication color temp variables
int mItemText = mBlackColor;
int mItemTime;
int mItemTitle;
int mDateColor;
int mButtonText = mBlackColor;
int mNotifyNone;
int mNotifyTicker;
int mNotifyLatest;
int mNotifyOngoing;
int mSettingsColor;
int IntruderTime;
LinearLayout mAvalMemLayout;
TextView memHeader;
ProgressBar avalMemPB;
double totalMemory;
double availableMemory;
// Tracking finger for opening/closing.
int mEdgeBorder; // corresponds to R.dimen.status_bar_edge_ignore
boolean mTracking;
VelocityTracker mVelocityTracker;
static final int ANIM_FRAME_DURATION = (1000/60);
boolean mAnimating;
long mCurAnimationTime;
float mDisplayHeight;
float mAnimY;
float mAnimVel;
float mAnimAccel;
long mAnimLastTime;
boolean mAnimatingReveal = false;
int mViewDelta;
int[] mAbsPos = new int[2];
// for disabling the status bar
int mDisabled = 0;
// tracking for the last visible power widget id so hide toggle works properly
int mLastPowerToggle = 1;
// weather or not to show status bar on bottom
boolean mBottomBar;
boolean mButtonsLeft;
boolean mDeadZone;
boolean mHasSoftButtons;
boolean autoBrightness = false;
private boolean shouldTick = false;
Context mContext;
private int mStatusBarCarrier;
private int mStatusBarCarrierLogo;
private int mStatusBarClock;
private boolean mShowDate = false;
private boolean mShowNotif = false;
private boolean mFirstis = true;
private boolean mNaviShow = true;
private boolean mStatusBarReverse = false;
private boolean mStatusBarTab = false;
private boolean mStatusBarTileView = false;
private boolean mStatusBarGrid = false;
private boolean LogoStatusBar = false;
private boolean mShowCmBatteryStatusBar = false;
private boolean mShowCmBatterySideBar = false;
private boolean mTinyExpanded = true;
private boolean mMoreExpanded = true;
private boolean mShowRam = true;
// tracks changes to settings, so status bar is moved to top/bottom
// as soon as cmparts setting is changed
class SettingsObserver extends ContentObserver {
SettingsObserver(Handler handler) {
super(handler);
}
void observe() {
ContentResolver resolver = mContext.getContentResolver();
resolver.registerContentObserver(
Settings.System.getUriFor(Settings.System.STATUS_BAR_BOTTOM), false, this);
resolver.registerContentObserver(
Settings.System.getUriFor(Settings.System.SOFT_BUTTONS_LEFT), false, this);
resolver.registerContentObserver(
Settings.System.getUriFor(Settings.System.SHOW_NAVI_BUTTONS), false, this);
resolver.registerContentObserver(
Settings.System.getUriFor(Settings.System.NAVI_BUTTONS), false, this);
resolver.registerContentObserver(
Settings.System.getUriFor(Settings.System.STATUS_BAR_DEAD_ZONE), false, this);
resolver.registerContentObserver(
Settings.System.getUriFor(Settings.System.STATUS_BAR_CARRIER), false, this);
resolver.registerContentObserver(
Settings.System.getUriFor(Settings.System.CARRIER_LOGO), false, this);
resolver.registerContentObserver(
Settings.System.getUriFor(Settings.System.STATUS_BAR_CLOCK), false, this);
resolver.registerContentObserver(
Settings.System.getUriFor(Settings.System.STATUS_BAR_REVERSE), false, this);
resolver.registerContentObserver(
Settings.System.getUriFor(Settings.System.EXPANDED_VIEW_WIDGET), false, this);
resolver.registerContentObserver(
Settings.System.getUriFor(Settings.System.EXPANDED_VIEW_WIDGET_GRID_ONE), false, this);
resolver.registerContentObserver(
Settings.System.getUriFor(Settings.System.EXPANDED_VIEW_WIDGET_GRID_TWO), false, this);
resolver.registerContentObserver(
Settings.System.getUriFor(Settings.System.EXPANDED_VIEW_WIDGET_GRID_THREE), false, this);
resolver.registerContentObserver(
Settings.System.getUriFor(Settings.System.EXPANDED_VIEW_WIDGET_GRID_FOUR), false, this);
resolver.registerContentObserver(
Settings.System.getUriFor(Settings.System.STATUS_BAR_DATE), false, this);
resolver.registerContentObserver(
Settings.System.getUriFor(Settings.System.CARRIER_LOGO_STATUS_BAR), false, this);
resolver.registerContentObserver(
Settings.System.getUriFor(Settings.System.STATUS_BAR_CLOCKCOLOR), false, this);
resolver.registerContentObserver(
Settings.System.getUriFor(Settings.System.STATUS_BAR_SETTINGSCOLOR), false, this);
resolver.registerContentObserver(
Settings.System.getUriFor(Settings.System.STATUSBAR_STATS_SIZE), false, this);
resolver.registerContentObserver(
Settings.System.getUriFor(Settings.System.STATUSBAR_ICONS_SIZE), false, this);
resolver.registerContentObserver(
Settings.System.getUriFor(Settings.System.STATUSBAR_NAVI_SIZE), false, this);
resolver.registerContentObserver(
Settings.System.getUriFor(Settings.System.STATUSBAR_EXPANDED_SIZE), false, this);
resolver.registerContentObserver(
Settings.System.getUriFor(Settings.System.STATUSBAR_TINY_EXPANDED), false, this);
resolver.registerContentObserver(
Settings.System.getUriFor(Settings.System.STATUSBAR_MORE_EXPANDED), false, this);
resolver.registerContentObserver(
Settings.System.getUriFor(Settings.System.COLOR_DATE), false, this);
resolver.registerContentObserver(
Settings.System.getUriFor(Settings.System.COLOR_NOTIFICATION_NONE), false, this);
resolver.registerContentObserver(
Settings.System.getUriFor(Settings.System.COLOR_NOTIFICATION_LATEST), false, this);
resolver.registerContentObserver(
Settings.System.getUriFor(Settings.System.COLOR_NOTIFICATION_ONGOING), false, this);
resolver.registerContentObserver(
Settings.System.getUriFor(Settings.System.COLOR_NOTIFICATION_TICKER_TEXT), false, this);
resolver.registerContentObserver(
Settings.System.getUriFor(Settings.System.COLOR_NOTIFICATION_CLEAR_BUTTON), false, this);
resolver.registerContentObserver(
Settings.System.getUriFor(Settings.System.COLOR_NOTIFICATION_ITEM_TITLE), false, this);
resolver.registerContentObserver(
Settings.System.getUriFor(Settings.System.COLOR_NOTIFICATION_ITEM_TEXT), false, this);
resolver.registerContentObserver(
Settings.System.getUriFor(Settings.System.COLOR_NOTIFICATION_ITEM_TIME), false, this);
resolver.registerContentObserver(
Settings.System.getUriFor(Settings.System.TRANSPARENT_STATUS_BAR), false, this);
resolver.registerContentObserver(
Settings.System.getUriFor(Settings.System.STATUS_BAR_COLOR), false, this);
resolver.registerContentObserver(
Settings.System.getUriFor(Settings.System.TRANSPARENT_NAVI_BAR), false, this);
resolver.registerContentObserver(
Settings.System.getUriFor(Settings.System.NAVI_BAR_COLOR), false, this);
resolver.registerContentObserver(
Settings.System.getUriFor(Settings.System.USE_SOFT_BUTTONS), false, this);
resolver.registerContentObserver(
Settings.System.getUriFor(Settings.System.STATUS_BAR_BRIGHTNESS_TOGGLE), false, this);
resolver.registerContentObserver(
Settings.System.getUriFor(Settings.System.STATUS_BAR_INTRUDER_ALERT), false, this);
resolver.registerContentObserver(
Settings.System.getUriFor(Settings.System.STATUS_BAR_NOTIF), false, this);
resolver.registerContentObserver(
Settings.System.getUriFor(Settings.System.STATUS_BAR_SHOWRAM), false, this);
onChange(true);
}
@Override
public void onChange(boolean selfChange) {
ContentResolver resolver = mContext.getContentResolver();
int defValue;
int defValuesColor = mContext.getResources().getInteger(com.android.internal.R.color.color_default_cyanmobile);
defValue=(CmSystem.getDefaultBool(mContext, CmSystem.CM_DEFAULT_BOTTOM_STATUS_BAR) ? 1 : 0);
mBottomBar = (Settings.System.getInt(resolver,
Settings.System.STATUS_BAR_BOTTOM, defValue) == 1);
defValue=(CmSystem.getDefaultBool(mContext, CmSystem.CM_DEFAULT_SOFT_BUTTONS_LEFT) ? 1 : 0);
mButtonsLeft = (Settings.System.getInt(resolver,
Settings.System.SOFT_BUTTONS_LEFT, defValue) == 1);
defValue=(CmSystem.getDefaultBool(mContext, CmSystem.CM_DEFAULT_USE_DEAD_ZONE) ? 1 : 0);
mDeadZone = (Settings.System.getInt(resolver,
Settings.System.STATUS_BAR_DEAD_ZONE, defValue) == 1);
mStatusBarCarrier = Settings.System.getInt(resolver,
Settings.System.STATUS_BAR_CARRIER, 6);
mStatusBarClock = Settings.System.getInt(resolver,
Settings.System.STATUS_BAR_CLOCK, 1);
mStatusBarCarrierLogo = Settings.System.getInt(resolver,
Settings.System.CARRIER_LOGO, 0);
mStatusBarReverse = (Settings.System.getInt(resolver,
Settings.System.STATUS_BAR_REVERSE, 0) == 1);
mShowCmBatteryStatusBar = (Settings.System.getInt(resolver,
Settings.System.STATUS_BAR_BATTERY, 0) == 5);
mShowDate = (Settings.System.getInt(resolver,
Settings.System.STATUS_BAR_DATE, 0) == 1);
mShowNotif = (Settings.System.getInt(resolver,
Settings.System.STATUS_BAR_NOTIF, 1) == 1);
mShowRam = (Settings.System.getInt(resolver,
Settings.System.STATUS_BAR_SHOWRAM, 1) == 1);
mShowCmBatterySideBar = (Settings.System.getInt(resolver,
Settings.System.STATUS_BAR_BATTERY, 0) == 4);
mHasSoftButtons = (Settings.System.getInt(resolver,
Settings.System.USE_SOFT_BUTTONS, 0) == 1);
LogoStatusBar = (Settings.System.getInt(resolver,
Settings.System.CARRIER_LOGO_STATUS_BAR, 0) == 1);
shouldTick = (Settings.System.getInt(resolver,
Settings.System.STATUS_BAR_INTRUDER_ALERT, 1) == 1);
mClockColor = (Settings.System.getInt(resolver,
Settings.System.STATUS_BAR_CLOCKCOLOR, defValuesColor));
mSettingsColor = (Settings.System.getInt(resolver,
Settings.System.STATUS_BAR_SETTINGSCOLOR, defValuesColor));
mStatusBarTab = (Settings.System.getInt(resolver,
Settings.System.EXPANDED_VIEW_WIDGET, 1) == 4);
mStatusBarTileView = (Settings.System.getInt(resolver,
Settings.System.EXPANDED_VIEW_WIDGET, 1) == 5);
mStatusBarGrid = (Settings.System.getInt(resolver,
Settings.System.EXPANDED_VIEW_WIDGET, 1) == 3);
mNaviShow = (Settings.System.getInt(resolver,
Settings.System.SHOW_NAVI_BUTTONS, 1) == 1);
mTinyExpanded = (Settings.System.getInt(resolver,
Settings.System.STATUSBAR_TINY_EXPANDED, 1) == 1);
mMoreExpanded = (Settings.System.getInt(resolver,
Settings.System.STATUSBAR_MORE_EXPANDED, 1) == 1);
autoBrightness = Settings.System.getInt(
resolver, Settings.System.SCREEN_BRIGHTNESS_MODE, 0) ==
Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;
mBrightnessControl = !autoBrightness && Settings.System.getInt(
resolver, Settings.System.STATUS_BAR_BRIGHTNESS_TOGGLE, 0) == 1;
IntruderTime = Settings.System.getInt(resolver,
Settings.System.STATUS_BAR_INTRUDER_TIME, INTRUDER_ALERT_DECAY_MS);
updateColors();
updateLayout();
updateCarrierLabel();
updateSettings();
}
}
// for brightness control on status bar
int mLinger;
int mInitialTouchX;
int mInitialTouchY;
private class ExpandedDialog extends Dialog {
ExpandedDialog(Context context) {
super(context, com.android.internal.R.style.Theme_Light_NoTitleBar);
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
boolean down = event.getAction() == KeyEvent.ACTION_DOWN;
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_BACK:
if (!down) {
animateCollapse();
}
return true;
}
return super.dispatchKeyEvent(event);
}
}
Runnable mLongPressBrightnessChange = new Runnable() {
public void run() {
mStatusBarView.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
adjustBrightness(mInitialTouchX);
mLinger = BRIGHTNESS_CONTROL_LINGER_THRESHOLD + 1;
}
};
@Override
public void onCreate() {
// First set up our views and stuff.
mDisplay = ((WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
CustomTheme currentTheme = getResources().getConfiguration().customTheme;
if (currentTheme != null) {
mCurrentTheme = (CustomTheme)currentTheme.clone();
}
makeStatusBarView(this);
// reset vars for bottom bar
if(mBottomBar){
EXPANDED_LEAVE_ALONE *= -1;
EXPANDED_FULL_OPEN *= -1;
}
// receive broadcasts
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_CONFIGURATION_CHANGED);
filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
filter.addAction(Intent.ACTION_SCREEN_OFF);
registerReceiver(mBroadcastReceiver, filter);
// Connect in to the status bar manager service
StatusBarIconList iconList = new StatusBarIconList();
ArrayList<IBinder> notificationKeys = new ArrayList<IBinder>();
ArrayList<StatusBarNotification> notifications = new ArrayList<StatusBarNotification>();
mCommandQueue = new CommandQueue(this, iconList);
mBarService = IStatusBarService.Stub.asInterface(
ServiceManager.getService(Context.STATUS_BAR_SERVICE));
int[] switches = new int[3];
try {
mBarService.registerStatusBar(mCommandQueue, iconList, notificationKeys, notifications,
switches);
} catch (RemoteException ex) {
// If the system process isn't there we're doomed anyway.
}
disable(switches[0]);
setIMEVisible(switches[1] != 0);
showNaviBar(switches[2] != 0);
// Set up the initial icon state
int N = iconList.size();
int viewIndex = 0;
for (int i=0; i<N; i++) {
StatusBarIcon icon = iconList.getIcon(i);
if (icon != null) {
addIcon(iconList.getSlot(i), i, viewIndex, icon);
viewIndex++;
}
}
// Set up the initial notification state
N = notificationKeys.size();
if (N == notifications.size()) {
for (int i=0; i<N; i++) {
addNotification(notificationKeys.get(i), notifications.get(i));
}
} else {
Slog.e(TAG, "Notification list length mismatch: keys=" + N
+ " notifications=" + notifications.size());
}
// Put up the view
FrameLayout container = new FrameLayout(this);
container.addView(mStatusBarView);
mStatusBarContainer = container;
addStatusBarView();
makeBatterySideBarViewLeft();
makeBatterySideBarViewRight();
addNavigationBar();
addIntruderView();
// Lastly, call to the icon policy to install/update all the icons.
mIconPolicy = new StatusBarPolicy(this);
mNetworkPolicy = new NetworkController(this);
mContext = getApplicationContext();
// set up settings observer
SettingsObserver settingsObserver = new SettingsObserver(mHandler);
settingsObserver.observe();
}
@Override
public void onDestroy() {
// we're never destroyed
}
// for immersive activities
private View mIntruderAlertView;
/**
* Nobody binds to us.
*/
@Override
public IBinder onBind(Intent intent) {
return null;
}
// ================================================================================
// Constructing the view
// ================================================================================
private void makeStatusBarView(Context context) {
Resources res = context.getResources();
mTouchDispatcher = new ItemTouchDispatcher(this);
int defValuesColor = context.getResources().getInteger(com.android.internal.R.color.color_default_cyanmobile);
int defValuesIconSize = context.getResources().getInteger(com.android.internal.R.integer.config_iconsize_default_cyanmobile);
int mIconSizeval = Settings.System.getInt(context.getContentResolver(),
Settings.System.STATUSBAR_ICONS_SIZE, defValuesIconSize);
int IconSizepx = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, mIconSizeval, res.getDisplayMetrics());
mIconSize = IconSizepx;
//Check for compact carrier layout and apply if enabled
mStatusBarCarrier = Settings.System.getInt(getContentResolver(),
Settings.System.STATUS_BAR_CARRIER, 6);
mStatusBarClock = Settings.System.getInt(getContentResolver(),
Settings.System.STATUS_BAR_CLOCK, 1);
mStatusBarCarrierLogo = Settings.System.getInt(getContentResolver(),
Settings.System.CARRIER_LOGO, 0);
mStatusBarReverse = (Settings.System.getInt(getContentResolver(),
Settings.System.STATUS_BAR_REVERSE, 0) == 1);
mShowCmBatteryStatusBar = (Settings.System.getInt(getContentResolver(),
Settings.System.STATUS_BAR_BATTERY, 0) == 5);
mShowDate = (Settings.System.getInt(getContentResolver(),
Settings.System.STATUS_BAR_DATE, 0) == 1);
mShowNotif = (Settings.System.getInt(getContentResolver(),
Settings.System.STATUS_BAR_NOTIF, 1) == 1);
mShowRam = (Settings.System.getInt(getContentResolver(),
Settings.System.STATUS_BAR_SHOWRAM, 1) == 1);
mShowCmBatterySideBar = (Settings.System.getInt(getContentResolver(),
Settings.System.STATUS_BAR_BATTERY, 0) == 4);
mHasSoftButtons = (Settings.System.getInt(getContentResolver(),
Settings.System.USE_SOFT_BUTTONS, 0) == 1);
LogoStatusBar = (Settings.System.getInt(getContentResolver(),
Settings.System.CARRIER_LOGO_STATUS_BAR, 0) == 1);
shouldTick = (Settings.System.getInt(getContentResolver(),
Settings.System.STATUS_BAR_INTRUDER_ALERT, 1) == 1);
mClockColor = (Settings.System.getInt(getContentResolver(),
Settings.System.STATUS_BAR_CLOCKCOLOR, defValuesColor));
mSettingsColor = (Settings.System.getInt(getContentResolver(),
Settings.System.STATUS_BAR_SETTINGSCOLOR, defValuesColor));
mStatusBarTab = (Settings.System.getInt(getContentResolver(),
Settings.System.EXPANDED_VIEW_WIDGET, 1) == 4);
- mStatusBarTileView = (Settings.System.getInt(resolver,
+ mStatusBarTileView = (Settings.System.getInt(getContentResolver(),
Settings.System.EXPANDED_VIEW_WIDGET, 1) == 5);
mStatusBarGrid = (Settings.System.getInt(getContentResolver(),
Settings.System.EXPANDED_VIEW_WIDGET, 1) == 3);
mNaviShow = (Settings.System.getInt(getContentResolver(),
Settings.System.SHOW_NAVI_BUTTONS, 1) == 1);
mTinyExpanded = (Settings.System.getInt(getContentResolver(),
Settings.System.STATUSBAR_TINY_EXPANDED, 1) == 1);
mMoreExpanded = (Settings.System.getInt(getContentResolver(),
Settings.System.STATUSBAR_TINY_EXPANDED, 1) == 1);
autoBrightness = Settings.System.getInt(
getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, 0) ==
Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;
mBrightnessControl = !autoBrightness && Settings.System.getInt(
getContentResolver(), Settings.System.STATUS_BAR_BRIGHTNESS_TOGGLE, 0) == 1;
IntruderTime = Settings.System.getInt(getContentResolver(),
Settings.System.STATUS_BAR_INTRUDER_TIME, INTRUDER_ALERT_DECAY_MS);
if (!mStatusBarTab || !mStatusBarTileView) {
mExpandedView = (ExpandedView)View.inflate(context,
R.layout.status_bar_expanded, null);
} else {
mExpandedView = (ExpandedView)View.inflate(context,
R.layout.status_bar_expandedtab, null);
}
mExpandedView.mService = this;
mExpandedView.mTouchDispatcher = mTouchDispatcher;
if (!mStatusBarReverse) {
mStatusBarView = (CmStatusBarView)View.inflate(context, R.layout.status_bar, null);
} else {
mStatusBarView = (CmStatusBarView)View.inflate(context, R.layout.status_bar_reverse, null);
}
mStatusBarView.mService = this;
mIntruderAlertView = View.inflate(context, R.layout.intruder_alert, null);
mIntruderAlertView.setVisibility(View.GONE);
mIntruderAlertView.setClickable(true);
mNavigationBarView = (NavigationBarView)View.inflate(context, R.layout.navigation_bar, null);
mNaviBarContainer = (FrameLayout)mNavigationBarView.findViewById(R.id.navibarBackground);
mBackLogoLayout = (BackLogo)mStatusBarView.findViewById(R.id.backlogo);
// apply transparent status bar drawables
int transStatusBar = Settings.System.getInt(getContentResolver(), Settings.System.TRANSPARENT_STATUS_BAR, 0);
int statusBarColor = Settings.System.getInt(getContentResolver(), Settings.System.STATUS_BAR_COLOR, defValuesColor);
switch (transStatusBar) {
case 0 : // theme, leave alone
mStatusBarView.setBackgroundDrawable(getResources().getDrawable(R.drawable.statusbar_background));
break;
case 1 : // based on ROM
mStatusBarView.setBackgroundDrawable(getResources().getDrawable(R.drawable.statusbar_background_black));
break;
case 2 : // semi transparent
mStatusBarView.setBackgroundDrawable(getResources().getDrawable(R.drawable.statusbar_background_semi));
break;
case 3 : // gradient
mStatusBarView.setBackgroundDrawable(getResources().getDrawable(R.drawable.statusbar_background_gradient));
break;
case 4 : // user defined argb hex color
mStatusBarView.setBackgroundColor(statusBarColor);
break;
case 5 : // transparent
break;
case 6 : // transparent and BackLogo
mStatusBarView.setBackgroundDrawable(getResources().getDrawable(R.drawable.status_bar_transparent_background));
Uri savedImage = Uri.fromFile(new File("/data/data/com.cyanogenmod.cmparts/files/bc_background"));
if (savedImage != null) {
Bitmap bitmapImage = BitmapFactory.decodeFile(savedImage.getPath());
Drawable bgrImage = new BitmapDrawable(bitmapImage);
mBackLogoLayout.setBackgroundDrawable(bgrImage);
} else {
mBackLogoLayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.statusbar_background_semi));
}
break;
}
// apply transparent navi bar drawables
int transNaviBar = Settings.System.getInt(getContentResolver(), Settings.System.TRANSPARENT_NAVI_BAR, 0);
int naviBarColor = Settings.System.getInt(getContentResolver(), Settings.System.NAVI_BAR_COLOR, defValuesColor);
switch (transNaviBar) {
case 0 : // theme, leave alone
mNaviBarContainer.setBackgroundDrawable(getResources().getDrawable(R.drawable.navibar_background));
break;
case 1 : // based on ROM
mNaviBarContainer.setBackgroundDrawable(getResources().getDrawable(R.drawable.navibar_background_black));
break;
case 2 : // semi transparent
mNaviBarContainer.setBackgroundDrawable(getResources().getDrawable(R.drawable.navibar_background_semi));
break;
case 3 : // gradient
mNaviBarContainer.setBackgroundDrawable(getResources().getDrawable(R.drawable.navibar_background_gradient));
break;
case 4 : // user defined argb hex color
mNaviBarContainer.setBackgroundColor(naviBarColor);
break;
case 5 : // transparent
break;
case 6 : // BackLogo
Uri savedImage = Uri.fromFile(new File("/data/data/com.cyanogenmod.cmparts/files/navb_background"));
if (savedImage != null) {
Bitmap bitmapImage = BitmapFactory.decodeFile(savedImage.getPath());
Drawable bgrImage = new BitmapDrawable(bitmapImage);
mNaviBarContainer.setBackgroundDrawable(bgrImage);
} else {
mNaviBarContainer.setBackgroundDrawable(getResources().getDrawable(R.drawable.navibar_background_black));
}
break;
}
// figure out which pixel-format to use for the status bar.
mPixelFormat = PixelFormat.TRANSLUCENT;
mStatusIcons = (LinearLayout)mStatusBarView.findViewById(R.id.statusIcons);
mStatusIcons.setOnClickListener(mIconButtonListener);
mNotificationIcons = (IconMerger)mStatusBarView.findViewById(R.id.notificationIcons);
mIcons = (LinearLayout)mStatusBarView.findViewById(R.id.icons);
mCenterClock = (LinearLayout)mStatusBarView.findViewById(R.id.centerClock);
mLeftClock = (LinearLayout)mStatusBarView.findViewById(R.id.clockLeft);
mCarrierLabelStatusBarLayout = (CarrierLabelStatusBar)mStatusBarView.findViewById(R.id.carrier_label_status_bar_layout);
mCenterCarrierLabelStatusBarLayout = (CenterCarrierLabelStatusBar)mStatusBarView.findViewById(R.id.carrier_label_status_bar_center_layout);
mLeftCarrierLabelStatusBarLayout = (LeftCarrierLabelStatusBar)mStatusBarView.findViewById(R.id.carrier_label_status_bar_left_layout);
mCarrierLogoLayout = (CarrierLogo)mStatusBarView.findViewById(R.id.carrier_logo);
mCarrierLogoCenterLayout = (CenterCarrierLogo)mStatusBarView.findViewById(R.id.carrier_logo_center);
mCarrierLogoLeftLayout = (LeftCarrierLogo)mStatusBarView.findViewById(R.id.carrier_logo_left);
mCmBatteryStatusBar = (CmBatteryStatusBar)mStatusBarView.findViewById(R.id.batteryStatusBar);
mTickerView = mStatusBarView.findViewById(R.id.ticker);
mDateView = (DateView)mStatusBarView.findViewById(R.id.date);
mCmBatteryMiniIcon = (CmBatteryMiniIcon)mStatusBarView.findViewById(R.id.CmBatteryMiniIcon);
/* Destroy any existing widgets before recreating the expanded dialog
* to ensure there are no lost context issues */
if (mPowerWidget != null) {
mPowerWidget.destroyWidget();
}
if (mPowerWidgetBottom != null) {
mPowerWidgetBottom.destroyWidget();
}
if (mPowerWidgetOne != null) {
mPowerWidgetOne.destroyWidget();
}
if (mPowerWidgetTwo != null) {
mPowerWidgetTwo.destroyWidget();
}
if (mPowerWidgetThree != null) {
mPowerWidgetThree.destroyWidget();
}
if (mPowerWidgetFour != null) {
mPowerWidgetFour.destroyWidget();
}
mExpandedDialog = new ExpandedDialog(context);
if (!mStatusBarTab || !mStatusBarTileView) {
mExpandedContents = mExpandedView.findViewById(R.id.notificationLinearLayout);
} else {
mExpandedContents = mExpandedView.findViewById(R.id.notifications_layout);
mExpandededContents = mExpandedView.findViewById(R.id.power_and_carrier_layout);
}
mOngoingTitle = (TextView)mExpandedView.findViewById(R.id.ongoingTitle);
mOngoingItems = (LinearLayout)mExpandedView.findViewById(R.id.ongoingItems);
mLatestTitle = (TextView)mExpandedView.findViewById(R.id.latestTitle);
mLatestItems = (LinearLayout)mExpandedView.findViewById(R.id.latestItems);
mNoNotificationsTitle = (TextView)mExpandedView.findViewById(R.id.noNotificationsTitle);
if (mStatusBarTab || mStatusBarTileView) {
mLatestTitles = (TextView)mExpandedView.findViewById(R.id.latestTitles);
mNoNotificationsTitles = (TextView)mExpandedView.findViewById(R.id.noNotificationsTitles);
}
mClearButton = (ImageView)mExpandedView.findViewById(R.id.clear_all_button);
mClearButton.setOnClickListener(mClearButtonListener);
mClearOldButton = (TextView)mExpandedView.findViewById(R.id.clear_old_button);
mClearOldButton.setOnClickListener(mClearButtonListener);
mCompactClearButton = (TextView)mExpandedView.findViewById(R.id.compact_clear_all_button);
mCompactClearButton.setOnClickListener(mClearButtonListener);
mCarrierLabelExpLayout = (CarrierLabelExp)mExpandedView.findViewById(R.id.carrierExp);
mPowerAndCarrier = (LinearLayout)mExpandedView.findViewById(R.id.power_and_carrier);
int transPowerAndCarrier = Settings.System.getInt(getContentResolver(), Settings.System.TRANSPARENT_PWR_CRR, 0);
int PowerAndCarrierColor = Settings.System.getInt(getContentResolver(), Settings.System.PWR_CRR_COLOR, defValuesColor);
switch (transPowerAndCarrier) {
case 0 : // theme, leave alone
mPowerAndCarrier.setBackgroundDrawable(getResources().getDrawable(R.drawable.title_bar_portrait));
break;
case 1 : // user defined argb hex color
mPowerAndCarrier.setBackgroundColor(PowerAndCarrierColor);
break;
case 2 : // transparent
break;
}
mScrollView = (ScrollView)mExpandedView.findViewById(R.id.scroll);
mBottomScrollView = (ScrollView)mExpandedView.findViewById(R.id.bottomScroll);
mNotificationLinearLayout = (LinearLayout)mExpandedView.findViewById(R.id.notificationLinearLayout);
mBottomNotificationLinearLayout = (LinearLayout)mExpandedView.findViewById(R.id.bottomNotificationLinearLayout);
mMusicToggleButton = (ImageView)mExpandedView.findViewById(R.id.music_toggle_button);
mMusicToggleButton.setOnClickListener(mMusicToggleButtonListener);
mCenterClockex = (LinearLayout)mExpandedView.findViewById(R.id.centerClockex);
mCenterIconex = (SignalClusterView)mExpandedView.findViewById(R.id.centerIconex);
mSettingsIconButton = (ImageView)mExpandedView.findViewById(R.id.settingIcon);
mSettingsIconButton.setOnClickListener(mSettingsIconButtonListener);
mStatusIconsExp = (LinearLayout)mExpandedView.findViewById(R.id.expstatusIcons);
if (mStatusBarTileView) {
mQuickContainer = (QuickSettingsContainerView)mExpandedView.findViewById(R.id.quick_settings_container);
}
if (mStatusBarTileView && (mQuickContainer != null)) {
mQS = new QuickSettingsController(context, mQuickContainer);
}
mExpandedView.setVisibility(View.GONE);
mOngoingTitle.setVisibility(View.GONE);
mLatestTitle.setVisibility(View.GONE);
if (mStatusBarTab || mStatusBarTileView) {
mLatestTitles.setVisibility(View.GONE);
}
mMusicControls = (MusicControls)mExpandedView.findViewById(R.id.exp_music_controls);
mPowerWidget = (PowerWidget)mExpandedView.findViewById(R.id.exp_power_stat);
mPowerWidget.setGlobalButtonOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(Settings.System.getInt(getContentResolver(),
Settings.System.EXPANDED_HIDE_ONCHANGE, 0) == 1) {
animateCollapse();
}
}
});
mPowerWidget.setGlobalButtonOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View v) {
animateCollapse();
return true;
}
});
mPowerWidgetOne = (PowerWidgetOne)mExpandedView.findViewById(R.id.exp_power_stat_one);
mPowerWidgetOne.setGlobalButtonOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(Settings.System.getInt(getContentResolver(),
Settings.System.EXPANDED_HIDE_ONCHANGE, 0) == 1) {
animateCollapse();
}
}
});
mPowerWidgetOne.setGlobalButtonOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View v) {
animateCollapse();
return true;
}
});
mPowerWidgetTwo = (PowerWidgetTwo)mExpandedView.findViewById(R.id.exp_power_stat_two);
mPowerWidgetTwo.setGlobalButtonOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(Settings.System.getInt(getContentResolver(),
Settings.System.EXPANDED_HIDE_ONCHANGE, 0) == 1) {
animateCollapse();
}
}
});
mPowerWidgetTwo.setGlobalButtonOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View v) {
animateCollapse();
return true;
}
});
mPowerWidgetThree = (PowerWidgetThree)mExpandedView.findViewById(R.id.exp_power_stat_three);
mPowerWidgetThree.setGlobalButtonOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(Settings.System.getInt(getContentResolver(),
Settings.System.EXPANDED_HIDE_ONCHANGE, 0) == 1) {
animateCollapse();
}
}
});
mPowerWidgetThree.setGlobalButtonOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View v) {
animateCollapse();
return true;
}
});
mPowerWidgetFour = (PowerWidgetFour)mExpandedView.findViewById(R.id.exp_power_stat_four);
mPowerWidgetFour.setGlobalButtonOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(Settings.System.getInt(getContentResolver(),
Settings.System.EXPANDED_HIDE_ONCHANGE, 0) == 1) {
animateCollapse();
}
}
});
mPowerWidgetFour.setGlobalButtonOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View v) {
animateCollapse();
return true;
}
});
mCarrierLabelLayout = (LinearLayout)mExpandedView.findViewById(R.id.carrier_label_layout);
mCompactCarrierLayout = (LinearLayout)mExpandedView.findViewById(R.id.compact_carrier_layout);
mAvalMemLayout = (LinearLayout)mExpandedView.findViewById(R.id.memlabel_layout);
memHeader = (TextView) mExpandedView.findViewById(R.id.avail_mem_text);
avalMemPB = (ProgressBar) mExpandedView.findViewById(R.id.aval_memos);
mTicker = new MyTicker(context, mStatusBarView);
mTickerText = (TickerView)mStatusBarView.findViewById(R.id.tickerText);
mTickerText.mTicker = mTicker;
if (!mStatusBarTab || !mStatusBarTileView) {
mTrackingView = (TrackingView)View.inflate(context, R.layout.status_bar_tracking, null);
} else {
mTrackingView = (TrackingView)View.inflate(context, R.layout.status_bar_trackingtab, null);
}
mTrackingView.mService = this;
mCloseView = (CloseDragHandle)mTrackingView.findViewById(R.id.close);
mCloseView.mService = this;
mNotificationBackgroundView = (View)mTrackingView.findViewById(R.id.notificationBackground);
// apply transparent notification background drawables
int transNotificationBackground = Settings.System.getInt(getContentResolver(), Settings.System.TRANSPARENT_NOTIFICATION_BACKGROUND, 0);
int notificationBackgroundColor = Settings.System.getInt(getContentResolver(), Settings.System.NOTIFICATION_BACKGROUND_COLOR, defValuesColor);
switch (transNotificationBackground) {
case 0 : // theme, leave alone
mNotificationBackgroundView.setBackgroundDrawable(getResources().getDrawable(R.drawable.shade_bg));
break;
case 1 : // default based on ROM
mNotificationBackgroundView.setBackgroundDrawable(getResources().getDrawable(R.drawable.shade_bg2));
break;
case 2 : // user defined argb hex color
mNotificationBackgroundView.setBackgroundColor(notificationBackgroundColor);
break;
case 3 : // semi transparent
mNotificationBackgroundView.setBackgroundDrawable(getResources().getDrawable(R.drawable.shade_trans_bg));
break;
case 4 : // peeping android background image
mNotificationBackgroundView.setBackgroundDrawable(getResources().getDrawable(R.drawable.status_bar_special));
break;
case 5 : // user selected background image
Uri savedImage = Uri.fromFile(new File("/data/data/com.cyanogenmod.cmparts/files/nb_background"));
if (savedImage != null) {
Bitmap bitmapImage = BitmapFactory.decodeFile(savedImage.getPath());
Drawable bgrImage = new BitmapDrawable(bitmapImage);
mNotificationBackgroundView.setBackgroundDrawable(bgrImage);
} else {
mNotificationBackgroundView.setBackgroundDrawable(getResources().getDrawable(R.drawable.status_bar_special));
}
break;
}
mContext=context;
if (mStatusBarTab || mStatusBarTileView) {
mPowerCarrier = (LinearLayout)mExpandedView.findViewById(R.id.power_and_carrier_layout);
mNotifications = (LinearLayout)mExpandedView.findViewById(R.id.notifications_layout);
mNotificationsToggle = (TextView)mTrackingView.findViewById(R.id.statusbar_notification_toggle);
mButtonsToggle = (TextView)mTrackingView.findViewById(R.id.statusbar_buttons_toggle);
mButtonsToggle.setTextColor(mClockColor);
mNotificationsToggle.setTextColor(Color.parseColor("#666666"));
mNotifications.setVisibility(View.GONE);
}
mSettingsButton = (ImageView)mTrackingView.findViewById(R.id.settingUp);
int transSettingsButton = Settings.System.getInt(getContentResolver(), Settings.System.TRANSPARENT_STS_BTT, 0);
int SettingsButtonColor = Settings.System.getInt(getContentResolver(), Settings.System.STS_BTT_COLOR, defValuesColor);
switch (transSettingsButton) {
case 0 : // theme, leave alone
mSettingsButton.setImageBitmap(getNinePatch(R.drawable.status_bar_close_on, getExpandedWidth(), getStatBarSize(), context));
break;
case 1 : // user defined argb hex color
mSettingsButton.setImageBitmap(getNinePatch(R.drawable.status_bar_transparent_background, getExpandedWidth(), getCloseDragSize(), context));
mSettingsButton.setBackgroundColor(SettingsButtonColor);
break;
case 2 : // transparent
mSettingsButton.setImageBitmap(getNinePatch(R.drawable.status_bar_transparent_background, getExpandedWidth(), getCloseDragSize(), context));
break;
}
mSettingsButton.setOnLongClickListener(mSettingsButtonListener);
mCarrierLabelBottomLayout = (CarrierLabelBottom) mTrackingView.findViewById(R.id.carrierlabel_bottom);
mPowerWidgetBottom = (PowerWidgetBottom) mTrackingView.findViewById(R.id.exp_power_stat);
mPowerWidgetBottom.setGlobalButtonOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(Settings.System.getInt(getContentResolver(),
Settings.System.EXPANDED_HIDE_ONCHANGE, 0) == 1) {
animateCollapse();
}
}
});
mPowerWidgetBottom.setGlobalButtonOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View v) {
animateCollapse();
return true;
}
});
if (mStatusBarTab || mStatusBarTileView) {
mNotificationsToggle.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
mNotificationsToggle.setTextColor(mClockColor);
mButtonsToggle.setTextColor(Color.parseColor("#666666"));
LinearLayout parent = (LinearLayout)mButtonsToggle.getParent();
parent.setBackgroundResource(R.drawable.title_bar_portrait);
mPowerCarrier.setVisibility(View.GONE);
mPowerCarrier.startAnimation(loadAnim(com.android.internal.R.anim.fade_out, null));
mNotifications.setVisibility(View.VISIBLE);
mNotifications.startAnimation(loadAnim(com.android.internal.R.anim.fade_in, null));
updateExpandedViewPos(EXPANDED_FULL_OPEN);
}
});
mButtonsToggle.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
mButtonsToggle.setTextColor(mClockColor);
mNotificationsToggle.setTextColor(Color.parseColor("#666666"));
LinearLayout parent = (LinearLayout)mButtonsToggle.getParent();
parent.setBackgroundResource(R.drawable.title_bar_portrait);
mPowerCarrier.setVisibility(View.VISIBLE);
mPowerCarrier.startAnimation(loadAnim(com.android.internal.R.anim.fade_in, null));
mNotifications.setVisibility(View.GONE);
mNotifications.startAnimation(loadAnim(com.android.internal.R.anim.fade_out, null));
updateExpandedViewPos(EXPANDED_FULL_OPEN);
}
});
}
updateColors();
updateLayout();
updateCarrierLabel();
if (mStatusBarCarrierLogo == 1) {
if (LogoStatusBar) {
Uri savedImage = Uri.fromFile(new File("/data/data/com.cyanogenmod.cmparts/files/lg_background"));
Bitmap bitmapImage = BitmapFactory.decodeFile(savedImage.getPath());
Drawable bgrImage = new BitmapDrawable(bitmapImage);
mCarrierLogoLayout.setBackgroundDrawable(bgrImage);
} else {
mCarrierLogoLayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.ic_statusbar_carrier_logos));
}
} else if (mStatusBarCarrierLogo == 2) {
if (LogoStatusBar) {
Uri savedImage = Uri.fromFile(new File("/data/data/com.cyanogenmod.cmparts/files/lg_background"));
Bitmap bitmapImage = BitmapFactory.decodeFile(savedImage.getPath());
Drawable bgrImage = new BitmapDrawable(bitmapImage);
mCarrierLogoCenterLayout.setBackgroundDrawable(bgrImage);
} else {
mCarrierLogoCenterLayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.ic_statusbar_carrier_logos));
}
} else if (mStatusBarCarrierLogo == 3) {
if (LogoStatusBar) {
Uri savedImage = Uri.fromFile(new File("/data/data/com.cyanogenmod.cmparts/files/lg_background"));
Bitmap bitmapImage = BitmapFactory.decodeFile(savedImage.getPath());
Drawable bgrImage = new BitmapDrawable(bitmapImage);
mCarrierLogoLeftLayout.setBackgroundDrawable(bgrImage);
} else {
mCarrierLogoLeftLayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.ic_statusbar_carrier_logos));
}
}
mEdgeBorder = res.getDimensionPixelSize(R.dimen.status_bar_edge_ignore);
// set the inital view visibility
setAreThereNotifications();
mDateView.setVisibility(View.INVISIBLE);
showClock(Settings.System.getInt(getContentResolver(), Settings.System.STATUS_BAR_CLOCK, 1) != 0);
mVelocityTracker = VelocityTracker.obtain();
mDoNotDisturb = new DoNotDisturb(mContext);
totalMemory = 0;
availableMemory = 0;
getMemInfo();
}
private void updateColors() {
ContentResolver resolver = mContext.getContentResolver();
int defValuesColor = mContext.getResources().getInteger(com.android.internal.R.color.color_default_cyanmobile);
mItemText = Settings.System.getInt(resolver, Settings.System.COLOR_NOTIFICATION_ITEM_TEXT, mBlackColor);
mItemTime = Settings.System.getInt(resolver, Settings.System.COLOR_NOTIFICATION_ITEM_TIME, defValuesColor);
mItemTitle = Settings.System.getInt(resolver, Settings.System.COLOR_NOTIFICATION_ITEM_TITLE, defValuesColor);
mDateColor = Settings.System.getInt(resolver, Settings.System.COLOR_DATE, defValuesColor);
mDateView.setTextColor(mDateColor);
mClearButton.setColorFilter(mDateColor, Mode.MULTIPLY);
mSettingsIconButton.setColorFilter(mDateColor, Mode.MULTIPLY);
mButtonText = Settings.System.getInt(resolver, Settings.System.COLOR_NOTIFICATION_CLEAR_BUTTON, mBlackColor);
if (mStatusBarTab || mStatusBarTileView) {
mCompactClearButton.setTextColor(mButtonText);
} else {
if (mMoreExpanded) {
mClearOldButton.setTextColor(mButtonText);
}
}
mNotifyNone = Settings.System
.getInt(resolver, Settings.System.COLOR_NOTIFICATION_NONE, defValuesColor);
mNoNotificationsTitle.setTextColor(mNotifyNone);
if ((mStatusBarTab || mStatusBarTileView) && (mNoNotificationsTitles != null)) {
mNoNotificationsTitles.setTextColor(mNotifyNone);
}
mNotifyTicker = Settings.System
.getInt(resolver, Settings.System.COLOR_NOTIFICATION_TICKER_TEXT, defValuesColor);
mTickerText.updateColor(mNotifyTicker);
mNotifyLatest = Settings.System
.getInt(resolver, Settings.System.COLOR_NOTIFICATION_LATEST, defValuesColor);
mLatestTitle.setTextColor(mNotifyLatest);
if (mStatusBarTab || mStatusBarTileView) {
mLatestTitles.setTextColor(mNotifyLatest);
}
mNotifyOngoing = Settings.System
.getInt(resolver, Settings.System.COLOR_NOTIFICATION_ONGOING, defValuesColor);
mOngoingTitle.setTextColor(mNotifyOngoing);
}
void resetTextViewColors(View vw) {
ViewGroup gv = (ViewGroup)vw;
int ct = gv.getChildCount();
if (ct > 0) {
for (int i = 0; i < ct; i++) {
try {
setTextViewColors((TextView)gv.getChildAt(i));
} catch (Exception ex) { }
try {
resetTextViewColors((View)gv.getChildAt(i));
} catch (Exception ex) { }
}
}
}
void setTextViewColors(TextView tc) {
try {
int id = tc.getId();
switch (id) {
case com.android.internal.R.id.text:
tc.setTextColor(mItemText);
break;
case com.android.internal.R.id.time:
tc.setTextColor(mItemTime);
break;
case com.android.internal.R.id.title:
tc.setTextColor(mItemTitle);
break;
default:
tc.setTextColor(mItemText);
break;
}
} catch (Exception e) { }
}
private void updateSettings() {
int changedVal = Settings.System.getInt(getContentResolver(),
Settings.System.EXPANDED_VIEW_WIDGET, 1);
// check that it's not 0 to not reset the variable
// this should be the only place mLastPowerToggle is set
if (changedVal != 0) {
mLastPowerToggle = changedVal;
}
}
private void makeBatterySideBarViewLeft() {
if (!mShowCmBatterySideBar) {
return;
}
CmBatterySideBar batterySideBarLeft = (CmBatterySideBar) View.inflate(this, R.layout.battery_sidebars, null);
WindowManagerImpl wm = WindowManagerImpl.getDefault();
DisplayMetrics metrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(metrics);
Resources res = getResources();
int width = res.getDimensionPixelSize(R.dimen.battery_sidebar_width);
WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
width, metrics.heightPixels,
WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
PixelFormat.RGBX_8888);
lp.gravity = Gravity.LEFT;
lp.setTitle("Battery SideBarLeft");
wm.addView(batterySideBarLeft, lp);
}
private void makeBatterySideBarViewRight() {
if (!mShowCmBatterySideBar) {
return;
}
CmBatterySideBar batterySideBarRight = (CmBatterySideBar) View.inflate(this, R.layout.battery_sidebars, null);
WindowManagerImpl wm = WindowManagerImpl.getDefault();
DisplayMetrics metrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(metrics);
Resources res = getResources();
int width = res.getDimensionPixelSize(R.dimen.battery_sidebar_width);
WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
width, metrics.heightPixels,
WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
PixelFormat.RGBX_8888);
lp.gravity = Gravity.RIGHT;
lp.setTitle("Battery SideBarRight");
wm.addView(batterySideBarRight, lp);
}
private void updateCarrierLabel() {
if (mStatusBarCarrier == 5) {
mCarrierLabelLayout.setVisibility(View.GONE);
mCarrierLabelStatusBarLayout.setVisibility(View.GONE);
mCenterCarrierLabelStatusBarLayout.setVisibility(View.GONE);
mLeftCarrierLabelStatusBarLayout.setVisibility(View.GONE);
mCarrierLabelBottomLayout.setVisibility(View.GONE);
// Disable compact carrier when bottom bar is enabled for now
// till we find a better solution (looks ugly alone at the top)
if (mBottomBar) {
mCompactCarrierLayout.setVisibility(View.GONE);
}
} else if (mStatusBarCarrier == 0) {
mCarrierLabelBottomLayout.setVisibility(View.GONE);
mCarrierLabelLayout.setVisibility(View.GONE);
mCarrierLabelStatusBarLayout.setVisibility(View.GONE);
mCenterCarrierLabelStatusBarLayout.setVisibility(View.GONE);
mLeftCarrierLabelStatusBarLayout.setVisibility(View.GONE);
mCompactCarrierLayout.setVisibility(View.GONE);
} else if (mStatusBarCarrier == 1) {
mCarrierLabelBottomLayout.setVisibility(View.GONE);
mCarrierLabelStatusBarLayout.setVisibility(View.VISIBLE);
mCenterCarrierLabelStatusBarLayout.setVisibility(View.GONE);
mLeftCarrierLabelStatusBarLayout.setVisibility(View.GONE);
mCarrierLabelLayout.setVisibility(View.GONE);
mCompactCarrierLayout.setVisibility(View.GONE);
} else if (mStatusBarCarrier == 2) {
mCarrierLabelBottomLayout.setVisibility(View.GONE);
mCarrierLabelStatusBarLayout.setVisibility(View.GONE);
mCenterCarrierLabelStatusBarLayout.setVisibility(View.VISIBLE);
mLeftCarrierLabelStatusBarLayout.setVisibility(View.GONE);
mCarrierLabelLayout.setVisibility(View.GONE);
mCompactCarrierLayout.setVisibility(View.GONE);
} else if (mStatusBarCarrier == 3) {
mCarrierLabelBottomLayout.setVisibility(View.GONE);
mCarrierLabelStatusBarLayout.setVisibility(View.GONE);
mCenterCarrierLabelStatusBarLayout.setVisibility(View.GONE);
mLeftCarrierLabelStatusBarLayout.setVisibility(View.VISIBLE);
mCarrierLabelLayout.setVisibility(View.GONE);
mCompactCarrierLayout.setVisibility(View.GONE);
} else if (mStatusBarCarrier == 4) {
mCarrierLogoLayout.setVisibility(View.GONE);
mCarrierLabelLayout.setVisibility(View.GONE);
mCarrierLogoCenterLayout.setVisibility(View.GONE);
mCarrierLogoLeftLayout.setVisibility(View.GONE);
mCompactCarrierLayout.setVisibility(View.GONE);
if (mBottomBar) {
mCarrierLabelBottomLayout.setVisibility(View.GONE);
} else {
mCarrierLabelBottomLayout.setVisibility(View.VISIBLE);
}
} else if (mStatusBarCarrierLogo == 1) {
mCarrierLogoLayout.setVisibility(View.VISIBLE);
mCarrierLogoCenterLayout.setVisibility(View.GONE);
mCarrierLogoLeftLayout.setVisibility(View.GONE);
} else if (mStatusBarCarrierLogo == 2) {
mCarrierLogoLayout.setVisibility(View.GONE);
mCarrierLogoCenterLayout.setVisibility(View.VISIBLE);
mCarrierLogoLeftLayout.setVisibility(View.GONE);
} else if (mStatusBarCarrierLogo == 3) {
mCarrierLogoLayout.setVisibility(View.GONE);
mCarrierLogoCenterLayout.setVisibility(View.GONE);
mCarrierLogoLeftLayout.setVisibility(View.VISIBLE);
} else {
mCarrierLabelLayout.setVisibility(View.VISIBLE);
mCarrierLabelBottomLayout.setVisibility(View.GONE);
mCarrierLabelStatusBarLayout.setVisibility(View.GONE);
mCenterCarrierLabelStatusBarLayout.setVisibility(View.GONE);
mLeftCarrierLabelStatusBarLayout.setVisibility(View.GONE);
mCarrierLogoLayout.setVisibility(View.GONE);
mCarrierLogoCenterLayout.setVisibility(View.GONE);
mCarrierLogoLeftLayout.setVisibility(View.GONE);
mCompactCarrierLayout.setVisibility(View.GONE);
mMusicToggleButton.setVisibility(View.VISIBLE);
}
mCenterClockex.setVisibility(mMoreExpanded ? View.VISIBLE : View.GONE);
mAvalMemLayout.setVisibility(mShowRam ? View.VISIBLE : View.GONE);
}
private boolean getDataStates(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getMobileDataEnabled();
}
private void updateLayout() {
if(mTrackingView==null || mCloseView==null || mExpandedView==null)
return;
// handle trackingview
mTrackingView.removeView(mCloseView);
mTrackingView.addView(mCloseView, mBottomBar ? 0 : 1);
// handle expanded view reording for bottom bar
LinearLayout powerAndCarrier=(LinearLayout)mExpandedView.findViewById(R.id.power_and_carrier);
PowerWidget power=(PowerWidget)mExpandedView.findViewById(R.id.exp_power_stat);
PowerWidgetOne powerOne=(PowerWidgetOne)mExpandedView.findViewById(R.id.exp_power_stat_one);
PowerWidgetTwo powerTwo=(PowerWidgetTwo)mExpandedView.findViewById(R.id.exp_power_stat_two);
PowerWidgetThree powerThree=(PowerWidgetThree)mExpandedView.findViewById(R.id.exp_power_stat_three);
PowerWidgetFour powerFour=(PowerWidgetFour)mExpandedView.findViewById(R.id.exp_power_stat_four);
//FrameLayout notifications=(FrameLayout)mExpandedView.findViewById(R.id.notifications);
// remove involved views
powerAndCarrier.removeView(power);
if (mStatusBarGrid) {
powerAndCarrier.removeView(powerOne);
powerAndCarrier.removeView(powerTwo);
powerAndCarrier.removeView(powerThree);
powerAndCarrier.removeView(powerFour);
}
mExpandedView.removeView(powerAndCarrier);
// readd in right order
mExpandedView.addView(powerAndCarrier, mBottomBar ? 1 : 0);
if (mStatusBarGrid) {
powerAndCarrier.addView(powerFour, mBottomBar && mStatusBarCarrier != 5 ? 1 : 0);
powerAndCarrier.addView(powerThree, mBottomBar && mStatusBarCarrier != 5 ? 1 : 0);
powerAndCarrier.addView(powerTwo, mBottomBar && mStatusBarCarrier != 5 ? 1 : 0);
powerAndCarrier.addView(powerOne, mBottomBar && mStatusBarCarrier != 5 ? 1 : 0);
}
powerAndCarrier.addView(power, mBottomBar && mStatusBarCarrier != 5 ? 1 : 0);
// Remove all notification views
mNotificationLinearLayout.removeAllViews();
mBottomNotificationLinearLayout.removeAllViews();
// Readd to correct scrollview depending on mBottomBar
if (mBottomBar) {
mScrollView.setVisibility(View.GONE);
mBottomNotificationLinearLayout.addView(mCompactClearButton);
mBottomNotificationLinearLayout.addView(mNoNotificationsTitle);
mBottomNotificationLinearLayout.addView(mOngoingTitle);
mBottomNotificationLinearLayout.addView(mOngoingItems);
mBottomNotificationLinearLayout.addView(mLatestTitle);
mBottomNotificationLinearLayout.addView(mLatestItems);
mBottomScrollView.setVisibility(View.VISIBLE);
} else {
mBottomScrollView.setVisibility(View.GONE);
mNotificationLinearLayout.addView(mNoNotificationsTitle);
mNotificationLinearLayout.addView(mOngoingTitle);
mNotificationLinearLayout.addView(mOngoingItems);
mNotificationLinearLayout.addView(mLatestTitle);
mNotificationLinearLayout.addView(mLatestItems);
mNotificationLinearLayout.addView(mCompactClearButton);
mScrollView.setVisibility(View.VISIBLE);
mCompactCarrierLayout.setVisibility(View.VISIBLE);
}
}
private int getNavBarSize() {
int defValuesNaviSize = mContext.getResources().getInteger(com.android.internal.R.integer.config_navibarsize_default_cyanmobile);
int navSizeval = Settings.System.getInt(mContext.getContentResolver(),
Settings.System.STATUSBAR_NAVI_SIZE, defValuesNaviSize);
int navSizepx = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
navSizeval, mContext.getResources().getDisplayMetrics());
return mNaviShow ? navSizepx : 0;
}
// For small-screen devices (read: phones) that lack hardware navigation buttons
private void addNavigationBar() {
mNavigationBarView.reorient();
WindowManagerImpl.getDefault().addView(
mNavigationBarView, getNavigationBarLayoutParams());
}
private void repositionNavigationBar() {
mNavigationBarView.reorient();
WindowManagerImpl.getDefault().updateViewLayout(
mNavigationBarView, getNavigationBarLayoutParams());
}
private WindowManager.LayoutParams getNavigationBarLayoutParams() {
final int rotation = mDisplay.getRotation();
Resources res = mContext.getResources();
final boolean sideways =
(mNaviShow && (Settings.System.getInt(mContext.getContentResolver(),
Settings.System.NAVI_BUTTONS, 1) == 1));
final boolean anotherways =
(rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270);
final int size = getNavBarSize();
final int oldsize = getStatBarSize();
WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
sideways ? (anotherways ? oldsize : size) : 0,
WindowManager.LayoutParams.TYPE_NAVIGATION_BAR,
0
| WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
| WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
| WindowManager.LayoutParams.FLAG_TOUCHABLE_WHEN_WAKING
| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_SPLIT_TOUCH,
PixelFormat.TRANSLUCENT);
lp.setTitle("NavigationBar");
lp.gravity = Gravity.BOTTOM | Gravity.FILL_HORIZONTAL;
lp.windowAnimations = 0;
return lp;
}
private int getStatBarSize() {
int defValuesStatsSize = mContext.getResources().getInteger(com.android.internal.R.integer.config_statbarsize_default_cyanmobile);
int statSizeval = Settings.System.getInt(mContext.getContentResolver(),
Settings.System.STATUSBAR_STATS_SIZE, defValuesStatsSize);
int statSizepx = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
statSizeval, mContext.getResources().getDisplayMetrics());
return statSizepx;
}
private int getCloseDragSize() {
int defValuesStatsSize = mContext.getResources().getInteger(com.android.internal.R.integer.config_statbarsize_default_cyanmobile);
int dragSizeval = Settings.System.getInt(mContext.getContentResolver(),
Settings.System.STATUSBAR_STATS_SIZE, defValuesStatsSize);
int dragSizefitUp = (dragSizeval-5);
int dragSizepx = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
dragSizefitUp, mContext.getResources().getDisplayMetrics());
return dragSizepx;
}
private void addIntruderView() {
final int height = getStatBarSize();
WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_NAVIGATION_BAR_PANEL,
WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
| WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
| WindowManager.LayoutParams.FLAG_TOUCHABLE_WHEN_WAKING
| WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
lp.gravity = Gravity.TOP | Gravity.FILL_HORIZONTAL;
lp.y += height * 1.5; // FIXME
lp.setTitle("IntruderAlert");
lp.windowAnimations = R.style.Animations_PopDownMenu_Center;
WindowManagerImpl.getDefault().addView(mIntruderAlertView, lp);
}
protected void addStatusBarView() {
final int height = getStatBarSize();
final View view = mStatusBarContainer;
WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
height,
WindowManager.LayoutParams.TYPE_STATUS_BAR,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_TOUCHABLE_WHEN_WAKING,
PixelFormat.TRANSLUCENT);
lp.gravity = Gravity.TOP | Gravity.FILL_HORIZONTAL;
lp.setTitle("StatusBar");
lp.windowAnimations = com.android.internal.R.style.Animation_StatusBar;
WindowManagerImpl.getDefault().addView(view, lp);
//mRecentApps.setupRecentApps();
mPowerWidget.setupWidget();
mPowerWidgetBottom.setupWidget();
mPowerWidgetOne.setupWidget();
mPowerWidgetTwo.setupWidget();
mPowerWidgetThree.setupWidget();
mPowerWidgetFour.setupWidget();
mMusicControls.setupControls();
if (mQS != null) mQS.setupQuickSettings();
}
public void addIcon(String slot, int index, int viewIndex, StatusBarIcon icon) {
if (SPEW_ICONS) {
Slog.d(TAG, "addIcon slot=" + slot + " index=" + index + " viewIndex=" + viewIndex
+ " icon=" + icon);
}
StatusBarIconView view = new StatusBarIconView(this, slot);
view.set(icon);
mStatusIcons.addView(view, viewIndex, new LinearLayout.LayoutParams(mIconSize, mIconSize));
StatusBarIconView viewExp = new StatusBarIconView(this, slot);
viewExp.set(icon);
mStatusIconsExp.addView(viewExp, viewIndex, new LinearLayout.LayoutParams(mIconSize, mIconSize));
}
public void updateIcon(String slot, int index, int viewIndex,
StatusBarIcon old, StatusBarIcon icon) {
if (SPEW_ICONS) {
Slog.d(TAG, "updateIcon slot=" + slot + " index=" + index + " viewIndex=" + viewIndex
+ " old=" + old + " icon=" + icon);
}
StatusBarIconView view = (StatusBarIconView)mStatusIcons.getChildAt(viewIndex);
view.set(icon);
StatusBarIconView viewExp = (StatusBarIconView)mStatusIconsExp.getChildAt(viewIndex);
viewExp.set(icon);
}
public void removeIcon(String slot, int index, int viewIndex) {
if (SPEW_ICONS) {
Slog.d(TAG, "removeIcon slot=" + slot + " index=" + index + " viewIndex=" + viewIndex);
}
mStatusIcons.removeViewAt(viewIndex);
mStatusIconsExp.removeViewAt(viewIndex);
}
public void addNotification(IBinder key, StatusBarNotification notification) {
boolean shouldTicker = true;
if (notification.notification.fullScreenIntent != null) {
shouldTicker = false;
Slog.d(TAG, "Notification has fullScreenIntent; sending fullScreenIntent");
try {
notification.notification.fullScreenIntent.send();
} catch (PendingIntent.CanceledException e) {
}
}
StatusBarIconView iconView = addNotificationViews(key, notification);
if (iconView == null) return;
if (shouldTicker && mShowNotif) {
if (!shouldTick) {
tick(notification);
} else {
IntroducerView(notification);
}
}
// Recalculate the position of the sliding windows and the titles.
setAreThereNotifications();
updateExpandedViewPos(EXPANDED_LEAVE_ALONE);
}
private void IntroducerView(StatusBarNotification notification) {
ImageView alertIcon = (ImageView) mIntruderAlertView.findViewById(R.id.alertIcon);
TextView alertText = (TextView) mIntruderAlertView.findViewById(R.id.alertText);
alertIcon.setImageDrawable(StatusBarIconView.getIcon(
alertIcon.getContext(),
new StatusBarIcon(notification.pkg, notification.notification.icon, notification.notification.iconLevel, 0)));
alertText.setText(notification.notification.tickerText);
View button = mIntruderAlertView.findViewById(R.id.intruder_alert_content);
button.setOnClickListener(
new Launcher(notification.notification.contentIntent,
notification.pkg, notification.tag, notification.id));
mHandler.sendEmptyMessage(MSG_SHOW_INTRUDER);
mHandler.removeMessages(MSG_HIDE_INTRUDER);
mHandler.sendEmptyMessageDelayed(MSG_HIDE_INTRUDER, IntruderTime);
}
public void updateNotification(IBinder key, StatusBarNotification notification) {
NotificationData oldList;
int oldIndex = mOngoing.findEntry(key);
if (oldIndex >= 0) {
oldList = mOngoing;
} else {
oldIndex = mLatest.findEntry(key);
if (oldIndex < 0) {
Slog.w(TAG, "updateNotification for unknown key: " + key);
return;
}
oldList = mLatest;
}
final NotificationData.Entry oldEntry = oldList.getEntryAt(oldIndex);
final StatusBarNotification oldNotification = oldEntry.notification;
final RemoteViews oldContentView = oldNotification.notification.contentView;
final RemoteViews contentView = notification.notification.contentView;
if (false) {
Slog.d(TAG, "old notification: when=" + oldNotification.notification.when
+ " ongoing=" + oldNotification.isOngoing()
+ " expanded=" + oldEntry.expanded
+ " contentView=" + oldContentView);
Slog.d(TAG, "new notification: when=" + notification.notification.when
+ " ongoing=" + oldNotification.isOngoing()
+ " contentView=" + contentView);
}
// Can we just reapply the RemoteViews in place? If when didn't change, the order
// didn't change.
if (notification.notification.when == oldNotification.notification.when
&& notification.isOngoing() == oldNotification.isOngoing()
&& oldEntry.expanded != null
&& contentView != null && oldContentView != null
&& contentView.getPackage() != null
&& oldContentView.getPackage() != null
&& oldContentView.getPackage().equals(contentView.getPackage())
&& oldContentView.getLayoutId() == contentView.getLayoutId()) {
if (SPEW) Slog.d(TAG, "reusing notification");
oldEntry.notification = notification;
try {
// Reapply the RemoteViews
contentView.reapply(this, oldEntry.content);
// update the contentIntent
final PendingIntent contentIntent = notification.notification.contentIntent;
if (contentIntent != null) {
oldEntry.content.setOnClickListener(new Launcher(contentIntent,
notification.pkg, notification.tag, notification.id));
}
// Update the icon.
final StatusBarIcon ic = new StatusBarIcon(notification.pkg,
notification.notification.icon, notification.notification.iconLevel,
notification.notification.number);
if (!oldEntry.icon.set(ic)) {
handleNotificationError(key, notification, "Couldn't update icon: " + ic);
return;
}
}
catch (RuntimeException e) {
// It failed to add cleanly. Log, and remove the view from the panel.
Slog.w(TAG, "Couldn't reapply views for package " + contentView.getPackage(), e);
removeNotificationViews(key);
addNotificationViews(key, notification);
}
} else {
if (SPEW) Slog.d(TAG, "not reusing notification");
removeNotificationViews(key);
addNotificationViews(key, notification);
}
// Restart the ticker if it's still running
if (notification.notification.tickerText != null
&& !TextUtils.equals(notification.notification.tickerText,
oldEntry.notification.notification.tickerText) && mShowNotif) {
if (!shouldTick) {
tick(notification);
} else {
mHandler.sendEmptyMessage(MSG_HIDE_INTRUDER);
IntroducerView(notification);
}
}
// Recalculate the position of the sliding windows and the titles.
setAreThereNotifications();
updateExpandedViewPos(EXPANDED_LEAVE_ALONE);
}
public void removeNotification(IBinder key) {
StatusBarNotification old = removeNotificationViews(key);
if (SPEW) Slog.d(TAG, "removeNotification key=" + key + " old=" + old);
if (old != null) {
// Cancel the ticker if it's still running
mTicker.removeEntry(old);
// Recalculate the position of the sliding windows and the titles.
setAreThereNotifications();
updateExpandedViewPos(EXPANDED_LEAVE_ALONE);
}
}
private int chooseIconIndex(boolean isOngoing, int viewIndex) {
final int latestSize = mLatest.size();
if (isOngoing) {
return latestSize + (mOngoing.size() - viewIndex);
} else {
return latestSize - viewIndex;
}
}
View[] makeNotificationView(final IBinder key, final StatusBarNotification notification, ViewGroup parent) {
Notification n = notification.notification;
RemoteViews remoteViews = n.contentView;
if (remoteViews == null) {
return null;
}
// create the row view
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LatestItemContainer row = (LatestItemContainer) inflater.inflate(R.layout.status_bar_latest_event, parent, false);
if ((n.flags & Notification.FLAG_ONGOING_EVENT) == 0 && (n.flags & Notification.FLAG_NO_CLEAR) == 0) {
row.setOnSwipeCallback(mTouchDispatcher, new Runnable() {
public void run() {
try {
mBarService.onNotificationClear(notification.pkg, notification.tag, notification.id);
NotificationData list = mLatest;
int index = mLatest.findEntry(key);
if (index < 0) {
list = mOngoing;
index = mOngoing.findEntry(key);
}
if (index >= 0) {
list.getEntryAt(index).cancelled = true;
}
} catch (RemoteException e) {
// Skip it, don't crash.
}
}
});
}
// bind the click event to the content area
ViewGroup content = (ViewGroup)row.findViewById(R.id.content);
content.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
content.setOnFocusChangeListener(mFocusChangeListener);
PendingIntent contentIntent = n.contentIntent;
if (contentIntent != null) {
content.setOnClickListener(new Launcher(contentIntent, notification.pkg,
notification.tag, notification.id));
}
View expanded = null;
Exception exception = null;
try {
expanded = remoteViews.apply(this, content);
}
catch (RuntimeException e) {
exception = e;
}
if (expanded == null) {
String ident = notification.pkg + "/0x" + Integer.toHexString(notification.id);
Slog.e(TAG, "couldn't inflate view for notification " + ident, exception);
return null;
} else {
resetTextViewColors(expanded);
content.addView(expanded);
row.setDrawingCacheEnabled(true);
}
return new View[] { row, content, expanded };
}
StatusBarIconView addNotificationViews(IBinder key, StatusBarNotification notification) {
NotificationData list;
ViewGroup parent;
final boolean isOngoing = notification.isOngoing();
if (isOngoing) {
list = mOngoing;
parent = mOngoingItems;
} else {
list = mLatest;
parent = mLatestItems;
}
// Construct the expanded view.
final View[] views = makeNotificationView(key, notification, parent);
if (views == null) {
handleNotificationError(key, notification, "Couldn't expand RemoteViews for: "
+ notification);
return null;
}
final View row = views[0];
final View content = views[1];
final View expanded = views[2];
// Construct the icon.
final StatusBarIconView iconView = new StatusBarIconView(this,
notification.pkg + "/0x" + Integer.toHexString(notification.id));
final StatusBarIcon ic = new StatusBarIcon(notification.pkg, notification.notification.icon,
notification.notification.iconLevel, notification.notification.number);
if (!iconView.set(ic)) {
handleNotificationError(key, notification, "Coulding create icon: " + ic);
return null;
}
// Add the expanded view.
final int viewIndex = list.add(key, notification, row, content, expanded, iconView);
parent.addView(row, viewIndex);
// Add the icon.
final int iconIndex = chooseIconIndex(isOngoing, viewIndex);
mNotificationIcons.addView(iconView, iconIndex);
return iconView;
}
StatusBarNotification removeNotificationViews(IBinder key) {
NotificationData.Entry entry = mOngoing.remove(key);
if (entry == null) {
entry = mLatest.remove(key);
if (entry == null) {
Slog.w(TAG, "removeNotification for unknown key: " + key);
return null;
}
}
// Remove the expanded view.
((ViewGroup)entry.row.getParent()).removeView(entry.row);
// Remove the icon.
((ViewGroup)entry.icon.getParent()).removeView(entry.icon);
if (entry.cancelled) {
if (!mOngoing.hasClearableItems() && !mLatest.hasClearableItems()) {
animateCollapse();
}
}
return entry.notification;
}
private void setAreThereNotifications() {
boolean ongoing = mOngoing.hasVisibleItems();
boolean latest = mLatest.hasVisibleItems();
// (no ongoing notifications are clearable)
if (mLatest.hasClearableItems()) {
if (mStatusBarTab || mStatusBarTileView) {
mCompactClearButton.setVisibility(View.VISIBLE);
mClearButton.setVisibility(View.INVISIBLE);
mClearOldButton.setVisibility(View.GONE);
} else {
mCompactClearButton.setVisibility(View.GONE);
if (mMoreExpanded) {
mClearButton.setVisibility(View.VISIBLE);
} else {
mClearOldButton.setVisibility(View.VISIBLE);
}
}
} else {
mCompactClearButton.setVisibility(View.GONE);
mClearButton.setVisibility(View.INVISIBLE);
mClearOldButton.setVisibility(View.GONE);
}
mOngoingTitle.setVisibility(ongoing ? View.VISIBLE : View.GONE);
mLatestTitle.setVisibility(latest ? View.VISIBLE : View.GONE);
if (mStatusBarTab || mStatusBarTileView) {
mLatestTitles.setVisibility(latest ? View.VISIBLE : View.GONE);
}
if (latest) {
if (mStatusBarTab || mStatusBarTileView) {
mNoNotificationsTitles.setVisibility(View.GONE);
}
} else {
if (mStatusBarTab || mStatusBarTileView) {
mNoNotificationsTitles.setVisibility(View.VISIBLE);
}
}
if (ongoing || latest) {
mNoNotificationsTitle.setVisibility(View.GONE);
} else {
mNoNotificationsTitle.setVisibility(View.VISIBLE);
}
}
public void showClock(boolean show) {
if (mStatusBarView != null) {
Clock clock = (Clock)mStatusBarView.findViewById(R.id.clock);
if (clock != null) {
clock.VisibilityChecks(show);
clock.setOnClickListener(mCarrierButtonListener);
}
CenterClock centerClo = (CenterClock)mStatusBarView.findViewById(R.id.centerClo);
if (centerClo != null) {
centerClo.VisibilityChecks(show);
centerClo.setOnClickListener(mCarrierButtonListener);
}
LeftClock clockLeft = (LeftClock)mStatusBarView.findViewById(R.id.clockLe);
if (clockLeft != null) {
clockLeft.VisibilityChecks(show);
clockLeft.setOnClickListener(mCarrierButtonListener);
}
}
}
public void showNaviBar(boolean show) {
if (mNavigationBarView != null) {
mNavigationBarView.setNaviVisible(show);
}
}
/**
* State is one or more of the DISABLE constants from StatusBarManager.
*/
public void disable(int state) {
final int old = mDisabled;
final int diff = state ^ old;
mDisabled = state;
if ((diff & StatusBarManager.DISABLE_CLOCK) != 0) {
boolean show = (state & StatusBarManager.DISABLE_CLOCK) == 0;
Slog.d(TAG, "DISABLE_CLOCK: " + (show ? "no" : "yes"));
showClock(show);
}
if ((diff & StatusBarManager.DISABLE_NAVIGATION) != 0) {
boolean show = (state & StatusBarManager.DISABLE_NAVIGATION) == 0;
Slog.d(TAG, "DISABLE_NAVIGATION: " + (show ? "no" : "yes"));
showNaviBar(show);
}
if ((diff & StatusBarManager.DISABLE_EXPAND) != 0) {
if ((state & StatusBarManager.DISABLE_EXPAND) != 0) {
if (SPEW) Slog.d(TAG, "DISABLE_EXPAND: yes");
animateCollapse();
}
}
if (((diff & StatusBarManager.DISABLE_NOTIFICATION_ICONS) != 0)) {
if ((state & StatusBarManager.DISABLE_NOTIFICATION_ICONS) != 0) {
if (SPEW) Slog.d(TAG, "DISABLE_NOTIFICATION_ICONS: yes");
if (mTicking) {
mTicker.halt();
} else {
setNotificationIconVisibility(false, com.android.internal.R.anim.fade_out);
}
} else {
if (SPEW) Slog.d(TAG, "DISABLE_NOTIFICATION_ICONS: no");
if (!mExpandedVisible) {
setNotificationIconVisibility(true, com.android.internal.R.anim.fade_in);
}
}
} else if ((diff & StatusBarManager.DISABLE_NOTIFICATION_TICKER) != 0) {
if (mTicking && (state & StatusBarManager.DISABLE_NOTIFICATION_TICKER) != 0) {
if (SPEW) Slog.d(TAG, "DISABLE_NOTIFICATION_TICKER: yes");
mTicker.halt();
}
}
}
/**
* All changes to the status bar and notifications funnel through here and are batched.
*/
private class H extends Handler {
public void handleMessage(Message m) {
switch (m.what) {
case MSG_ANIMATE:
doAnimation();
break;
case MSG_ANIMATE_REVEAL:
doRevealAnimation();
break;
case MSG_SHOW_INTRUDER:
setIntruderAlertVisibility(true);
break;
case MSG_HIDE_INTRUDER:
setIntruderAlertVisibility(false);
break;
}
}
}
View.OnFocusChangeListener mFocusChangeListener = new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
// Because 'v' is a ViewGroup, all its children will be (un)selected
// too, which allows marqueeing to work.
v.setSelected(hasFocus);
}
};
private void makeExpandedVisible() {
if (SPEW) Slog.d(TAG, "Make expanded visible: expanded visible=" + mExpandedVisible);
if (mExpandedVisible) {
return;
}
mExpandedVisible = true;
visibilityChanged(true);
//mRecentApps.setupRecentApps();
mPowerWidget.updateAllButtons();
mPowerWidgetBottom.updateAllButtons();
mPowerWidgetOne.updateAllButtons();
mPowerWidgetTwo.updateAllButtons();
mPowerWidgetThree.updateAllButtons();
mPowerWidgetFour.updateAllButtons();
mMusicControls.updateControls();
updateExpandedViewPos(EXPANDED_LEAVE_ALONE);
mExpandedParams.flags &= ~WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
mExpandedParams.flags |= WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
mExpandedDialog.getWindow().setAttributes(mExpandedParams);
mExpandedView.requestFocus(View.FOCUS_FORWARD);
mTrackingView.setVisibility(View.VISIBLE);
mExpandedView.setVisibility(View.VISIBLE);
mCarrierLabelExpLayout.setVisibility(getDataStates(mContext) ? View.GONE : View.VISIBLE);
if (!mTicking) {
setDateViewVisibility(true, com.android.internal.R.anim.fade_in);
setNotificationIconVisibility(false, com.android.internal.R.anim.fade_out);
setAllViewVisibility(false, com.android.internal.R.anim.fade_out);
}
}
public void animateExpand() {
if (SPEW) Slog.d(TAG, "Animate expand: expanded=" + mExpanded);
if ((mDisabled & StatusBarManager.DISABLE_EXPAND) != 0) {
return ;
}
if (mExpanded) {
return;
}
prepareTracking(0, true);
performFling(0, 40000.0f, true);
}
public void animateCollapse() {
if (SPEW) {
Slog.d(TAG, "animateCollapse(): mExpanded=" + mExpanded
+ " mExpandedVisible=" + mExpandedVisible
+ " mExpanded=" + mExpanded
+ " mAnimating=" + mAnimating
+ " mAnimY=" + mAnimY
+ " mAnimVel=" + mAnimVel);
}
if (!mExpandedVisible) {
return;
}
int y;
if (mAnimating) {
y = (int)mAnimY;
} else {
if(mBottomBar)
y = 0;
else
y = mDisplay.getHeight()-1;
}
// Let the fling think that we're open so it goes in the right direction
// and doesn't try to re-open the windowshade.
mExpanded = true;
prepareTracking(y, false);
performFling(y, -40000.0f, true);
}
void performExpand() {
if (SPEW) Slog.d(TAG, "performExpand: mExpanded=" + mExpanded);
if ((mDisabled & StatusBarManager.DISABLE_EXPAND) != 0) {
return ;
}
if (mExpanded) {
return;
}
mExpanded = true;
mStatusBarView.updateQuickNaImage();
makeExpandedVisible();
updateExpandedViewPos(EXPANDED_FULL_OPEN);
if (false) postStartTracing();
}
void performCollapse() {
if (SPEW) Slog.d(TAG, "performCollapse: mExpanded=" + mExpanded
+ " mExpandedVisible=" + mExpandedVisible
+ " mTicking=" + mTicking);
if (!mExpandedVisible) {
return;
}
mExpandedVisible = false;
visibilityChanged(false);
mExpandedParams.flags |= WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
mExpandedParams.flags &= ~WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
mExpandedDialog.getWindow().setAttributes(mExpandedParams);
mTrackingView.setVisibility(View.GONE);
mExpandedView.setVisibility(View.GONE);
if ((mDisabled & StatusBarManager.DISABLE_NOTIFICATION_ICONS) == 0) {
setNotificationIconVisibility(true, com.android.internal.R.anim.fade_in);
}
if (mDateView.getVisibility() == View.VISIBLE) {
setDateViewVisibility(false, com.android.internal.R.anim.fade_out);
setAllViewVisibility(true, com.android.internal.R.anim.fade_in);
} else if (mDateView.getVisibility() == View.INVISIBLE || mDateView.getVisibility() == View.GONE) {
setAllViewVisibility(true, com.android.internal.R.anim.fade_in);
}
if (!mExpanded) {
return;
}
mExpanded = false;
mStatusBarView.updateQuickNaImage();
}
void doAnimation() {
if (mAnimating) {
if (SPEW) Slog.d(TAG, "doAnimation");
if (SPEW) Slog.d(TAG, "doAnimation before mAnimY=" + mAnimY);
incrementAnim();
if (SPEW) Slog.d(TAG, "doAnimation after mAnimY=" + mAnimY);
if ((!mBottomBar && mAnimY >= mDisplay.getHeight()-1) || (mBottomBar && mAnimY <= 0)) {
if (SPEW) Slog.d(TAG, "Animation completed to expanded state.");
mAnimating = false;
updateExpandedViewPos(EXPANDED_FULL_OPEN);
performExpand();
}
else if ((!mBottomBar && mAnimY < getStatBarSize())
|| (mBottomBar && mAnimY > (mDisplay.getHeight()-(mShowDate ? getStatBarSize() : 0)))) {
if (SPEW) Slog.d(TAG, "Animation completed to collapsed state.");
mAnimating = false;
if(mBottomBar)
updateExpandedViewPos(mDisplay.getHeight());
else
updateExpandedViewPos(0);
performCollapse();
}
else {
updateExpandedViewPos((int)mAnimY);
mCurAnimationTime += ANIM_FRAME_DURATION;
mHandler.sendMessageAtTime(mHandler.obtainMessage(MSG_ANIMATE), mCurAnimationTime);
}
}
}
void stopTracking() {
mTracking = false;
mVelocityTracker.clear();
}
void incrementAnim() {
long now = SystemClock.uptimeMillis();
float t = ((float)(now - mAnimLastTime)) / 1000; // ms -> s
final float y = mAnimY;
final float v = mAnimVel; // px/s
final float a = mAnimAccel; // px/s/s
if(mBottomBar)
mAnimY = y - (v*t) - (0.5f*a*t*t); // px
else
mAnimY = y + (v*t) + (0.5f*a*t*t); // px
mAnimVel = v + (a*t); // px/s
mAnimLastTime = now; // ms
//Slog.d(TAG, "y=" + y + " v=" + v + " a=" + a + " t=" + t + " mAnimY=" + mAnimY
// + " mAnimAccel=" + mAnimAccel);
}
void doRevealAnimation() {
int h = mCloseView.getHeight() + (mShowDate ? getStatBarSize() : 0);
if(mBottomBar)
h = mDisplay.getHeight() - (mShowDate ? getStatBarSize() : 0);
if (mAnimatingReveal && mAnimating &&
((mBottomBar && mAnimY > h) || (!mBottomBar && mAnimY < h))) {
incrementAnim();
if ((mBottomBar && mAnimY <= h) || (!mBottomBar && mAnimY >=h)) {
mAnimY = h;
updateExpandedViewPos((int)mAnimY);
} else {
updateExpandedViewPos((int)mAnimY);
mCurAnimationTime += ANIM_FRAME_DURATION;
mHandler.sendMessageAtTime(mHandler.obtainMessage(MSG_ANIMATE_REVEAL),
mCurAnimationTime);
}
}
}
void prepareTracking(int y, boolean opening) {
mTracking = true;
mVelocityTracker.clear();
if (opening) {
mAnimAccel = 40000.0f;
mAnimVel = 200;
mAnimY = mBottomBar ? mDisplay.getHeight() : (mShowDate ? getStatBarSize() : mDisplay.getHeight());
updateExpandedViewPos((int)mAnimY);
mAnimating = true;
mAnimatingReveal = true;
mHandler.removeMessages(MSG_ANIMATE);
mHandler.removeMessages(MSG_ANIMATE_REVEAL);
long now = SystemClock.uptimeMillis();
mAnimLastTime = now;
mCurAnimationTime = now + ANIM_FRAME_DURATION;
mAnimating = true;
mHandler.sendMessageAtTime(mHandler.obtainMessage(MSG_ANIMATE_REVEAL),
mCurAnimationTime);
makeExpandedVisible();
} else {
// it's open, close it?
if (mAnimating) {
mAnimating = false;
mHandler.removeMessages(MSG_ANIMATE);
}
updateExpandedViewPos(y + mViewDelta);
}
}
void performFling(int y, float vel, boolean always) {
mAnimatingReveal = false;
mDisplayHeight = mDisplay.getHeight();
mAnimY = y;
mAnimVel = vel;
//Slog.d(TAG, "starting with mAnimY=" + mAnimY + " mAnimVel=" + mAnimVel);
if (mExpanded) {
if (!always &&
((mBottomBar && (vel < -200.0f || (y < 25 && vel < 200.0f))) ||
(!mBottomBar && (vel > 200.0f || (y > (mDisplayHeight-25) && vel > -200.0f))))) {
// We are expanded, but they didn't move sufficiently to cause
// us to retract. Animate back to the expanded position.
mAnimAccel = 40000.0f;
if (vel < 0) {
mAnimVel *= -1;
}
}
else {
// We are expanded and are now going to animate away.
mAnimAccel = -40000.0f;
if (vel > 0) {
mAnimVel *= -1;
}
}
} else {
if (always
|| ( mBottomBar && (vel < -200.0f || (y < (mDisplayHeight/2) && vel < 200.0f)))
|| (!mBottomBar && (vel > 200.0f || (y > (mDisplayHeight/2) && vel > -200.0f)))) {
// We are collapsed, and they moved enough to allow us to
// expand. Animate in the notifications.
mAnimAccel = 40000.0f;
if (vel < 0) {
mAnimVel *= -1;
}
}
else {
// We are collapsed, but they didn't move sufficiently to cause
// us to retract. Animate back to the collapsed position.
mAnimAccel = -40000.0f;
if (vel > 0) {
mAnimVel *= -1;
}
}
}
//Slog.d(TAG, "mAnimY=" + mAnimY + " mAnimVel=" + mAnimVel
// + " mAnimAccel=" + mAnimAccel);
long now = SystemClock.uptimeMillis();
mAnimLastTime = now;
mCurAnimationTime = now + ANIM_FRAME_DURATION;
mAnimating = true;
mHandler.removeMessages(MSG_ANIMATE);
mHandler.removeMessages(MSG_ANIMATE_REVEAL);
mHandler.sendMessageAtTime(mHandler.obtainMessage(MSG_ANIMATE), mCurAnimationTime);
stopTracking();
}
private void adjustBrightness(int x) {
float screen_width = (float)(mContext.getResources().getDisplayMetrics().widthPixels);
float raw = ((float) x) / screen_width;
int minBrightness = 4;
// Add a padding to the brightness control on both sides to
// make it easier to reach min/max brightness
float padded = Math.min(1.0f - BRIGHTNESS_CONTROL_PADDING,
Math.max(BRIGHTNESS_CONTROL_PADDING, raw));
float value = (padded - BRIGHTNESS_CONTROL_PADDING) /
(1 - (2.0f * BRIGHTNESS_CONTROL_PADDING));
int newBrightness = minBrightness + (int) Math.round(value *
(android.os.Power.BRIGHTNESS_ON - minBrightness));
newBrightness = Math.min(newBrightness, android.os.Power.BRIGHTNESS_ON);
newBrightness = Math.max(newBrightness, minBrightness);
try {
IPowerManager power = IPowerManager.Stub.asInterface(
ServiceManager.getService("power"));
if (power != null) {
power.setBacklightBrightness(newBrightness);
Settings.System.putInt(mContext.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS, newBrightness);
if (mBrightnessPanel == null) {
mBrightnessPanel = new BrightnessPanel(mContext);
}
mBrightnessPanel.postBrightnessChanged(newBrightness, android.os.Power.BRIGHTNESS_ON);
}
} catch (RemoteException e) {
Slog.w(TAG, "Setting Brightness failed: " + e);
}
}
private void brightnessControl(MotionEvent event)
{
if (mBrightnessControl)
{
final int statusBarSize = getStatBarSize();
final int action = event.getAction();
final int x = (int)event.getRawX();
final int y = (int)event.getRawY();
if (action == MotionEvent.ACTION_DOWN) {
mLinger = 0;
mInitialTouchX = x;
mInitialTouchY = y;
mHandler.removeCallbacks(mLongPressBrightnessChange);
mHandler.postDelayed(mLongPressBrightnessChange,
BRIGHTNESS_CONTROL_LONG_PRESS_TIMEOUT);
} else if (action == MotionEvent.ACTION_MOVE) {
int minY = statusBarSize + mCloseView.getHeight();
if (mBottomBar)
minY = mDisplay.getHeight() - statusBarSize - mCloseView.getHeight();
if ((!mBottomBar && y < minY) ||
(mBottomBar && y > minY)) {
mVelocityTracker.computeCurrentVelocity(1000);
float yVel = mVelocityTracker.getYVelocity();
if (yVel < 0) {
yVel = -yVel;
}
if (yVel < 50.0f) {
if (mLinger > BRIGHTNESS_CONTROL_LINGER_THRESHOLD) {
adjustBrightness(x);
} else {
mLinger++;
}
}
int touchSlop = ViewConfiguration.get(mContext).getScaledTouchSlop();
if (Math.abs(x - mInitialTouchX) > touchSlop ||
Math.abs(y - mInitialTouchY) > touchSlop) {
mHandler.removeCallbacks(mLongPressBrightnessChange);
}
} else {
mHandler.removeCallbacks(mLongPressBrightnessChange);
}
} else if (action == MotionEvent.ACTION_UP) {
mHandler.removeCallbacks(mLongPressBrightnessChange);
mLinger = 0;
}
}
}
boolean interceptTouchEvent(MotionEvent event) {
if (SPEW) {
Slog.d(TAG, "Touch: rawY=" + event.getRawY() + " event=" + event + " mDisabled="
+ mDisabled);
}
final int statusBarSize = getStatBarSize();
final int hitSize = statusBarSize*2;
final int y = (int)event.getRawY();
final int x = (int)event.getRawX();
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (!mExpanded) {
mViewDelta = mBottomBar ? mDisplay.getHeight() - y : statusBarSize - y;
} else {
mTrackingView.getLocationOnScreen(mAbsPos);
mViewDelta = mAbsPos[1] + (mBottomBar ? 0 : mTrackingView.getHeight()) - y;
}
}
brightnessControl(event);
if ((mDisabled & StatusBarManager.DISABLE_EXPAND) != 0) {
return false;
}
if (!mTrackingView.mIsAttachedToWindow) {
return false;
}
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if ((!mBottomBar && ((!mExpanded && y < hitSize) || ( mExpanded && y > (mDisplay.getHeight()-hitSize)))) ||
(mBottomBar && (( mExpanded && y < hitSize) || (!mExpanded && y > (mDisplay.getHeight()-hitSize))))) {
// We drop events at the edge of the screen to make the windowshade come
// down by accident less, especially when pushing open a device with a keyboard
// that rotates (like g1 and droid)
final int edgeBorder = mEdgeBorder;
int edgeLeft = mButtonsLeft ? mStatusBarView.getSoftButtonsWidth() : 0;
int edgeRight = mButtonsLeft ? 0 : mStatusBarView.getSoftButtonsWidth();
final int w = mDisplay.getWidth();
final int deadLeft = w / 2 - w / 4; // left side of the dead zone
final int deadRight = w / 2 + w / 4; // right side of the dead zone
boolean expandedHit = (mExpanded && (x >= edgeBorder && x < w - edgeBorder));
boolean collapsedHit = (!mExpanded && (x >= edgeBorder + edgeLeft && x < w - edgeBorder - edgeRight)
&& (!mDeadZone || mDeadZone && (x < deadLeft || x > deadRight)));
if (expandedHit || collapsedHit) {
prepareTracking(y, !mExpanded);// opening if we're not already fully visible
trackMovement(event);
}
}
} else if (mTracking) {
trackMovement(event);
int minY = statusBarSize + mCloseView.getHeight();
if (mBottomBar)
minY = mDisplay.getHeight() - statusBarSize - mCloseView.getHeight();
if (event.getAction() == MotionEvent.ACTION_MOVE) {
if ((!mBottomBar && mAnimatingReveal && y < minY) ||
(mBottomBar && mAnimatingReveal && y > minY)) {
// nothing
} else {
mAnimatingReveal = false;
updateExpandedViewPos(y + (mBottomBar ? -mViewDelta : mViewDelta));
}
mSettingsButton.setColorFilter(mSettingsColor, Mode.MULTIPLY);
getMemInfo();
} else if (event.getAction() == MotionEvent.ACTION_UP) {
mVelocityTracker.computeCurrentVelocity(1000);
float yVel = mVelocityTracker.getYVelocity();
boolean negative = yVel < 0;
float xVel = mVelocityTracker.getXVelocity();
if (xVel < 0) {
xVel = -xVel;
}
if (xVel > 150.0f) {
xVel = 150.0f; // limit how much we care about the x axis
}
float vel = (float)Math.hypot(yVel, xVel);
if (negative) {
vel = -vel;
}
performFling(y + mViewDelta, vel, false);
mHandler.postDelayed(new Runnable() {
public void run() {
mSettingsButton.clearColorFilter();
getMemInfo();
}
}, 100);
}
}
return false;
}
private void trackMovement(MotionEvent event) {
// Add movement to velocity tracker using raw screen X and Y coordinates instead
// of window coordinates because the window frame may be moving at the same time.
float deltaX = event.getRawX() - event.getX();
float deltaY = event.getRawY() - event.getY();
event.offsetLocation(deltaX, deltaY);
mVelocityTracker.addMovement(event);
event.offsetLocation(-deltaX, -deltaY);
}
private class Launcher implements View.OnClickListener {
private PendingIntent mIntent;
private String mPkg;
private String mTag;
private int mId;
Launcher(PendingIntent intent, String pkg, String tag, int id) {
mIntent = intent;
mPkg = pkg;
mTag = tag;
mId = id;
}
public void onClick(View v) {
try {
// The intent we are sending is for the application, which
// won't have permission to immediately start an activity after
// the user switches to home. We know it is safe to do at this
// point, so make sure new activity switches are now allowed.
ActivityManagerNative.getDefault().resumeAppSwitches();
} catch (RemoteException e) {
}
if (mIntent != null) {
int[] pos = new int[2];
v.getLocationOnScreen(pos);
Intent overlay = new Intent();
overlay.setSourceBounds(
new Rect(pos[0], pos[1], pos[0]+v.getWidth(), pos[1]+v.getHeight()));
try {
mIntent.send(StatusBarService.this, 0, overlay);
} catch (PendingIntent.CanceledException e) {
// the stack trace isn't very helpful here. Just log the exception message.
Slog.w(TAG, "Sending contentIntent failed: " + e);
}
}
try {
mBarService.onNotificationClick(mPkg, mTag, mId);
} catch (RemoteException ex) {
// system process is dead if we're here.
}
// close the shade if it was open
animateCollapse();
// If this click was on the intruder alert, hide that instead
if (shouldTick && mShowNotif) {
mHandler.sendEmptyMessage(MSG_HIDE_INTRUDER);
}
}
}
private void tick(StatusBarNotification n) {
// Show the ticker if one is requested. Also don't do this
// until status bar window is attached to the window manager,
// because... well, what's the point otherwise? And trying to
// run a ticker without being attached will crash!
if (n.notification.tickerText != null && mStatusBarView.getWindowToken() != null) {
if (0 == (mDisabled & (StatusBarManager.DISABLE_NOTIFICATION_ICONS
| StatusBarManager.DISABLE_NOTIFICATION_TICKER))) {
if(!mHasSoftButtons || mStatusBarView.getSoftButtonsWidth() == 0)
mTicker.addEntry(n);
}
}
}
/**
* Cancel this notification and tell the StatusBarManagerService / NotificationManagerService
* about the failure.
*
* WARNING: this will call back into us. Don't hold any locks.
*/
void handleNotificationError(IBinder key, StatusBarNotification n, String message) {
removeNotification(key);
try {
mBarService.onNotificationError(n.pkg, n.tag, n.id, n.uid, n.initialPid, message);
} catch (RemoteException ex) {
// The end is nigh.
}
}
private class MyTicker extends Ticker {
MyTicker(Context context, CmStatusBarView mStatusBarView) {
super(context, mStatusBarView);
}
@Override
void tickerStarting() {
if (SPEW) Slog.d(TAG, "tickerStarting");
mTicking = true;
mTickerView.setVisibility(View.VISIBLE);
mTickerView.startAnimation(loadAnim(com.android.internal.R.anim.push_up_in, null));
if (!mExpandedVisible) {
setAllViewVisibility(false, com.android.internal.R.anim.push_up_out);
}
if (mExpandedVisible) {
setDateViewVisibility(false, com.android.internal.R.anim.push_up_out);
}
}
@Override
void tickerDone() {
if (SPEW) Slog.d(TAG, "tickerDone");
mTicking = false;
mTickerView.setVisibility(View.GONE);
mTickerView.startAnimation(loadAnim(com.android.internal.R.anim.push_down_out, null));
if (!mExpandedVisible) {
setAllViewVisibility(true, com.android.internal.R.anim.push_down_in);
}
if (mExpandedVisible) {
setDateViewVisibility(true, com.android.internal.R.anim.push_down_in);
}
}
void tickerHalting() {
if (SPEW) Slog.d(TAG, "tickerHalting");
mTicking = false;
mTickerView.setVisibility(View.GONE);
mTickerView.startAnimation(loadAnim(com.android.internal.R.anim.fade_out, null));
if (!mExpandedVisible) {
setAllViewVisibility(true, com.android.internal.R.anim.fade_in);
}
if (mExpandedVisible) {
setDateViewVisibility(true, com.android.internal.R.anim.fade_in);
}
}
}
private Animation loadAnim(int id, Animation.AnimationListener listener) {
Animation anim = AnimationUtils.loadAnimation(StatusBarService.this, id);
if (listener != null) {
anim.setAnimationListener(listener);
}
return anim;
}
public String viewInfo(View v) {
return "(" + v.getLeft() + "," + v.getTop() + ")(" + v.getRight() + "," + v.getBottom()
+ " " + v.getWidth() + "x" + v.getHeight() + ")";
}
protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
if (checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
!= PackageManager.PERMISSION_GRANTED) {
pw.println("Permission Denial: can't dump StatusBar from from pid="
+ Binder.getCallingPid()
+ ", uid=" + Binder.getCallingUid());
return;
}
synchronized (mQueueLock) {
pw.println("Current Status Bar state:");
pw.println(" mExpanded=" + mExpanded
+ ", mExpandedVisible=" + mExpandedVisible);
pw.println(" mTicking=" + mTicking);
pw.println(" mTracking=" + mTracking);
pw.println(" mAnimating=" + mAnimating
+ ", mAnimY=" + mAnimY + ", mAnimVel=" + mAnimVel
+ ", mAnimAccel=" + mAnimAccel);
pw.println(" mCurAnimationTime=" + mCurAnimationTime
+ " mAnimLastTime=" + mAnimLastTime);
pw.println(" mDisplayHeight=" + mDisplayHeight
+ " mAnimatingReveal=" + mAnimatingReveal
+ " mViewDelta=" + mViewDelta);
pw.println(" mDisplayHeight=" + mDisplayHeight);
pw.println(" mExpandedParams: " + mExpandedParams);
pw.println(" mExpandedView: " + viewInfo(mExpandedView));
pw.println(" mExpandedDialog: " + mExpandedDialog);
pw.println(" mTrackingParams: " + mTrackingParams);
pw.println(" mTrackingView: " + viewInfo(mTrackingView));
pw.println(" mOngoingTitle: " + viewInfo(mOngoingTitle));
pw.println(" mOngoingItems: " + viewInfo(mOngoingItems));
pw.println(" mLatestTitle: " + viewInfo(mLatestTitle));
pw.println(" mLatestItems: " + viewInfo(mLatestItems));
pw.println(" mNoNotificationsTitle: " + viewInfo(mNoNotificationsTitle));
pw.println(" mCloseView: " + viewInfo(mCloseView));
pw.println(" mTickerView: " + viewInfo(mTickerView));
pw.println(" mScrollView: " + viewInfo(mScrollView)
+ " scroll " + mScrollView.getScrollX() + "," + mScrollView.getScrollY());
pw.println(" mBottomScrollView: " + viewInfo(mBottomScrollView)
+ " scroll " + mBottomScrollView.getScrollX() + "," + mBottomScrollView.getScrollY());
pw.println("mNotificationLinearLayout: " + viewInfo(mNotificationLinearLayout));
pw.println("mBottomNotificationLinearLayout: " + viewInfo(mBottomNotificationLinearLayout));
}
if (true) {
// must happen on ui thread
mHandler.post(new Runnable() {
public void run() {
Slog.d(TAG, "mStatusIcons:");
mStatusIcons.debug();
if (mStatusIconsExp != null) {
Slog.d(TAG, "mStatusIconsExp:");
mStatusIconsExp.debug();
}
}
});
}
}
void onBarViewAttached() {
WindowManager.LayoutParams lp;
int pixelFormat;
Drawable bg;
/// ---------- Tracking View --------------
pixelFormat = PixelFormat.TRANSLUCENT;
lp = new WindowManager.LayoutParams(
mTinyExpanded ? getExpandedWidth() : ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL,
WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
| WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
| WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
pixelFormat);
if (mTinyExpanded) {
lp.gravity = Gravity.TOP | Gravity.CENTER_HORIZONTAL;
} else {
lp.gravity = Gravity.TOP | Gravity.FILL_HORIZONTAL;
}
lp.setTitle("TrackingView");
lp.y = mTrackingPosition;
mTrackingParams = lp;
WindowManagerImpl.getDefault().addView(mTrackingView, lp);
}
void onBarViewDetached() {
WindowManagerImpl.getDefault().removeView(mTrackingView);
}
void onTrackingViewAttached() {
WindowManager.LayoutParams lp;
Drawable bg;
/// ---------- Expanded View --------------
int mPixelFormat = PixelFormat.TRANSLUCENT;
final int disph = mBottomBar ? mDisplay.getHeight() : (mDisplay.getHeight()-getNavBarSize());
lp = mExpandedDialog.getWindow().getAttributes();
lp.width = mTinyExpanded ? getExpandedWidth() : ViewGroup.LayoutParams.MATCH_PARENT;
lp.height = mBottomBar ? getExpandedHeight() : (getExpandedHeight()-getNavBarSize());
lp.x = 0;
mTrackingPosition = lp.y = (mBottomBar ? disph : -disph); // sufficiently large positive
lp.type = WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL;
lp.flags = WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
| WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
| WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
| WindowManager.LayoutParams.FLAG_DITHER
| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
lp.format = mPixelFormat;
if (mTinyExpanded) {
lp.gravity = Gravity.TOP | Gravity.CENTER_HORIZONTAL;
} else {
lp.gravity = Gravity.TOP | Gravity.FILL_HORIZONTAL;
}
lp.setTitle("StatusBarExpanded");
mExpandedDialog.getWindow().setAttributes(lp);
mExpandedDialog.getWindow().setFormat(mPixelFormat);
mExpandedParams = lp;
mExpandedDialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
mExpandedDialog.setContentView(mExpandedView,
new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
mExpandedDialog.getWindow().setBackgroundDrawable(null);
mExpandedDialog.show();
FrameLayout hack = (FrameLayout)mExpandedView.getParent();
}
void onTrackingViewDetached() {
}
void setDateViewVisibility(boolean visible, int anim) {
if(mHasSoftButtons && mButtonsLeft)
return;
if(!mShowDate)
return;
mDateView.setVisibility(visible ? View.VISIBLE : View.INVISIBLE);
mDateView.startAnimation(loadAnim(anim, null));
if (visible) {
setNotificationIconVisibility(false, com.android.internal.R.anim.fade_out);
} else {
setNotificationIconVisibility(true, com.android.internal.R.anim.fade_in);
}
}
void setAllViewVisibility(boolean visible, int anim) {
mIcons.setVisibility(visible ? View.VISIBLE : View.GONE);
mIcons.startAnimation(loadAnim(anim, null));
if (mStatusBarClock == 2) {
mCenterClock.setVisibility(visible ? View.VISIBLE : View.GONE);
mCenterClock.startAnimation(loadAnim(anim, null));
} else if (mStatusBarClock == 3) {
mLeftClock.setVisibility(visible ? View.VISIBLE : View.GONE);
mLeftClock.startAnimation(loadAnim(anim, null));
}
if (mStatusBarCarrier == 1) {
mCarrierLabelStatusBarLayout.setVisibility(visible ? View.VISIBLE : View.GONE);
mCarrierLabelStatusBarLayout.startAnimation(loadAnim(anim, null));
} else if (mStatusBarCarrier == 2) {
mCenterCarrierLabelStatusBarLayout.setVisibility(visible ? View.VISIBLE : View.GONE);
mCenterCarrierLabelStatusBarLayout.startAnimation(loadAnim(anim, null));
} else if (mStatusBarCarrier == 3) {
mLeftCarrierLabelStatusBarLayout.setVisibility(visible ? View.VISIBLE : View.GONE);
mLeftCarrierLabelStatusBarLayout.startAnimation(loadAnim(anim, null));
}
if (mStatusBarCarrierLogo == 1) {
mCarrierLogoLayout.setVisibility(visible ? View.VISIBLE : View.GONE);
mCarrierLogoLayout.startAnimation(loadAnim(anim, null));
} else if (mStatusBarCarrierLogo == 2) {
mCarrierLogoCenterLayout.setVisibility(visible ? View.VISIBLE : View.GONE);
mCarrierLogoCenterLayout.startAnimation(loadAnim(anim, null));
} else if (mStatusBarCarrierLogo == 3) {
mCarrierLogoLeftLayout.setVisibility(visible ? View.VISIBLE : View.GONE);
mCarrierLogoLeftLayout.startAnimation(loadAnim(anim, null));
}
if (mShowCmBatteryStatusBar) {
mCmBatteryStatusBar.setVisibility(visible ? View.VISIBLE : View.GONE);
mCmBatteryStatusBar.startAnimation(loadAnim(anim, null));
}
}
void setNotificationIconVisibility(boolean visible, int anim) {
int old = mNotificationIcons.getVisibility();
int v = visible ? View.VISIBLE : View.INVISIBLE;
if (old != v) {
if (mStatusBarCarrierLogo == 2 && mStatusBarReverse) {
mNotificationIcons.setVisibility(View.INVISIBLE);
mNotificationIcons.startAnimation(loadAnim(anim, null));
} else if (mStatusBarCarrier == 2 && mStatusBarReverse) {
mNotificationIcons.setVisibility(View.INVISIBLE);
mNotificationIcons.startAnimation(loadAnim(anim, null));
} else {
mNotificationIcons.setVisibility(v);
mNotificationIcons.startAnimation(loadAnim(anim, null));
}
}
}
void updateExpandedViewPos(int expandedPosition) {
if (SPEW) {
Slog.d(TAG, "updateExpandedViewPos before expandedPosition=" + expandedPosition
+ " mTrackingParams.y="
+ ((mTrackingParams == null) ? "???" : mTrackingParams.y)
+ " mTrackingPosition=" + mTrackingPosition);
}
int h = mBottomBar ? 0 : (mShowDate ? getStatBarSize() : 0);
int disph = mBottomBar ? mDisplay.getHeight() : (mDisplay.getHeight()-getNavBarSize());
// If the expanded view is not visible, make sure they're still off screen.
// Maybe the view was resized.
if (!mExpandedVisible) {
if (mTrackingView != null) {
mTrackingPosition = mBottomBar ? disph : -disph;
if (mTrackingParams != null) {
mTrackingParams.y = mTrackingPosition;
WindowManagerImpl.getDefault().updateViewLayout(mTrackingView, mTrackingParams);
}
}
if (mExpandedParams != null) {
mExpandedParams.y = mBottomBar ? disph : -disph;
mExpandedDialog.getWindow().setAttributes(mExpandedParams);
}
return;
}
// tracking view...
int pos;
if (expandedPosition == EXPANDED_FULL_OPEN) {
pos = h;
}
else if (expandedPosition == EXPANDED_LEAVE_ALONE) {
pos = mTrackingPosition;
}
else {
if ((mBottomBar && expandedPosition >= 0) || (!mBottomBar && expandedPosition <= disph)) {
pos = expandedPosition;
} else {
pos = disph;
}
pos -= mBottomBar ? mCloseView.getHeight() : disph-h;
}
if(mBottomBar && pos < 0)
pos=0;
mTrackingPosition = mTrackingParams.y = pos;
mTrackingParams.height = disph-h;
WindowManagerImpl.getDefault().updateViewLayout(mTrackingView, mTrackingParams);
if (mExpandedParams != null) {
mCloseView.getLocationInWindow(mPositionTmp);
final int closePos = mPositionTmp[1];
int conBot;
if (!mStatusBarTab || !mStatusBarTileView) {
mExpandedContents.getLocationInWindow(mPositionTmp);
conBot = mPositionTmp[1] + mExpandedContents.getHeight();
} else {
conBot = mPositionTmp[1] + getExpandedHeight();
}
final int contentsBottom = conBot;
if (expandedPosition != EXPANDED_LEAVE_ALONE) {
if(mBottomBar)
mExpandedParams.y = pos + mCloseView.getHeight();
else
mExpandedParams.y = pos + mTrackingView.getHeight()
- (mTrackingParams.height-closePos) - contentsBottom;
int max = mBottomBar ? (mDisplay.getHeight()-getNavBarSize()) : h;
if (mExpandedParams.y > max) {
mExpandedParams.y = max;
}
int min = mBottomBar ? mCloseView.getHeight() : mTrackingPosition;
if (mExpandedParams.y < min) {
mExpandedParams.y = min;
if(mBottomBar)
mTrackingParams.y = 0;
}
boolean visible = mBottomBar ? mTrackingPosition < mDisplay.getHeight()
: (mTrackingPosition + mTrackingView.getHeight()) > h;
if (!visible) {
// if the contents aren't visible, move the expanded view way off screen
// because the window itself extends below the content view.
mExpandedParams.y = mBottomBar ? disph : -disph;
}
mExpandedDialog.getWindow().setAttributes(mExpandedParams);
if (SPEW) Slog.d(TAG, "updateExpandedViewPos visibilityChanged(" + visible + ")");
visibilityChanged(visible);
}
}
if (SPEW) {
Slog.d(TAG, "updateExpandedViewPos after expandedPosition=" + expandedPosition
+ " mTrackingParams.y=" + mTrackingParams.y
+ " mTrackingView.getHeight=" + mTrackingView.getHeight()
+ " mTrackingPosition=" + mTrackingPosition
+ " mExpandedParams.y=" + mExpandedParams.y
+ " mExpandedParams.height=" + mExpandedParams.height);
}
}
int getExpandedWidth() {
int defValuesTinyExpSize = mContext.getResources().getInteger(com.android.internal.R.integer.config_tinyexpsize_default_cyanmobile);
int expandedSizeval = Settings.System.getInt(mContext.getContentResolver(),
Settings.System.STATUSBAR_EXPANDED_SIZE, defValuesTinyExpSize);
int expandedSizepx = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
expandedSizeval, mContext.getResources().getDisplayMetrics());
return (mDisplay.getWidth()-expandedSizepx);
}
int getExpandedHeight() {
return (mDisplay.getHeight()-(mShowDate ? getStatBarSize() : 0)-mCloseView.getHeight());
}
void updateExpandedHeight() {
if (mExpandedView != null) {
mExpandedParams.height = mBottomBar ? getExpandedHeight() : (getExpandedHeight()-getNavBarSize());
if (mTinyExpanded) {
mExpandedParams.width = getExpandedWidth();
}
mExpandedDialog.getWindow().setAttributes(mExpandedParams);
}
}
/**
* The LEDs are turned o)ff when the notification panel is shown, even just a little bit.
* This was added last-minute and is inconsistent with the way the rest of the notifications
* are handled, because the notification isn't really cancelled. The lights are just
* turned off. If any other notifications happen, the lights will turn back on. Steve says
* this is what he wants. (see bug 1131461)
*/
void visibilityChanged(boolean visible) {
if (mPanelSlightlyVisible != visible) {
mPanelSlightlyVisible = visible;
try {
mBarService.onPanelRevealed();
} catch (RemoteException ex) {
// Won't fail unless the world has ended.
}
}
}
void performDisableActions(int net) {
int old = mDisabled;
int diff = net ^ old;
mDisabled = net;
// act accordingly
if ((diff & StatusBarManager.DISABLE_EXPAND) != 0) {
if ((net & StatusBarManager.DISABLE_EXPAND) != 0) {
Slog.d(TAG, "DISABLE_EXPAND: yes");
animateCollapse();
}
}
if ((diff & StatusBarManager.DISABLE_NOTIFICATION_ICONS) != 0) {
if ((net & StatusBarManager.DISABLE_NOTIFICATION_ICONS) != 0) {
Slog.d(TAG, "DISABLE_NOTIFICATION_ICONS: yes");
if (mTicking) {
mNotificationIcons.setVisibility(View.INVISIBLE);
mTicker.halt();
} else {
setNotificationIconVisibility(false, com.android.internal.R.anim.fade_out);
}
} else {
Slog.d(TAG, "DISABLE_NOTIFICATION_ICONS: no");
if (!mExpandedVisible) {
setNotificationIconVisibility(true, com.android.internal.R.anim.fade_in);
}
}
} else if ((diff & StatusBarManager.DISABLE_NOTIFICATION_TICKER) != 0) {
Slog.d(TAG, "DISABLE_NOTIFICATION_TICKER: "
+ (((net & StatusBarManager.DISABLE_NOTIFICATION_TICKER) != 0)
? "yes" : "no"));
if (mTicking && (net & StatusBarManager.DISABLE_NOTIFICATION_TICKER) != 0) {
mTicker.halt();
}
}
}
public View.OnClickListener mMusicToggleButtonListener = new View.OnClickListener() {
public void onClick(View v) {
if (mStatusBarTab || mStatusBarTileView) {
mPowerCarrier.setVisibility(View.VISIBLE);
mPowerCarrier.startAnimation(loadAnim(com.android.internal.R.anim.fade_out, null));
}
mMusicControls.visibilityToggled();
}
};
private View.OnClickListener mClearButtonListener = new View.OnClickListener() {
public void onClick(View v) {
mClearButton.clearColorFilter();
try {
mBarService.onClearAllNotifications();
} catch (RemoteException ex) {
// system process is dead if we're here.
}
mHandler.postDelayed(new Runnable() {
public void run() {
mClearButton.setColorFilter(mSettingsColor, Mode.MULTIPLY);
}
}, 100);
animateCollapse();
}
};
private View.OnClickListener mSettingsIconButtonListener = new View.OnClickListener() {
public void onClick(View v) {
mSettingsIconButton.clearColorFilter();
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setClassName("com.android.settings", "com.android.settings.MainSettings");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
v.getContext().startActivity(intent);
mHandler.postDelayed(new Runnable() {
public void run() {
mSettingsIconButton.setColorFilter(mSettingsColor, Mode.MULTIPLY);
}
}, 100);
animateCollapse();
}
};
private static Bitmap getNinePatch(int id,int x, int y, Context context){
Bitmap bitmap = BitmapFactory.decodeResource(
context.getResources(), id);
byte[] chunk = bitmap.getNinePatchChunk();
NinePatchDrawable np_drawable = new NinePatchDrawable(bitmap,
chunk, new Rect(), null);
np_drawable.setBounds(0, 0,x, y);
Bitmap output_bitmap = Bitmap.createBitmap(x, y, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output_bitmap);
np_drawable.draw(canvas);
return output_bitmap;
}
private View.OnLongClickListener mSettingsButtonListener = new View.OnLongClickListener() {
public boolean onLongClick(View v) {
if (Settings.System.getInt(getContentResolver(),
Settings.System.ENABLE_SETTING_BUTTON, 0) == 1) {
if (mFirstis) {
Settings.System.putInt(mContext.getContentResolver(), Settings.System.NAVI_BUTTONS, 0);
mFirstis = false;
} else {
Settings.System.putInt(mContext.getContentResolver(), Settings.System.NAVI_BUTTONS, 1);
mFirstis = true;
}
animateCollapse();
return true;
} else if (Settings.System.getInt(getContentResolver(),
Settings.System.ENABLE_SETTING_BUTTON, 0) == 2) {
WeatherPopup weatherWindow = new WeatherPopup(v);
weatherWindow.showWeatherAction();
animateCollapse();
return true;
}
return false;
}
};
private View.OnClickListener mCarrierButtonListener = new View.OnClickListener() {
public void onClick(View v) {
if(Settings.System.getInt(getContentResolver(),
Settings.System.EXPANDED_VIEW_WIDGET, 1) == 0) {
QuickSettingsPopupWindow quickSettingsWindow = new QuickSettingsPopupWindow(v);
quickSettingsWindow.showLikeQuickAction();
}
}
};
public void setIMEVisible(boolean visible) {
mNavigationBarView.setIMEVisible(visible);
}
private View.OnClickListener mIconButtonListener = new View.OnClickListener() {
public void onClick(View v) {
if(Settings.System.getInt(getContentResolver(),
Settings.System.USE_CUSTOM_SHORTCUT_TOGGLE, 0) == 1) {
if (mBrightnessControl) {
final View vW = v;
mHandler.postDelayed(new Runnable() {
public void run() {
ShortcutPopupWindow shortCutWindow = new ShortcutPopupWindow(vW);
shortCutWindow.showLikeQuickAction();
animateCollapse();
}
}, (BRIGHTNESS_CONTROL_LONG_PRESS_TIMEOUT + 50));
} else {
ShortcutPopupWindow shortCutWindow = new ShortcutPopupWindow(v);
shortCutWindow.showLikeQuickAction();
animateCollapse();
}
}
}
};
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)
|| Intent.ACTION_SCREEN_OFF.equals(action)) {
animateCollapse();
} else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
// update clock for changing font
if (mStatusBarView != null) {
Clock clock = (Clock)mStatusBarView.findViewById(R.id.clock);
if (clock != null) {
clock.invalidate();
}
CenterClock centerClo = (CenterClock)mStatusBarView.findViewById(R.id.centerClo);
if (centerClo != null) {
centerClo.invalidate();
}
PowerClock centerCloex = (PowerClock)mExpandedView.findViewById(R.id.centerCloex);
if (centerCloex != null) {
centerCloex.invalidate();
}
ClockExpand clockExp = (ClockExpand)mExpandedView.findViewById(R.id.expclock_power);
if (clockExp != null) {
clockExp.invalidate();
}
PowerDateView powDateView = (PowerDateView)mExpandedView.findViewById(R.id.datestats);
if (powDateView != null) {
powDateView.invalidate();
}
LeftClock clockLeft = (LeftClock)mStatusBarView.findViewById(R.id.clockLe);
if (clockLeft != null) {
clockLeft.invalidate();
}
}
repositionNavigationBar();
updateResources();
}
}
};
private void setIntruderAlertVisibility(boolean vis) {
mIntruderAlertView.setVisibility(vis ? View.VISIBLE : View.GONE);
}
private void getMemInfo() {
if (!mShowRam) return;
if(totalMemory == 0) {
try {
RandomAccessFile reader = new RandomAccessFile("/proc/meminfo", "r");
String load = reader.readLine();
String[] memInfo = load.split(" ");
totalMemory = Double.parseDouble(memInfo[9])/1024;
} catch (IOException ex) {
ex.printStackTrace();
}
}
ActivityManager activityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
MemoryInfo mi = new MemoryInfo();
activityManager.getMemoryInfo(mi);
availableMemory = mi.availMem / 1048576L;
memHeader.setText("Ram Info: Available: "+(int)(availableMemory)+"MB Total: "+(int)totalMemory+"MB.");
int progress = (int) (((totalMemory-availableMemory)/totalMemory)*100);
avalMemPB.setProgress(progress);
}
/**
* Reload some of our resources when the configuration changes.
*
* We don't reload everything when the configuration changes -- we probably
* should, but getting that smooth is tough. Someday we'll fix that. In the
* meantime, just update the things that we know change.
*/
void updateResources() {
Resources res = getResources();
// detect theme change.
CustomTheme newTheme = res.getConfiguration().customTheme;
if (newTheme != null &&
(mCurrentTheme == null || !mCurrentTheme.equals(newTheme))) {
mCurrentTheme = (CustomTheme)newTheme.clone();
mCmBatteryMiniIcon.updateIconCache();
mCmBatteryMiniIcon.updateMatrix();
// restart system ui on theme change
try {
Runtime.getRuntime().exec("pkill -TERM -f com.android.systemui");
} catch (IOException e) {
// we're screwed here fellas
}
} else {
mOngoingTitle.setText(getText(R.string.status_bar_ongoing_events_title));
mLatestTitle.setText(getText(R.string.status_bar_latest_events_title));
if (mStatusBarTab || mStatusBarTileView) {
mLatestTitles.setText(getText(R.string.status_bar_latestnews_events_title));
}
mNoNotificationsTitle.setText(getText(R.string.status_bar_no_notifications_title));
// update clock for changing font
if(mStatusBarView != null && mStatusBarView.mDate != null) {
mStatusBarView.mDate.invalidate();
}
mEdgeBorder = res.getDimensionPixelSize(R.dimen.status_bar_edge_ignore);
}
if (mQS != null) mQS.updateResources();
if (false) Slog.v(TAG, "updateResources");
}
//
// tracing
//
void postStartTracing() {
mHandler.postDelayed(mStartTracing, 3000);
}
void vibrate() {
android.os.Vibrator vib = (android.os.Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
vib.vibrate(250);
}
Runnable mStartTracing = new Runnable() {
public void run() {
vibrate();
SystemClock.sleep(250);
Slog.d(TAG, "startTracing");
android.os.Debug.startMethodTracing("/data/statusbar-traces/trace");
mHandler.postDelayed(mStopTracing, 10000);
}
};
Runnable mStopTracing = new Runnable() {
public void run() {
android.os.Debug.stopMethodTracing();
Slog.d(TAG, "stopTracing");
vibrate();
}
};
}
| true | true | private void makeStatusBarView(Context context) {
Resources res = context.getResources();
mTouchDispatcher = new ItemTouchDispatcher(this);
int defValuesColor = context.getResources().getInteger(com.android.internal.R.color.color_default_cyanmobile);
int defValuesIconSize = context.getResources().getInteger(com.android.internal.R.integer.config_iconsize_default_cyanmobile);
int mIconSizeval = Settings.System.getInt(context.getContentResolver(),
Settings.System.STATUSBAR_ICONS_SIZE, defValuesIconSize);
int IconSizepx = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, mIconSizeval, res.getDisplayMetrics());
mIconSize = IconSizepx;
//Check for compact carrier layout and apply if enabled
mStatusBarCarrier = Settings.System.getInt(getContentResolver(),
Settings.System.STATUS_BAR_CARRIER, 6);
mStatusBarClock = Settings.System.getInt(getContentResolver(),
Settings.System.STATUS_BAR_CLOCK, 1);
mStatusBarCarrierLogo = Settings.System.getInt(getContentResolver(),
Settings.System.CARRIER_LOGO, 0);
mStatusBarReverse = (Settings.System.getInt(getContentResolver(),
Settings.System.STATUS_BAR_REVERSE, 0) == 1);
mShowCmBatteryStatusBar = (Settings.System.getInt(getContentResolver(),
Settings.System.STATUS_BAR_BATTERY, 0) == 5);
mShowDate = (Settings.System.getInt(getContentResolver(),
Settings.System.STATUS_BAR_DATE, 0) == 1);
mShowNotif = (Settings.System.getInt(getContentResolver(),
Settings.System.STATUS_BAR_NOTIF, 1) == 1);
mShowRam = (Settings.System.getInt(getContentResolver(),
Settings.System.STATUS_BAR_SHOWRAM, 1) == 1);
mShowCmBatterySideBar = (Settings.System.getInt(getContentResolver(),
Settings.System.STATUS_BAR_BATTERY, 0) == 4);
mHasSoftButtons = (Settings.System.getInt(getContentResolver(),
Settings.System.USE_SOFT_BUTTONS, 0) == 1);
LogoStatusBar = (Settings.System.getInt(getContentResolver(),
Settings.System.CARRIER_LOGO_STATUS_BAR, 0) == 1);
shouldTick = (Settings.System.getInt(getContentResolver(),
Settings.System.STATUS_BAR_INTRUDER_ALERT, 1) == 1);
mClockColor = (Settings.System.getInt(getContentResolver(),
Settings.System.STATUS_BAR_CLOCKCOLOR, defValuesColor));
mSettingsColor = (Settings.System.getInt(getContentResolver(),
Settings.System.STATUS_BAR_SETTINGSCOLOR, defValuesColor));
mStatusBarTab = (Settings.System.getInt(getContentResolver(),
Settings.System.EXPANDED_VIEW_WIDGET, 1) == 4);
mStatusBarTileView = (Settings.System.getInt(resolver,
Settings.System.EXPANDED_VIEW_WIDGET, 1) == 5);
mStatusBarGrid = (Settings.System.getInt(getContentResolver(),
Settings.System.EXPANDED_VIEW_WIDGET, 1) == 3);
mNaviShow = (Settings.System.getInt(getContentResolver(),
Settings.System.SHOW_NAVI_BUTTONS, 1) == 1);
mTinyExpanded = (Settings.System.getInt(getContentResolver(),
Settings.System.STATUSBAR_TINY_EXPANDED, 1) == 1);
mMoreExpanded = (Settings.System.getInt(getContentResolver(),
Settings.System.STATUSBAR_TINY_EXPANDED, 1) == 1);
autoBrightness = Settings.System.getInt(
getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, 0) ==
Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;
mBrightnessControl = !autoBrightness && Settings.System.getInt(
getContentResolver(), Settings.System.STATUS_BAR_BRIGHTNESS_TOGGLE, 0) == 1;
IntruderTime = Settings.System.getInt(getContentResolver(),
Settings.System.STATUS_BAR_INTRUDER_TIME, INTRUDER_ALERT_DECAY_MS);
if (!mStatusBarTab || !mStatusBarTileView) {
mExpandedView = (ExpandedView)View.inflate(context,
R.layout.status_bar_expanded, null);
} else {
mExpandedView = (ExpandedView)View.inflate(context,
R.layout.status_bar_expandedtab, null);
}
mExpandedView.mService = this;
mExpandedView.mTouchDispatcher = mTouchDispatcher;
if (!mStatusBarReverse) {
mStatusBarView = (CmStatusBarView)View.inflate(context, R.layout.status_bar, null);
} else {
mStatusBarView = (CmStatusBarView)View.inflate(context, R.layout.status_bar_reverse, null);
}
mStatusBarView.mService = this;
mIntruderAlertView = View.inflate(context, R.layout.intruder_alert, null);
mIntruderAlertView.setVisibility(View.GONE);
mIntruderAlertView.setClickable(true);
mNavigationBarView = (NavigationBarView)View.inflate(context, R.layout.navigation_bar, null);
mNaviBarContainer = (FrameLayout)mNavigationBarView.findViewById(R.id.navibarBackground);
mBackLogoLayout = (BackLogo)mStatusBarView.findViewById(R.id.backlogo);
// apply transparent status bar drawables
int transStatusBar = Settings.System.getInt(getContentResolver(), Settings.System.TRANSPARENT_STATUS_BAR, 0);
int statusBarColor = Settings.System.getInt(getContentResolver(), Settings.System.STATUS_BAR_COLOR, defValuesColor);
switch (transStatusBar) {
case 0 : // theme, leave alone
mStatusBarView.setBackgroundDrawable(getResources().getDrawable(R.drawable.statusbar_background));
break;
case 1 : // based on ROM
mStatusBarView.setBackgroundDrawable(getResources().getDrawable(R.drawable.statusbar_background_black));
break;
case 2 : // semi transparent
mStatusBarView.setBackgroundDrawable(getResources().getDrawable(R.drawable.statusbar_background_semi));
break;
case 3 : // gradient
mStatusBarView.setBackgroundDrawable(getResources().getDrawable(R.drawable.statusbar_background_gradient));
break;
case 4 : // user defined argb hex color
mStatusBarView.setBackgroundColor(statusBarColor);
break;
case 5 : // transparent
break;
case 6 : // transparent and BackLogo
mStatusBarView.setBackgroundDrawable(getResources().getDrawable(R.drawable.status_bar_transparent_background));
Uri savedImage = Uri.fromFile(new File("/data/data/com.cyanogenmod.cmparts/files/bc_background"));
if (savedImage != null) {
Bitmap bitmapImage = BitmapFactory.decodeFile(savedImage.getPath());
Drawable bgrImage = new BitmapDrawable(bitmapImage);
mBackLogoLayout.setBackgroundDrawable(bgrImage);
} else {
mBackLogoLayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.statusbar_background_semi));
}
break;
}
// apply transparent navi bar drawables
int transNaviBar = Settings.System.getInt(getContentResolver(), Settings.System.TRANSPARENT_NAVI_BAR, 0);
int naviBarColor = Settings.System.getInt(getContentResolver(), Settings.System.NAVI_BAR_COLOR, defValuesColor);
switch (transNaviBar) {
case 0 : // theme, leave alone
mNaviBarContainer.setBackgroundDrawable(getResources().getDrawable(R.drawable.navibar_background));
break;
case 1 : // based on ROM
mNaviBarContainer.setBackgroundDrawable(getResources().getDrawable(R.drawable.navibar_background_black));
break;
case 2 : // semi transparent
mNaviBarContainer.setBackgroundDrawable(getResources().getDrawable(R.drawable.navibar_background_semi));
break;
case 3 : // gradient
mNaviBarContainer.setBackgroundDrawable(getResources().getDrawable(R.drawable.navibar_background_gradient));
break;
case 4 : // user defined argb hex color
mNaviBarContainer.setBackgroundColor(naviBarColor);
break;
case 5 : // transparent
break;
case 6 : // BackLogo
Uri savedImage = Uri.fromFile(new File("/data/data/com.cyanogenmod.cmparts/files/navb_background"));
if (savedImage != null) {
Bitmap bitmapImage = BitmapFactory.decodeFile(savedImage.getPath());
Drawable bgrImage = new BitmapDrawable(bitmapImage);
mNaviBarContainer.setBackgroundDrawable(bgrImage);
} else {
mNaviBarContainer.setBackgroundDrawable(getResources().getDrawable(R.drawable.navibar_background_black));
}
break;
}
// figure out which pixel-format to use for the status bar.
mPixelFormat = PixelFormat.TRANSLUCENT;
mStatusIcons = (LinearLayout)mStatusBarView.findViewById(R.id.statusIcons);
mStatusIcons.setOnClickListener(mIconButtonListener);
mNotificationIcons = (IconMerger)mStatusBarView.findViewById(R.id.notificationIcons);
mIcons = (LinearLayout)mStatusBarView.findViewById(R.id.icons);
mCenterClock = (LinearLayout)mStatusBarView.findViewById(R.id.centerClock);
mLeftClock = (LinearLayout)mStatusBarView.findViewById(R.id.clockLeft);
mCarrierLabelStatusBarLayout = (CarrierLabelStatusBar)mStatusBarView.findViewById(R.id.carrier_label_status_bar_layout);
mCenterCarrierLabelStatusBarLayout = (CenterCarrierLabelStatusBar)mStatusBarView.findViewById(R.id.carrier_label_status_bar_center_layout);
mLeftCarrierLabelStatusBarLayout = (LeftCarrierLabelStatusBar)mStatusBarView.findViewById(R.id.carrier_label_status_bar_left_layout);
mCarrierLogoLayout = (CarrierLogo)mStatusBarView.findViewById(R.id.carrier_logo);
mCarrierLogoCenterLayout = (CenterCarrierLogo)mStatusBarView.findViewById(R.id.carrier_logo_center);
mCarrierLogoLeftLayout = (LeftCarrierLogo)mStatusBarView.findViewById(R.id.carrier_logo_left);
mCmBatteryStatusBar = (CmBatteryStatusBar)mStatusBarView.findViewById(R.id.batteryStatusBar);
mTickerView = mStatusBarView.findViewById(R.id.ticker);
mDateView = (DateView)mStatusBarView.findViewById(R.id.date);
mCmBatteryMiniIcon = (CmBatteryMiniIcon)mStatusBarView.findViewById(R.id.CmBatteryMiniIcon);
/* Destroy any existing widgets before recreating the expanded dialog
* to ensure there are no lost context issues */
if (mPowerWidget != null) {
mPowerWidget.destroyWidget();
}
if (mPowerWidgetBottom != null) {
mPowerWidgetBottom.destroyWidget();
}
if (mPowerWidgetOne != null) {
mPowerWidgetOne.destroyWidget();
}
if (mPowerWidgetTwo != null) {
mPowerWidgetTwo.destroyWidget();
}
if (mPowerWidgetThree != null) {
mPowerWidgetThree.destroyWidget();
}
if (mPowerWidgetFour != null) {
mPowerWidgetFour.destroyWidget();
}
mExpandedDialog = new ExpandedDialog(context);
if (!mStatusBarTab || !mStatusBarTileView) {
mExpandedContents = mExpandedView.findViewById(R.id.notificationLinearLayout);
} else {
mExpandedContents = mExpandedView.findViewById(R.id.notifications_layout);
mExpandededContents = mExpandedView.findViewById(R.id.power_and_carrier_layout);
}
mOngoingTitle = (TextView)mExpandedView.findViewById(R.id.ongoingTitle);
mOngoingItems = (LinearLayout)mExpandedView.findViewById(R.id.ongoingItems);
mLatestTitle = (TextView)mExpandedView.findViewById(R.id.latestTitle);
mLatestItems = (LinearLayout)mExpandedView.findViewById(R.id.latestItems);
mNoNotificationsTitle = (TextView)mExpandedView.findViewById(R.id.noNotificationsTitle);
if (mStatusBarTab || mStatusBarTileView) {
mLatestTitles = (TextView)mExpandedView.findViewById(R.id.latestTitles);
mNoNotificationsTitles = (TextView)mExpandedView.findViewById(R.id.noNotificationsTitles);
}
mClearButton = (ImageView)mExpandedView.findViewById(R.id.clear_all_button);
mClearButton.setOnClickListener(mClearButtonListener);
mClearOldButton = (TextView)mExpandedView.findViewById(R.id.clear_old_button);
mClearOldButton.setOnClickListener(mClearButtonListener);
mCompactClearButton = (TextView)mExpandedView.findViewById(R.id.compact_clear_all_button);
mCompactClearButton.setOnClickListener(mClearButtonListener);
mCarrierLabelExpLayout = (CarrierLabelExp)mExpandedView.findViewById(R.id.carrierExp);
mPowerAndCarrier = (LinearLayout)mExpandedView.findViewById(R.id.power_and_carrier);
int transPowerAndCarrier = Settings.System.getInt(getContentResolver(), Settings.System.TRANSPARENT_PWR_CRR, 0);
int PowerAndCarrierColor = Settings.System.getInt(getContentResolver(), Settings.System.PWR_CRR_COLOR, defValuesColor);
switch (transPowerAndCarrier) {
case 0 : // theme, leave alone
mPowerAndCarrier.setBackgroundDrawable(getResources().getDrawable(R.drawable.title_bar_portrait));
break;
case 1 : // user defined argb hex color
mPowerAndCarrier.setBackgroundColor(PowerAndCarrierColor);
break;
case 2 : // transparent
break;
}
mScrollView = (ScrollView)mExpandedView.findViewById(R.id.scroll);
mBottomScrollView = (ScrollView)mExpandedView.findViewById(R.id.bottomScroll);
mNotificationLinearLayout = (LinearLayout)mExpandedView.findViewById(R.id.notificationLinearLayout);
mBottomNotificationLinearLayout = (LinearLayout)mExpandedView.findViewById(R.id.bottomNotificationLinearLayout);
mMusicToggleButton = (ImageView)mExpandedView.findViewById(R.id.music_toggle_button);
mMusicToggleButton.setOnClickListener(mMusicToggleButtonListener);
mCenterClockex = (LinearLayout)mExpandedView.findViewById(R.id.centerClockex);
mCenterIconex = (SignalClusterView)mExpandedView.findViewById(R.id.centerIconex);
mSettingsIconButton = (ImageView)mExpandedView.findViewById(R.id.settingIcon);
mSettingsIconButton.setOnClickListener(mSettingsIconButtonListener);
mStatusIconsExp = (LinearLayout)mExpandedView.findViewById(R.id.expstatusIcons);
if (mStatusBarTileView) {
mQuickContainer = (QuickSettingsContainerView)mExpandedView.findViewById(R.id.quick_settings_container);
}
if (mStatusBarTileView && (mQuickContainer != null)) {
mQS = new QuickSettingsController(context, mQuickContainer);
}
mExpandedView.setVisibility(View.GONE);
mOngoingTitle.setVisibility(View.GONE);
mLatestTitle.setVisibility(View.GONE);
if (mStatusBarTab || mStatusBarTileView) {
mLatestTitles.setVisibility(View.GONE);
}
mMusicControls = (MusicControls)mExpandedView.findViewById(R.id.exp_music_controls);
mPowerWidget = (PowerWidget)mExpandedView.findViewById(R.id.exp_power_stat);
mPowerWidget.setGlobalButtonOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(Settings.System.getInt(getContentResolver(),
Settings.System.EXPANDED_HIDE_ONCHANGE, 0) == 1) {
animateCollapse();
}
}
});
mPowerWidget.setGlobalButtonOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View v) {
animateCollapse();
return true;
}
});
mPowerWidgetOne = (PowerWidgetOne)mExpandedView.findViewById(R.id.exp_power_stat_one);
mPowerWidgetOne.setGlobalButtonOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(Settings.System.getInt(getContentResolver(),
Settings.System.EXPANDED_HIDE_ONCHANGE, 0) == 1) {
animateCollapse();
}
}
});
mPowerWidgetOne.setGlobalButtonOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View v) {
animateCollapse();
return true;
}
});
mPowerWidgetTwo = (PowerWidgetTwo)mExpandedView.findViewById(R.id.exp_power_stat_two);
mPowerWidgetTwo.setGlobalButtonOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(Settings.System.getInt(getContentResolver(),
Settings.System.EXPANDED_HIDE_ONCHANGE, 0) == 1) {
animateCollapse();
}
}
});
mPowerWidgetTwo.setGlobalButtonOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View v) {
animateCollapse();
return true;
}
});
mPowerWidgetThree = (PowerWidgetThree)mExpandedView.findViewById(R.id.exp_power_stat_three);
mPowerWidgetThree.setGlobalButtonOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(Settings.System.getInt(getContentResolver(),
Settings.System.EXPANDED_HIDE_ONCHANGE, 0) == 1) {
animateCollapse();
}
}
});
mPowerWidgetThree.setGlobalButtonOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View v) {
animateCollapse();
return true;
}
});
mPowerWidgetFour = (PowerWidgetFour)mExpandedView.findViewById(R.id.exp_power_stat_four);
mPowerWidgetFour.setGlobalButtonOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(Settings.System.getInt(getContentResolver(),
Settings.System.EXPANDED_HIDE_ONCHANGE, 0) == 1) {
animateCollapse();
}
}
});
mPowerWidgetFour.setGlobalButtonOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View v) {
animateCollapse();
return true;
}
});
mCarrierLabelLayout = (LinearLayout)mExpandedView.findViewById(R.id.carrier_label_layout);
mCompactCarrierLayout = (LinearLayout)mExpandedView.findViewById(R.id.compact_carrier_layout);
mAvalMemLayout = (LinearLayout)mExpandedView.findViewById(R.id.memlabel_layout);
memHeader = (TextView) mExpandedView.findViewById(R.id.avail_mem_text);
avalMemPB = (ProgressBar) mExpandedView.findViewById(R.id.aval_memos);
mTicker = new MyTicker(context, mStatusBarView);
mTickerText = (TickerView)mStatusBarView.findViewById(R.id.tickerText);
mTickerText.mTicker = mTicker;
if (!mStatusBarTab || !mStatusBarTileView) {
mTrackingView = (TrackingView)View.inflate(context, R.layout.status_bar_tracking, null);
} else {
mTrackingView = (TrackingView)View.inflate(context, R.layout.status_bar_trackingtab, null);
}
mTrackingView.mService = this;
mCloseView = (CloseDragHandle)mTrackingView.findViewById(R.id.close);
mCloseView.mService = this;
mNotificationBackgroundView = (View)mTrackingView.findViewById(R.id.notificationBackground);
// apply transparent notification background drawables
int transNotificationBackground = Settings.System.getInt(getContentResolver(), Settings.System.TRANSPARENT_NOTIFICATION_BACKGROUND, 0);
int notificationBackgroundColor = Settings.System.getInt(getContentResolver(), Settings.System.NOTIFICATION_BACKGROUND_COLOR, defValuesColor);
switch (transNotificationBackground) {
case 0 : // theme, leave alone
mNotificationBackgroundView.setBackgroundDrawable(getResources().getDrawable(R.drawable.shade_bg));
break;
case 1 : // default based on ROM
mNotificationBackgroundView.setBackgroundDrawable(getResources().getDrawable(R.drawable.shade_bg2));
break;
case 2 : // user defined argb hex color
mNotificationBackgroundView.setBackgroundColor(notificationBackgroundColor);
break;
case 3 : // semi transparent
mNotificationBackgroundView.setBackgroundDrawable(getResources().getDrawable(R.drawable.shade_trans_bg));
break;
case 4 : // peeping android background image
mNotificationBackgroundView.setBackgroundDrawable(getResources().getDrawable(R.drawable.status_bar_special));
break;
case 5 : // user selected background image
Uri savedImage = Uri.fromFile(new File("/data/data/com.cyanogenmod.cmparts/files/nb_background"));
if (savedImage != null) {
Bitmap bitmapImage = BitmapFactory.decodeFile(savedImage.getPath());
Drawable bgrImage = new BitmapDrawable(bitmapImage);
mNotificationBackgroundView.setBackgroundDrawable(bgrImage);
} else {
mNotificationBackgroundView.setBackgroundDrawable(getResources().getDrawable(R.drawable.status_bar_special));
}
break;
}
mContext=context;
if (mStatusBarTab || mStatusBarTileView) {
mPowerCarrier = (LinearLayout)mExpandedView.findViewById(R.id.power_and_carrier_layout);
mNotifications = (LinearLayout)mExpandedView.findViewById(R.id.notifications_layout);
mNotificationsToggle = (TextView)mTrackingView.findViewById(R.id.statusbar_notification_toggle);
mButtonsToggle = (TextView)mTrackingView.findViewById(R.id.statusbar_buttons_toggle);
mButtonsToggle.setTextColor(mClockColor);
mNotificationsToggle.setTextColor(Color.parseColor("#666666"));
mNotifications.setVisibility(View.GONE);
}
mSettingsButton = (ImageView)mTrackingView.findViewById(R.id.settingUp);
int transSettingsButton = Settings.System.getInt(getContentResolver(), Settings.System.TRANSPARENT_STS_BTT, 0);
int SettingsButtonColor = Settings.System.getInt(getContentResolver(), Settings.System.STS_BTT_COLOR, defValuesColor);
switch (transSettingsButton) {
case 0 : // theme, leave alone
mSettingsButton.setImageBitmap(getNinePatch(R.drawable.status_bar_close_on, getExpandedWidth(), getStatBarSize(), context));
break;
case 1 : // user defined argb hex color
mSettingsButton.setImageBitmap(getNinePatch(R.drawable.status_bar_transparent_background, getExpandedWidth(), getCloseDragSize(), context));
mSettingsButton.setBackgroundColor(SettingsButtonColor);
break;
case 2 : // transparent
mSettingsButton.setImageBitmap(getNinePatch(R.drawable.status_bar_transparent_background, getExpandedWidth(), getCloseDragSize(), context));
break;
}
mSettingsButton.setOnLongClickListener(mSettingsButtonListener);
mCarrierLabelBottomLayout = (CarrierLabelBottom) mTrackingView.findViewById(R.id.carrierlabel_bottom);
mPowerWidgetBottom = (PowerWidgetBottom) mTrackingView.findViewById(R.id.exp_power_stat);
mPowerWidgetBottom.setGlobalButtonOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(Settings.System.getInt(getContentResolver(),
Settings.System.EXPANDED_HIDE_ONCHANGE, 0) == 1) {
animateCollapse();
}
}
});
mPowerWidgetBottom.setGlobalButtonOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View v) {
animateCollapse();
return true;
}
});
if (mStatusBarTab || mStatusBarTileView) {
mNotificationsToggle.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
mNotificationsToggle.setTextColor(mClockColor);
mButtonsToggle.setTextColor(Color.parseColor("#666666"));
LinearLayout parent = (LinearLayout)mButtonsToggle.getParent();
parent.setBackgroundResource(R.drawable.title_bar_portrait);
mPowerCarrier.setVisibility(View.GONE);
mPowerCarrier.startAnimation(loadAnim(com.android.internal.R.anim.fade_out, null));
mNotifications.setVisibility(View.VISIBLE);
mNotifications.startAnimation(loadAnim(com.android.internal.R.anim.fade_in, null));
updateExpandedViewPos(EXPANDED_FULL_OPEN);
}
});
mButtonsToggle.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
mButtonsToggle.setTextColor(mClockColor);
mNotificationsToggle.setTextColor(Color.parseColor("#666666"));
LinearLayout parent = (LinearLayout)mButtonsToggle.getParent();
parent.setBackgroundResource(R.drawable.title_bar_portrait);
mPowerCarrier.setVisibility(View.VISIBLE);
mPowerCarrier.startAnimation(loadAnim(com.android.internal.R.anim.fade_in, null));
mNotifications.setVisibility(View.GONE);
mNotifications.startAnimation(loadAnim(com.android.internal.R.anim.fade_out, null));
updateExpandedViewPos(EXPANDED_FULL_OPEN);
}
});
}
updateColors();
updateLayout();
updateCarrierLabel();
if (mStatusBarCarrierLogo == 1) {
if (LogoStatusBar) {
Uri savedImage = Uri.fromFile(new File("/data/data/com.cyanogenmod.cmparts/files/lg_background"));
Bitmap bitmapImage = BitmapFactory.decodeFile(savedImage.getPath());
Drawable bgrImage = new BitmapDrawable(bitmapImage);
mCarrierLogoLayout.setBackgroundDrawable(bgrImage);
} else {
mCarrierLogoLayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.ic_statusbar_carrier_logos));
}
} else if (mStatusBarCarrierLogo == 2) {
if (LogoStatusBar) {
Uri savedImage = Uri.fromFile(new File("/data/data/com.cyanogenmod.cmparts/files/lg_background"));
Bitmap bitmapImage = BitmapFactory.decodeFile(savedImage.getPath());
Drawable bgrImage = new BitmapDrawable(bitmapImage);
mCarrierLogoCenterLayout.setBackgroundDrawable(bgrImage);
} else {
mCarrierLogoCenterLayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.ic_statusbar_carrier_logos));
}
} else if (mStatusBarCarrierLogo == 3) {
if (LogoStatusBar) {
Uri savedImage = Uri.fromFile(new File("/data/data/com.cyanogenmod.cmparts/files/lg_background"));
Bitmap bitmapImage = BitmapFactory.decodeFile(savedImage.getPath());
Drawable bgrImage = new BitmapDrawable(bitmapImage);
mCarrierLogoLeftLayout.setBackgroundDrawable(bgrImage);
} else {
mCarrierLogoLeftLayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.ic_statusbar_carrier_logos));
}
}
mEdgeBorder = res.getDimensionPixelSize(R.dimen.status_bar_edge_ignore);
// set the inital view visibility
setAreThereNotifications();
mDateView.setVisibility(View.INVISIBLE);
showClock(Settings.System.getInt(getContentResolver(), Settings.System.STATUS_BAR_CLOCK, 1) != 0);
mVelocityTracker = VelocityTracker.obtain();
mDoNotDisturb = new DoNotDisturb(mContext);
totalMemory = 0;
availableMemory = 0;
getMemInfo();
}
| private void makeStatusBarView(Context context) {
Resources res = context.getResources();
mTouchDispatcher = new ItemTouchDispatcher(this);
int defValuesColor = context.getResources().getInteger(com.android.internal.R.color.color_default_cyanmobile);
int defValuesIconSize = context.getResources().getInteger(com.android.internal.R.integer.config_iconsize_default_cyanmobile);
int mIconSizeval = Settings.System.getInt(context.getContentResolver(),
Settings.System.STATUSBAR_ICONS_SIZE, defValuesIconSize);
int IconSizepx = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, mIconSizeval, res.getDisplayMetrics());
mIconSize = IconSizepx;
//Check for compact carrier layout and apply if enabled
mStatusBarCarrier = Settings.System.getInt(getContentResolver(),
Settings.System.STATUS_BAR_CARRIER, 6);
mStatusBarClock = Settings.System.getInt(getContentResolver(),
Settings.System.STATUS_BAR_CLOCK, 1);
mStatusBarCarrierLogo = Settings.System.getInt(getContentResolver(),
Settings.System.CARRIER_LOGO, 0);
mStatusBarReverse = (Settings.System.getInt(getContentResolver(),
Settings.System.STATUS_BAR_REVERSE, 0) == 1);
mShowCmBatteryStatusBar = (Settings.System.getInt(getContentResolver(),
Settings.System.STATUS_BAR_BATTERY, 0) == 5);
mShowDate = (Settings.System.getInt(getContentResolver(),
Settings.System.STATUS_BAR_DATE, 0) == 1);
mShowNotif = (Settings.System.getInt(getContentResolver(),
Settings.System.STATUS_BAR_NOTIF, 1) == 1);
mShowRam = (Settings.System.getInt(getContentResolver(),
Settings.System.STATUS_BAR_SHOWRAM, 1) == 1);
mShowCmBatterySideBar = (Settings.System.getInt(getContentResolver(),
Settings.System.STATUS_BAR_BATTERY, 0) == 4);
mHasSoftButtons = (Settings.System.getInt(getContentResolver(),
Settings.System.USE_SOFT_BUTTONS, 0) == 1);
LogoStatusBar = (Settings.System.getInt(getContentResolver(),
Settings.System.CARRIER_LOGO_STATUS_BAR, 0) == 1);
shouldTick = (Settings.System.getInt(getContentResolver(),
Settings.System.STATUS_BAR_INTRUDER_ALERT, 1) == 1);
mClockColor = (Settings.System.getInt(getContentResolver(),
Settings.System.STATUS_BAR_CLOCKCOLOR, defValuesColor));
mSettingsColor = (Settings.System.getInt(getContentResolver(),
Settings.System.STATUS_BAR_SETTINGSCOLOR, defValuesColor));
mStatusBarTab = (Settings.System.getInt(getContentResolver(),
Settings.System.EXPANDED_VIEW_WIDGET, 1) == 4);
mStatusBarTileView = (Settings.System.getInt(getContentResolver(),
Settings.System.EXPANDED_VIEW_WIDGET, 1) == 5);
mStatusBarGrid = (Settings.System.getInt(getContentResolver(),
Settings.System.EXPANDED_VIEW_WIDGET, 1) == 3);
mNaviShow = (Settings.System.getInt(getContentResolver(),
Settings.System.SHOW_NAVI_BUTTONS, 1) == 1);
mTinyExpanded = (Settings.System.getInt(getContentResolver(),
Settings.System.STATUSBAR_TINY_EXPANDED, 1) == 1);
mMoreExpanded = (Settings.System.getInt(getContentResolver(),
Settings.System.STATUSBAR_TINY_EXPANDED, 1) == 1);
autoBrightness = Settings.System.getInt(
getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, 0) ==
Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;
mBrightnessControl = !autoBrightness && Settings.System.getInt(
getContentResolver(), Settings.System.STATUS_BAR_BRIGHTNESS_TOGGLE, 0) == 1;
IntruderTime = Settings.System.getInt(getContentResolver(),
Settings.System.STATUS_BAR_INTRUDER_TIME, INTRUDER_ALERT_DECAY_MS);
if (!mStatusBarTab || !mStatusBarTileView) {
mExpandedView = (ExpandedView)View.inflate(context,
R.layout.status_bar_expanded, null);
} else {
mExpandedView = (ExpandedView)View.inflate(context,
R.layout.status_bar_expandedtab, null);
}
mExpandedView.mService = this;
mExpandedView.mTouchDispatcher = mTouchDispatcher;
if (!mStatusBarReverse) {
mStatusBarView = (CmStatusBarView)View.inflate(context, R.layout.status_bar, null);
} else {
mStatusBarView = (CmStatusBarView)View.inflate(context, R.layout.status_bar_reverse, null);
}
mStatusBarView.mService = this;
mIntruderAlertView = View.inflate(context, R.layout.intruder_alert, null);
mIntruderAlertView.setVisibility(View.GONE);
mIntruderAlertView.setClickable(true);
mNavigationBarView = (NavigationBarView)View.inflate(context, R.layout.navigation_bar, null);
mNaviBarContainer = (FrameLayout)mNavigationBarView.findViewById(R.id.navibarBackground);
mBackLogoLayout = (BackLogo)mStatusBarView.findViewById(R.id.backlogo);
// apply transparent status bar drawables
int transStatusBar = Settings.System.getInt(getContentResolver(), Settings.System.TRANSPARENT_STATUS_BAR, 0);
int statusBarColor = Settings.System.getInt(getContentResolver(), Settings.System.STATUS_BAR_COLOR, defValuesColor);
switch (transStatusBar) {
case 0 : // theme, leave alone
mStatusBarView.setBackgroundDrawable(getResources().getDrawable(R.drawable.statusbar_background));
break;
case 1 : // based on ROM
mStatusBarView.setBackgroundDrawable(getResources().getDrawable(R.drawable.statusbar_background_black));
break;
case 2 : // semi transparent
mStatusBarView.setBackgroundDrawable(getResources().getDrawable(R.drawable.statusbar_background_semi));
break;
case 3 : // gradient
mStatusBarView.setBackgroundDrawable(getResources().getDrawable(R.drawable.statusbar_background_gradient));
break;
case 4 : // user defined argb hex color
mStatusBarView.setBackgroundColor(statusBarColor);
break;
case 5 : // transparent
break;
case 6 : // transparent and BackLogo
mStatusBarView.setBackgroundDrawable(getResources().getDrawable(R.drawable.status_bar_transparent_background));
Uri savedImage = Uri.fromFile(new File("/data/data/com.cyanogenmod.cmparts/files/bc_background"));
if (savedImage != null) {
Bitmap bitmapImage = BitmapFactory.decodeFile(savedImage.getPath());
Drawable bgrImage = new BitmapDrawable(bitmapImage);
mBackLogoLayout.setBackgroundDrawable(bgrImage);
} else {
mBackLogoLayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.statusbar_background_semi));
}
break;
}
// apply transparent navi bar drawables
int transNaviBar = Settings.System.getInt(getContentResolver(), Settings.System.TRANSPARENT_NAVI_BAR, 0);
int naviBarColor = Settings.System.getInt(getContentResolver(), Settings.System.NAVI_BAR_COLOR, defValuesColor);
switch (transNaviBar) {
case 0 : // theme, leave alone
mNaviBarContainer.setBackgroundDrawable(getResources().getDrawable(R.drawable.navibar_background));
break;
case 1 : // based on ROM
mNaviBarContainer.setBackgroundDrawable(getResources().getDrawable(R.drawable.navibar_background_black));
break;
case 2 : // semi transparent
mNaviBarContainer.setBackgroundDrawable(getResources().getDrawable(R.drawable.navibar_background_semi));
break;
case 3 : // gradient
mNaviBarContainer.setBackgroundDrawable(getResources().getDrawable(R.drawable.navibar_background_gradient));
break;
case 4 : // user defined argb hex color
mNaviBarContainer.setBackgroundColor(naviBarColor);
break;
case 5 : // transparent
break;
case 6 : // BackLogo
Uri savedImage = Uri.fromFile(new File("/data/data/com.cyanogenmod.cmparts/files/navb_background"));
if (savedImage != null) {
Bitmap bitmapImage = BitmapFactory.decodeFile(savedImage.getPath());
Drawable bgrImage = new BitmapDrawable(bitmapImage);
mNaviBarContainer.setBackgroundDrawable(bgrImage);
} else {
mNaviBarContainer.setBackgroundDrawable(getResources().getDrawable(R.drawable.navibar_background_black));
}
break;
}
// figure out which pixel-format to use for the status bar.
mPixelFormat = PixelFormat.TRANSLUCENT;
mStatusIcons = (LinearLayout)mStatusBarView.findViewById(R.id.statusIcons);
mStatusIcons.setOnClickListener(mIconButtonListener);
mNotificationIcons = (IconMerger)mStatusBarView.findViewById(R.id.notificationIcons);
mIcons = (LinearLayout)mStatusBarView.findViewById(R.id.icons);
mCenterClock = (LinearLayout)mStatusBarView.findViewById(R.id.centerClock);
mLeftClock = (LinearLayout)mStatusBarView.findViewById(R.id.clockLeft);
mCarrierLabelStatusBarLayout = (CarrierLabelStatusBar)mStatusBarView.findViewById(R.id.carrier_label_status_bar_layout);
mCenterCarrierLabelStatusBarLayout = (CenterCarrierLabelStatusBar)mStatusBarView.findViewById(R.id.carrier_label_status_bar_center_layout);
mLeftCarrierLabelStatusBarLayout = (LeftCarrierLabelStatusBar)mStatusBarView.findViewById(R.id.carrier_label_status_bar_left_layout);
mCarrierLogoLayout = (CarrierLogo)mStatusBarView.findViewById(R.id.carrier_logo);
mCarrierLogoCenterLayout = (CenterCarrierLogo)mStatusBarView.findViewById(R.id.carrier_logo_center);
mCarrierLogoLeftLayout = (LeftCarrierLogo)mStatusBarView.findViewById(R.id.carrier_logo_left);
mCmBatteryStatusBar = (CmBatteryStatusBar)mStatusBarView.findViewById(R.id.batteryStatusBar);
mTickerView = mStatusBarView.findViewById(R.id.ticker);
mDateView = (DateView)mStatusBarView.findViewById(R.id.date);
mCmBatteryMiniIcon = (CmBatteryMiniIcon)mStatusBarView.findViewById(R.id.CmBatteryMiniIcon);
/* Destroy any existing widgets before recreating the expanded dialog
* to ensure there are no lost context issues */
if (mPowerWidget != null) {
mPowerWidget.destroyWidget();
}
if (mPowerWidgetBottom != null) {
mPowerWidgetBottom.destroyWidget();
}
if (mPowerWidgetOne != null) {
mPowerWidgetOne.destroyWidget();
}
if (mPowerWidgetTwo != null) {
mPowerWidgetTwo.destroyWidget();
}
if (mPowerWidgetThree != null) {
mPowerWidgetThree.destroyWidget();
}
if (mPowerWidgetFour != null) {
mPowerWidgetFour.destroyWidget();
}
mExpandedDialog = new ExpandedDialog(context);
if (!mStatusBarTab || !mStatusBarTileView) {
mExpandedContents = mExpandedView.findViewById(R.id.notificationLinearLayout);
} else {
mExpandedContents = mExpandedView.findViewById(R.id.notifications_layout);
mExpandededContents = mExpandedView.findViewById(R.id.power_and_carrier_layout);
}
mOngoingTitle = (TextView)mExpandedView.findViewById(R.id.ongoingTitle);
mOngoingItems = (LinearLayout)mExpandedView.findViewById(R.id.ongoingItems);
mLatestTitle = (TextView)mExpandedView.findViewById(R.id.latestTitle);
mLatestItems = (LinearLayout)mExpandedView.findViewById(R.id.latestItems);
mNoNotificationsTitle = (TextView)mExpandedView.findViewById(R.id.noNotificationsTitle);
if (mStatusBarTab || mStatusBarTileView) {
mLatestTitles = (TextView)mExpandedView.findViewById(R.id.latestTitles);
mNoNotificationsTitles = (TextView)mExpandedView.findViewById(R.id.noNotificationsTitles);
}
mClearButton = (ImageView)mExpandedView.findViewById(R.id.clear_all_button);
mClearButton.setOnClickListener(mClearButtonListener);
mClearOldButton = (TextView)mExpandedView.findViewById(R.id.clear_old_button);
mClearOldButton.setOnClickListener(mClearButtonListener);
mCompactClearButton = (TextView)mExpandedView.findViewById(R.id.compact_clear_all_button);
mCompactClearButton.setOnClickListener(mClearButtonListener);
mCarrierLabelExpLayout = (CarrierLabelExp)mExpandedView.findViewById(R.id.carrierExp);
mPowerAndCarrier = (LinearLayout)mExpandedView.findViewById(R.id.power_and_carrier);
int transPowerAndCarrier = Settings.System.getInt(getContentResolver(), Settings.System.TRANSPARENT_PWR_CRR, 0);
int PowerAndCarrierColor = Settings.System.getInt(getContentResolver(), Settings.System.PWR_CRR_COLOR, defValuesColor);
switch (transPowerAndCarrier) {
case 0 : // theme, leave alone
mPowerAndCarrier.setBackgroundDrawable(getResources().getDrawable(R.drawable.title_bar_portrait));
break;
case 1 : // user defined argb hex color
mPowerAndCarrier.setBackgroundColor(PowerAndCarrierColor);
break;
case 2 : // transparent
break;
}
mScrollView = (ScrollView)mExpandedView.findViewById(R.id.scroll);
mBottomScrollView = (ScrollView)mExpandedView.findViewById(R.id.bottomScroll);
mNotificationLinearLayout = (LinearLayout)mExpandedView.findViewById(R.id.notificationLinearLayout);
mBottomNotificationLinearLayout = (LinearLayout)mExpandedView.findViewById(R.id.bottomNotificationLinearLayout);
mMusicToggleButton = (ImageView)mExpandedView.findViewById(R.id.music_toggle_button);
mMusicToggleButton.setOnClickListener(mMusicToggleButtonListener);
mCenterClockex = (LinearLayout)mExpandedView.findViewById(R.id.centerClockex);
mCenterIconex = (SignalClusterView)mExpandedView.findViewById(R.id.centerIconex);
mSettingsIconButton = (ImageView)mExpandedView.findViewById(R.id.settingIcon);
mSettingsIconButton.setOnClickListener(mSettingsIconButtonListener);
mStatusIconsExp = (LinearLayout)mExpandedView.findViewById(R.id.expstatusIcons);
if (mStatusBarTileView) {
mQuickContainer = (QuickSettingsContainerView)mExpandedView.findViewById(R.id.quick_settings_container);
}
if (mStatusBarTileView && (mQuickContainer != null)) {
mQS = new QuickSettingsController(context, mQuickContainer);
}
mExpandedView.setVisibility(View.GONE);
mOngoingTitle.setVisibility(View.GONE);
mLatestTitle.setVisibility(View.GONE);
if (mStatusBarTab || mStatusBarTileView) {
mLatestTitles.setVisibility(View.GONE);
}
mMusicControls = (MusicControls)mExpandedView.findViewById(R.id.exp_music_controls);
mPowerWidget = (PowerWidget)mExpandedView.findViewById(R.id.exp_power_stat);
mPowerWidget.setGlobalButtonOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(Settings.System.getInt(getContentResolver(),
Settings.System.EXPANDED_HIDE_ONCHANGE, 0) == 1) {
animateCollapse();
}
}
});
mPowerWidget.setGlobalButtonOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View v) {
animateCollapse();
return true;
}
});
mPowerWidgetOne = (PowerWidgetOne)mExpandedView.findViewById(R.id.exp_power_stat_one);
mPowerWidgetOne.setGlobalButtonOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(Settings.System.getInt(getContentResolver(),
Settings.System.EXPANDED_HIDE_ONCHANGE, 0) == 1) {
animateCollapse();
}
}
});
mPowerWidgetOne.setGlobalButtonOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View v) {
animateCollapse();
return true;
}
});
mPowerWidgetTwo = (PowerWidgetTwo)mExpandedView.findViewById(R.id.exp_power_stat_two);
mPowerWidgetTwo.setGlobalButtonOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(Settings.System.getInt(getContentResolver(),
Settings.System.EXPANDED_HIDE_ONCHANGE, 0) == 1) {
animateCollapse();
}
}
});
mPowerWidgetTwo.setGlobalButtonOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View v) {
animateCollapse();
return true;
}
});
mPowerWidgetThree = (PowerWidgetThree)mExpandedView.findViewById(R.id.exp_power_stat_three);
mPowerWidgetThree.setGlobalButtonOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(Settings.System.getInt(getContentResolver(),
Settings.System.EXPANDED_HIDE_ONCHANGE, 0) == 1) {
animateCollapse();
}
}
});
mPowerWidgetThree.setGlobalButtonOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View v) {
animateCollapse();
return true;
}
});
mPowerWidgetFour = (PowerWidgetFour)mExpandedView.findViewById(R.id.exp_power_stat_four);
mPowerWidgetFour.setGlobalButtonOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(Settings.System.getInt(getContentResolver(),
Settings.System.EXPANDED_HIDE_ONCHANGE, 0) == 1) {
animateCollapse();
}
}
});
mPowerWidgetFour.setGlobalButtonOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View v) {
animateCollapse();
return true;
}
});
mCarrierLabelLayout = (LinearLayout)mExpandedView.findViewById(R.id.carrier_label_layout);
mCompactCarrierLayout = (LinearLayout)mExpandedView.findViewById(R.id.compact_carrier_layout);
mAvalMemLayout = (LinearLayout)mExpandedView.findViewById(R.id.memlabel_layout);
memHeader = (TextView) mExpandedView.findViewById(R.id.avail_mem_text);
avalMemPB = (ProgressBar) mExpandedView.findViewById(R.id.aval_memos);
mTicker = new MyTicker(context, mStatusBarView);
mTickerText = (TickerView)mStatusBarView.findViewById(R.id.tickerText);
mTickerText.mTicker = mTicker;
if (!mStatusBarTab || !mStatusBarTileView) {
mTrackingView = (TrackingView)View.inflate(context, R.layout.status_bar_tracking, null);
} else {
mTrackingView = (TrackingView)View.inflate(context, R.layout.status_bar_trackingtab, null);
}
mTrackingView.mService = this;
mCloseView = (CloseDragHandle)mTrackingView.findViewById(R.id.close);
mCloseView.mService = this;
mNotificationBackgroundView = (View)mTrackingView.findViewById(R.id.notificationBackground);
// apply transparent notification background drawables
int transNotificationBackground = Settings.System.getInt(getContentResolver(), Settings.System.TRANSPARENT_NOTIFICATION_BACKGROUND, 0);
int notificationBackgroundColor = Settings.System.getInt(getContentResolver(), Settings.System.NOTIFICATION_BACKGROUND_COLOR, defValuesColor);
switch (transNotificationBackground) {
case 0 : // theme, leave alone
mNotificationBackgroundView.setBackgroundDrawable(getResources().getDrawable(R.drawable.shade_bg));
break;
case 1 : // default based on ROM
mNotificationBackgroundView.setBackgroundDrawable(getResources().getDrawable(R.drawable.shade_bg2));
break;
case 2 : // user defined argb hex color
mNotificationBackgroundView.setBackgroundColor(notificationBackgroundColor);
break;
case 3 : // semi transparent
mNotificationBackgroundView.setBackgroundDrawable(getResources().getDrawable(R.drawable.shade_trans_bg));
break;
case 4 : // peeping android background image
mNotificationBackgroundView.setBackgroundDrawable(getResources().getDrawable(R.drawable.status_bar_special));
break;
case 5 : // user selected background image
Uri savedImage = Uri.fromFile(new File("/data/data/com.cyanogenmod.cmparts/files/nb_background"));
if (savedImage != null) {
Bitmap bitmapImage = BitmapFactory.decodeFile(savedImage.getPath());
Drawable bgrImage = new BitmapDrawable(bitmapImage);
mNotificationBackgroundView.setBackgroundDrawable(bgrImage);
} else {
mNotificationBackgroundView.setBackgroundDrawable(getResources().getDrawable(R.drawable.status_bar_special));
}
break;
}
mContext=context;
if (mStatusBarTab || mStatusBarTileView) {
mPowerCarrier = (LinearLayout)mExpandedView.findViewById(R.id.power_and_carrier_layout);
mNotifications = (LinearLayout)mExpandedView.findViewById(R.id.notifications_layout);
mNotificationsToggle = (TextView)mTrackingView.findViewById(R.id.statusbar_notification_toggle);
mButtonsToggle = (TextView)mTrackingView.findViewById(R.id.statusbar_buttons_toggle);
mButtonsToggle.setTextColor(mClockColor);
mNotificationsToggle.setTextColor(Color.parseColor("#666666"));
mNotifications.setVisibility(View.GONE);
}
mSettingsButton = (ImageView)mTrackingView.findViewById(R.id.settingUp);
int transSettingsButton = Settings.System.getInt(getContentResolver(), Settings.System.TRANSPARENT_STS_BTT, 0);
int SettingsButtonColor = Settings.System.getInt(getContentResolver(), Settings.System.STS_BTT_COLOR, defValuesColor);
switch (transSettingsButton) {
case 0 : // theme, leave alone
mSettingsButton.setImageBitmap(getNinePatch(R.drawable.status_bar_close_on, getExpandedWidth(), getStatBarSize(), context));
break;
case 1 : // user defined argb hex color
mSettingsButton.setImageBitmap(getNinePatch(R.drawable.status_bar_transparent_background, getExpandedWidth(), getCloseDragSize(), context));
mSettingsButton.setBackgroundColor(SettingsButtonColor);
break;
case 2 : // transparent
mSettingsButton.setImageBitmap(getNinePatch(R.drawable.status_bar_transparent_background, getExpandedWidth(), getCloseDragSize(), context));
break;
}
mSettingsButton.setOnLongClickListener(mSettingsButtonListener);
mCarrierLabelBottomLayout = (CarrierLabelBottom) mTrackingView.findViewById(R.id.carrierlabel_bottom);
mPowerWidgetBottom = (PowerWidgetBottom) mTrackingView.findViewById(R.id.exp_power_stat);
mPowerWidgetBottom.setGlobalButtonOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(Settings.System.getInt(getContentResolver(),
Settings.System.EXPANDED_HIDE_ONCHANGE, 0) == 1) {
animateCollapse();
}
}
});
mPowerWidgetBottom.setGlobalButtonOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View v) {
animateCollapse();
return true;
}
});
if (mStatusBarTab || mStatusBarTileView) {
mNotificationsToggle.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
mNotificationsToggle.setTextColor(mClockColor);
mButtonsToggle.setTextColor(Color.parseColor("#666666"));
LinearLayout parent = (LinearLayout)mButtonsToggle.getParent();
parent.setBackgroundResource(R.drawable.title_bar_portrait);
mPowerCarrier.setVisibility(View.GONE);
mPowerCarrier.startAnimation(loadAnim(com.android.internal.R.anim.fade_out, null));
mNotifications.setVisibility(View.VISIBLE);
mNotifications.startAnimation(loadAnim(com.android.internal.R.anim.fade_in, null));
updateExpandedViewPos(EXPANDED_FULL_OPEN);
}
});
mButtonsToggle.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
mButtonsToggle.setTextColor(mClockColor);
mNotificationsToggle.setTextColor(Color.parseColor("#666666"));
LinearLayout parent = (LinearLayout)mButtonsToggle.getParent();
parent.setBackgroundResource(R.drawable.title_bar_portrait);
mPowerCarrier.setVisibility(View.VISIBLE);
mPowerCarrier.startAnimation(loadAnim(com.android.internal.R.anim.fade_in, null));
mNotifications.setVisibility(View.GONE);
mNotifications.startAnimation(loadAnim(com.android.internal.R.anim.fade_out, null));
updateExpandedViewPos(EXPANDED_FULL_OPEN);
}
});
}
updateColors();
updateLayout();
updateCarrierLabel();
if (mStatusBarCarrierLogo == 1) {
if (LogoStatusBar) {
Uri savedImage = Uri.fromFile(new File("/data/data/com.cyanogenmod.cmparts/files/lg_background"));
Bitmap bitmapImage = BitmapFactory.decodeFile(savedImage.getPath());
Drawable bgrImage = new BitmapDrawable(bitmapImage);
mCarrierLogoLayout.setBackgroundDrawable(bgrImage);
} else {
mCarrierLogoLayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.ic_statusbar_carrier_logos));
}
} else if (mStatusBarCarrierLogo == 2) {
if (LogoStatusBar) {
Uri savedImage = Uri.fromFile(new File("/data/data/com.cyanogenmod.cmparts/files/lg_background"));
Bitmap bitmapImage = BitmapFactory.decodeFile(savedImage.getPath());
Drawable bgrImage = new BitmapDrawable(bitmapImage);
mCarrierLogoCenterLayout.setBackgroundDrawable(bgrImage);
} else {
mCarrierLogoCenterLayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.ic_statusbar_carrier_logos));
}
} else if (mStatusBarCarrierLogo == 3) {
if (LogoStatusBar) {
Uri savedImage = Uri.fromFile(new File("/data/data/com.cyanogenmod.cmparts/files/lg_background"));
Bitmap bitmapImage = BitmapFactory.decodeFile(savedImage.getPath());
Drawable bgrImage = new BitmapDrawable(bitmapImage);
mCarrierLogoLeftLayout.setBackgroundDrawable(bgrImage);
} else {
mCarrierLogoLeftLayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.ic_statusbar_carrier_logos));
}
}
mEdgeBorder = res.getDimensionPixelSize(R.dimen.status_bar_edge_ignore);
// set the inital view visibility
setAreThereNotifications();
mDateView.setVisibility(View.INVISIBLE);
showClock(Settings.System.getInt(getContentResolver(), Settings.System.STATUS_BAR_CLOCK, 1) != 0);
mVelocityTracker = VelocityTracker.obtain();
mDoNotDisturb = new DoNotDisturb(mContext);
totalMemory = 0;
availableMemory = 0;
getMemInfo();
}
|
diff --git a/src/jcue/ui/DeviceControlPanel.java b/src/jcue/ui/DeviceControlPanel.java
index c57351b..188f184 100644
--- a/src/jcue/ui/DeviceControlPanel.java
+++ b/src/jcue/ui/DeviceControlPanel.java
@@ -1,159 +1,160 @@
package jcue.ui;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.text.NumberFormat;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import jcue.domain.SoundDevice;
import jcue.domain.audiocue.AudioCue;
import net.miginfocom.swing.MigLayout;
/**
*
* @author Jaakko
*/
public class DeviceControlPanel extends JPanel implements ChangeListener,
ItemListener, ActionListener {
private JLabel volumeLabel, panLabel;
private JSlider volumeSlider, panSlider;
private JFormattedTextField volumeField, panField;
private JCheckBox muteCheck;
private JButton removeButton;
private SoundDevice targetDevice;
private AudioCue targetCue;
private static final ImageIcon removeIcon = new ImageIcon("Images/remove_small.png");
public DeviceControlPanel(AudioCue targetCue, SoundDevice targetDevice) {
super(new MigLayout("fillx"));
super.setBorder(BorderFactory.createTitledBorder(targetDevice.getName()));
this.targetCue = targetCue;
this.targetDevice = targetDevice;
this.volumeLabel = new JLabel("Volume:");
this.volumeSlider = new JSlider(0, 1000);
this.volumeSlider.setValue((int) (targetCue.getDeviceVolume(targetDevice) * 1000));
this.volumeSlider.addChangeListener(this);
NumberFormat volFormat = NumberFormat.getNumberInstance();
volFormat.setMinimumFractionDigits(2);
volFormat.setMaximumFractionDigits(2);
this.volumeField = new JFormattedTextField(volFormat);
this.volumeField.setColumns(5);
this.volumeField.setValue(targetCue.getDeviceVolume(targetDevice) * 100.0);
this.panLabel = new JLabel("Panning:");
this.panSlider = new JSlider(-1000, 1000);
this.panSlider.setValue((int) (targetCue.getAudio().getDevicePan(targetDevice) * 1000.0));
this.panSlider.addChangeListener(this);
NumberFormat panFormat = (NumberFormat) volFormat.clone();
this.panField = new JFormattedTextField(panFormat);
this.panField.setColumns(5);
this.panField.setValue(targetCue.getAudio().getDevicePan(targetDevice) * 100.0);
this.muteCheck = new JCheckBox("Mute");
this.muteCheck.addItemListener(this);
+ this.muteCheck.setSelected(targetCue.getAudio().isMuted(targetDevice));
this.removeButton = new JButton(removeIcon);
this.removeButton.addActionListener(this);
addComponents();
}
private void addComponents() {
//this.add(this.deviceLabel);
this.add(this.muteCheck);
this.add(this.volumeLabel);
this.add(this.volumeSlider, "span, growx, split 2");
this.add(this.volumeField, "wrap");
this.add(this.removeButton);
this.add(this.panLabel);
this.add(this.panSlider, "span, growx, split 2");
this.add(this.panField);
}
@Override
public void stateChanged(ChangeEvent ce) {
Object source = ce.getSource();
if (source == this.volumeSlider) {
int value = this.volumeSlider.getValue();
double newVolume = value / 1000.0;
this.targetCue.setDeviceVolume(this.targetDevice, newVolume);
this.volumeField.setValue(value / 10.0);
} else if (source == this.panSlider) {
int value = this.panSlider.getValue();
double newPan = value / 1000.0;
this.targetCue.getAudio().setDevicePan(newPan, this.targetDevice);
this.panField.setValue(value / 10.0);
}
}
@Override
public void itemStateChanged(ItemEvent ie) {
Object source = ie.getSource();
boolean muted = false;
if (source == this.muteCheck) {
if (ie.getStateChange() == ItemEvent.SELECTED) {
muted = true;
this.targetCue.getAudio().muteOutput(this.targetDevice);
} else if (ie.getStateChange() == ItemEvent.DESELECTED) {
muted = false;
this.targetCue.getAudio().unmuteOutput(this.targetDevice);
}
}
this.volumeLabel.setEnabled(!muted);
this.volumeSlider.setEnabled(!muted);
this.volumeField.setEnabled(!muted);
this.panLabel.setEnabled(!muted);
this.panSlider.setEnabled(!muted);
this.panField.setEnabled(!muted);
}
@Override
public void actionPerformed(ActionEvent ae) {
Object source = ae.getSource();
if (source == this.removeButton) {
boolean removeOutput = this.targetCue.removeOutput(this.targetDevice);
//Last output cannot be removed
if (!removeOutput) {
JOptionPane.showMessageDialog(this, "Cannot delete output.\nAudio cues must have at least one output.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
}
| true | true | public DeviceControlPanel(AudioCue targetCue, SoundDevice targetDevice) {
super(new MigLayout("fillx"));
super.setBorder(BorderFactory.createTitledBorder(targetDevice.getName()));
this.targetCue = targetCue;
this.targetDevice = targetDevice;
this.volumeLabel = new JLabel("Volume:");
this.volumeSlider = new JSlider(0, 1000);
this.volumeSlider.setValue((int) (targetCue.getDeviceVolume(targetDevice) * 1000));
this.volumeSlider.addChangeListener(this);
NumberFormat volFormat = NumberFormat.getNumberInstance();
volFormat.setMinimumFractionDigits(2);
volFormat.setMaximumFractionDigits(2);
this.volumeField = new JFormattedTextField(volFormat);
this.volumeField.setColumns(5);
this.volumeField.setValue(targetCue.getDeviceVolume(targetDevice) * 100.0);
this.panLabel = new JLabel("Panning:");
this.panSlider = new JSlider(-1000, 1000);
this.panSlider.setValue((int) (targetCue.getAudio().getDevicePan(targetDevice) * 1000.0));
this.panSlider.addChangeListener(this);
NumberFormat panFormat = (NumberFormat) volFormat.clone();
this.panField = new JFormattedTextField(panFormat);
this.panField.setColumns(5);
this.panField.setValue(targetCue.getAudio().getDevicePan(targetDevice) * 100.0);
this.muteCheck = new JCheckBox("Mute");
this.muteCheck.addItemListener(this);
this.removeButton = new JButton(removeIcon);
this.removeButton.addActionListener(this);
addComponents();
}
| public DeviceControlPanel(AudioCue targetCue, SoundDevice targetDevice) {
super(new MigLayout("fillx"));
super.setBorder(BorderFactory.createTitledBorder(targetDevice.getName()));
this.targetCue = targetCue;
this.targetDevice = targetDevice;
this.volumeLabel = new JLabel("Volume:");
this.volumeSlider = new JSlider(0, 1000);
this.volumeSlider.setValue((int) (targetCue.getDeviceVolume(targetDevice) * 1000));
this.volumeSlider.addChangeListener(this);
NumberFormat volFormat = NumberFormat.getNumberInstance();
volFormat.setMinimumFractionDigits(2);
volFormat.setMaximumFractionDigits(2);
this.volumeField = new JFormattedTextField(volFormat);
this.volumeField.setColumns(5);
this.volumeField.setValue(targetCue.getDeviceVolume(targetDevice) * 100.0);
this.panLabel = new JLabel("Panning:");
this.panSlider = new JSlider(-1000, 1000);
this.panSlider.setValue((int) (targetCue.getAudio().getDevicePan(targetDevice) * 1000.0));
this.panSlider.addChangeListener(this);
NumberFormat panFormat = (NumberFormat) volFormat.clone();
this.panField = new JFormattedTextField(panFormat);
this.panField.setColumns(5);
this.panField.setValue(targetCue.getAudio().getDevicePan(targetDevice) * 100.0);
this.muteCheck = new JCheckBox("Mute");
this.muteCheck.addItemListener(this);
this.muteCheck.setSelected(targetCue.getAudio().isMuted(targetDevice));
this.removeButton = new JButton(removeIcon);
this.removeButton.addActionListener(this);
addComponents();
}
|
diff --git a/plugins/org.eclipse.emf.ecore.xcore/src/org/eclipse/emf/ecore/xcore/validation/XcoreJvmTypeReferencesValidator.java b/plugins/org.eclipse.emf.ecore.xcore/src/org/eclipse/emf/ecore/xcore/validation/XcoreJvmTypeReferencesValidator.java
index c1a6f900c..0b75249de 100644
--- a/plugins/org.eclipse.emf.ecore.xcore/src/org/eclipse/emf/ecore/xcore/validation/XcoreJvmTypeReferencesValidator.java
+++ b/plugins/org.eclipse.emf.ecore.xcore/src/org/eclipse/emf/ecore/xcore/validation/XcoreJvmTypeReferencesValidator.java
@@ -1,27 +1,27 @@
/**
* Copyright (c) 2013 Eclipse contributors and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.emf.ecore.xcore.validation;
import org.eclipse.emf.ecore.xcore.XClassifier;
import org.eclipse.emf.ecore.xcore.XcorePackage;
import org.eclipse.xtext.common.types.JvmParameterizedTypeReference;
import org.eclipse.xtext.xbase.validation.JvmTypeReferencesValidator;
public class XcoreJvmTypeReferencesValidator extends JvmTypeReferencesValidator
{
@Override
public void checkTypeArgsAgainstTypeParameters(JvmParameterizedTypeReference typeRef)
{
if (typeRef.eContainmentFeature() != XcorePackage.Literals.XCLASSIFIER__INSTANCE_TYPE ||
- ((XClassifier)typeRef.eContainer()).getTypeParameters().isEmpty())
+ ((XClassifier)typeRef.eContainer()).getTypeParameters().isEmpty() && !"java.util.Map$Entry".equals(typeRef.getIdentifier()))
{
super.checkTypeArgsAgainstTypeParameters(typeRef);
}
}
}
| true | true | public void checkTypeArgsAgainstTypeParameters(JvmParameterizedTypeReference typeRef)
{
if (typeRef.eContainmentFeature() != XcorePackage.Literals.XCLASSIFIER__INSTANCE_TYPE ||
((XClassifier)typeRef.eContainer()).getTypeParameters().isEmpty())
{
super.checkTypeArgsAgainstTypeParameters(typeRef);
}
}
| public void checkTypeArgsAgainstTypeParameters(JvmParameterizedTypeReference typeRef)
{
if (typeRef.eContainmentFeature() != XcorePackage.Literals.XCLASSIFIER__INSTANCE_TYPE ||
((XClassifier)typeRef.eContainer()).getTypeParameters().isEmpty() && !"java.util.Map$Entry".equals(typeRef.getIdentifier()))
{
super.checkTypeArgsAgainstTypeParameters(typeRef);
}
}
|
diff --git a/servers/sip-servlets/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/session/SipApplicationSessionImpl.java b/servers/sip-servlets/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/session/SipApplicationSessionImpl.java
index a30699b34..c1de26709 100644
--- a/servers/sip-servlets/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/session/SipApplicationSessionImpl.java
+++ b/servers/sip-servlets/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/session/SipApplicationSessionImpl.java
@@ -1,923 +1,926 @@
/*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.mobicents.servlet.sip.core.session;
import java.net.URL;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpSession;
import javax.servlet.sip.ServletTimer;
import javax.servlet.sip.SipApplicationSessionActivationListener;
import javax.servlet.sip.SipApplicationSessionAttributeListener;
import javax.servlet.sip.SipApplicationSessionBindingEvent;
import javax.servlet.sip.SipApplicationSessionBindingListener;
import javax.servlet.sip.SipApplicationSessionEvent;
import javax.servlet.sip.SipApplicationSessionListener;
import javax.servlet.sip.SipSession;
import javax.servlet.sip.URI;
import org.apache.catalina.Session;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mobicents.servlet.sip.address.RFC2396UrlDecoder;
import org.mobicents.servlet.sip.core.timers.ExecutorServiceWrapper;
import org.mobicents.servlet.sip.startup.SipContext;
/**
* <p>Implementation of the SipApplicationSession interface.
* An instance of this sip application session can only be retrieved through the Session Manager
* (extended class from Tomcat's manager classes implementing the <code>Manager</code> interface)
* to constrain the creation of sip application session and to make sure that all sessions created
* can be retrieved only through the session manager<p/>
*
* <p>
* As a SipApplicationSession represents a call (that can contain multiple call legs, in the B2BUA case by example),
* the call id and the app name are used as a unique key for a given SipApplicationSession instance.
* </p>
*
* @author <A HREF="mailto:[email protected]">Jean Deruelle</A>
*/
public class SipApplicationSessionImpl implements MobicentsSipApplicationSession {
private transient static final Log logger = LogFactory.getLog(SipApplicationSessionImpl.class);
/**
* Timer task that will notify the listeners that the sip application session has expired
* @author <A HREF="mailto:[email protected]">Jean Deruelle</A>
*/
public class SipApplicationSessionTimerTask implements Runnable {
public void run() {
if(logger.isDebugEnabled()) {
logger.debug("SipApplicationSessionTimerTask now running for sip application session " + getId());
}
notifySipApplicationSessionListeners(SipApplicationSessionEventType.EXPIRATION);
//It is possible that the application grant an extension to the lifetime of the session, thus the sip application
//should not be treated as expired.
if(expirationTimerFuture.getDelay(TimeUnit.MILLISECONDS) <= 0) {
setExpired(true);
sipContext.enterSipApp(null, null, null, true, false);
try {
invalidate();
} finally {
sipContext.exitSipApp();
}
}
}
}
protected Map<String, Object> sipApplicationSessionAttributeMap;
protected transient ConcurrentHashMap<String,MobicentsSipSession> sipSessions;
protected transient ConcurrentHashMap<String, HttpSession> httpSessions;
protected SipApplicationSessionKey key;
protected long lastAccessedTime;
protected long creationTime;
// private long expirationTime;
protected boolean expired;
protected transient SipApplicationSessionTimerTask expirationTimerTask;
protected transient ScheduledFuture<MobicentsSipApplicationSession> expirationTimerFuture;
protected transient ConcurrentHashMap<String, ServletTimer> servletTimers;
protected boolean isValid;
protected boolean invalidateWhenReady = true;
protected boolean readyToInvalidate = false;
protected transient ThreadPoolExecutor executorService = new ThreadPoolExecutor(1, 1,
90, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
/**
* The first sip application for subsequent requests.
*/
protected transient SipContext sipContext;
protected String currentRequestHandler;
protected SipApplicationSessionImpl(SipApplicationSessionKey key, SipContext sipContext) {
sipApplicationSessionAttributeMap = new ConcurrentHashMap<String,Object>() ;
sipSessions = new ConcurrentHashMap<String,MobicentsSipSession>();
httpSessions = new ConcurrentHashMap<String,HttpSession>();
servletTimers = new ConcurrentHashMap<String, ServletTimer>();
this.key = key;
this.sipContext = sipContext;
this.currentRequestHandler = sipContext.getMainServlet();
lastAccessedTime = creationTime = System.currentTimeMillis();
expired = false;
isValid = true;
// the sip context can be null if the AR returned an application that was not deployed
if(sipContext != null) {
//scheduling the timer for session expiration
if(sipContext.getSipApplicationSessionTimeout() > 0) {
long expirationTime = sipContext.getSipApplicationSessionTimeout() * 60 * 1000;
expirationTimerTask = new SipApplicationSessionTimerTask();
if(logger.isDebugEnabled()) {
logger.debug("Scheduling sip application session "+ key +" to expire in " + (expirationTime / 1000 / 60) + " minutes");
}
expirationTimerFuture = (ScheduledFuture<MobicentsSipApplicationSession>) ExecutorServiceWrapper.getInstance().schedule(expirationTimerTask, expirationTime, TimeUnit.MILLISECONDS);
} else {
if(logger.isDebugEnabled()) {
logger.debug("The sip application session "+ key +" will never expire ");
}
// If the session timeout value is 0 or less, then an application session timer
// never starts for the SipApplicationSession object and the container does
// not consider the object to ever have expired
// expirationTime = -1;
}
notifySipApplicationSessionListeners(SipApplicationSessionEventType.CREATION);
}
}
/**
* Notifies the listeners that a lifecycle event occured on that sip application session
* @param sipApplicationSessionEventType the type of event that happened
*/
public void notifySipApplicationSessionListeners(SipApplicationSessionEventType sipApplicationSessionEventType) {
SipApplicationSessionEvent event = new SipApplicationSessionEvent(this);
if(logger.isDebugEnabled()) {
logger.debug("notifying sip application session listeners of context " +
key.getApplicationName() + " of following event " + sipApplicationSessionEventType);
}
ClassLoader oldLoader = java.lang.Thread.currentThread().getContextClassLoader();
java.lang.Thread.currentThread().setContextClassLoader(sipContext.getLoader().getClassLoader());
List<SipApplicationSessionListener> listeners =
sipContext.getListeners().getSipApplicationSessionListeners();
for (SipApplicationSessionListener sipApplicationSessionListener : listeners) {
try {
if(SipApplicationSessionEventType.CREATION.equals(sipApplicationSessionEventType)) {
sipApplicationSessionListener.sessionCreated(event);
} else if (SipApplicationSessionEventType.DELETION.equals(sipApplicationSessionEventType)) {
sipApplicationSessionListener.sessionDestroyed(event);
} else if (SipApplicationSessionEventType.EXPIRATION.equals(sipApplicationSessionEventType)) {
sipApplicationSessionListener.sessionExpired(event);
} else if (SipApplicationSessionEventType.READYTOINVALIDATE.equals(sipApplicationSessionEventType)) {
sipApplicationSessionListener.sessionReadyToInvalidate(event);
}
} catch (Throwable t) {
logger.error("SipApplicationSessionListener threw exception", t);
}
}
java.lang.Thread.currentThread().setContextClassLoader(oldLoader);
}
public void addSipSession(MobicentsSipSession mobicentsSipSession) {
this.sipSessions.putIfAbsent(mobicentsSipSession.getKey().toString(), mobicentsSipSession);
readyToInvalidate = false;
// sipSessionImpl.setSipApplicationSession(this);
}
public MobicentsSipSession removeSipSession (MobicentsSipSession mobicentsSipSession) {
return this.sipSessions.remove(mobicentsSipSession.getKey().toString());
}
public void addHttpSession(HttpSession httpSession) {
this.httpSessions.putIfAbsent(httpSession.getId(), httpSession);
readyToInvalidate = false;
}
public HttpSession removeHttpSession(HttpSession httpSession) {
return this.httpSessions.remove(httpSession.getId());
}
public HttpSession findHttpSession (HttpSession httpSession) {
return this.httpSessions.get(httpSession.getId());
}
/**
* {@inheritDoc}
*/
public void encodeURI(URI uri) {
uri.setParameter(SIP_APPLICATION_KEY_PARAM_NAME, RFC2396UrlDecoder.encode(getId()));
}
/**
* {@inheritDoc}
* Adds a get parameter to the URL like this:
* http://hostname/link -> http://hostname/link?org.mobicents.servlet.sip.ApplicationSessionKey=0
* http://hostname/link?something=1 -> http://hostname/link?something=1&org.mobicents.servlet.sip.ApplicationSessionKey=0
*/
public URL encodeURL(URL url) {
if(!isValid) {
throw new IllegalStateException("SipApplicationSession already invalidated !");
}
String urlStr = url.toExternalForm();
try {
URL ret;
if (urlStr.contains("?")) {
ret = new URL(url + "&" + SIP_APPLICATION_KEY_PARAM_NAME + "="
+ getId().toString());
} else {
ret = new URL(url + "?" + SIP_APPLICATION_KEY_PARAM_NAME + "="
+ getId().toString());
}
return ret;
} catch (Exception e) {
throw new IllegalArgumentException("Failed encoding URL : " + url, e);
}
}
/**
* {@inheritDoc}
*/
public Object getAttribute(String name) {
if(!isValid) {
throw new IllegalStateException("SipApplicationSession already invalidated !");
}
return this.sipApplicationSessionAttributeMap.get(name);
}
/*
* (non-Javadoc)
* @see javax.servlet.sip.SipApplicationSession#getAttributeNames()
*/
public Iterator<String> getAttributeNames() {
if(!isValid) {
throw new IllegalStateException("SipApplicationSession already invalidated !");
}
return this.sipApplicationSessionAttributeMap.keySet().iterator();
}
/*
* (non-Javadoc)
* @see javax.servlet.sip.SipApplicationSession#getCreationTime()
*/
public long getCreationTime() {
if(!isValid) {
throw new IllegalStateException("SipApplicationSession already invalidated !");
}
return creationTime;
}
/*
* (non-Javadoc)
* @see javax.servlet.sip.SipApplicationSession#getExpirationTime()
*/
public long getExpirationTime() {
if(!isValid()) {
throw new IllegalStateException("this sip application session is not valid anymore");
}
if(expirationTimerFuture == null || expirationTimerFuture.getDelay(TimeUnit.MILLISECONDS) <= 0) {
return 0;
}
if(expired) {
return Long.MIN_VALUE;
}
return expirationTimerFuture.getDelay(TimeUnit.MILLISECONDS);
}
/**
* {@inheritDoc}
*/
public String getId() {
return key.toString();
}
/*
* (non-Javadoc)
* @see javax.servlet.sip.SipApplicationSession#getLastAccessedTime()
*/
public long getLastAccessedTime() {
return lastAccessedTime;
}
private void setLastAccessedTime(long lastAccessTime) {
this.lastAccessedTime= lastAccessTime;
}
/**
* Update the accessed time information for this session. This method
* should be called by the context when a request comes in for a particular
* session, even if the application does not reference it.
*/
//TODO : Section 6.3 : Whenever the last accessed time for a SipApplicationSession is updated, it is considered refreshed i.e.,
//the expiry timer for that SipApplicationSession starts anew.
// this method should be called as soon as there is any modifications to the Sip Application Session
public void access() {
setLastAccessedTime(System.currentTimeMillis());
}
/*
* (non-Javadoc)
* @see javax.servlet.sip.SipApplicationSession#getSessions()
*/
public Iterator<?> getSessions() {
if(!isValid) {
throw new IllegalStateException("SipApplicationSession already invalidated !");
}
return sipSessions.values().iterator();
}
/*
* (non-Javadoc)
* @see javax.servlet.sip.SipApplicationSession#getSessions(java.lang.String)
*/
public Iterator<?> getSessions(String protocol) {
if(!isValid) {
throw new IllegalStateException("SipApplicationSession already invalidated !");
}
if(protocol == null) {
throw new NullPointerException("protocol given in argument is null");
}
if("SIP".equalsIgnoreCase(protocol)) {
return sipSessions.values().iterator();
} else if("HTTP".equalsIgnoreCase(protocol)) {
return httpSessions.values().iterator();
} else {
throw new IllegalArgumentException(protocol + " sessions are not handled by this container");
}
}
/*
* (non-Javadoc)
* @see javax.servlet.sip.SipApplicationSession#getSipSession(java.lang.String)
*/
public SipSession getSipSession(String id) {
if(!isValid) {
throw new IllegalStateException("SipApplicationSession already invalidated !");
}
if(logger.isDebugEnabled()) {
logger.debug("Trying to find a session with the id " + id);
dumpSipSessions();
}
return sipSessions.get(id);
}
private void dumpSipSessions() {
if(logger.isDebugEnabled()) {
logger.debug("sessions contained in the following app session " + key);
for (String sessionKey : sipSessions.keySet()) {
logger.debug("session key " + sessionKey + ", value = " + sipSessions.get(sessionKey));
}
}
}
/*
* (non-Javadoc)
* @see javax.servlet.sip.SipApplicationSession#getTimers()
*/
public Collection<ServletTimer> getTimers() {
if(!isValid) {
throw new IllegalStateException("SipApplicationSession already invalidated !");
}
return servletTimers.values();
}
/**
* Add a servlet timer to this application session
* @param servletTimer the servlet timer to add
*/
public void addServletTimer(ServletTimer servletTimer){
servletTimers.putIfAbsent(servletTimer.getId(), servletTimer);
}
/**
* Remove a servlet timer from this application session
* @param servletTimer the servlet timer to remove
*/
public void removeServletTimer(ServletTimer servletTimer){
servletTimers.remove(servletTimer.getId());
updateReadyToInvalidateState();
}
/*
* (non-Javadoc)
* @see javax.servlet.sip.SipApplicationSession#invalidate()
*/
public void invalidate() {
if(!isValid) {
throw new IllegalStateException("SipApplicationSession already invalidated !");
}
if(logger.isInfoEnabled()) {
logger.info("Invalidating the following sip application session " + key);
}
//JSR 289 Section 6.1.2.2.1
//When the IllegalStateException is thrown, the application is guaranteed
//that the state of the SipApplicationSession object will be unchanged from its state prior to the invalidate()
//method call. Even session objects that were eligible for invalidation will not have been invalidated.
//need to check before doing the real invalidation if they are eligible
//for invalidation
// checkInvalidation not needed after PFD2
/*
for(SipSessionImpl session: sipSessions.values()) {
if(session.isValid()) {
try {
session.checkInvalidation();
} catch (IllegalStateException e) {
throw new IllegalStateException("All SIP " +
"and HTTP sessions must be invalidated" +
" before invalidating the application session.", e);
}
}
} */
//doing the invalidation
for(MobicentsSipSession session: sipSessions.values()) {
if(session.isValid()) {
session.invalidate();
}
}
for(HttpSession session: httpSessions.values()) {
- if(((Session)session).isValid()) {
+ try {
session.invalidate();
+ } catch(IllegalStateException ignore) {
+ //we ignore this exception, ugly but the only way to test for validity of the session since we cannot cast to catalina Session
+ //See Issue 523 http://code.google.com/p/mobicents/issues/detail?id=523
}
}
for (String key : sipApplicationSessionAttributeMap.keySet()) {
removeAttribute(key);
}
notifySipApplicationSessionListeners(SipApplicationSessionEventType.DELETION);
isValid = false;
//cancelling the timers
for (Map.Entry<String, ServletTimer> servletTimerEntry : servletTimers.entrySet()) {
ServletTimer timerEntry = servletTimerEntry.getValue();
if(timerEntry != null) {
timerEntry.cancel();
}
}
if(!expired && expirationTimerFuture != null) {
cancelExpirationTimer();
}
/*
* Compute how long this session has been alive, and update
* session manager's related properties accordingly
*/
long timeNow = System.currentTimeMillis();
int timeAlive = (int) ((timeNow - creationTime)/1000);
SipManager manager = sipContext.getSipManager();
synchronized (manager) {
if (timeAlive > manager.getSipApplicationSessionMaxAliveTime()) {
manager.setSipApplicationSessionMaxAliveTime(timeAlive);
}
int numExpired = manager.getExpiredSipApplicationSessions();
numExpired++;
manager.setExpiredSipApplicationSessions(numExpired);
int average = manager.getSipApplicationSessionAverageAliveTime();
average = ((average * (numExpired-1)) + timeAlive)/numExpired;
manager.setSipApplicationSessionAverageAliveTime(average);
}
sipContext.getSipManager().removeSipApplicationSession(key);
expirationTimerTask = null;
expirationTimerFuture = null;
httpSessions.clear();
// key = null;
servletTimers.clear();
sipApplicationSessionAttributeMap.clear();
sipSessions.clear();
httpSessions.clear();
executorService.shutdown();
executorService = null;
httpSessions = null;
sipSessions = null;
sipApplicationSessionAttributeMap = null;
servletTimers = null;
sipContext = null;
if(logger.isInfoEnabled()) {
logger.info("The following sip application session " + key + " has been invalidated");
}
currentRequestHandler = null;
key = null;
}
private void cancelExpirationTimer() {
boolean removed = ExecutorServiceWrapper.getInstance().remove((Runnable)expirationTimerFuture);
if(logger.isDebugEnabled()) {
logger.debug("expiration timer on sip application session " + key + " removed : " + removed);
}
boolean cancelled = expirationTimerFuture.cancel(true);
if(logger.isDebugEnabled()) {
logger.debug("expiration timer on sip application session " + key + " Cancelled : " + cancelled);
}
ExecutorServiceWrapper.getInstance().purge();
}
/*
* (non-Javadoc)
* @see javax.servlet.sip.SipApplicationSession#isValid()
*/
public boolean isValid() {
return isValid;
}
/*
* (non-Javadoc)
* @see javax.servlet.sip.SipApplicationSession#removeAttribute(java.lang.String)
*/
public void removeAttribute(String name) {
if (!isValid())
throw new IllegalStateException(
"Can not bind object to session that has been invalidated!!");
if (name == null)
// throw new NullPointerException("Name of attribute to bind cant be
// null!!!");
return;
SipApplicationSessionBindingEvent event = new SipApplicationSessionBindingEvent(this, name);
Object value = this.sipApplicationSessionAttributeMap.remove(name);
// Call the valueUnbound() method if necessary
if (value != null && value instanceof SipApplicationSessionBindingListener) {
((SipApplicationSessionBindingListener) value).valueUnbound(event);
}
SipListenersHolder listeners = sipContext.getListeners();
if(logger.isDebugEnabled()) {
logger.debug("notifying SipApplicationSessionAttributeListener of attribute removed on key "+ key);
}
for (SipApplicationSessionAttributeListener listener : listeners
.getSipApplicationSessionAttributeListeners()) {
try {
listener.attributeRemoved(event);
} catch (Throwable t) {
logger.error("SipApplicationSessionAttributeListener threw exception", t);
}
}
}
/*
* (non-Javadoc)
* @see javax.servlet.sip.SipApplicationSession#setAttribute(java.lang.String, java.lang.Object)
*/
public void setAttribute(String key, Object attribute) {
if (!isValid())
throw new IllegalStateException(
"Can not bind object to session that has been invalidated!!");
if (key == null)
throw new NullPointerException(
"Name of attribute to bind cant be null!!!");
if (attribute == null)
throw new NullPointerException(
"Attribute that is to be bound cant be null!!!");
// Construct an event with the new value
SipApplicationSessionBindingEvent event = new SipApplicationSessionBindingEvent(this, key);
// Call the valueBound() method if necessary
if (attribute instanceof SipApplicationSessionBindingListener) {
// Don't call any notification if replacing with the same value
Object oldValue = sipApplicationSessionAttributeMap.get(key);
if (attribute != oldValue) {
try {
((SipApplicationSessionBindingListener) attribute).valueBound(event);
} catch (Throwable t){
logger.error("SipSessionBindingListener threw exception", t);
}
}
}
Object previousValue = this.sipApplicationSessionAttributeMap.put(key, attribute);
if (previousValue != null && previousValue != attribute &&
previousValue instanceof SipApplicationSessionBindingListener) {
try {
((SipApplicationSessionBindingListener) previousValue).valueUnbound
(new SipApplicationSessionBindingEvent(this, key));
} catch (Throwable t) {
logger.error("SipSessionBindingListener threw exception", t);
}
}
SipListenersHolder listeners = sipContext.getListeners();
if (previousValue == null) {
if(logger.isDebugEnabled()) {
logger.debug("notifying SipApplicationSessionAttributeListener of attribute added on key "+ key);
}
for (SipApplicationSessionAttributeListener listener : listeners
.getSipApplicationSessionAttributeListeners()) {
try {
listener.attributeAdded(event);
} catch (Throwable t) {
logger.error("SipApplicationSessionAttributeListener threw exception", t);
}
}
} else {
if(logger.isDebugEnabled()) {
logger.debug("notifying SipApplicationSessionAttributeListener of attribute replaced on key "+ key);
}
for (SipApplicationSessionAttributeListener listener : listeners
.getSipApplicationSessionAttributeListeners()) {
try {
listener.attributeReplaced(event);
} catch (Throwable t) {
logger.error("SipApplicationSessionAttributeListener threw exception", t);
}
}
}
}
/*
* (non-Javadoc)
* @see javax.servlet.sip.SipApplicationSession#setExpires(int)
*/
public int setExpires(int deltaMinutes) {
if(!isValid()) {
throw new IllegalStateException("Impossible to change the sip application " +
"session timeout when it has been invalidated !");
}
expired = false;
if(logger.isDebugEnabled()) {
logger.debug("Postponing the expiratin of the sip application session "
+ key +" to expire in " + deltaMinutes + " minutes.");
}
if(deltaMinutes <= 0) {
if(logger.isDebugEnabled()) {
logger.debug("The sip application session "+ key +" won't expire anymore ");
}
// If the session timeout value is 0 or less, then an application session timer
// never starts for the SipApplicationSession object and the container
// does not consider the object to ever have expired
// this.expirationTime = -1;
if(expirationTimerFuture != null) {
cancelExpirationTimer();
expirationTimerFuture = null;
}
return Integer.MAX_VALUE;
} else {
long expirationTime = 0;
if(expirationTimerFuture != null) {
//extending the app session life time
// expirationTime = expirationTimerFuture.getDelay(TimeUnit.MILLISECONDS) + deltaMinutes * 1000 * 60;
expirationTime = deltaMinutes * 1000 * 60;
} else {
//the app session was scheduled to never expire and now an expiration time is set
expirationTime = deltaMinutes * 1000 * 60;
}
if(expirationTimerFuture != null) {
if(logger.isDebugEnabled()) {
logger.debug("Re-Scheduling sip application session "+ key +" to expire in " + deltaMinutes + " minutes");
logger.debug("Re-Scheduling sip application session "+ key +" will expires in " + expirationTime + " milliseconds");
}
cancelExpirationTimer();
expirationTimerTask = new SipApplicationSessionTimerTask();
expirationTimerFuture = (ScheduledFuture<MobicentsSipApplicationSession>) ExecutorServiceWrapper.getInstance().schedule(expirationTimerTask, expirationTime, TimeUnit.MILLISECONDS);
}
return deltaMinutes;
}
}
public boolean hasTimerListener() {
return this.sipContext.getListeners().getTimerListener() != null;
}
public SipContext getSipContext() {
return sipContext;
}
void expirationTimerFired() {
notifySipApplicationSessionListeners(SipApplicationSessionEventType.EXPIRATION);
}
/**
* @return the key
*/
public SipApplicationSessionKey getKey() {
return key;
}
/**
* @param key the key to set
*/
public void setKey(SipApplicationSessionKey key) {
this.key = key;
}
/*
* (non-Javadoc)
* @see javax.servlet.sip.SipApplicationSession#getApplicationName()
*/
public String getApplicationName() {
return key.getApplicationName();
}
/*
* (non-Javadoc)
* @see javax.servlet.sip.SipApplicationSession#getTimer(java.lang.String)
*/
public ServletTimer getTimer(String id) {
if(!isValid) {
throw new IllegalStateException("SipApplicationSession already invalidated !");
}
return servletTimers.get(id);
}
/**
* Perform the internal processing required to passivate
* this session.
*/
public void passivate() {
// Notify ActivationListeners
SipApplicationSessionEvent event = null;
Set<String> keySet = sipApplicationSessionAttributeMap.keySet();
for (String key : keySet) {
Object attribute = sipApplicationSessionAttributeMap.get(key);
if (attribute instanceof SipApplicationSessionActivationListener) {
if (event == null)
event = new SipApplicationSessionEvent(this);
try {
((SipApplicationSessionActivationListener)attribute)
.sessionWillPassivate(event);
} catch (Throwable t) {
logger.error("SipApplicationSessionActivationListener threw exception", t);
}
}
}
}
/**
* Perform internal processing required to activate this
* session.
*/
public void activate() {
// Notify ActivationListeners
SipApplicationSessionEvent event = null;
Set<String> keySet = sipApplicationSessionAttributeMap.keySet();
for (String key : keySet) {
Object attribute = sipApplicationSessionAttributeMap.get(key);
if (attribute instanceof SipApplicationSessionActivationListener) {
if (event == null)
event = new SipApplicationSessionEvent(this);
try {
((SipApplicationSessionActivationListener)attribute)
.sessionDidActivate(event);
} catch (Throwable t) {
logger.error("SipApplicationSessionActivationListener threw exception", t);
}
}
}
}
public boolean getInvalidateWhenReady() {
if(!isValid) {
throw new IllegalStateException("SipApplicationSession already invalidated !");
}
return invalidateWhenReady;
}
/**
* {@inheritDoc}
*/
public Object getSession(String id, Protocol protocol) {
if(!isValid) {
throw new IllegalStateException("SipApplicationSession already invalidated !");
}
if(id == null) {
throw new NullPointerException("id is null");
}
if(protocol == null) {
throw new NullPointerException("protocol is null");
}
switch (protocol) {
case SIP :
return sipSessions.get(id);
case HTTP :
return httpSessions.get(id);
}
return null;
}
public boolean isReadyToInvalidate() {
if(!isValid) {
throw new IllegalStateException("SipApplicationSession already invalidated !");
}
updateReadyToInvalidateState();
return readyToInvalidate;
}
public void setInvalidateWhenReady(boolean invalidateWhenReady) {
if(!isValid) {
throw new IllegalStateException("SipApplicationSession already invalidated !");
}
this.invalidateWhenReady = invalidateWhenReady;
}
public void onSipSessionReadyToInvalidate(MobicentsSipSession mobicentsSipSession) {
removeSipSession(mobicentsSipSession);
updateReadyToInvalidateState();
}
synchronized private void updateReadyToInvalidateState() {
if(isValid) {
boolean allSipSessionsReadyToInvalidate = true;
for(MobicentsSipSession sipSession:this.sipSessions.values()) {
if(sipSession.isValid() && !sipSession.isReadyToInvalidate()) {
if(logger.isDebugEnabled()) {
logger.debug("Session not ready to be invalidated : " + sipSession.getKey());
}
allSipSessionsReadyToInvalidate = false;
break;
}
}
if(allSipSessionsReadyToInvalidate) {
if(this.servletTimers.size() <= 0) {
this.readyToInvalidate = true;
} else {
if(logger.isDebugEnabled()) {
logger.debug(servletTimers.size() + " Timers still alive, cannot invalidate this application session " + key);
}
}
}
} else {
if(logger.isDebugEnabled()) {
logger.debug("Sip application session already invalidated "+ key);
}
this.readyToInvalidate = true;
}
}
public void tryToInvalidate() {
if(isValid && invalidateWhenReady) {
notifySipApplicationSessionListeners(SipApplicationSessionEventType.READYTOINVALIDATE);
if(readyToInvalidate) {
boolean allSipSessionsInvalidated = true;
for(MobicentsSipSession sipSession:this.sipSessions.values()) {
if(sipSession.isValid()) {
allSipSessionsInvalidated = false;
break;
}
}
if(allSipSessionsInvalidated) {
this.invalidate();
}
}
}
}
/**
* @return the expired
*/
public boolean isExpired() {
return expired;
}
/**
* @param expired the expired to set
*/
public void setExpired(boolean expired) {
this.expired = expired;
}
/**
* @param currentServletHandler the currentServletHandler to set
*/
public void setCurrentRequestHandler(String currentRequestHandler) {
this.currentRequestHandler = currentRequestHandler;
}
/**
* @return the currentServletHandler
*/
public String getCurrentRequestHandler() {
return currentRequestHandler;
}
public ThreadPoolExecutor getExecutorService() {
return executorService;
}
}
| false | true | public void invalidate() {
if(!isValid) {
throw new IllegalStateException("SipApplicationSession already invalidated !");
}
if(logger.isInfoEnabled()) {
logger.info("Invalidating the following sip application session " + key);
}
//JSR 289 Section 6.1.2.2.1
//When the IllegalStateException is thrown, the application is guaranteed
//that the state of the SipApplicationSession object will be unchanged from its state prior to the invalidate()
//method call. Even session objects that were eligible for invalidation will not have been invalidated.
//need to check before doing the real invalidation if they are eligible
//for invalidation
// checkInvalidation not needed after PFD2
/*
for(SipSessionImpl session: sipSessions.values()) {
if(session.isValid()) {
try {
session.checkInvalidation();
} catch (IllegalStateException e) {
throw new IllegalStateException("All SIP " +
"and HTTP sessions must be invalidated" +
" before invalidating the application session.", e);
}
}
} */
//doing the invalidation
for(MobicentsSipSession session: sipSessions.values()) {
if(session.isValid()) {
session.invalidate();
}
}
for(HttpSession session: httpSessions.values()) {
if(((Session)session).isValid()) {
session.invalidate();
}
}
for (String key : sipApplicationSessionAttributeMap.keySet()) {
removeAttribute(key);
}
notifySipApplicationSessionListeners(SipApplicationSessionEventType.DELETION);
isValid = false;
//cancelling the timers
for (Map.Entry<String, ServletTimer> servletTimerEntry : servletTimers.entrySet()) {
ServletTimer timerEntry = servletTimerEntry.getValue();
if(timerEntry != null) {
timerEntry.cancel();
}
}
if(!expired && expirationTimerFuture != null) {
cancelExpirationTimer();
}
/*
* Compute how long this session has been alive, and update
* session manager's related properties accordingly
*/
long timeNow = System.currentTimeMillis();
int timeAlive = (int) ((timeNow - creationTime)/1000);
SipManager manager = sipContext.getSipManager();
synchronized (manager) {
if (timeAlive > manager.getSipApplicationSessionMaxAliveTime()) {
manager.setSipApplicationSessionMaxAliveTime(timeAlive);
}
int numExpired = manager.getExpiredSipApplicationSessions();
numExpired++;
manager.setExpiredSipApplicationSessions(numExpired);
int average = manager.getSipApplicationSessionAverageAliveTime();
average = ((average * (numExpired-1)) + timeAlive)/numExpired;
manager.setSipApplicationSessionAverageAliveTime(average);
}
sipContext.getSipManager().removeSipApplicationSession(key);
expirationTimerTask = null;
expirationTimerFuture = null;
httpSessions.clear();
// key = null;
servletTimers.clear();
sipApplicationSessionAttributeMap.clear();
sipSessions.clear();
httpSessions.clear();
executorService.shutdown();
executorService = null;
httpSessions = null;
sipSessions = null;
sipApplicationSessionAttributeMap = null;
servletTimers = null;
sipContext = null;
if(logger.isInfoEnabled()) {
logger.info("The following sip application session " + key + " has been invalidated");
}
currentRequestHandler = null;
key = null;
}
| public void invalidate() {
if(!isValid) {
throw new IllegalStateException("SipApplicationSession already invalidated !");
}
if(logger.isInfoEnabled()) {
logger.info("Invalidating the following sip application session " + key);
}
//JSR 289 Section 6.1.2.2.1
//When the IllegalStateException is thrown, the application is guaranteed
//that the state of the SipApplicationSession object will be unchanged from its state prior to the invalidate()
//method call. Even session objects that were eligible for invalidation will not have been invalidated.
//need to check before doing the real invalidation if they are eligible
//for invalidation
// checkInvalidation not needed after PFD2
/*
for(SipSessionImpl session: sipSessions.values()) {
if(session.isValid()) {
try {
session.checkInvalidation();
} catch (IllegalStateException e) {
throw new IllegalStateException("All SIP " +
"and HTTP sessions must be invalidated" +
" before invalidating the application session.", e);
}
}
} */
//doing the invalidation
for(MobicentsSipSession session: sipSessions.values()) {
if(session.isValid()) {
session.invalidate();
}
}
for(HttpSession session: httpSessions.values()) {
try {
session.invalidate();
} catch(IllegalStateException ignore) {
//we ignore this exception, ugly but the only way to test for validity of the session since we cannot cast to catalina Session
//See Issue 523 http://code.google.com/p/mobicents/issues/detail?id=523
}
}
for (String key : sipApplicationSessionAttributeMap.keySet()) {
removeAttribute(key);
}
notifySipApplicationSessionListeners(SipApplicationSessionEventType.DELETION);
isValid = false;
//cancelling the timers
for (Map.Entry<String, ServletTimer> servletTimerEntry : servletTimers.entrySet()) {
ServletTimer timerEntry = servletTimerEntry.getValue();
if(timerEntry != null) {
timerEntry.cancel();
}
}
if(!expired && expirationTimerFuture != null) {
cancelExpirationTimer();
}
/*
* Compute how long this session has been alive, and update
* session manager's related properties accordingly
*/
long timeNow = System.currentTimeMillis();
int timeAlive = (int) ((timeNow - creationTime)/1000);
SipManager manager = sipContext.getSipManager();
synchronized (manager) {
if (timeAlive > manager.getSipApplicationSessionMaxAliveTime()) {
manager.setSipApplicationSessionMaxAliveTime(timeAlive);
}
int numExpired = manager.getExpiredSipApplicationSessions();
numExpired++;
manager.setExpiredSipApplicationSessions(numExpired);
int average = manager.getSipApplicationSessionAverageAliveTime();
average = ((average * (numExpired-1)) + timeAlive)/numExpired;
manager.setSipApplicationSessionAverageAliveTime(average);
}
sipContext.getSipManager().removeSipApplicationSession(key);
expirationTimerTask = null;
expirationTimerFuture = null;
httpSessions.clear();
// key = null;
servletTimers.clear();
sipApplicationSessionAttributeMap.clear();
sipSessions.clear();
httpSessions.clear();
executorService.shutdown();
executorService = null;
httpSessions = null;
sipSessions = null;
sipApplicationSessionAttributeMap = null;
servletTimers = null;
sipContext = null;
if(logger.isInfoEnabled()) {
logger.info("The following sip application session " + key + " has been invalidated");
}
currentRequestHandler = null;
key = null;
}
|
diff --git a/src/statemachine/year1/microwaveoven/MicroWaveOven.java b/src/statemachine/year1/microwaveoven/MicroWaveOven.java
index 3fe910b..a85c9cd 100644
--- a/src/statemachine/year1/microwaveoven/MicroWaveOven.java
+++ b/src/statemachine/year1/microwaveoven/MicroWaveOven.java
@@ -1,56 +1,56 @@
package statemachine.year1.microwaveoven;
import javax.swing.JLabel;
import quickqui.QuickGUI;
import statemachine.year1.library.GraphicalMachine;
public class MicroWaveOven extends GraphicalMachine {
private static String POWER_ON_COMMAND = "__ON__";
public static class ControlGUI extends QuickGUI.GUIModel {
@Override
public void build() {
- frame("Microwve oven",Layout.VERTICAL,
+ frame("Microwave oven",Layout.VERTICAL,
panel(Layout.HORIZONTAL,
label(text("Current state: ")),
label(name("state"),text("?"))),
panel(Layout.HORIZONTAL,
label(text("Controls: ")),
button(name("START"),text("Start")),
button(name("STOP"),text("Stop"))
),
panel(Layout.HORIZONTAL,
label(text("Door: ")),
button(name("OPEN"),text("Open")),
button(name("CLOSE"),text("Close"))
),
panel(Layout.HORIZONTAL,
label(text("Timer: ")),
button(name("TIMER"),text("Trigger"))
),
button(name(POWER_ON_COMMAND),text("Power on machine"))
)
;
}
}
/**
* Create GUI and then activate robot server functionality
*/
public static void main(String argv[]) {
new MicroWaveOven();
}
public MicroWaveOven() {
super(new ControlGUI(),new MicrowaveMachine(),POWER_ON_COMMAND);
}
@Override
public void update() {
((JLabel)gui.getComponent("state")).setText(machine.getState().toString());
}
}
| true | true | public void build() {
frame("Microwve oven",Layout.VERTICAL,
panel(Layout.HORIZONTAL,
label(text("Current state: ")),
label(name("state"),text("?"))),
panel(Layout.HORIZONTAL,
label(text("Controls: ")),
button(name("START"),text("Start")),
button(name("STOP"),text("Stop"))
),
panel(Layout.HORIZONTAL,
label(text("Door: ")),
button(name("OPEN"),text("Open")),
button(name("CLOSE"),text("Close"))
),
panel(Layout.HORIZONTAL,
label(text("Timer: ")),
button(name("TIMER"),text("Trigger"))
),
button(name(POWER_ON_COMMAND),text("Power on machine"))
)
;
}
| public void build() {
frame("Microwave oven",Layout.VERTICAL,
panel(Layout.HORIZONTAL,
label(text("Current state: ")),
label(name("state"),text("?"))),
panel(Layout.HORIZONTAL,
label(text("Controls: ")),
button(name("START"),text("Start")),
button(name("STOP"),text("Stop"))
),
panel(Layout.HORIZONTAL,
label(text("Door: ")),
button(name("OPEN"),text("Open")),
button(name("CLOSE"),text("Close"))
),
panel(Layout.HORIZONTAL,
label(text("Timer: ")),
button(name("TIMER"),text("Trigger"))
),
button(name(POWER_ON_COMMAND),text("Power on machine"))
)
;
}
|
diff --git a/plugins/org.eclipse.acceleo.engine/src/org/eclipse/acceleo/engine/service/properties/BundleAcceleoPropertiesLoaderService.java b/plugins/org.eclipse.acceleo.engine/src/org/eclipse/acceleo/engine/service/properties/BundleAcceleoPropertiesLoaderService.java
index a53bcb54..1e634767 100644
--- a/plugins/org.eclipse.acceleo.engine/src/org/eclipse/acceleo/engine/service/properties/BundleAcceleoPropertiesLoaderService.java
+++ b/plugins/org.eclipse.acceleo.engine/src/org/eclipse/acceleo/engine/service/properties/BundleAcceleoPropertiesLoaderService.java
@@ -1,84 +1,84 @@
/*******************************************************************************
* Copyright (c) 2010, 2011 Obeo.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Obeo - initial API and implementation
*******************************************************************************/
package org.eclipse.acceleo.engine.service.properties;
import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
import java.util.Properties;
import org.eclipse.acceleo.engine.service.AcceleoService;
import org.eclipse.emf.common.EMFPlugin;
import org.osgi.framework.Bundle;
/**
* This property loader will only be used if eclipse is running, it will look for properties files in bundles.
*
* @author <a href="mailto:[email protected]">Stephane Begaudeau</a>
* @since 3.1
*/
public class BundleAcceleoPropertiesLoaderService extends AbstractAcceleoPropertiesLoaderService {
/**
* The bundle of the generator.
*/
private Bundle bundle;
/**
* The constructor.
*
* @param acceleoService
* The Acceleo service.
* @param bundle
* The bundle in which we will look for the properties files.
*/
public BundleAcceleoPropertiesLoaderService(AcceleoService acceleoService, Bundle bundle) {
this.acceleoService = acceleoService;
this.bundle = bundle;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.acceleo.engine.service.properties.AbstractAcceleoPropertiesLoader#alternatePropertiesLoading(java.lang.String)
*/
@SuppressWarnings("unchecked")
@Override
protected Properties alternatePropertiesLoading(String filepath) {
Properties properties = new Properties();
if (EMFPlugin.IS_ECLIPSE_RUNNING && bundle != null) {
try {
URL resource = bundle.getResource(filepath);
if (resource != null) {
properties.load(resource.openStream());
} else if (filepath != null && !filepath.endsWith(".properties")) { //$NON-NLS-1$
String filename = filepath;
if (filename.contains(".")) { //$NON-NLS-1$
filename = filename.substring(filename.lastIndexOf(".") + 1); //$NON-NLS-1$
}
filename = filename + ".properties"; //$NON-NLS-1$
- Enumeration<Object> entries = bundle.findEntries("/", filename, true); //$NON-NLS-1$
+ Enumeration<?> entries = bundle.findEntries("/", filename, true); //$NON-NLS-1$
Object firstEntry = null;
if (entries.hasMoreElements()) {
firstEntry = entries.nextElement();
}
if (firstEntry instanceof URL) {
properties.load(((URL)firstEntry).openStream());
}
}
} catch (IOException e) {
return null;
}
}
return properties;
}
}
| true | true | protected Properties alternatePropertiesLoading(String filepath) {
Properties properties = new Properties();
if (EMFPlugin.IS_ECLIPSE_RUNNING && bundle != null) {
try {
URL resource = bundle.getResource(filepath);
if (resource != null) {
properties.load(resource.openStream());
} else if (filepath != null && !filepath.endsWith(".properties")) { //$NON-NLS-1$
String filename = filepath;
if (filename.contains(".")) { //$NON-NLS-1$
filename = filename.substring(filename.lastIndexOf(".") + 1); //$NON-NLS-1$
}
filename = filename + ".properties"; //$NON-NLS-1$
Enumeration<Object> entries = bundle.findEntries("/", filename, true); //$NON-NLS-1$
Object firstEntry = null;
if (entries.hasMoreElements()) {
firstEntry = entries.nextElement();
}
if (firstEntry instanceof URL) {
properties.load(((URL)firstEntry).openStream());
}
}
} catch (IOException e) {
return null;
}
}
return properties;
}
| protected Properties alternatePropertiesLoading(String filepath) {
Properties properties = new Properties();
if (EMFPlugin.IS_ECLIPSE_RUNNING && bundle != null) {
try {
URL resource = bundle.getResource(filepath);
if (resource != null) {
properties.load(resource.openStream());
} else if (filepath != null && !filepath.endsWith(".properties")) { //$NON-NLS-1$
String filename = filepath;
if (filename.contains(".")) { //$NON-NLS-1$
filename = filename.substring(filename.lastIndexOf(".") + 1); //$NON-NLS-1$
}
filename = filename + ".properties"; //$NON-NLS-1$
Enumeration<?> entries = bundle.findEntries("/", filename, true); //$NON-NLS-1$
Object firstEntry = null;
if (entries.hasMoreElements()) {
firstEntry = entries.nextElement();
}
if (firstEntry instanceof URL) {
properties.load(((URL)firstEntry).openStream());
}
}
} catch (IOException e) {
return null;
}
}
return properties;
}
|
diff --git a/nuget-server/src/jetbrains/buildServer/nuget/server/toolRegistry/ui/ToolSelectorController.java b/nuget-server/src/jetbrains/buildServer/nuget/server/toolRegistry/ui/ToolSelectorController.java
index 29ad1266..6bd12238 100644
--- a/nuget-server/src/jetbrains/buildServer/nuget/server/toolRegistry/ui/ToolSelectorController.java
+++ b/nuget-server/src/jetbrains/buildServer/nuget/server/toolRegistry/ui/ToolSelectorController.java
@@ -1,132 +1,132 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.buildServer.nuget.server.toolRegistry.ui;
import jetbrains.buildServer.controllers.BaseController;
import jetbrains.buildServer.controllers.BasePropertiesBean;
import jetbrains.buildServer.nuget.server.settings.SettingsSection;
import jetbrains.buildServer.nuget.server.settings.tab.ServerSettingsTab;
import jetbrains.buildServer.nuget.server.toolRegistry.NuGetInstalledTool;
import jetbrains.buildServer.nuget.server.toolRegistry.NuGetToolManager;
import jetbrains.buildServer.nuget.server.toolRegistry.tab.InstalledToolsController;
import jetbrains.buildServer.util.StringUtil;
import jetbrains.buildServer.web.openapi.PluginDescriptor;
import jetbrains.buildServer.web.openapi.WebControllerManager;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Collection;
/**
* Created by Eugene Petrenko ([email protected])
* Date: 16.08.11 10:21
*/
public class ToolSelectorController extends BaseController {
private final NuGetToolManager myToolManager;
private final PluginDescriptor myDescriptor;
private final String myPath;
public ToolSelectorController(@NotNull final NuGetToolManager toolManager,
@NotNull final PluginDescriptor descriptor,
@NotNull final WebControllerManager web) {
myToolManager = toolManager;
myDescriptor = descriptor;
myPath = descriptor.getPluginResourcesPath("tool/runnerSettings.html");
web.registerController(myPath, this);
}
@NotNull
public String getPath() {
return myPath;
}
@Override
protected ModelAndView doHandle(HttpServletRequest request, HttpServletResponse response) throws Exception {
final String name = safe(request.getParameter("name"));
String value = parseValue(request, "value", name);
final Collection<ToolInfo> tools = getTools();
final ToolInfo bundledTool = ensureVersion(value, tools);
if (!StringUtil.isEmptyOrSpaces(request.getParameter("view"))) {
ModelAndView mv = new ModelAndView(myDescriptor.getPluginResourcesPath("tool/runnerSettingsView.jsp"));
if (bundledTool != null) {
mv.getModel().put("tool", bundledTool.getVersion());
mv.getModel().put("bundled", true);
} else {
mv.getModel().put("tool", value);
mv.getModel().put("bundled", false);
}
return mv;
} else {
ModelAndView mv = new ModelAndView(myDescriptor.getPluginResourcesPath("tool/runnerSettingsEdit.jsp"));
mv.getModel().put("name", name);
mv.getModel().put("value", value);
mv.getModel().put("customValue", safe(parseValue(request, "customValue", "nugetCustomPath")));
mv.getModel().put("clazz", safe(request.getParameter("class")));
mv.getModel().put("style", safe(request.getParameter("style")));
mv.getModel().put("items", tools);
- mv.getModel().put("settingsUrl", "/admin/serverConfig.html?init=1&tab=" + ServerSettingsTab.TAB_ID + "&" + SettingsSection.SELECTED_SECTION_KEY + "=" + InstalledToolsController.SETTINGS_PAGE_ID) ;
+ mv.getModel().put("settingsUrl", "/admin/admin.html?init=1§ion=" + ServerSettingsTab.TAB_ID + "&" + SettingsSection.SELECTED_SECTION_KEY + "=" + InstalledToolsController.SETTINGS_PAGE_ID) ;
return mv;
}
}
@Nullable
private ToolInfo ensureVersion(@NotNull final String version, @NotNull Collection<ToolInfo> actionInfos) {
if (!version.startsWith("?")) return null;
for (ToolInfo actionInfo : actionInfos) {
if (actionInfo.getId().equals(version)) return actionInfo;
}
final ToolInfo notInstalled = new ToolInfo(version, "Not Installed: " + version.substring(1));
actionInfos.add(notInstalled);
return notInstalled;
}
@NotNull
private Collection<ToolInfo> getTools() {
final ArrayList<ToolInfo> result = new ArrayList<ToolInfo>();
for (NuGetInstalledTool nuGetInstalledTool : myToolManager.getInstalledTools()) {
result.add(new ToolInfo(nuGetInstalledTool));
}
return result;
}
private static String safe(@Nullable String s) {
if (StringUtil.isEmptyOrSpaces(s)) return "";
return s;
}
@NotNull
private String parseValue(HttpServletRequest request, final String requestName, String propertyName) {
String value = null;
final BasePropertiesBean bean = (BasePropertiesBean)request.getAttribute("propertiesBean");
if (bean != null) {
value = bean.getProperties().get(propertyName);
}
if (value == null) {
value = request.getParameter(requestName);
}
if (value == null) {
value = "";
}
return value;
}
}
| true | true | protected ModelAndView doHandle(HttpServletRequest request, HttpServletResponse response) throws Exception {
final String name = safe(request.getParameter("name"));
String value = parseValue(request, "value", name);
final Collection<ToolInfo> tools = getTools();
final ToolInfo bundledTool = ensureVersion(value, tools);
if (!StringUtil.isEmptyOrSpaces(request.getParameter("view"))) {
ModelAndView mv = new ModelAndView(myDescriptor.getPluginResourcesPath("tool/runnerSettingsView.jsp"));
if (bundledTool != null) {
mv.getModel().put("tool", bundledTool.getVersion());
mv.getModel().put("bundled", true);
} else {
mv.getModel().put("tool", value);
mv.getModel().put("bundled", false);
}
return mv;
} else {
ModelAndView mv = new ModelAndView(myDescriptor.getPluginResourcesPath("tool/runnerSettingsEdit.jsp"));
mv.getModel().put("name", name);
mv.getModel().put("value", value);
mv.getModel().put("customValue", safe(parseValue(request, "customValue", "nugetCustomPath")));
mv.getModel().put("clazz", safe(request.getParameter("class")));
mv.getModel().put("style", safe(request.getParameter("style")));
mv.getModel().put("items", tools);
mv.getModel().put("settingsUrl", "/admin/serverConfig.html?init=1&tab=" + ServerSettingsTab.TAB_ID + "&" + SettingsSection.SELECTED_SECTION_KEY + "=" + InstalledToolsController.SETTINGS_PAGE_ID) ;
return mv;
}
}
| protected ModelAndView doHandle(HttpServletRequest request, HttpServletResponse response) throws Exception {
final String name = safe(request.getParameter("name"));
String value = parseValue(request, "value", name);
final Collection<ToolInfo> tools = getTools();
final ToolInfo bundledTool = ensureVersion(value, tools);
if (!StringUtil.isEmptyOrSpaces(request.getParameter("view"))) {
ModelAndView mv = new ModelAndView(myDescriptor.getPluginResourcesPath("tool/runnerSettingsView.jsp"));
if (bundledTool != null) {
mv.getModel().put("tool", bundledTool.getVersion());
mv.getModel().put("bundled", true);
} else {
mv.getModel().put("tool", value);
mv.getModel().put("bundled", false);
}
return mv;
} else {
ModelAndView mv = new ModelAndView(myDescriptor.getPluginResourcesPath("tool/runnerSettingsEdit.jsp"));
mv.getModel().put("name", name);
mv.getModel().put("value", value);
mv.getModel().put("customValue", safe(parseValue(request, "customValue", "nugetCustomPath")));
mv.getModel().put("clazz", safe(request.getParameter("class")));
mv.getModel().put("style", safe(request.getParameter("style")));
mv.getModel().put("items", tools);
mv.getModel().put("settingsUrl", "/admin/admin.html?init=1§ion=" + ServerSettingsTab.TAB_ID + "&" + SettingsSection.SELECTED_SECTION_KEY + "=" + InstalledToolsController.SETTINGS_PAGE_ID) ;
return mv;
}
}
|
diff --git a/plugins/com.aptana.editor.ruby/src/com/aptana/editor/ruby/validator/RubyValidator.java b/plugins/com.aptana.editor.ruby/src/com/aptana/editor/ruby/validator/RubyValidator.java
index 2b25b8e..a6ace8f 100644
--- a/plugins/com.aptana.editor.ruby/src/com/aptana/editor/ruby/validator/RubyValidator.java
+++ b/plugins/com.aptana.editor.ruby/src/com/aptana/editor/ruby/validator/RubyValidator.java
@@ -1,156 +1,157 @@
package com.aptana.editor.ruby.validator;
import java.io.File;
import java.io.StringReader;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.Document;
import org.jrubyparser.CompatVersion;
import org.jrubyparser.IRubyWarnings;
import org.jrubyparser.SourcePosition;
import org.jrubyparser.lexer.LexerSource;
import org.jrubyparser.lexer.SyntaxException;
import org.jrubyparser.parser.ParserConfiguration;
import org.jrubyparser.parser.ParserSupport;
import org.jrubyparser.parser.ParserSupport19;
import org.jrubyparser.parser.Ruby18Parser;
import org.jrubyparser.parser.Ruby19Parser;
import org.jrubyparser.parser.RubyParser;
import com.aptana.editor.common.validator.IValidationItem;
import com.aptana.editor.common.validator.IValidationManager;
import com.aptana.editor.common.validator.IValidator;
import com.aptana.ruby.launching.RubyLaunchingPlugin;
public class RubyValidator implements IValidator
{
public RubyValidator()
{
}
public List<IValidationItem> validate(String source, final URI path, final IValidationManager manager)
{
List<IValidationItem> items = new ArrayList<IValidationItem>();
// Check what the version of the current ruby interpreter is and use that to determine which parser compat
// to use!
CompatVersion version = CompatVersion.BOTH;
IProject project = null;
// get the working dir
IPath workingDir = null;
if (path != null && "file".equals(path.getScheme())) //$NON-NLS-1$
{
File file = new File(path);
workingDir = Path.fromOSString(file.getParent());
}
// Find the project root for the file in question!
if (workingDir != null)
{
IContainer container = ResourcesPlugin.getWorkspace().getRoot().getContainerForLocation(workingDir);
if (container != null)
{
project = container.getProject();
}
}
String rubyVersion = RubyLaunchingPlugin.getRubyVersionForProject(project);
if (rubyVersion != null && rubyVersion.startsWith("ruby 1.9")) //$NON-NLS-1$
{
version = CompatVersion.RUBY1_9;
}
// TODO set up warnings/ version/line number/etc in RubyParseState and re-use RubyParser.parse(IParseState)!
ParserConfiguration config = new ParserConfiguration(1, version);
RubyParser parser;
if (version == CompatVersion.RUBY1_8)
{
ParserSupport support = new ParserSupport();
support.setConfiguration(config);
parser = new Ruby18Parser(support);
}
else
{
ParserSupport19 support = new ParserSupport19();
support.setConfiguration(config);
parser = new Ruby19Parser(support);
}
// Hook up our own warning impl to grab them and add them as validation items!
IRubyWarnings warnings = new IRubyWarnings()
{
public void warn(ID id, SourcePosition position, String message, Object... data)
{
int length = position.getEndOffset() - position.getStartOffset() + 1;
manager.addWarning(message, position.getStartLine(), 0, length, path);
}
public void warn(ID id, String fileName, int lineNumber, String message, Object... data)
{
manager.addWarning(message, lineNumber, 0, 1, path);
}
public boolean isVerbose()
{
return true;
}
public void warn(ID id, String message, Object... data)
{
manager.addWarning(message, 1, 0, 1, path);
}
public void warning(ID id, String message, Object... data)
{
warn(id, message, data);
}
public void warning(ID id, SourcePosition position, String message, Object... data)
{
warn(id, position, message, data);
}
public void warning(ID id, String fileName, int lineNumber, String message, Object... data)
{
warn(id, fileName, lineNumber, message, data);
}
};
parser.setWarnings(warnings);
- LexerSource lexerSource = LexerSource.getSource(path.getPath(), new StringReader(source), config);
+ LexerSource lexerSource = LexerSource.getSource(
+ path == null ? "filename" : path.getPath(), new StringReader(source), config); //$NON-NLS-1$
try
{
parser.parse(config, lexerSource);
}
catch (SyntaxException e)
{
int start = e.getPosition().getStartOffset();
int end = e.getPosition().getEndOffset();
// FIXME This seems to point at the token after the error...
int lineNumber = e.getPosition().getStartLine();
int charLineOffset = 0;
try
{
int lineOffset = new Document(source).getLineOffset(lineNumber - 1);
charLineOffset = start - lineOffset;
}
catch (BadLocationException ble)
{
}
if (start == end && end == source.length() && charLineOffset > 0)
{
charLineOffset--;
}
items.add(manager.addError(e.getMessage(), lineNumber, charLineOffset, end - start + 1, path));
}
return items;
}
}
| true | true | public List<IValidationItem> validate(String source, final URI path, final IValidationManager manager)
{
List<IValidationItem> items = new ArrayList<IValidationItem>();
// Check what the version of the current ruby interpreter is and use that to determine which parser compat
// to use!
CompatVersion version = CompatVersion.BOTH;
IProject project = null;
// get the working dir
IPath workingDir = null;
if (path != null && "file".equals(path.getScheme())) //$NON-NLS-1$
{
File file = new File(path);
workingDir = Path.fromOSString(file.getParent());
}
// Find the project root for the file in question!
if (workingDir != null)
{
IContainer container = ResourcesPlugin.getWorkspace().getRoot().getContainerForLocation(workingDir);
if (container != null)
{
project = container.getProject();
}
}
String rubyVersion = RubyLaunchingPlugin.getRubyVersionForProject(project);
if (rubyVersion != null && rubyVersion.startsWith("ruby 1.9")) //$NON-NLS-1$
{
version = CompatVersion.RUBY1_9;
}
// TODO set up warnings/ version/line number/etc in RubyParseState and re-use RubyParser.parse(IParseState)!
ParserConfiguration config = new ParserConfiguration(1, version);
RubyParser parser;
if (version == CompatVersion.RUBY1_8)
{
ParserSupport support = new ParserSupport();
support.setConfiguration(config);
parser = new Ruby18Parser(support);
}
else
{
ParserSupport19 support = new ParserSupport19();
support.setConfiguration(config);
parser = new Ruby19Parser(support);
}
// Hook up our own warning impl to grab them and add them as validation items!
IRubyWarnings warnings = new IRubyWarnings()
{
public void warn(ID id, SourcePosition position, String message, Object... data)
{
int length = position.getEndOffset() - position.getStartOffset() + 1;
manager.addWarning(message, position.getStartLine(), 0, length, path);
}
public void warn(ID id, String fileName, int lineNumber, String message, Object... data)
{
manager.addWarning(message, lineNumber, 0, 1, path);
}
public boolean isVerbose()
{
return true;
}
public void warn(ID id, String message, Object... data)
{
manager.addWarning(message, 1, 0, 1, path);
}
public void warning(ID id, String message, Object... data)
{
warn(id, message, data);
}
public void warning(ID id, SourcePosition position, String message, Object... data)
{
warn(id, position, message, data);
}
public void warning(ID id, String fileName, int lineNumber, String message, Object... data)
{
warn(id, fileName, lineNumber, message, data);
}
};
parser.setWarnings(warnings);
LexerSource lexerSource = LexerSource.getSource(path.getPath(), new StringReader(source), config);
try
{
parser.parse(config, lexerSource);
}
catch (SyntaxException e)
{
int start = e.getPosition().getStartOffset();
int end = e.getPosition().getEndOffset();
// FIXME This seems to point at the token after the error...
int lineNumber = e.getPosition().getStartLine();
int charLineOffset = 0;
try
{
int lineOffset = new Document(source).getLineOffset(lineNumber - 1);
charLineOffset = start - lineOffset;
}
catch (BadLocationException ble)
{
}
if (start == end && end == source.length() && charLineOffset > 0)
{
charLineOffset--;
}
items.add(manager.addError(e.getMessage(), lineNumber, charLineOffset, end - start + 1, path));
}
return items;
}
| public List<IValidationItem> validate(String source, final URI path, final IValidationManager manager)
{
List<IValidationItem> items = new ArrayList<IValidationItem>();
// Check what the version of the current ruby interpreter is and use that to determine which parser compat
// to use!
CompatVersion version = CompatVersion.BOTH;
IProject project = null;
// get the working dir
IPath workingDir = null;
if (path != null && "file".equals(path.getScheme())) //$NON-NLS-1$
{
File file = new File(path);
workingDir = Path.fromOSString(file.getParent());
}
// Find the project root for the file in question!
if (workingDir != null)
{
IContainer container = ResourcesPlugin.getWorkspace().getRoot().getContainerForLocation(workingDir);
if (container != null)
{
project = container.getProject();
}
}
String rubyVersion = RubyLaunchingPlugin.getRubyVersionForProject(project);
if (rubyVersion != null && rubyVersion.startsWith("ruby 1.9")) //$NON-NLS-1$
{
version = CompatVersion.RUBY1_9;
}
// TODO set up warnings/ version/line number/etc in RubyParseState and re-use RubyParser.parse(IParseState)!
ParserConfiguration config = new ParserConfiguration(1, version);
RubyParser parser;
if (version == CompatVersion.RUBY1_8)
{
ParserSupport support = new ParserSupport();
support.setConfiguration(config);
parser = new Ruby18Parser(support);
}
else
{
ParserSupport19 support = new ParserSupport19();
support.setConfiguration(config);
parser = new Ruby19Parser(support);
}
// Hook up our own warning impl to grab them and add them as validation items!
IRubyWarnings warnings = new IRubyWarnings()
{
public void warn(ID id, SourcePosition position, String message, Object... data)
{
int length = position.getEndOffset() - position.getStartOffset() + 1;
manager.addWarning(message, position.getStartLine(), 0, length, path);
}
public void warn(ID id, String fileName, int lineNumber, String message, Object... data)
{
manager.addWarning(message, lineNumber, 0, 1, path);
}
public boolean isVerbose()
{
return true;
}
public void warn(ID id, String message, Object... data)
{
manager.addWarning(message, 1, 0, 1, path);
}
public void warning(ID id, String message, Object... data)
{
warn(id, message, data);
}
public void warning(ID id, SourcePosition position, String message, Object... data)
{
warn(id, position, message, data);
}
public void warning(ID id, String fileName, int lineNumber, String message, Object... data)
{
warn(id, fileName, lineNumber, message, data);
}
};
parser.setWarnings(warnings);
LexerSource lexerSource = LexerSource.getSource(
path == null ? "filename" : path.getPath(), new StringReader(source), config); //$NON-NLS-1$
try
{
parser.parse(config, lexerSource);
}
catch (SyntaxException e)
{
int start = e.getPosition().getStartOffset();
int end = e.getPosition().getEndOffset();
// FIXME This seems to point at the token after the error...
int lineNumber = e.getPosition().getStartLine();
int charLineOffset = 0;
try
{
int lineOffset = new Document(source).getLineOffset(lineNumber - 1);
charLineOffset = start - lineOffset;
}
catch (BadLocationException ble)
{
}
if (start == end && end == source.length() && charLineOffset > 0)
{
charLineOffset--;
}
items.add(manager.addError(e.getMessage(), lineNumber, charLineOffset, end - start + 1, path));
}
return items;
}
|
diff --git a/conan-atlas-processes/src/main/java/uk/ac/ebi/fgpt/conan/process/atlas/PerlExperimentEligibilityCheckingProcess.java b/conan-atlas-processes/src/main/java/uk/ac/ebi/fgpt/conan/process/atlas/PerlExperimentEligibilityCheckingProcess.java
index 36c79bc..11a289a 100755
--- a/conan-atlas-processes/src/main/java/uk/ac/ebi/fgpt/conan/process/atlas/PerlExperimentEligibilityCheckingProcess.java
+++ b/conan-atlas-processes/src/main/java/uk/ac/ebi/fgpt/conan/process/atlas/PerlExperimentEligibilityCheckingProcess.java
@@ -1,99 +1,99 @@
package uk.ac.ebi.fgpt.conan.process.atlas;
import net.sourceforge.fluxion.spi.ServiceProvider;
import uk.ac.ebi.fgpt.conan.ae.AccessionParameter;
import uk.ac.ebi.fgpt.conan.lsf.AbstractLSFProcess;
import uk.ac.ebi.fgpt.conan.lsf.LSFProcess;
import uk.ac.ebi.fgpt.conan.model.ConanParameter;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
/**
* Conan process to check experiment for eligibility for
* the Expression Atlas.
*
* @author Amy Tang
* @date 25-Apr-2013
*/
@ServiceProvider
public class PerlExperimentEligibilityCheckingProcess extends AbstractLSFProcess {
private final Collection<ConanParameter> parameters;
private final AccessionParameter accessionParameter;
public PerlExperimentEligibilityCheckingProcess() {
parameters = new ArrayList<ConanParameter>();
accessionParameter = new AccessionParameter();
parameters.add(accessionParameter);
// setQueueName("production");
}
public String getName() {
return "atlas eligibility";
}
public Collection<ConanParameter> getParameters() {
return parameters;
}
protected String getComponentName() {
return LSFProcess.UNSPECIFIED_COMPONENT_NAME;
}
protected String getCommand(Map<ConanParameter, String> parameters) throws IllegalArgumentException {
getLog().debug("Executing " + getName() + " with the following parameters: " + parameters.toString());
// deal with parameters
AccessionParameter accession = new AccessionParameter();
accession.setAccession(parameters.get(accessionParameter));
if (accession.getAccession() == null) {
throw new IllegalArgumentException("Accession cannot be null");
}
else {
if (accession.isExperiment()) {
// main command to execute perl script
/* Writing back to productio Subs Tracking database, will implement later
* String mainCommand = "cd " + accession.getFile().getParentFile().getAbsolutePath() + "; " +
* "perl /ebi/microarray/home/fgpt/sw/lib/perl/Red_Hat/check_atlas_eligibility.pl -w -a " +
* accession.getAccession();
*/
String mainCommand = "cd " + accession.getFile().getParentFile().getAbsolutePath() + "; " +
- "perl /ebi/microarray/home/fgpt/sw/lib/perl/FGPT_RH_prod/check_atlas_eligiblity.pl";
+ "perl /ebi/microarray/home/fgpt/sw/lib/perl/FGPT_RH_prod/check_atlas_eligibility.pl";
// path to relevant file
String filePath = accession.getFile().getAbsolutePath();
// return command string
return mainCommand + " -i " + filePath;
}
else {
throw new IllegalArgumentException("Cannot run atlas eligibility checks for Arrays");
}
}
}
protected String getLSFOutputFilePath(Map<ConanParameter, String> parameters)
throws IllegalArgumentException {
// deal with parameters
AccessionParameter accession = new AccessionParameter();
accession.setAccession(parameters.get(accessionParameter));
if (accession.getAccession() == null) {
throw new IllegalArgumentException("Accession cannot be null");
}
else {
// get the mageFile parent directory
final File parentDir = accession.getFile().getAbsoluteFile().getParentFile();
// files to write output to
final File outputDir = new File(parentDir, ".conan");
// lsf output file
return new File(outputDir, "atlas_eligibility.lsfoutput.txt").getAbsolutePath();
}
}
}
| true | true | protected String getCommand(Map<ConanParameter, String> parameters) throws IllegalArgumentException {
getLog().debug("Executing " + getName() + " with the following parameters: " + parameters.toString());
// deal with parameters
AccessionParameter accession = new AccessionParameter();
accession.setAccession(parameters.get(accessionParameter));
if (accession.getAccession() == null) {
throw new IllegalArgumentException("Accession cannot be null");
}
else {
if (accession.isExperiment()) {
// main command to execute perl script
/* Writing back to productio Subs Tracking database, will implement later
* String mainCommand = "cd " + accession.getFile().getParentFile().getAbsolutePath() + "; " +
* "perl /ebi/microarray/home/fgpt/sw/lib/perl/Red_Hat/check_atlas_eligibility.pl -w -a " +
* accession.getAccession();
*/
String mainCommand = "cd " + accession.getFile().getParentFile().getAbsolutePath() + "; " +
"perl /ebi/microarray/home/fgpt/sw/lib/perl/FGPT_RH_prod/check_atlas_eligiblity.pl";
// path to relevant file
String filePath = accession.getFile().getAbsolutePath();
// return command string
return mainCommand + " -i " + filePath;
}
else {
throw new IllegalArgumentException("Cannot run atlas eligibility checks for Arrays");
}
}
}
| protected String getCommand(Map<ConanParameter, String> parameters) throws IllegalArgumentException {
getLog().debug("Executing " + getName() + " with the following parameters: " + parameters.toString());
// deal with parameters
AccessionParameter accession = new AccessionParameter();
accession.setAccession(parameters.get(accessionParameter));
if (accession.getAccession() == null) {
throw new IllegalArgumentException("Accession cannot be null");
}
else {
if (accession.isExperiment()) {
// main command to execute perl script
/* Writing back to productio Subs Tracking database, will implement later
* String mainCommand = "cd " + accession.getFile().getParentFile().getAbsolutePath() + "; " +
* "perl /ebi/microarray/home/fgpt/sw/lib/perl/Red_Hat/check_atlas_eligibility.pl -w -a " +
* accession.getAccession();
*/
String mainCommand = "cd " + accession.getFile().getParentFile().getAbsolutePath() + "; " +
"perl /ebi/microarray/home/fgpt/sw/lib/perl/FGPT_RH_prod/check_atlas_eligibility.pl";
// path to relevant file
String filePath = accession.getFile().getAbsolutePath();
// return command string
return mainCommand + " -i " + filePath;
}
else {
throw new IllegalArgumentException("Cannot run atlas eligibility checks for Arrays");
}
}
}
|
diff --git a/src/java/com/thomasdimson/wikipedia/lda/java/TopicSensitivePageRank.java b/src/java/com/thomasdimson/wikipedia/lda/java/TopicSensitivePageRank.java
index e381c14..39727d6 100644
--- a/src/java/com/thomasdimson/wikipedia/lda/java/TopicSensitivePageRank.java
+++ b/src/java/com/thomasdimson/wikipedia/lda/java/TopicSensitivePageRank.java
@@ -1,297 +1,296 @@
package com.thomasdimson.wikipedia.lda.java;
import com.google.common.base.Joiner;
import com.google.common.base.Predicate;
import com.google.common.base.Splitter;
import com.google.common.collect.Iterators;
import com.google.common.collect.Maps;
import com.google.common.collect.Ordering;
import com.thomasdimson.wikipedia.Data;
import java.io.*;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class TopicSensitivePageRank {
public static double BETA = 0.85;
private static double chiSquareScore(int index, Data.TSPRGraphNode node) {
double observed = node.getTspr(index);
double expected = node.getTspr(node.getTsprCount() - 1);
return Math.pow(observed - expected, 2) / expected;
}
private static double massScore(int index, Data.TSPRGraphNode node) {
return node.getTspr(index) / node.getTspr(node.getTsprCount() - 1);
}
private static Ordering<Data.TSPRGraphNode> byLDA(final int index) {
return new Ordering<Data.TSPRGraphNode>() {
@Override
public int compare(Data.TSPRGraphNode tsprGraphNode, Data.TSPRGraphNode tsprGraphNode2) {
return Double.compare(tsprGraphNode.getLda(index), tsprGraphNode2.getLda(index));
}
};
}
private static Ordering<Data.TSPRGraphNode> byTSPR(final int index) {
return new Ordering<Data.TSPRGraphNode>() {
@Override
public int compare(Data.TSPRGraphNode tsprGraphNode, Data.TSPRGraphNode tsprGraphNode2) {
return Double.compare(tsprGraphNode.getTspr(index), tsprGraphNode2.getTspr(index));
}
};
}
private static Ordering<Data.TSPRGraphNode> byChiSquaredTSPR(final int index) {
return new Ordering<Data.TSPRGraphNode>() {
@Override
public int compare(Data.TSPRGraphNode tsprGraphNode, Data.TSPRGraphNode tsprGraphNode2) {
return Double.compare(chiSquareScore(index, tsprGraphNode), chiSquareScore(index, tsprGraphNode2));
}
};
}
private static Ordering<Data.TSPRGraphNode> byMassTSPR(final int index) {
return new Ordering<Data.TSPRGraphNode>() {
@Override
public int compare(Data.TSPRGraphNode tsprGraphNode, Data.TSPRGraphNode tsprGraphNode2) {
return Double.compare(massScore(index, tsprGraphNode), massScore(index, tsprGraphNode2));
}
};
}
public static List<Data.TSPRGraphNode> topBy(Ordering<Data.TSPRGraphNode> ordering,
Iterator<Data.TSPRGraphNode> nodes, int k,
final String infoboxMatch) {
final boolean matchExclusive = infoboxMatch != null && infoboxMatch.startsWith("^");
final String match;
if(matchExclusive) {
match = infoboxMatch.substring(1);
} else {
match = infoboxMatch;
}
return ordering.greatestOf(Iterators.filter(nodes, new Predicate<Data.TSPRGraphNode>() {
@Override
public boolean apply(Data.TSPRGraphNode tsprGraphNode) {
if(match == null) {
return true;
} else if(matchExclusive) {
return !match.equalsIgnoreCase(tsprGraphNode.getInfoboxType());
} else {
return match.equalsIgnoreCase(tsprGraphNode.getInfoboxType());
}
}
}), k);
}
public static List<Data.TSPRGraphNode> topKLDA(Iterator<Data.TSPRGraphNode> nodes, int index, int k,
final String infoboxMatch) {
return topBy(byLDA(index), nodes, k, infoboxMatch);
}
public static List<Data.TSPRGraphNode> topKTSPR(Iterator<Data.TSPRGraphNode> nodes, int index, int k,
final String infoboxMatch) {
return topBy(byTSPR(index), nodes, k, infoboxMatch);
}
public static List<Data.TSPRGraphNode> topKChiSquareTSPR(Iterator<Data.TSPRGraphNode> nodes, int index, int k,
final String infoboxMatch) {
return topBy(byChiSquaredTSPR(index), nodes, k, infoboxMatch);
}
public static List<Data.TSPRGraphNode> topKMassTSPR(Iterator<Data.TSPRGraphNode> nodes, int index, int k,
final String infoboxMatch) {
return topBy(byMassTSPR(index), nodes, k, infoboxMatch);
}
public static Iterator<Data.TSPRGraphNode> newTSPRGraphNodeIterator(String filename) throws IOException {
final InputStream inputStream = new BufferedInputStream(new FileInputStream(filename));
try {
return new Iterator<Data.TSPRGraphNode>() {
Data.TSPRGraphNode nextMessage = Data.TSPRGraphNode.parseDelimitedFrom(inputStream);
@Override
public boolean hasNext() {
return nextMessage != null;
}
@Override
public Data.TSPRGraphNode next() {
Data.TSPRGraphNode ret = nextMessage;
try {
nextMessage = Data.TSPRGraphNode.parseDelimitedFrom(inputStream);
} catch (IOException e) {
throw new RuntimeException(e);
}
return ret;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static Map<String, double[]> readLDAMap(String filename) throws IOException {
BufferedReader r = new BufferedReader(new InputStreamReader(new FileInputStream(filename), Charset.forName("UTF-8")));
String line;
Splitter splitter = Splitter.on("\t").omitEmptyStrings().trimResults();
Map<String, double[]> ret = Maps.newHashMapWithExpectedSize(1000000);
int lastTopicLength = -1;
int lineNum = 0;
System.out.println();
while((line = r.readLine()) != null) {
if(line.startsWith("#")) {
continue;
}
List<String> split = splitter.splitToList(line);
String title = split.get(1);
double[] topics = new double[(split.size() - 2) / 2 + 1];
topics[topics.length - 1] = 1.0;
if(lastTopicLength == -1) {
lastTopicLength = topics.length;
} else if(lastTopicLength != topics.length) {
throw new RuntimeException("Bad topics length for " + line);
}
int nextTopicId = -1;
for(int i = 2; i < split.size(); i++) {
if(i % 2 == 0) {
nextTopicId = Integer.parseInt(split.get(i));
} else {
topics[nextTopicId] = Double.parseDouble(split.get(i));
}
}
ret.put(title, topics);
lineNum++;
if(lineNum % 10000 == 0) {
System.out.print("Reached line " + lineNum + " \r");
System.out.flush();
}
}
return ret;
}
public static class RankInPlaceRunnable implements Runnable {
final double sum;
final int topicNum;
final List<IntermediateTSPRNode> nodes;
final Map<Long, IntermediateTSPRNode> nodeById;
final int numNodes;
final double convergence;
public RankInPlaceRunnable(Map<Long, IntermediateTSPRNode> nodeById,
List<IntermediateTSPRNode> nodes, double sum, int topicNum,
double convergence) {
this.nodeById = nodeById;
this.nodes = nodes;
this.sum = sum;
this.topicNum = topicNum;
this.numNodes = nodes.size();
this.convergence = convergence;
}
@Override
public void run() {
double [] lastRank = new double[numNodes];
double [] thisRank = new double[numNodes];
- final int numIterations = 15;
for(int iteration = 0; ; iteration++) {
double []tmp = thisRank;
thisRank = lastRank;
lastRank = tmp;
if(iteration == 0) {
// Initialize
for(IntermediateTSPRNode node : nodes) {
thisRank[node.linearId] = node.lda[topicNum] / sum;
}
} else {
// Clear old values
for(int i = 0; i < numNodes; i++) {
thisRank[i] = 0.0;
}
}
// Power iteration
for(IntermediateTSPRNode node : nodes) {
int numNeighbors = node.edges.length;
double contribution = BETA * lastRank[node.linearId] / numNeighbors;
for(long targetId : node.edges) {
IntermediateTSPRNode neighbor = nodeById.get(targetId);
thisRank[neighbor.linearId] += contribution;
}
}
// Reinsert leaked
double topicSum = 0.0;
for(IntermediateTSPRNode node : nodes) {
topicSum += thisRank[node.linearId];
}
double difference = 0.0;
for(IntermediateTSPRNode node : nodes) {
thisRank[node.linearId] += (1.0 - topicSum) * (node.lda[topicNum] / sum);
// Calculate L1 difference too
difference += Math.abs(thisRank[node.linearId] - lastRank[node.linearId]);
}
System.err.println("Pagerank topic " + topicNum + " iteration "
+ iteration + ": delta=" + difference);
if(difference < convergence) {
break;
}
}
for(IntermediateTSPRNode node : nodes) {
node.tspr[topicNum] = thisRank[node.linearId];
}
}
}
public static void rankInPlace(List<IntermediateTSPRNode> nodes, double convergence) throws InterruptedException {
if(nodes.size() == 0) {
return;
}
final int numNodes = nodes.size();
final int numTopics = nodes.get(0).lda.length;
Map<Long, IntermediateTSPRNode> nodeById = Maps.newHashMapWithExpectedSize(nodes.size());
// Compute id map and topic sums
final double []ldaSums = new double[nodes.size()];
for(IntermediateTSPRNode node : nodes) {
for(int j = 0; j < numTopics; j++) {
ldaSums[j] += node.lda[j];
}
nodeById.put(node.id, node);
}
ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() + 2);
System.out.println("Nodes " + numNodes);
for(int tnum = 0; tnum < numTopics; tnum++) {
executorService.submit(new RankInPlaceRunnable(nodeById, nodes, ldaSums[tnum], tnum, convergence));
}
executorService.shutdown();
executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
}
}
| true | true | public void run() {
double [] lastRank = new double[numNodes];
double [] thisRank = new double[numNodes];
final int numIterations = 15;
for(int iteration = 0; ; iteration++) {
double []tmp = thisRank;
thisRank = lastRank;
lastRank = tmp;
if(iteration == 0) {
// Initialize
for(IntermediateTSPRNode node : nodes) {
thisRank[node.linearId] = node.lda[topicNum] / sum;
}
} else {
// Clear old values
for(int i = 0; i < numNodes; i++) {
thisRank[i] = 0.0;
}
}
// Power iteration
for(IntermediateTSPRNode node : nodes) {
int numNeighbors = node.edges.length;
double contribution = BETA * lastRank[node.linearId] / numNeighbors;
for(long targetId : node.edges) {
IntermediateTSPRNode neighbor = nodeById.get(targetId);
thisRank[neighbor.linearId] += contribution;
}
}
// Reinsert leaked
double topicSum = 0.0;
for(IntermediateTSPRNode node : nodes) {
topicSum += thisRank[node.linearId];
}
double difference = 0.0;
for(IntermediateTSPRNode node : nodes) {
thisRank[node.linearId] += (1.0 - topicSum) * (node.lda[topicNum] / sum);
// Calculate L1 difference too
difference += Math.abs(thisRank[node.linearId] - lastRank[node.linearId]);
}
System.err.println("Pagerank topic " + topicNum + " iteration "
+ iteration + ": delta=" + difference);
if(difference < convergence) {
break;
}
}
for(IntermediateTSPRNode node : nodes) {
node.tspr[topicNum] = thisRank[node.linearId];
}
}
| public void run() {
double [] lastRank = new double[numNodes];
double [] thisRank = new double[numNodes];
for(int iteration = 0; ; iteration++) {
double []tmp = thisRank;
thisRank = lastRank;
lastRank = tmp;
if(iteration == 0) {
// Initialize
for(IntermediateTSPRNode node : nodes) {
thisRank[node.linearId] = node.lda[topicNum] / sum;
}
} else {
// Clear old values
for(int i = 0; i < numNodes; i++) {
thisRank[i] = 0.0;
}
}
// Power iteration
for(IntermediateTSPRNode node : nodes) {
int numNeighbors = node.edges.length;
double contribution = BETA * lastRank[node.linearId] / numNeighbors;
for(long targetId : node.edges) {
IntermediateTSPRNode neighbor = nodeById.get(targetId);
thisRank[neighbor.linearId] += contribution;
}
}
// Reinsert leaked
double topicSum = 0.0;
for(IntermediateTSPRNode node : nodes) {
topicSum += thisRank[node.linearId];
}
double difference = 0.0;
for(IntermediateTSPRNode node : nodes) {
thisRank[node.linearId] += (1.0 - topicSum) * (node.lda[topicNum] / sum);
// Calculate L1 difference too
difference += Math.abs(thisRank[node.linearId] - lastRank[node.linearId]);
}
System.err.println("Pagerank topic " + topicNum + " iteration "
+ iteration + ": delta=" + difference);
if(difference < convergence) {
break;
}
}
for(IntermediateTSPRNode node : nodes) {
node.tspr[topicNum] = thisRank[node.linearId];
}
}
|
diff --git a/modello-plugins/modello-plugin-xsd/src/main/java/org/codehaus/modello/plugin/xsd/XsdGenerator.java b/modello-plugins/modello-plugin-xsd/src/main/java/org/codehaus/modello/plugin/xsd/XsdGenerator.java
index 3c90b75d..ad6c3ca0 100644
--- a/modello-plugins/modello-plugin-xsd/src/main/java/org/codehaus/modello/plugin/xsd/XsdGenerator.java
+++ b/modello-plugins/modello-plugin-xsd/src/main/java/org/codehaus/modello/plugin/xsd/XsdGenerator.java
@@ -1,585 +1,586 @@
package org.codehaus.modello.plugin.xsd;
/*
* Copyright (c) 2005, Codehaus.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import org.codehaus.modello.ModelloException;
import org.codehaus.modello.ModelloParameterConstants;
import org.codehaus.modello.model.Model;
import org.codehaus.modello.model.ModelAssociation;
import org.codehaus.modello.model.ModelClass;
import org.codehaus.modello.model.ModelField;
import org.codehaus.modello.plugin.xsd.metadata.XsdClassMetadata;
import org.codehaus.modello.plugin.xsd.metadata.XsdModelMetadata;
import org.codehaus.modello.plugins.xml.AbstractXmlGenerator;
import org.codehaus.modello.plugins.xml.metadata.XmlAssociationMetadata;
import org.codehaus.modello.plugins.xml.metadata.XmlFieldMetadata;
import org.codehaus.modello.plugins.xml.metadata.XmlModelMetadata;
import org.codehaus.plexus.util.StringUtils;
import org.codehaus.plexus.util.WriterFactory;
import org.codehaus.plexus.util.xml.PrettyPrintXMLWriter;
import org.codehaus.plexus.util.xml.XMLWriter;
import java.io.File;
import java.io.IOException;
import java.io.Writer;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Set;
/**
* @author <a href="mailto:[email protected]">Brett Porter</a>
* @version $Id$
*/
public class XsdGenerator
extends AbstractXmlGenerator
{
public void generate( Model model, Properties parameters )
throws ModelloException
{
initialize( model, parameters );
try
{
generateXsd( parameters );
}
catch ( IOException ex )
{
throw new ModelloException( "Exception while generating xsd.", ex );
}
}
private void generateXsd( Properties parameters )
throws IOException, ModelloException
{
Model objectModel = getModel();
File directory = getOutputDirectory();
if ( isPackageWithVersion() )
{
directory = new File( directory, getGeneratedVersion().toString() );
}
if ( !directory.exists() )
{
directory.mkdirs();
}
// we assume parameters not null
String xsdFileName = parameters.getProperty( ModelloParameterConstants.OUTPUT_XSD_FILE_NAME );
File f = new File( directory, objectModel.getId() + "-" + getGeneratedVersion() + ".xsd" );
if ( xsdFileName != null )
{
f = new File( directory, xsdFileName );
}
Writer writer = WriterFactory.newXmlWriter( f );
try
{
XMLWriter w = new PrettyPrintXMLWriter( writer );
writer.write( "<?xml version=\"1.0\"?>\n" );
initHeader( w );
// TODO: the writer should be knowledgeable of namespaces, but this works
w.startElement( "xs:schema" );
w.addAttribute( "xmlns:xs", "http://www.w3.org/2001/XMLSchema" );
w.addAttribute( "elementFormDefault", "qualified" );
ModelClass root = objectModel.getClass( objectModel.getRoot( getGeneratedVersion() ),
getGeneratedVersion() );
XmlModelMetadata xmlModelMetadata = (XmlModelMetadata) root.getModel().getMetadata( XmlModelMetadata.ID );
XsdModelMetadata xsdModelMetadata = (XsdModelMetadata) root.getModel().getMetadata( XsdModelMetadata.ID );
String namespace;
if ( StringUtils.isNotEmpty( xsdModelMetadata.getNamespace() ) )
{
namespace = xsdModelMetadata.getNamespace( getGeneratedVersion() );
}
else
{
// xsd.namespace is not set, try using xml.namespace
if ( StringUtils.isEmpty( xmlModelMetadata.getNamespace() ) )
{
throw new ModelloException( "Cannot generate xsd without xmlns specification:"
+ " <model xml.namespace='...'> or <model xsd.namespace='...'>" );
}
namespace = xmlModelMetadata.getNamespace( getGeneratedVersion() );
}
w.addAttribute( "xmlns", namespace );
String targetNamespace;
if ( xsdModelMetadata.getTargetNamespace() == null )
{
// xsd.target-namespace not set, using namespace
targetNamespace = namespace;
}
else
{
targetNamespace = xsdModelMetadata.getTargetNamespace( getGeneratedVersion() );
}
// add targetNamespace if attribute is not blank (specifically set to avoid a target namespace)
if ( StringUtils.isNotBlank( targetNamespace ) )
{
w.addAttribute( "targetNamespace", targetNamespace );
}
w.startElement( "xs:element" );
String tagName = resolveTagName( root );
w.addAttribute( "name", tagName );
w.addAttribute( "type", root.getName() );
writeClassDocumentation( w, root );
w.endElement();
// Element descriptors
// Traverse from root so "abstract" models aren't included
int initialCapacity = objectModel.getClasses( getGeneratedVersion() ).size();
writeComplexTypeDescriptor( w, objectModel, root, new HashSet( initialCapacity ) );
w.endElement();
}
finally
{
writer.close();
}
}
private static void writeClassDocumentation( XMLWriter w, ModelClass modelClass )
{
writeDocumentation( w, modelClass.getVersionRange().toString(), modelClass.getDescription() );
}
private static void writeFieldDocumentation( XMLWriter w, ModelField field )
{
writeDocumentation( w, field.getVersionRange().toString(), field.getDescription() );
}
private static void writeDocumentation( XMLWriter w, String version, String description )
{
if ( version != null || description != null )
{
w.startElement( "xs:annotation" );
if ( version != null )
{
w.startElement( "xs:documentation" );
w.addAttribute( "source", "version" );
w.writeText( version );
w.endElement();
}
if ( description != null )
{
w.startElement( "xs:documentation" );
w.addAttribute( "source", "description" );
w.writeText( description );
w.endElement();
}
w.endElement();
}
}
private void writeComplexTypeDescriptor( XMLWriter w, Model objectModel, ModelClass modelClass, Set written )
{
written.add( modelClass );
w.startElement( "xs:complexType" );
w.addAttribute( "name", modelClass.getName() );
List fields = getFieldsForClass( modelClass );
boolean hasContentField = hasContentField( fields );
List attributeFields = getAttributeFieldsForClass( modelClass );
fields.removeAll( attributeFields );
boolean mixedContent = hasContentField && fields.size() > 0;
// other fields with complexType
// if yes it's a mixed content element and attribute
if ( mixedContent )
{
w.addAttribute( "mixed", "true" );
}
else if ( hasContentField )
{
// yes it's only an extension of xs:string
w.startElement( "xs:simpleContent" );
w.startElement( "xs:extension" );
w.addAttribute( "base", "xs:string" );
}
writeClassDocumentation( w, modelClass );
Set toWrite = new HashSet();
if ( fields.size() > 0 )
{
XsdClassMetadata xsdClassMetadata = (XsdClassMetadata) modelClass.getMetadata( XsdClassMetadata.ID );
boolean compositorAll = XsdClassMetadata.COMPOSITOR_ALL.equals( xsdClassMetadata.getCompositor() );
if ( ( mixedContent ) || ( !hasContentField ) )
{
if ( compositorAll )
{
w.startElement( "xs:all" );
}
else
{
w.startElement( "xs:sequence" );
}
}
for ( Iterator j = fields.iterator(); j.hasNext(); )
{
ModelField field = (ModelField) j.next();
XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID );
String fieldTagName = resolveTagName( field, xmlFieldMetadata );
if ( !hasContentField )
{
w.startElement( "xs:element" );
}
// Usually, would only do this if the field is not "required", but due to inheritance, it may be
// present, even if not here, so we need to let it slide
if ( !hasContentField )
{
w.addAttribute( "minOccurs", "0" );
}
String xsdType = getXsdType( field.getType() );
if ( "Date".equals( field.getType() ) && "long".equals( xmlFieldMetadata.getFormat() ) )
{
xsdType = getXsdType( "long" );
}
if ( ( xsdType != null ) || "char".equals( field.getType() ) || "Char".equals( field.getType() ) )
{
w.addAttribute( "name", fieldTagName );
if ( xsdType != null )
{
// schema built-in datatype
w.addAttribute( "type", xsdType );
}
if ( field.getDefaultValue() != null )
{
w.addAttribute( "default", field.getDefaultValue() );
}
writeFieldDocumentation( w, field );
if ( xsdType == null )
{
writeCharElement( w );
}
}
else
{
// TODO cleanup/split this part it's no really human readable :-)
if ( isInnerAssociation( field ) )
{
ModelAssociation association = (ModelAssociation) field;
ModelClass fieldModelClass = objectModel.getClass( association.getTo(), getGeneratedVersion() );
toWrite.add( fieldModelClass );
if ( association.isManyMultiplicity() )
{
XmlAssociationMetadata xmlAssociationMetadata =
(XmlAssociationMetadata) association.getAssociationMetadata( XmlAssociationMetadata.ID );
if ( xmlAssociationMetadata.isWrappedItems() )
{
w.addAttribute( "name", fieldTagName );
writeFieldDocumentation( w, field );
writeListElement( w, xmlFieldMetadata, xmlAssociationMetadata, field,
fieldModelClass.getName() );
}
else
{
if ( compositorAll )
{
// xs:all does not accept maxOccurs="unbounded", xs:sequence MUST be used
// to be able to represent this constraint
throw new IllegalStateException( field.getName() + " field is declared as xml.listStyle=\"flat\" "
+ "then class " + modelClass.getName() + " MUST be declared as xsd.compositor=\"sequence\"" );
}
if ( mixedContent )
{
w.startElement( "xs:element" );
w.addAttribute( "minOccurs", "0" );
}
w.addAttribute( "name", resolveTagName( fieldTagName, xmlAssociationMetadata ) );
w.addAttribute( "type", fieldModelClass.getName() );
w.addAttribute( "maxOccurs", "unbounded" );
writeFieldDocumentation( w, field );
if ( mixedContent )
{
w.endElement();
}
}
}
else
{
// not many multiplicity
w.addAttribute( "name", fieldTagName );
w.addAttribute( "type", fieldModelClass.getName() );
writeFieldDocumentation( w, field );
}
}
else // not inner association
{
if (! "Content".equals( field.getType() ) )
{
w.addAttribute( "name", fieldTagName );
}
writeFieldDocumentation( w, field );
if ( List.class.getName().equals( field.getType() ) )
{
ModelAssociation association = (ModelAssociation) field;
XmlAssociationMetadata xmlAssociationMetadata =
(XmlAssociationMetadata) association.getAssociationMetadata( XmlAssociationMetadata.ID );
writeListElement( w, xmlFieldMetadata, xmlAssociationMetadata, field,
getXsdType( "String" ) );
}
else if ( Properties.class.getName().equals( field.getType() )
|| "DOM".equals( field.getType() ) )
{
writePropertiesElement( w );
}
else if ( "Content".equals( field.getType() ) )
{
// skip this
}
else
{
throw new IllegalStateException( "Non-association field of a non-primitive type '"
- + field.getType() + "' for '" + field.getName() + "'" );
+ + field.getType() + "' for '" + field.getName() + "' in '"
+ + modelClass.getName() + "' model class" );
}
}
}
if ( !hasContentField )
{
w.endElement();
}
}// end fields iterator
if ( !hasContentField || mixedContent )
{
w.endElement(); // xs:all or xs:sequence
}
}
for ( Iterator j = attributeFields.iterator(); j.hasNext(); )
{
ModelField field = (ModelField) j.next();
XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID );
w.startElement( "xs:attribute" );
String xsdType = getXsdType( field.getType() );
String tagName = resolveTagName( field, xmlFieldMetadata );
w.addAttribute( "name", tagName );
if ( xsdType != null )
{
w.addAttribute( "type", xsdType );
}
if ( field.getDefaultValue() != null )
{
w.addAttribute( "default", field.getDefaultValue() );
}
writeFieldDocumentation( w, field );
if ( "char".equals( field.getType() ) || "Char".equals( field.getType() ) )
{
writeCharElement( w );
}
else if ( xsdType == null )
{
throw new IllegalStateException( "Attribute field of a non-primitive type '" + field.getType()
- + "' for '" + field.getName() + "'" );
+ + "' for '" + field.getName() + "' in '" + modelClass.getName() + "' model class" );
}
w.endElement();
}
if ( hasContentField && !mixedContent )
{
w.endElement(); //xs:extension
w.endElement(); //xs:simpleContent
}
w.endElement(); // xs:complexType
for ( Iterator iter = toWrite.iterator(); iter.hasNext(); )
{
ModelClass fieldModelClass = (ModelClass) iter.next();
if ( !written.contains( fieldModelClass ) )
{
writeComplexTypeDescriptor( w, objectModel, fieldModelClass, written );
}
}
}
private static void writeCharElement( XMLWriter w )
{
// a char, described as a simpleType base on string with a length restriction to 1
w.startElement( "xs:simpleType" );
w.startElement( "xs:restriction" );
w.addAttribute( "base", "xs:string" );
w.startElement( "xs:length" );
w.addAttribute( "value", "1" );
w.addAttribute( "fixed", "true" );
w.endElement();
w.endElement();
w.endElement();
}
private static void writePropertiesElement( XMLWriter w )
{
w.startElement( "xs:complexType" );
w.startElement( "xs:sequence" );
w.startElement( "xs:any" );
w.addAttribute( "minOccurs", "0" );
w.addAttribute( "maxOccurs", "unbounded" );
w.addAttribute( "processContents", "skip" );
w.endElement();
w.endElement();
w.endElement();
}
private void writeListElement( XMLWriter w, XmlFieldMetadata xmlFieldMetadata,
XmlAssociationMetadata xmlAssociationMetadata, ModelField field, String type )
{
String fieldTagName = resolveTagName( field, xmlFieldMetadata );
String valuesTagName = resolveTagName( fieldTagName, xmlAssociationMetadata );
w.startElement( "xs:complexType" );
w.startElement( "xs:sequence" );
w.startElement( "xs:element" );
w.addAttribute( "name", valuesTagName );
w.addAttribute( "minOccurs", "0" );
w.addAttribute( "maxOccurs", "unbounded" );
w.addAttribute( "type", type );
w.endElement();
w.endElement();
w.endElement();
}
private static String getXsdType( String type )
{
if ( "String".equals( type ) )
{
return "xs:string";
}
else if ( "boolean".equals( type ) || "Boolean".equals( type ) )
{
return "xs:boolean";
}
else if ( "byte".equals( type ) || "Byte".equals( type ) )
{
return "xs:byte";
}
else if ( "short".equals( type ) || "Short".equals( type ) )
{
return "xs:short";
}
else if ( "int".equals( type ) || "Integer".equals( type ) )
{
return "xs:int";
}
else if ( "long".equals( type ) || "Long".equals( type ) )
{
return "xs:long";
}
else if ("float".equals( type ) || "Float".equals( type ) )
{
return "xs:float";
}
else if ("double".equals( type ) || "Double".equals( type ) )
{
return "xs:double";
}
else if ( "Date".equals( type ) )
{
return "xs:dateTime";
}
else
{
return null;
}
}
}
| false | true | private void writeComplexTypeDescriptor( XMLWriter w, Model objectModel, ModelClass modelClass, Set written )
{
written.add( modelClass );
w.startElement( "xs:complexType" );
w.addAttribute( "name", modelClass.getName() );
List fields = getFieldsForClass( modelClass );
boolean hasContentField = hasContentField( fields );
List attributeFields = getAttributeFieldsForClass( modelClass );
fields.removeAll( attributeFields );
boolean mixedContent = hasContentField && fields.size() > 0;
// other fields with complexType
// if yes it's a mixed content element and attribute
if ( mixedContent )
{
w.addAttribute( "mixed", "true" );
}
else if ( hasContentField )
{
// yes it's only an extension of xs:string
w.startElement( "xs:simpleContent" );
w.startElement( "xs:extension" );
w.addAttribute( "base", "xs:string" );
}
writeClassDocumentation( w, modelClass );
Set toWrite = new HashSet();
if ( fields.size() > 0 )
{
XsdClassMetadata xsdClassMetadata = (XsdClassMetadata) modelClass.getMetadata( XsdClassMetadata.ID );
boolean compositorAll = XsdClassMetadata.COMPOSITOR_ALL.equals( xsdClassMetadata.getCompositor() );
if ( ( mixedContent ) || ( !hasContentField ) )
{
if ( compositorAll )
{
w.startElement( "xs:all" );
}
else
{
w.startElement( "xs:sequence" );
}
}
for ( Iterator j = fields.iterator(); j.hasNext(); )
{
ModelField field = (ModelField) j.next();
XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID );
String fieldTagName = resolveTagName( field, xmlFieldMetadata );
if ( !hasContentField )
{
w.startElement( "xs:element" );
}
// Usually, would only do this if the field is not "required", but due to inheritance, it may be
// present, even if not here, so we need to let it slide
if ( !hasContentField )
{
w.addAttribute( "minOccurs", "0" );
}
String xsdType = getXsdType( field.getType() );
if ( "Date".equals( field.getType() ) && "long".equals( xmlFieldMetadata.getFormat() ) )
{
xsdType = getXsdType( "long" );
}
if ( ( xsdType != null ) || "char".equals( field.getType() ) || "Char".equals( field.getType() ) )
{
w.addAttribute( "name", fieldTagName );
if ( xsdType != null )
{
// schema built-in datatype
w.addAttribute( "type", xsdType );
}
if ( field.getDefaultValue() != null )
{
w.addAttribute( "default", field.getDefaultValue() );
}
writeFieldDocumentation( w, field );
if ( xsdType == null )
{
writeCharElement( w );
}
}
else
{
// TODO cleanup/split this part it's no really human readable :-)
if ( isInnerAssociation( field ) )
{
ModelAssociation association = (ModelAssociation) field;
ModelClass fieldModelClass = objectModel.getClass( association.getTo(), getGeneratedVersion() );
toWrite.add( fieldModelClass );
if ( association.isManyMultiplicity() )
{
XmlAssociationMetadata xmlAssociationMetadata =
(XmlAssociationMetadata) association.getAssociationMetadata( XmlAssociationMetadata.ID );
if ( xmlAssociationMetadata.isWrappedItems() )
{
w.addAttribute( "name", fieldTagName );
writeFieldDocumentation( w, field );
writeListElement( w, xmlFieldMetadata, xmlAssociationMetadata, field,
fieldModelClass.getName() );
}
else
{
if ( compositorAll )
{
// xs:all does not accept maxOccurs="unbounded", xs:sequence MUST be used
// to be able to represent this constraint
throw new IllegalStateException( field.getName() + " field is declared as xml.listStyle=\"flat\" "
+ "then class " + modelClass.getName() + " MUST be declared as xsd.compositor=\"sequence\"" );
}
if ( mixedContent )
{
w.startElement( "xs:element" );
w.addAttribute( "minOccurs", "0" );
}
w.addAttribute( "name", resolveTagName( fieldTagName, xmlAssociationMetadata ) );
w.addAttribute( "type", fieldModelClass.getName() );
w.addAttribute( "maxOccurs", "unbounded" );
writeFieldDocumentation( w, field );
if ( mixedContent )
{
w.endElement();
}
}
}
else
{
// not many multiplicity
w.addAttribute( "name", fieldTagName );
w.addAttribute( "type", fieldModelClass.getName() );
writeFieldDocumentation( w, field );
}
}
else // not inner association
{
if (! "Content".equals( field.getType() ) )
{
w.addAttribute( "name", fieldTagName );
}
writeFieldDocumentation( w, field );
if ( List.class.getName().equals( field.getType() ) )
{
ModelAssociation association = (ModelAssociation) field;
XmlAssociationMetadata xmlAssociationMetadata =
(XmlAssociationMetadata) association.getAssociationMetadata( XmlAssociationMetadata.ID );
writeListElement( w, xmlFieldMetadata, xmlAssociationMetadata, field,
getXsdType( "String" ) );
}
else if ( Properties.class.getName().equals( field.getType() )
|| "DOM".equals( field.getType() ) )
{
writePropertiesElement( w );
}
else if ( "Content".equals( field.getType() ) )
{
// skip this
}
else
{
throw new IllegalStateException( "Non-association field of a non-primitive type '"
+ field.getType() + "' for '" + field.getName() + "'" );
}
}
}
if ( !hasContentField )
{
w.endElement();
}
}// end fields iterator
if ( !hasContentField || mixedContent )
{
w.endElement(); // xs:all or xs:sequence
}
}
for ( Iterator j = attributeFields.iterator(); j.hasNext(); )
{
ModelField field = (ModelField) j.next();
XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID );
w.startElement( "xs:attribute" );
String xsdType = getXsdType( field.getType() );
String tagName = resolveTagName( field, xmlFieldMetadata );
w.addAttribute( "name", tagName );
if ( xsdType != null )
{
w.addAttribute( "type", xsdType );
}
if ( field.getDefaultValue() != null )
{
w.addAttribute( "default", field.getDefaultValue() );
}
writeFieldDocumentation( w, field );
if ( "char".equals( field.getType() ) || "Char".equals( field.getType() ) )
{
writeCharElement( w );
}
else if ( xsdType == null )
{
throw new IllegalStateException( "Attribute field of a non-primitive type '" + field.getType()
+ "' for '" + field.getName() + "'" );
}
w.endElement();
}
if ( hasContentField && !mixedContent )
{
w.endElement(); //xs:extension
w.endElement(); //xs:simpleContent
}
w.endElement(); // xs:complexType
for ( Iterator iter = toWrite.iterator(); iter.hasNext(); )
{
ModelClass fieldModelClass = (ModelClass) iter.next();
if ( !written.contains( fieldModelClass ) )
{
writeComplexTypeDescriptor( w, objectModel, fieldModelClass, written );
}
}
}
| private void writeComplexTypeDescriptor( XMLWriter w, Model objectModel, ModelClass modelClass, Set written )
{
written.add( modelClass );
w.startElement( "xs:complexType" );
w.addAttribute( "name", modelClass.getName() );
List fields = getFieldsForClass( modelClass );
boolean hasContentField = hasContentField( fields );
List attributeFields = getAttributeFieldsForClass( modelClass );
fields.removeAll( attributeFields );
boolean mixedContent = hasContentField && fields.size() > 0;
// other fields with complexType
// if yes it's a mixed content element and attribute
if ( mixedContent )
{
w.addAttribute( "mixed", "true" );
}
else if ( hasContentField )
{
// yes it's only an extension of xs:string
w.startElement( "xs:simpleContent" );
w.startElement( "xs:extension" );
w.addAttribute( "base", "xs:string" );
}
writeClassDocumentation( w, modelClass );
Set toWrite = new HashSet();
if ( fields.size() > 0 )
{
XsdClassMetadata xsdClassMetadata = (XsdClassMetadata) modelClass.getMetadata( XsdClassMetadata.ID );
boolean compositorAll = XsdClassMetadata.COMPOSITOR_ALL.equals( xsdClassMetadata.getCompositor() );
if ( ( mixedContent ) || ( !hasContentField ) )
{
if ( compositorAll )
{
w.startElement( "xs:all" );
}
else
{
w.startElement( "xs:sequence" );
}
}
for ( Iterator j = fields.iterator(); j.hasNext(); )
{
ModelField field = (ModelField) j.next();
XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID );
String fieldTagName = resolveTagName( field, xmlFieldMetadata );
if ( !hasContentField )
{
w.startElement( "xs:element" );
}
// Usually, would only do this if the field is not "required", but due to inheritance, it may be
// present, even if not here, so we need to let it slide
if ( !hasContentField )
{
w.addAttribute( "minOccurs", "0" );
}
String xsdType = getXsdType( field.getType() );
if ( "Date".equals( field.getType() ) && "long".equals( xmlFieldMetadata.getFormat() ) )
{
xsdType = getXsdType( "long" );
}
if ( ( xsdType != null ) || "char".equals( field.getType() ) || "Char".equals( field.getType() ) )
{
w.addAttribute( "name", fieldTagName );
if ( xsdType != null )
{
// schema built-in datatype
w.addAttribute( "type", xsdType );
}
if ( field.getDefaultValue() != null )
{
w.addAttribute( "default", field.getDefaultValue() );
}
writeFieldDocumentation( w, field );
if ( xsdType == null )
{
writeCharElement( w );
}
}
else
{
// TODO cleanup/split this part it's no really human readable :-)
if ( isInnerAssociation( field ) )
{
ModelAssociation association = (ModelAssociation) field;
ModelClass fieldModelClass = objectModel.getClass( association.getTo(), getGeneratedVersion() );
toWrite.add( fieldModelClass );
if ( association.isManyMultiplicity() )
{
XmlAssociationMetadata xmlAssociationMetadata =
(XmlAssociationMetadata) association.getAssociationMetadata( XmlAssociationMetadata.ID );
if ( xmlAssociationMetadata.isWrappedItems() )
{
w.addAttribute( "name", fieldTagName );
writeFieldDocumentation( w, field );
writeListElement( w, xmlFieldMetadata, xmlAssociationMetadata, field,
fieldModelClass.getName() );
}
else
{
if ( compositorAll )
{
// xs:all does not accept maxOccurs="unbounded", xs:sequence MUST be used
// to be able to represent this constraint
throw new IllegalStateException( field.getName() + " field is declared as xml.listStyle=\"flat\" "
+ "then class " + modelClass.getName() + " MUST be declared as xsd.compositor=\"sequence\"" );
}
if ( mixedContent )
{
w.startElement( "xs:element" );
w.addAttribute( "minOccurs", "0" );
}
w.addAttribute( "name", resolveTagName( fieldTagName, xmlAssociationMetadata ) );
w.addAttribute( "type", fieldModelClass.getName() );
w.addAttribute( "maxOccurs", "unbounded" );
writeFieldDocumentation( w, field );
if ( mixedContent )
{
w.endElement();
}
}
}
else
{
// not many multiplicity
w.addAttribute( "name", fieldTagName );
w.addAttribute( "type", fieldModelClass.getName() );
writeFieldDocumentation( w, field );
}
}
else // not inner association
{
if (! "Content".equals( field.getType() ) )
{
w.addAttribute( "name", fieldTagName );
}
writeFieldDocumentation( w, field );
if ( List.class.getName().equals( field.getType() ) )
{
ModelAssociation association = (ModelAssociation) field;
XmlAssociationMetadata xmlAssociationMetadata =
(XmlAssociationMetadata) association.getAssociationMetadata( XmlAssociationMetadata.ID );
writeListElement( w, xmlFieldMetadata, xmlAssociationMetadata, field,
getXsdType( "String" ) );
}
else if ( Properties.class.getName().equals( field.getType() )
|| "DOM".equals( field.getType() ) )
{
writePropertiesElement( w );
}
else if ( "Content".equals( field.getType() ) )
{
// skip this
}
else
{
throw new IllegalStateException( "Non-association field of a non-primitive type '"
+ field.getType() + "' for '" + field.getName() + "' in '"
+ modelClass.getName() + "' model class" );
}
}
}
if ( !hasContentField )
{
w.endElement();
}
}// end fields iterator
if ( !hasContentField || mixedContent )
{
w.endElement(); // xs:all or xs:sequence
}
}
for ( Iterator j = attributeFields.iterator(); j.hasNext(); )
{
ModelField field = (ModelField) j.next();
XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID );
w.startElement( "xs:attribute" );
String xsdType = getXsdType( field.getType() );
String tagName = resolveTagName( field, xmlFieldMetadata );
w.addAttribute( "name", tagName );
if ( xsdType != null )
{
w.addAttribute( "type", xsdType );
}
if ( field.getDefaultValue() != null )
{
w.addAttribute( "default", field.getDefaultValue() );
}
writeFieldDocumentation( w, field );
if ( "char".equals( field.getType() ) || "Char".equals( field.getType() ) )
{
writeCharElement( w );
}
else if ( xsdType == null )
{
throw new IllegalStateException( "Attribute field of a non-primitive type '" + field.getType()
+ "' for '" + field.getName() + "' in '" + modelClass.getName() + "' model class" );
}
w.endElement();
}
if ( hasContentField && !mixedContent )
{
w.endElement(); //xs:extension
w.endElement(); //xs:simpleContent
}
w.endElement(); // xs:complexType
for ( Iterator iter = toWrite.iterator(); iter.hasNext(); )
{
ModelClass fieldModelClass = (ModelClass) iter.next();
if ( !written.contains( fieldModelClass ) )
{
writeComplexTypeDescriptor( w, objectModel, fieldModelClass, written );
}
}
}
|
diff --git a/src/tconstruct/client/block/SearedRender.java b/src/tconstruct/client/block/SearedRender.java
index 7c71e5dd5..25025a408 100644
--- a/src/tconstruct/client/block/SearedRender.java
+++ b/src/tconstruct/client/block/SearedRender.java
@@ -1,455 +1,455 @@
package tconstruct.client.block;
import cpw.mods.fml.client.registry.*;
import net.minecraft.block.Block;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.item.ItemStack;
import net.minecraft.world.IBlockAccess;
import net.minecraftforge.fluids.Fluid;
import tconstruct.TConstruct;
import tconstruct.blocks.logic.*;
import tconstruct.client.TProxyClient;
import tconstruct.common.TContent;
import tconstruct.library.crafting.CastingRecipe;
public class SearedRender implements ISimpleBlockRenderingHandler
{
public static int searedModel = RenderingRegistry.getNextAvailableRenderId();
@Override
public void renderInventoryBlock (Block block, int metadata, int modelID, RenderBlocks renderer)
{
if (modelID == searedModel)
{
if (metadata == 0)
{
//Top
renderer.setRenderBounds(0.0F, 0.625F, 0.0F, 1.0F, 0.9375F, 1.0F);
TProxyClient.renderStandardInvBlock(renderer, block, metadata);
//Lip
renderer.setRenderBounds(0.0F, 0.9375, 0.0F, 0.0625, 1.0, 1.0F);
TProxyClient.renderStandardInvBlock(renderer, block, metadata);
renderer.setRenderBounds(0.0625, 0.9375, 0.9375, 0.9375, 1.0, 1.0F);
TProxyClient.renderStandardInvBlock(renderer, block, metadata);
renderer.setRenderBounds(0.9375, 0.9375, 0.0F, 1.0F, 1.0, 1.0F);
TProxyClient.renderStandardInvBlock(renderer, block, metadata);
renderer.setRenderBounds(0.0625, 0.9375, 0.0F, 0.9375, 1.0, 0.0625);
TProxyClient.renderStandardInvBlock(renderer, block, metadata);
//Legs
renderer.setRenderBounds(0.0F, 0.0F, 0.0F, 0.3125F, 0.625F, 0.3125F);
TProxyClient.renderStandardInvBlock(renderer, block, metadata);
renderer.setRenderBounds(0.6875, 0.0F, 0.0F, 1.0F, 0.625F, 0.25F);
TProxyClient.renderStandardInvBlock(renderer, block, metadata);
renderer.setRenderBounds(0.0F, 0.0F, 0.6875, 0.3125F, 0.625F, 1.0F);
TProxyClient.renderStandardInvBlock(renderer, block, metadata);
renderer.setRenderBounds(0.6875, 0.0F, 0.6875, 1.0F, 0.625F, 1.0F);
TProxyClient.renderStandardInvBlock(renderer, block, metadata);
}
else if (metadata == 1)
{
renderer.setRenderBounds(0.25, 0.25, 0.625, 0.75, 0.375, 1);
TProxyClient.renderStandardInvBlock(renderer, block, metadata);
renderer.setRenderBounds(0.25, 0.25, 0.625, 0.375, 0.625, 1);
TProxyClient.renderStandardInvBlock(renderer, block, metadata);
renderer.setRenderBounds(0.625, 0.25, 0.625, 0.75, 0.625, 1);
TProxyClient.renderStandardInvBlock(renderer, block, metadata);
renderer.setRenderBounds(0.375, 0.375, 0.625, 0.625, 0.625, 1);
}
else if (metadata == 2)
{
renderer.setRenderBounds(0.125F, 0.125f, 0.125F, 0.875F, 0.25F, 0.875F);
TProxyClient.renderStandardInvBlock(renderer, block, metadata);
//Details
renderer.setRenderBounds(0.001f, 0.1245f, 0.001f, 0.1245f, 0.999f, 0.4375f);
TProxyClient.renderStandardInvBlock(renderer, block, metadata);
renderer.setRenderBounds(0.001f, 0.1245f, 0.5625f, 0.1245f, 0.999f, 0.999f);
TProxyClient.renderStandardInvBlock(renderer, block, metadata);
renderer.setRenderBounds(0.001f, 0.8755f, 0.4375f, 0.1245f, 0.999f, 0.5625f);
TProxyClient.renderStandardInvBlock(renderer, block, metadata);
renderer.setRenderBounds(0.001f, 0.1245f, 0.4375f, 0.1245f, 0.25F, 0.5625f);
TProxyClient.renderStandardInvBlock(renderer, block, metadata);
renderer.setRenderBounds(0.8755f, 0.1245f, 0f, 0.999f, 0.999f, 0.4375f);
TProxyClient.renderStandardInvBlock(renderer, block, metadata);
renderer.setRenderBounds(0.8755f, 0.1245f, 0.5625f, 0.999f, 0.999f, 0.999f);
TProxyClient.renderStandardInvBlock(renderer, block, metadata);
renderer.setRenderBounds(0.8755f, 0.8755f, 0.4375f, 0.999f, 0.999f, 0.5625f);
TProxyClient.renderStandardInvBlock(renderer, block, metadata);
renderer.setRenderBounds(0.8755f, 0.1245f, 0.4375f, 0.999f, 0.25F, 0.5625f);
TProxyClient.renderStandardInvBlock(renderer, block, metadata);
renderer.setRenderBounds(0.1245f, 0.1245f, 0.8755f, 0.4375f, 0.999f, 0.999f);
TProxyClient.renderStandardInvBlock(renderer, block, metadata);
renderer.setRenderBounds(0.5625f, 0.1245f, 0.8755f, 0.8755f, 0.999f, 0.999f);
TProxyClient.renderStandardInvBlock(renderer, block, metadata);
renderer.setRenderBounds(0.4375f, 0.8755f, 0.8755f, 0.5625f, 0.999f, 0.999f);
TProxyClient.renderStandardInvBlock(renderer, block, metadata);
renderer.setRenderBounds(0.4375f, 0.1245f, 0.8755f, 0.5625f, 0.2495F, 0.999f);
TProxyClient.renderStandardInvBlock(renderer, block, metadata);
renderer.setRenderBounds(0.1245f, 0.1245f, 0.001f, 0.4375f, 0.999f, 0.1245f);
TProxyClient.renderStandardInvBlock(renderer, block, metadata);
renderer.setRenderBounds(0.5625f, 0.1245f, 0.001f, 0.8755f, 0.999f, 0.1245f);
TProxyClient.renderStandardInvBlock(renderer, block, metadata);
renderer.setRenderBounds(0.4375f, 0.8755f, 0.001f, 0.5625f, 0.999f, 0.1245f);
TProxyClient.renderStandardInvBlock(renderer, block, metadata);
renderer.setRenderBounds(0.4375f, 0.1245f, 0.001f, 0.5625f, 0.25F, 0.1245f);
TProxyClient.renderStandardInvBlock(renderer, block, metadata);
//Legs
renderer.setRenderBounds(0.0F, 0.0F, 0.0F, 0.3125F, 0.125, 0.3125F);
TProxyClient.renderStandardInvBlock(renderer, block, metadata);
renderer.setRenderBounds(0.6875F, 0.0F, 0.0F, 1.0F, 0.125, 0.3125F);
TProxyClient.renderStandardInvBlock(renderer, block, metadata);
renderer.setRenderBounds(0.0F, 0.0F, 0.6875F, 0.3125F, 0.125, 1.0F);
TProxyClient.renderStandardInvBlock(renderer, block, metadata);
renderer.setRenderBounds(0.6875F, 0.0F, 0.6875F, 1.0F, 0.125, 1.0F);
TProxyClient.renderStandardInvBlock(renderer, block, metadata);
//Outside
renderer.setRenderBounds(0.0f, 0.125, 0f, 0.125, 1.0F, 1);
TProxyClient.renderStandardInvBlock(renderer, block, metadata);
renderer.setRenderBounds(0.875f, 0.125, 0f, 1, 1.0F, 1);
TProxyClient.renderStandardInvBlock(renderer, block, metadata);
renderer.setRenderBounds(0.125f, 0.125, 0f, 0.875f, 1.0F, 0.125f);
TProxyClient.renderStandardInvBlock(renderer, block, metadata);
renderer.setRenderBounds(0.125f, 0.125, 0.875f, 0.875f, 1.0F, 1);
TProxyClient.renderStandardInvBlock(renderer, block, metadata);
}
else
{
renderer.setRenderBounds(0, 0, 0, 1, 1, 1);
TProxyClient.renderStandardInvBlock(renderer, block, metadata);
}
}
}
@Override
public boolean renderWorldBlock (IBlockAccess world, int x, int y, int z, Block block, int modelID, RenderBlocks renderer)
{
if (modelID == searedModel)
{
int metadata = world.getBlockMetadata(x, y, z);
if (metadata == 0)
{
//Top
renderer.setRenderBounds(0.0F, 0.625F, 0.0F, 1.0F, 0.9375F, 1.0F);
renderer.renderStandardBlock(block, x, y, z);
//Lip
renderer.setRenderBounds(0.0F, 0.9375, 0.0F, 0.0625, 1.0, 1.0F);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.0625, 0.9375, 0.9375, 0.9375, 1.0, 1.0F);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.9375, 0.9375, 0.0F, 1.0F, 1.0, 1.0F);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.0625, 0.9375, 0.0F, 0.9375, 1.0, 0.0625);
renderer.renderStandardBlock(block, x, y, z);
//Legs
renderer.setRenderBounds(0.0F, 0.0F, 0.0F, 0.3125F, 0.625F, 0.3125F);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.6875, 0.0F, 0.0F, 1.0F, 0.625F, 0.25F);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.0F, 0.0F, 0.6875, 0.3125F, 0.625F, 1.0F);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.6875, 0.0F, 0.6875, 1.0F, 0.625F, 1.0F);
renderer.renderStandardBlock(block, x, y, z);
CastingTableLogic logic = (CastingTableLogic) world.getBlockTileEntity(x, y, z);
if (logic.liquid != null)
{
float minHeight = 0.9375F;
float maxHeight = 1F;
float minX = 0.0625F;
float maxX = 0.9375F;
float minZ = 0.0625F;
float maxZ = 0.9375F;
ItemStack it = logic.getStackInSlot(0);
if(it != null){
CastingRecipe rec = TConstruct.tableCasting.getCastingRecipe(logic.liquid, it);
- if(rec != null){
+ if(rec != null && rec.fluidRenderProperties != null){
minHeight = rec.fluidRenderProperties.minHeight;
maxHeight = rec.fluidRenderProperties.maxHeight;
minX = rec.fluidRenderProperties.minX;
maxX = rec.fluidRenderProperties.maxX;
minZ = rec.fluidRenderProperties.minZ;
maxZ = rec.fluidRenderProperties.maxZ;
}
}
float height = logic.getLiquidAmount() / (logic.getCapacity() * 1.03F) / 16F;
renderer.setRenderBounds(minX, minHeight, minZ, maxX, minHeight + height, maxZ);
Fluid fluid = logic.liquid.getFluid();
BlockSkinRenderHelper.renderLiquidBlock(fluid.getStillIcon(), fluid.getFlowingIcon(), x, y, z, renderer, world);
/*if (logic.liquid.fluidID < 4096) //Block
{
Block liquidBlock = Block.blocksList[logic.liquid.fluidID];
if (liquidBlock != null)
{
//ForgeHooksClient.bindTexture(liquidBlock.getTextureFile(), 0);
BlockSkinRenderHelper.renderMetadataBlock(liquidBlock, 0, x, y, z, renderer, world);
}
}
else
//Item
{
Item liquidItem = Item.itemsList[logic.liquid.fluidID];
if (liquidItem != null)
{
//ForgeHooksClient.bindTexture(liquidItem.getTextureFile(), 0);
BlockSkinRenderHelper.renderFakeBlock(liquidItem.getIconFromDamage(0), x, y, z, renderer, world);
}
}*/
}
}
else if (metadata == 1)
{
FaucetLogic logic = (FaucetLogic) world.getBlockTileEntity(x, y, z);
float xMin = 0.375F, zMin = 0.375F, xMax = 0.625F, zMax = 0.625F;
switch (logic.getRenderDirection())
{
case 2:
renderer.setRenderBounds(0.25, 0.25, 0.625, 0.75, 0.375, 1);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.25, 0.375, 0.625, 0.375, 0.625, 1);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.625, 0.375, 0.625, 0.75, 0.625, 1);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.375, 0.375, 0.625, 0.625, 0.625, 1);
zMin = 0.5F;
//zMin = 0.625F;
break;
case 3:
renderer.setRenderBounds(0.25, 0.25, 0, 0.75, 0.375, 0.375);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.25, 0.375, 0, 0.375, 0.625, 0.375);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.625, 0.375, 0, 0.75, 0.625, 0.375);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.375, 0.375, 0, 0.625, 0.625, 0.375);
zMax = 0.5F;
break;
case 4:
renderer.setRenderBounds(0.625, 0.25, 0.25, 1, 0.375, 0.75);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.625, 0.375, 0.25, 1, 0.625, 0.375);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.625, 0.375, 0.625, 1, 0.625, 0.75);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.625, 0.375, 0.375, 1, 0.625, 0.625);
xMin = 0.5F;
break;
case 5:
renderer.setRenderBounds(0, 0.25, 0.25, 0.375, 0.375, 0.75);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0, 0.375, 0.25, 0.375, 0.625, 0.375);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0, 0.375, 0.625, 0.375, 0.625, 0.75);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0, 0.375, 0.375, 0.375, 0.625, 0.625);
xMax = 0.5F;
break;
}
float yMin = 0F;
int uID = world.getBlockId(x, y - 1, z);
int uMeta = world.getBlockMetadata(x, y - 1, z);
if (uID == TContent.searedBlock.blockID && uMeta == 0)
{
yMin = -0.125F;
}
else if (uID == TContent.searedBlock.blockID && uMeta == 2)
{
yMin = -0.75F;
}
else if (uID == TContent.lavaTank.blockID)
{
yMin = -1F;
}
else if (uID == TContent.castingChannel.blockID)
{
yMin = -0.5F;
}
if (logic.liquid != null)
{
Fluid fluid = logic.liquid.getFluid();
renderer.setRenderBounds(xMin, yMin, zMin, xMax, 0.625, zMax);
BlockSkinRenderHelper.renderLiquidBlock(fluid.getStillIcon(), fluid.getFlowingIcon(), x, y, z, renderer, world);
/*if (fluid.canBePlacedInWorld())
{
Block liquidBlock = Block.blocksList[blockToRender.itemID];
BlockSkinRenderHelper.renderMetadataBlock(liquidBlock, 0, x, y, z, renderer, world);
renderer.setRenderBounds(xMin, yMin, zMin, xMax, 0.625, zMax);
BlockSkinRenderHelper.renderMetadataBlock(liquidBlock, 0, x, y, z, renderer, world);
}*/
/*ItemStack blockToRender = new ItemStack(logic.liquid.fluidID, 1, logic.liquid.itemMeta);
if (blockToRender.itemID < 4096) //Block
{
}
else
//Item
{
Item liquidItem = Item.itemsList[blockToRender.itemID];
//ForgeHooksClient.bindTexture(liquidItem.getTextureFile(), 0);
int meta = blockToRender.getItemDamage();
BlockSkinRenderHelper.renderFakeBlock(liquidItem.getIconFromDamage(meta), x, y, z, renderer, world);
renderer.setRenderBounds(xMin, yMin, zMin, xMax, 0.625, zMax);
BlockSkinRenderHelper.renderFakeBlock(liquidItem.getIconFromDamage(meta), x, y, z, renderer, world);
}*/
//renderer.renderStandardBlock(block, x, y, z);
}
}
else if (metadata == 2)
{
renderer.setRenderBounds(0.125F, 0.125f, 0.125F, 0.875F, 0.25F, 0.875F);
renderer.renderStandardBlock(block, x, y, z);
//Outside
renderer.setRenderBounds(0.0f, 0.125, 0f, 0.125, 1.0F, 1);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.875f, 0.125, 0f, 1, 1.0F, 1);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.125f, 0.125, 0f, 0.875f, 1.0F, 0.125f);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.125f, 0.125, 0.875f, 0.875f, 1.0F, 1);
renderer.renderStandardBlock(block, x, y, z);
//Details
renderer.setRenderBounds(0.001f, 0.1245f, 0.001f, 0.1245f, 0.999f, 0.4375f);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.001f, 0.1245f, 0.5625f, 0.1245f, 0.999f, 0.999f);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.001f, 0.8755f, 0.4375f, 0.1245f, 0.999f, 0.5625f);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.001f, 0.1245f, 0.4375f, 0.1245f, 0.25F, 0.5625f);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.8755f, 0.1245f, 0f, 0.999f, 0.999f, 0.4375f);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.8755f, 0.1245f, 0.5625f, 0.999f, 0.999f, 0.999f);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.8755f, 0.8755f, 0.4375f, 0.999f, 0.999f, 0.5625f);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.8755f, 0.1245f, 0.4375f, 0.999f, 0.25F, 0.5625f);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.1245f, 0.1245f, 0.8755f, 0.4375f, 0.999f, 0.999f);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.5625f, 0.1245f, 0.8755f, 0.8755f, 0.999f, 0.999f);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.4375f, 0.8755f, 0.8755f, 0.5625f, 0.999f, 0.999f);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.4375f, 0.1245f, 0.8755f, 0.5625f, 0.2495F, 0.999f);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.1245f, 0.1245f, 0.001f, 0.4375f, 0.999f, 0.1245f);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.5625f, 0.1245f, 0.001f, 0.8755f, 0.999f, 0.1245f);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.4375f, 0.8755f, 0.001f, 0.5625f, 0.999f, 0.1245f);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.4375f, 0.1245f, 0.001f, 0.5625f, 0.25F, 0.1245f);
renderer.renderStandardBlock(block, x, y, z);
//Legs
renderer.setRenderBounds(0.0F, 0.0F, 0.0F, 0.3125F, 0.125, 0.3125F);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.6875F, 0.0F, 0.0F, 1.0F, 0.125, 0.3125F);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.0F, 0.0F, 0.6875F, 0.3125F, 0.125, 1.0F);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.6875F, 0.0F, 0.6875F, 1.0F, 0.125, 1.0F);
renderer.renderStandardBlock(block, x, y, z);
//Liquids
CastingBasinLogic logic = (CastingBasinLogic) world.getBlockTileEntity(x, y, z);
if (logic.liquid != null)
{
float minHeight = 0.25F;
float maxHeight = 0.95F;
float minX = 0.0625F;
float maxX = 0.9375F;
float minZ = 0.0625F;
float maxZ = 0.9375F;
ItemStack it = logic.getStackInSlot(0);
if(it != null){
CastingRecipe rec = TConstruct.basinCasting.getCastingRecipe(logic.liquid, it);
- if(rec != null){
+ if(rec != null && rec.fluidRenderProperties != null){
minHeight = rec.fluidRenderProperties.minHeight;
maxHeight = rec.fluidRenderProperties.maxHeight;
minX = rec.fluidRenderProperties.minX;
maxX = rec.fluidRenderProperties.maxX;
minZ = rec.fluidRenderProperties.minZ;
maxZ = rec.fluidRenderProperties.maxZ;
}
}
float height = (logic.getLiquidAmount() / (logic.getCapacity() * 1.05F) * 0.6875F) / maxHeight;
renderer.setRenderBounds(minX, minHeight, minZ, maxX, minHeight + height, maxZ);
Fluid fluid = logic.liquid.getFluid();
BlockSkinRenderHelper.renderLiquidBlock(fluid.getStillIcon(), fluid.getFlowingIcon(), x, y, z, renderer, world);
/*if (logic.liquid.itemID < 4096) //Block
{
Block liquidBlock = Block.blocksList[logic.liquid.itemID];
if (liquidBlock != null)
{
//ForgeHooksClient.bindTexture(liquidBlock.getTextureFile(), 0);
BlockSkinRenderHelper.renderMetadataBlock(liquidBlock, logic.liquid.itemMeta, x, y, z, renderer, world);
}
}
else
//Item
{
Item liquidItem = Item.itemsList[logic.liquid.itemID];
if (liquidItem != null)
{
//ForgeHooksClient.bindTexture(liquidItem.getTextureFile(), 0);
BlockSkinRenderHelper.renderFakeBlock(liquidItem.getIconFromDamage(logic.liquid.itemMeta), x, y, z, renderer, world);
}
}*/
}
}
else
{
renderer.setRenderBounds(0.0F, 0.75F, 0.0F, 1.0F, 1.0F, 1.0F);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.0F, 0.0F, 0.0F, 0.25F, 0.75F, 0.25F);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.75F, 0.0F, 0.0F, 1.0F, 0.75F, 0.25F);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.0F, 0.0F, 0.75F, 0.25F, 0.75F, 1.0F);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.75F, 0.0F, 0.75F, 1.0F, 0.75F, 1.0F);
renderer.renderStandardBlock(block, x, y, z);
}
}
return true;
}
@Override
public boolean shouldRender3DInInventory ()
{
return true;
}
@Override
public int getRenderId ()
{
return searedModel;
}
}
| false | true | public boolean renderWorldBlock (IBlockAccess world, int x, int y, int z, Block block, int modelID, RenderBlocks renderer)
{
if (modelID == searedModel)
{
int metadata = world.getBlockMetadata(x, y, z);
if (metadata == 0)
{
//Top
renderer.setRenderBounds(0.0F, 0.625F, 0.0F, 1.0F, 0.9375F, 1.0F);
renderer.renderStandardBlock(block, x, y, z);
//Lip
renderer.setRenderBounds(0.0F, 0.9375, 0.0F, 0.0625, 1.0, 1.0F);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.0625, 0.9375, 0.9375, 0.9375, 1.0, 1.0F);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.9375, 0.9375, 0.0F, 1.0F, 1.0, 1.0F);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.0625, 0.9375, 0.0F, 0.9375, 1.0, 0.0625);
renderer.renderStandardBlock(block, x, y, z);
//Legs
renderer.setRenderBounds(0.0F, 0.0F, 0.0F, 0.3125F, 0.625F, 0.3125F);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.6875, 0.0F, 0.0F, 1.0F, 0.625F, 0.25F);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.0F, 0.0F, 0.6875, 0.3125F, 0.625F, 1.0F);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.6875, 0.0F, 0.6875, 1.0F, 0.625F, 1.0F);
renderer.renderStandardBlock(block, x, y, z);
CastingTableLogic logic = (CastingTableLogic) world.getBlockTileEntity(x, y, z);
if (logic.liquid != null)
{
float minHeight = 0.9375F;
float maxHeight = 1F;
float minX = 0.0625F;
float maxX = 0.9375F;
float minZ = 0.0625F;
float maxZ = 0.9375F;
ItemStack it = logic.getStackInSlot(0);
if(it != null){
CastingRecipe rec = TConstruct.tableCasting.getCastingRecipe(logic.liquid, it);
if(rec != null){
minHeight = rec.fluidRenderProperties.minHeight;
maxHeight = rec.fluidRenderProperties.maxHeight;
minX = rec.fluidRenderProperties.minX;
maxX = rec.fluidRenderProperties.maxX;
minZ = rec.fluidRenderProperties.minZ;
maxZ = rec.fluidRenderProperties.maxZ;
}
}
float height = logic.getLiquidAmount() / (logic.getCapacity() * 1.03F) / 16F;
renderer.setRenderBounds(minX, minHeight, minZ, maxX, minHeight + height, maxZ);
Fluid fluid = logic.liquid.getFluid();
BlockSkinRenderHelper.renderLiquidBlock(fluid.getStillIcon(), fluid.getFlowingIcon(), x, y, z, renderer, world);
/*if (logic.liquid.fluidID < 4096) //Block
{
Block liquidBlock = Block.blocksList[logic.liquid.fluidID];
if (liquidBlock != null)
{
//ForgeHooksClient.bindTexture(liquidBlock.getTextureFile(), 0);
BlockSkinRenderHelper.renderMetadataBlock(liquidBlock, 0, x, y, z, renderer, world);
}
}
else
//Item
{
Item liquidItem = Item.itemsList[logic.liquid.fluidID];
if (liquidItem != null)
{
//ForgeHooksClient.bindTexture(liquidItem.getTextureFile(), 0);
BlockSkinRenderHelper.renderFakeBlock(liquidItem.getIconFromDamage(0), x, y, z, renderer, world);
}
}*/
}
}
else if (metadata == 1)
{
FaucetLogic logic = (FaucetLogic) world.getBlockTileEntity(x, y, z);
float xMin = 0.375F, zMin = 0.375F, xMax = 0.625F, zMax = 0.625F;
switch (logic.getRenderDirection())
{
case 2:
renderer.setRenderBounds(0.25, 0.25, 0.625, 0.75, 0.375, 1);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.25, 0.375, 0.625, 0.375, 0.625, 1);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.625, 0.375, 0.625, 0.75, 0.625, 1);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.375, 0.375, 0.625, 0.625, 0.625, 1);
zMin = 0.5F;
//zMin = 0.625F;
break;
case 3:
renderer.setRenderBounds(0.25, 0.25, 0, 0.75, 0.375, 0.375);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.25, 0.375, 0, 0.375, 0.625, 0.375);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.625, 0.375, 0, 0.75, 0.625, 0.375);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.375, 0.375, 0, 0.625, 0.625, 0.375);
zMax = 0.5F;
break;
case 4:
renderer.setRenderBounds(0.625, 0.25, 0.25, 1, 0.375, 0.75);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.625, 0.375, 0.25, 1, 0.625, 0.375);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.625, 0.375, 0.625, 1, 0.625, 0.75);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.625, 0.375, 0.375, 1, 0.625, 0.625);
xMin = 0.5F;
break;
case 5:
renderer.setRenderBounds(0, 0.25, 0.25, 0.375, 0.375, 0.75);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0, 0.375, 0.25, 0.375, 0.625, 0.375);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0, 0.375, 0.625, 0.375, 0.625, 0.75);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0, 0.375, 0.375, 0.375, 0.625, 0.625);
xMax = 0.5F;
break;
}
float yMin = 0F;
int uID = world.getBlockId(x, y - 1, z);
int uMeta = world.getBlockMetadata(x, y - 1, z);
if (uID == TContent.searedBlock.blockID && uMeta == 0)
{
yMin = -0.125F;
}
else if (uID == TContent.searedBlock.blockID && uMeta == 2)
{
yMin = -0.75F;
}
else if (uID == TContent.lavaTank.blockID)
{
yMin = -1F;
}
else if (uID == TContent.castingChannel.blockID)
{
yMin = -0.5F;
}
if (logic.liquid != null)
{
Fluid fluid = logic.liquid.getFluid();
renderer.setRenderBounds(xMin, yMin, zMin, xMax, 0.625, zMax);
BlockSkinRenderHelper.renderLiquidBlock(fluid.getStillIcon(), fluid.getFlowingIcon(), x, y, z, renderer, world);
/*if (fluid.canBePlacedInWorld())
{
Block liquidBlock = Block.blocksList[blockToRender.itemID];
BlockSkinRenderHelper.renderMetadataBlock(liquidBlock, 0, x, y, z, renderer, world);
renderer.setRenderBounds(xMin, yMin, zMin, xMax, 0.625, zMax);
BlockSkinRenderHelper.renderMetadataBlock(liquidBlock, 0, x, y, z, renderer, world);
}*/
/*ItemStack blockToRender = new ItemStack(logic.liquid.fluidID, 1, logic.liquid.itemMeta);
if (blockToRender.itemID < 4096) //Block
{
}
else
//Item
{
Item liquidItem = Item.itemsList[blockToRender.itemID];
//ForgeHooksClient.bindTexture(liquidItem.getTextureFile(), 0);
int meta = blockToRender.getItemDamage();
BlockSkinRenderHelper.renderFakeBlock(liquidItem.getIconFromDamage(meta), x, y, z, renderer, world);
renderer.setRenderBounds(xMin, yMin, zMin, xMax, 0.625, zMax);
BlockSkinRenderHelper.renderFakeBlock(liquidItem.getIconFromDamage(meta), x, y, z, renderer, world);
}*/
//renderer.renderStandardBlock(block, x, y, z);
}
}
else if (metadata == 2)
{
renderer.setRenderBounds(0.125F, 0.125f, 0.125F, 0.875F, 0.25F, 0.875F);
renderer.renderStandardBlock(block, x, y, z);
//Outside
renderer.setRenderBounds(0.0f, 0.125, 0f, 0.125, 1.0F, 1);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.875f, 0.125, 0f, 1, 1.0F, 1);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.125f, 0.125, 0f, 0.875f, 1.0F, 0.125f);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.125f, 0.125, 0.875f, 0.875f, 1.0F, 1);
renderer.renderStandardBlock(block, x, y, z);
//Details
renderer.setRenderBounds(0.001f, 0.1245f, 0.001f, 0.1245f, 0.999f, 0.4375f);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.001f, 0.1245f, 0.5625f, 0.1245f, 0.999f, 0.999f);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.001f, 0.8755f, 0.4375f, 0.1245f, 0.999f, 0.5625f);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.001f, 0.1245f, 0.4375f, 0.1245f, 0.25F, 0.5625f);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.8755f, 0.1245f, 0f, 0.999f, 0.999f, 0.4375f);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.8755f, 0.1245f, 0.5625f, 0.999f, 0.999f, 0.999f);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.8755f, 0.8755f, 0.4375f, 0.999f, 0.999f, 0.5625f);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.8755f, 0.1245f, 0.4375f, 0.999f, 0.25F, 0.5625f);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.1245f, 0.1245f, 0.8755f, 0.4375f, 0.999f, 0.999f);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.5625f, 0.1245f, 0.8755f, 0.8755f, 0.999f, 0.999f);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.4375f, 0.8755f, 0.8755f, 0.5625f, 0.999f, 0.999f);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.4375f, 0.1245f, 0.8755f, 0.5625f, 0.2495F, 0.999f);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.1245f, 0.1245f, 0.001f, 0.4375f, 0.999f, 0.1245f);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.5625f, 0.1245f, 0.001f, 0.8755f, 0.999f, 0.1245f);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.4375f, 0.8755f, 0.001f, 0.5625f, 0.999f, 0.1245f);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.4375f, 0.1245f, 0.001f, 0.5625f, 0.25F, 0.1245f);
renderer.renderStandardBlock(block, x, y, z);
//Legs
renderer.setRenderBounds(0.0F, 0.0F, 0.0F, 0.3125F, 0.125, 0.3125F);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.6875F, 0.0F, 0.0F, 1.0F, 0.125, 0.3125F);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.0F, 0.0F, 0.6875F, 0.3125F, 0.125, 1.0F);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.6875F, 0.0F, 0.6875F, 1.0F, 0.125, 1.0F);
renderer.renderStandardBlock(block, x, y, z);
//Liquids
CastingBasinLogic logic = (CastingBasinLogic) world.getBlockTileEntity(x, y, z);
if (logic.liquid != null)
{
float minHeight = 0.25F;
float maxHeight = 0.95F;
float minX = 0.0625F;
float maxX = 0.9375F;
float minZ = 0.0625F;
float maxZ = 0.9375F;
ItemStack it = logic.getStackInSlot(0);
if(it != null){
CastingRecipe rec = TConstruct.basinCasting.getCastingRecipe(logic.liquid, it);
if(rec != null){
minHeight = rec.fluidRenderProperties.minHeight;
maxHeight = rec.fluidRenderProperties.maxHeight;
minX = rec.fluidRenderProperties.minX;
maxX = rec.fluidRenderProperties.maxX;
minZ = rec.fluidRenderProperties.minZ;
maxZ = rec.fluidRenderProperties.maxZ;
}
}
float height = (logic.getLiquidAmount() / (logic.getCapacity() * 1.05F) * 0.6875F) / maxHeight;
renderer.setRenderBounds(minX, minHeight, minZ, maxX, minHeight + height, maxZ);
Fluid fluid = logic.liquid.getFluid();
BlockSkinRenderHelper.renderLiquidBlock(fluid.getStillIcon(), fluid.getFlowingIcon(), x, y, z, renderer, world);
/*if (logic.liquid.itemID < 4096) //Block
{
Block liquidBlock = Block.blocksList[logic.liquid.itemID];
if (liquidBlock != null)
{
//ForgeHooksClient.bindTexture(liquidBlock.getTextureFile(), 0);
BlockSkinRenderHelper.renderMetadataBlock(liquidBlock, logic.liquid.itemMeta, x, y, z, renderer, world);
}
}
else
//Item
{
Item liquidItem = Item.itemsList[logic.liquid.itemID];
if (liquidItem != null)
{
//ForgeHooksClient.bindTexture(liquidItem.getTextureFile(), 0);
BlockSkinRenderHelper.renderFakeBlock(liquidItem.getIconFromDamage(logic.liquid.itemMeta), x, y, z, renderer, world);
}
}*/
}
}
else
{
renderer.setRenderBounds(0.0F, 0.75F, 0.0F, 1.0F, 1.0F, 1.0F);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.0F, 0.0F, 0.0F, 0.25F, 0.75F, 0.25F);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.75F, 0.0F, 0.0F, 1.0F, 0.75F, 0.25F);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.0F, 0.0F, 0.75F, 0.25F, 0.75F, 1.0F);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.75F, 0.0F, 0.75F, 1.0F, 0.75F, 1.0F);
renderer.renderStandardBlock(block, x, y, z);
}
}
return true;
}
| public boolean renderWorldBlock (IBlockAccess world, int x, int y, int z, Block block, int modelID, RenderBlocks renderer)
{
if (modelID == searedModel)
{
int metadata = world.getBlockMetadata(x, y, z);
if (metadata == 0)
{
//Top
renderer.setRenderBounds(0.0F, 0.625F, 0.0F, 1.0F, 0.9375F, 1.0F);
renderer.renderStandardBlock(block, x, y, z);
//Lip
renderer.setRenderBounds(0.0F, 0.9375, 0.0F, 0.0625, 1.0, 1.0F);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.0625, 0.9375, 0.9375, 0.9375, 1.0, 1.0F);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.9375, 0.9375, 0.0F, 1.0F, 1.0, 1.0F);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.0625, 0.9375, 0.0F, 0.9375, 1.0, 0.0625);
renderer.renderStandardBlock(block, x, y, z);
//Legs
renderer.setRenderBounds(0.0F, 0.0F, 0.0F, 0.3125F, 0.625F, 0.3125F);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.6875, 0.0F, 0.0F, 1.0F, 0.625F, 0.25F);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.0F, 0.0F, 0.6875, 0.3125F, 0.625F, 1.0F);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.6875, 0.0F, 0.6875, 1.0F, 0.625F, 1.0F);
renderer.renderStandardBlock(block, x, y, z);
CastingTableLogic logic = (CastingTableLogic) world.getBlockTileEntity(x, y, z);
if (logic.liquid != null)
{
float minHeight = 0.9375F;
float maxHeight = 1F;
float minX = 0.0625F;
float maxX = 0.9375F;
float minZ = 0.0625F;
float maxZ = 0.9375F;
ItemStack it = logic.getStackInSlot(0);
if(it != null){
CastingRecipe rec = TConstruct.tableCasting.getCastingRecipe(logic.liquid, it);
if(rec != null && rec.fluidRenderProperties != null){
minHeight = rec.fluidRenderProperties.minHeight;
maxHeight = rec.fluidRenderProperties.maxHeight;
minX = rec.fluidRenderProperties.minX;
maxX = rec.fluidRenderProperties.maxX;
minZ = rec.fluidRenderProperties.minZ;
maxZ = rec.fluidRenderProperties.maxZ;
}
}
float height = logic.getLiquidAmount() / (logic.getCapacity() * 1.03F) / 16F;
renderer.setRenderBounds(minX, minHeight, minZ, maxX, minHeight + height, maxZ);
Fluid fluid = logic.liquid.getFluid();
BlockSkinRenderHelper.renderLiquidBlock(fluid.getStillIcon(), fluid.getFlowingIcon(), x, y, z, renderer, world);
/*if (logic.liquid.fluidID < 4096) //Block
{
Block liquidBlock = Block.blocksList[logic.liquid.fluidID];
if (liquidBlock != null)
{
//ForgeHooksClient.bindTexture(liquidBlock.getTextureFile(), 0);
BlockSkinRenderHelper.renderMetadataBlock(liquidBlock, 0, x, y, z, renderer, world);
}
}
else
//Item
{
Item liquidItem = Item.itemsList[logic.liquid.fluidID];
if (liquidItem != null)
{
//ForgeHooksClient.bindTexture(liquidItem.getTextureFile(), 0);
BlockSkinRenderHelper.renderFakeBlock(liquidItem.getIconFromDamage(0), x, y, z, renderer, world);
}
}*/
}
}
else if (metadata == 1)
{
FaucetLogic logic = (FaucetLogic) world.getBlockTileEntity(x, y, z);
float xMin = 0.375F, zMin = 0.375F, xMax = 0.625F, zMax = 0.625F;
switch (logic.getRenderDirection())
{
case 2:
renderer.setRenderBounds(0.25, 0.25, 0.625, 0.75, 0.375, 1);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.25, 0.375, 0.625, 0.375, 0.625, 1);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.625, 0.375, 0.625, 0.75, 0.625, 1);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.375, 0.375, 0.625, 0.625, 0.625, 1);
zMin = 0.5F;
//zMin = 0.625F;
break;
case 3:
renderer.setRenderBounds(0.25, 0.25, 0, 0.75, 0.375, 0.375);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.25, 0.375, 0, 0.375, 0.625, 0.375);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.625, 0.375, 0, 0.75, 0.625, 0.375);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.375, 0.375, 0, 0.625, 0.625, 0.375);
zMax = 0.5F;
break;
case 4:
renderer.setRenderBounds(0.625, 0.25, 0.25, 1, 0.375, 0.75);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.625, 0.375, 0.25, 1, 0.625, 0.375);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.625, 0.375, 0.625, 1, 0.625, 0.75);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.625, 0.375, 0.375, 1, 0.625, 0.625);
xMin = 0.5F;
break;
case 5:
renderer.setRenderBounds(0, 0.25, 0.25, 0.375, 0.375, 0.75);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0, 0.375, 0.25, 0.375, 0.625, 0.375);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0, 0.375, 0.625, 0.375, 0.625, 0.75);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0, 0.375, 0.375, 0.375, 0.625, 0.625);
xMax = 0.5F;
break;
}
float yMin = 0F;
int uID = world.getBlockId(x, y - 1, z);
int uMeta = world.getBlockMetadata(x, y - 1, z);
if (uID == TContent.searedBlock.blockID && uMeta == 0)
{
yMin = -0.125F;
}
else if (uID == TContent.searedBlock.blockID && uMeta == 2)
{
yMin = -0.75F;
}
else if (uID == TContent.lavaTank.blockID)
{
yMin = -1F;
}
else if (uID == TContent.castingChannel.blockID)
{
yMin = -0.5F;
}
if (logic.liquid != null)
{
Fluid fluid = logic.liquid.getFluid();
renderer.setRenderBounds(xMin, yMin, zMin, xMax, 0.625, zMax);
BlockSkinRenderHelper.renderLiquidBlock(fluid.getStillIcon(), fluid.getFlowingIcon(), x, y, z, renderer, world);
/*if (fluid.canBePlacedInWorld())
{
Block liquidBlock = Block.blocksList[blockToRender.itemID];
BlockSkinRenderHelper.renderMetadataBlock(liquidBlock, 0, x, y, z, renderer, world);
renderer.setRenderBounds(xMin, yMin, zMin, xMax, 0.625, zMax);
BlockSkinRenderHelper.renderMetadataBlock(liquidBlock, 0, x, y, z, renderer, world);
}*/
/*ItemStack blockToRender = new ItemStack(logic.liquid.fluidID, 1, logic.liquid.itemMeta);
if (blockToRender.itemID < 4096) //Block
{
}
else
//Item
{
Item liquidItem = Item.itemsList[blockToRender.itemID];
//ForgeHooksClient.bindTexture(liquidItem.getTextureFile(), 0);
int meta = blockToRender.getItemDamage();
BlockSkinRenderHelper.renderFakeBlock(liquidItem.getIconFromDamage(meta), x, y, z, renderer, world);
renderer.setRenderBounds(xMin, yMin, zMin, xMax, 0.625, zMax);
BlockSkinRenderHelper.renderFakeBlock(liquidItem.getIconFromDamage(meta), x, y, z, renderer, world);
}*/
//renderer.renderStandardBlock(block, x, y, z);
}
}
else if (metadata == 2)
{
renderer.setRenderBounds(0.125F, 0.125f, 0.125F, 0.875F, 0.25F, 0.875F);
renderer.renderStandardBlock(block, x, y, z);
//Outside
renderer.setRenderBounds(0.0f, 0.125, 0f, 0.125, 1.0F, 1);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.875f, 0.125, 0f, 1, 1.0F, 1);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.125f, 0.125, 0f, 0.875f, 1.0F, 0.125f);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.125f, 0.125, 0.875f, 0.875f, 1.0F, 1);
renderer.renderStandardBlock(block, x, y, z);
//Details
renderer.setRenderBounds(0.001f, 0.1245f, 0.001f, 0.1245f, 0.999f, 0.4375f);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.001f, 0.1245f, 0.5625f, 0.1245f, 0.999f, 0.999f);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.001f, 0.8755f, 0.4375f, 0.1245f, 0.999f, 0.5625f);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.001f, 0.1245f, 0.4375f, 0.1245f, 0.25F, 0.5625f);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.8755f, 0.1245f, 0f, 0.999f, 0.999f, 0.4375f);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.8755f, 0.1245f, 0.5625f, 0.999f, 0.999f, 0.999f);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.8755f, 0.8755f, 0.4375f, 0.999f, 0.999f, 0.5625f);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.8755f, 0.1245f, 0.4375f, 0.999f, 0.25F, 0.5625f);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.1245f, 0.1245f, 0.8755f, 0.4375f, 0.999f, 0.999f);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.5625f, 0.1245f, 0.8755f, 0.8755f, 0.999f, 0.999f);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.4375f, 0.8755f, 0.8755f, 0.5625f, 0.999f, 0.999f);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.4375f, 0.1245f, 0.8755f, 0.5625f, 0.2495F, 0.999f);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.1245f, 0.1245f, 0.001f, 0.4375f, 0.999f, 0.1245f);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.5625f, 0.1245f, 0.001f, 0.8755f, 0.999f, 0.1245f);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.4375f, 0.8755f, 0.001f, 0.5625f, 0.999f, 0.1245f);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.4375f, 0.1245f, 0.001f, 0.5625f, 0.25F, 0.1245f);
renderer.renderStandardBlock(block, x, y, z);
//Legs
renderer.setRenderBounds(0.0F, 0.0F, 0.0F, 0.3125F, 0.125, 0.3125F);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.6875F, 0.0F, 0.0F, 1.0F, 0.125, 0.3125F);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.0F, 0.0F, 0.6875F, 0.3125F, 0.125, 1.0F);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.6875F, 0.0F, 0.6875F, 1.0F, 0.125, 1.0F);
renderer.renderStandardBlock(block, x, y, z);
//Liquids
CastingBasinLogic logic = (CastingBasinLogic) world.getBlockTileEntity(x, y, z);
if (logic.liquid != null)
{
float minHeight = 0.25F;
float maxHeight = 0.95F;
float minX = 0.0625F;
float maxX = 0.9375F;
float minZ = 0.0625F;
float maxZ = 0.9375F;
ItemStack it = logic.getStackInSlot(0);
if(it != null){
CastingRecipe rec = TConstruct.basinCasting.getCastingRecipe(logic.liquid, it);
if(rec != null && rec.fluidRenderProperties != null){
minHeight = rec.fluidRenderProperties.minHeight;
maxHeight = rec.fluidRenderProperties.maxHeight;
minX = rec.fluidRenderProperties.minX;
maxX = rec.fluidRenderProperties.maxX;
minZ = rec.fluidRenderProperties.minZ;
maxZ = rec.fluidRenderProperties.maxZ;
}
}
float height = (logic.getLiquidAmount() / (logic.getCapacity() * 1.05F) * 0.6875F) / maxHeight;
renderer.setRenderBounds(minX, minHeight, minZ, maxX, minHeight + height, maxZ);
Fluid fluid = logic.liquid.getFluid();
BlockSkinRenderHelper.renderLiquidBlock(fluid.getStillIcon(), fluid.getFlowingIcon(), x, y, z, renderer, world);
/*if (logic.liquid.itemID < 4096) //Block
{
Block liquidBlock = Block.blocksList[logic.liquid.itemID];
if (liquidBlock != null)
{
//ForgeHooksClient.bindTexture(liquidBlock.getTextureFile(), 0);
BlockSkinRenderHelper.renderMetadataBlock(liquidBlock, logic.liquid.itemMeta, x, y, z, renderer, world);
}
}
else
//Item
{
Item liquidItem = Item.itemsList[logic.liquid.itemID];
if (liquidItem != null)
{
//ForgeHooksClient.bindTexture(liquidItem.getTextureFile(), 0);
BlockSkinRenderHelper.renderFakeBlock(liquidItem.getIconFromDamage(logic.liquid.itemMeta), x, y, z, renderer, world);
}
}*/
}
}
else
{
renderer.setRenderBounds(0.0F, 0.75F, 0.0F, 1.0F, 1.0F, 1.0F);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.0F, 0.0F, 0.0F, 0.25F, 0.75F, 0.25F);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.75F, 0.0F, 0.0F, 1.0F, 0.75F, 0.25F);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.0F, 0.0F, 0.75F, 0.25F, 0.75F, 1.0F);
renderer.renderStandardBlock(block, x, y, z);
renderer.setRenderBounds(0.75F, 0.0F, 0.75F, 1.0F, 0.75F, 1.0F);
renderer.renderStandardBlock(block, x, y, z);
}
}
return true;
}
|
diff --git a/src/FE_SRC_COMMON/com/ForgeEssentials/chat/commands/CommandR.java b/src/FE_SRC_COMMON/com/ForgeEssentials/chat/commands/CommandR.java
index 2bf830169..38df8afdb 100644
--- a/src/FE_SRC_COMMON/com/ForgeEssentials/chat/commands/CommandR.java
+++ b/src/FE_SRC_COMMON/com/ForgeEssentials/chat/commands/CommandR.java
@@ -1,155 +1,155 @@
package com.ForgeEssentials.chat.commands;
import java.util.List;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.server.MinecraftServer;
import com.ForgeEssentials.api.permissions.PermissionsAPI;
import com.ForgeEssentials.api.permissions.query.PermQueryPlayer;
import com.ForgeEssentials.core.commands.ForgeEssentialsCommandBase;
import com.ForgeEssentials.util.FEChatFormatCodes;
import com.ForgeEssentials.util.FunctionHelper;
import com.ForgeEssentials.util.Localization;
import com.ForgeEssentials.util.OutputHandler;
public class CommandR extends ForgeEssentialsCommandBase
{
public CommandR()
{
super();
}
@Override
public String getCommandName()
{
return "r";
}
@Override
public void processCommandPlayer(EntityPlayer sender, String[] args)
{
if (args.length == 0)
{
OutputHandler.chatError(sender, Localization.get(Localization.ERROR_BADSYNTAX) + "/r <message>");
return;
}
if (args.length > 0)
{
String target = CommandMsg.getPlayerReply(sender.getCommandSenderName());
if (target == null)
{
OutputHandler.chatError(sender, Localization.get("message.error.r.noPrevious"));
return;
}
if (target.equalsIgnoreCase("server"))
{
String senderMessage = FEChatFormatCodes.GOLD + "[ me -> " + FEChatFormatCodes.PURPLE + "Server" + FEChatFormatCodes.GOLD + "] " + FEChatFormatCodes.GREY;
String receiverMessage = FEChatFormatCodes.GOLD + "[" + FEChatFormatCodes.PURPLE + "Server" + FEChatFormatCodes.GOLD + " -> me ] ";
for (int i = 0; i < args.length; i++)
{
receiverMessage += args[i];
senderMessage += args[i];
if (i != args.length - 1)
{
receiverMessage += " ";
senderMessage += " ";
}
}
MinecraftServer.getServer().sendChatToPlayer(receiverMessage);
sender.sendChatToPlayer(senderMessage);
}
else
{
- EntityPlayerMP receiver = FunctionHelper.getPlayerForName(sender, args[0]);
+ EntityPlayerMP receiver = FunctionHelper.getPlayerForName(target);
if (receiver == null)
{
OutputHandler.chatError(sender, target + " is not a valid username");
return;
}
String senderMessage = FEChatFormatCodes.GOLD + "[ me -> " + FEChatFormatCodes.GREY + receiver.getCommandSenderName() + FEChatFormatCodes.GOLD + "] " + FEChatFormatCodes.GREY;
String receiverMessage = FEChatFormatCodes.GOLD + "[" + FEChatFormatCodes.GREY + sender.getCommandSenderName() + FEChatFormatCodes.GOLD + " -> me ] " + FEChatFormatCodes.GREY;
for (int i = 0; i < args.length; i++)
{
receiverMessage += args[i];
senderMessage += args[i];
if (i != args.length - 1)
{
receiverMessage += " ";
senderMessage += " ";
}
}
sender.sendChatToPlayer(senderMessage);
receiver.sendChatToPlayer(receiverMessage);
}
}
}
@Override
public void processCommandConsole(ICommandSender sender, String[] args)
{
if (args.length == 0)
{
sender.sendChatToPlayer(Localization.ERROR_BADSYNTAX + "/msg <player> <message>");
return;
}
if (args.length > 0)
{
String target = CommandMsg.getPlayerReply("server");
if (target == null)
{
sender.sendChatToPlayer(Localization.get("message.error.r.noPrevious"));
return;
}
EntityPlayer receiver = FunctionHelper.getPlayerForName(sender, args[0]);
if (receiver == null)
{
sender.sendChatToPlayer(target + " is not a valid username");
return;
}
else
{
String senderMessage = "[ me -> " + receiver.getCommandSenderName() + "] ";
String receiverMessage = FEChatFormatCodes.GOLD + "[" + FEChatFormatCodes.PURPLE + "Server" + FEChatFormatCodes.GOLD + " -> me ] " + FEChatFormatCodes.GREY;
for (int i = 0; i < args.length; i++)
{
receiverMessage += args[i];
senderMessage += args[i];
if (i != args.length - 1)
{
receiverMessage += " ";
senderMessage += " ";
}
}
sender.sendChatToPlayer(senderMessage);
receiver.sendChatToPlayer(receiverMessage);
}
}
}
@Override
public boolean canConsoleUseCommand()
{
return true;
}
@Override
public boolean canPlayerUseCommand(EntityPlayer player)
{
return PermissionsAPI.checkPermAllowed(new PermQueryPlayer(player, getCommandPerm()));
}
@Override
public String getCommandPerm()
{
return "ForgeEssentials.Chat.commands." + getCommandName();
}
@Override
public List<?> addTabCompletionOptions(ICommandSender sender, String[] args)
{
return null;
}
}
| true | true | public void processCommandPlayer(EntityPlayer sender, String[] args)
{
if (args.length == 0)
{
OutputHandler.chatError(sender, Localization.get(Localization.ERROR_BADSYNTAX) + "/r <message>");
return;
}
if (args.length > 0)
{
String target = CommandMsg.getPlayerReply(sender.getCommandSenderName());
if (target == null)
{
OutputHandler.chatError(sender, Localization.get("message.error.r.noPrevious"));
return;
}
if (target.equalsIgnoreCase("server"))
{
String senderMessage = FEChatFormatCodes.GOLD + "[ me -> " + FEChatFormatCodes.PURPLE + "Server" + FEChatFormatCodes.GOLD + "] " + FEChatFormatCodes.GREY;
String receiverMessage = FEChatFormatCodes.GOLD + "[" + FEChatFormatCodes.PURPLE + "Server" + FEChatFormatCodes.GOLD + " -> me ] ";
for (int i = 0; i < args.length; i++)
{
receiverMessage += args[i];
senderMessage += args[i];
if (i != args.length - 1)
{
receiverMessage += " ";
senderMessage += " ";
}
}
MinecraftServer.getServer().sendChatToPlayer(receiverMessage);
sender.sendChatToPlayer(senderMessage);
}
else
{
EntityPlayerMP receiver = FunctionHelper.getPlayerForName(sender, args[0]);
if (receiver == null)
{
OutputHandler.chatError(sender, target + " is not a valid username");
return;
}
String senderMessage = FEChatFormatCodes.GOLD + "[ me -> " + FEChatFormatCodes.GREY + receiver.getCommandSenderName() + FEChatFormatCodes.GOLD + "] " + FEChatFormatCodes.GREY;
String receiverMessage = FEChatFormatCodes.GOLD + "[" + FEChatFormatCodes.GREY + sender.getCommandSenderName() + FEChatFormatCodes.GOLD + " -> me ] " + FEChatFormatCodes.GREY;
for (int i = 0; i < args.length; i++)
{
receiverMessage += args[i];
senderMessage += args[i];
if (i != args.length - 1)
{
receiverMessage += " ";
senderMessage += " ";
}
}
sender.sendChatToPlayer(senderMessage);
receiver.sendChatToPlayer(receiverMessage);
}
}
}
| public void processCommandPlayer(EntityPlayer sender, String[] args)
{
if (args.length == 0)
{
OutputHandler.chatError(sender, Localization.get(Localization.ERROR_BADSYNTAX) + "/r <message>");
return;
}
if (args.length > 0)
{
String target = CommandMsg.getPlayerReply(sender.getCommandSenderName());
if (target == null)
{
OutputHandler.chatError(sender, Localization.get("message.error.r.noPrevious"));
return;
}
if (target.equalsIgnoreCase("server"))
{
String senderMessage = FEChatFormatCodes.GOLD + "[ me -> " + FEChatFormatCodes.PURPLE + "Server" + FEChatFormatCodes.GOLD + "] " + FEChatFormatCodes.GREY;
String receiverMessage = FEChatFormatCodes.GOLD + "[" + FEChatFormatCodes.PURPLE + "Server" + FEChatFormatCodes.GOLD + " -> me ] ";
for (int i = 0; i < args.length; i++)
{
receiverMessage += args[i];
senderMessage += args[i];
if (i != args.length - 1)
{
receiverMessage += " ";
senderMessage += " ";
}
}
MinecraftServer.getServer().sendChatToPlayer(receiverMessage);
sender.sendChatToPlayer(senderMessage);
}
else
{
EntityPlayerMP receiver = FunctionHelper.getPlayerForName(target);
if (receiver == null)
{
OutputHandler.chatError(sender, target + " is not a valid username");
return;
}
String senderMessage = FEChatFormatCodes.GOLD + "[ me -> " + FEChatFormatCodes.GREY + receiver.getCommandSenderName() + FEChatFormatCodes.GOLD + "] " + FEChatFormatCodes.GREY;
String receiverMessage = FEChatFormatCodes.GOLD + "[" + FEChatFormatCodes.GREY + sender.getCommandSenderName() + FEChatFormatCodes.GOLD + " -> me ] " + FEChatFormatCodes.GREY;
for (int i = 0; i < args.length; i++)
{
receiverMessage += args[i];
senderMessage += args[i];
if (i != args.length - 1)
{
receiverMessage += " ";
senderMessage += " ";
}
}
sender.sendChatToPlayer(senderMessage);
receiver.sendChatToPlayer(receiverMessage);
}
}
}
|
diff --git a/src/team/win/WhiteBoardView.java b/src/team/win/WhiteBoardView.java
index d722fd2..6f5ec43 100644
--- a/src/team/win/WhiteBoardView.java
+++ b/src/team/win/WhiteBoardView.java
@@ -1,158 +1,158 @@
package team.win;
import java.util.LinkedList;
import java.util.List;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.view.MotionEvent;
import android.view.View;
public class WhiteBoardView extends View {
private static final float TOUCH_TOLERANCE = 4;
private final Paint mPaint = new Paint();
private final DataStore mDataStore;
private List<Point> mPoints;
private HttpService mHttpService;
private float mWidth, mHeight;
private float mStrokeWidth;
private float mX, mY;
private int mColor;
public WhiteBoardView(Context context, DataStore ds, int strokeWidth, int color) {
super(context);
mDataStore = ds;
resetPoints();
initPaintState();
setPrimColor(color);
setPrimStrokeWidth(strokeWidth);
initSize(getResources().getDisplayMetrics().widthPixels,
getResources().getDisplayMetrics().heightPixels);
mStrokeWidth = strokeWidth;
mColor = color;
}
private void initSize(float w, float h) {
mDataStore.setAspectRatio(w / h);
mWidth = w;
mHeight = h;
}
private void initPaintState() {
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
}
private void resetPoints() {
mPoints = new LinkedList<Point>();
}
public void setHttpService(HttpService httpService) {
this.mHttpService = httpService;
}
public void undo() {
if (mDataStore.size() <= 0)
return;
mDataStore.remove(mDataStore.size() - 1);
invalidate();
}
protected void onDraw(Canvas c) {
Paint temp = new Paint();
temp.setColor(Color.WHITE);
temp.setStyle(Paint.Style.FILL);
c.drawRect(0, 0, mWidth, mHeight, temp);
for (Primitive p : mDataStore.mPrimitiveList) {
mPaint.setColor(p.mColor | 0xFF000000);
mPaint.setStrokeWidth(p.mStrokeWidth * mWidth);
Path path = new Path();
Point[] points = p.mPoints.toArray(new Point[0]);
float pX, pY;
float lX = points[0].mX * mWidth;
float lY = points[0].mY * mHeight;
path.moveTo(lX, lY);
for (int i = 1; i < points.length - 1; i++) {
pX = points[i].mX * mWidth;
pY = points[i].mY * mHeight;
- path.lineTo(pX, pY);
+ path.quadTo(lX, lY, (lX + pX) / 2, (lY + pY) / 2);
lX = pX;
- lY = pX;
+ lY = pY;
}
c.drawPath(path, mPaint);
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
initSize(w, h);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touchStart(x, y);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
touchMove(x, y);
invalidate();
break;
case MotionEvent.ACTION_UP:
invalidate();
break;
}
return true;
}
private void touchStart(float x, float y) {
// WTF?
if(x < 0.0 || y < 0.0 || x > mWidth || y > mHeight)
return;
resetPoints();
mPoints.add(new Point(x / mWidth, y / mHeight));
mDataStore.add(new Primitive(mStrokeWidth / mWidth, mColor, mPoints));
}
private void touchMove(float x, float y) {
// WTF?
if(x < 0.0 || y < 0.0 || x > mWidth || y > mHeight)
return;
float dx = Math.abs(x - mX);
float dy = Math.abs(y - mY);
if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
mPoints.add(new Point(x / mWidth, y / mHeight));
mDataStore.remove(mDataStore.size() - 1);
mDataStore.add(new Primitive(mStrokeWidth / mWidth, mColor, mPoints));
if (mHttpService != null) {
mHttpService.setDataStore(mDataStore);
}
mX = x;
mY = y;
}
}
protected void setPrimColor(int c) {
mColor = c;
}
protected void setPrimStrokeWidth(int w) {
mStrokeWidth = w;
}
}
| false | true | protected void onDraw(Canvas c) {
Paint temp = new Paint();
temp.setColor(Color.WHITE);
temp.setStyle(Paint.Style.FILL);
c.drawRect(0, 0, mWidth, mHeight, temp);
for (Primitive p : mDataStore.mPrimitiveList) {
mPaint.setColor(p.mColor | 0xFF000000);
mPaint.setStrokeWidth(p.mStrokeWidth * mWidth);
Path path = new Path();
Point[] points = p.mPoints.toArray(new Point[0]);
float pX, pY;
float lX = points[0].mX * mWidth;
float lY = points[0].mY * mHeight;
path.moveTo(lX, lY);
for (int i = 1; i < points.length - 1; i++) {
pX = points[i].mX * mWidth;
pY = points[i].mY * mHeight;
path.lineTo(pX, pY);
lX = pX;
lY = pX;
}
c.drawPath(path, mPaint);
}
}
| protected void onDraw(Canvas c) {
Paint temp = new Paint();
temp.setColor(Color.WHITE);
temp.setStyle(Paint.Style.FILL);
c.drawRect(0, 0, mWidth, mHeight, temp);
for (Primitive p : mDataStore.mPrimitiveList) {
mPaint.setColor(p.mColor | 0xFF000000);
mPaint.setStrokeWidth(p.mStrokeWidth * mWidth);
Path path = new Path();
Point[] points = p.mPoints.toArray(new Point[0]);
float pX, pY;
float lX = points[0].mX * mWidth;
float lY = points[0].mY * mHeight;
path.moveTo(lX, lY);
for (int i = 1; i < points.length - 1; i++) {
pX = points[i].mX * mWidth;
pY = points[i].mY * mHeight;
path.quadTo(lX, lY, (lX + pX) / 2, (lY + pY) / 2);
lX = pX;
lY = pY;
}
c.drawPath(path, mPaint);
}
}
|
diff --git a/native/test/SalesforceSDKTest/src/com/salesforce/androidsdk/phonegap/SDKInfoPluginTest.java b/native/test/SalesforceSDKTest/src/com/salesforce/androidsdk/phonegap/SDKInfoPluginTest.java
index 9a35e3b22..9912532b0 100644
--- a/native/test/SalesforceSDKTest/src/com/salesforce/androidsdk/phonegap/SDKInfoPluginTest.java
+++ b/native/test/SalesforceSDKTest/src/com/salesforce/androidsdk/phonegap/SDKInfoPluginTest.java
@@ -1,50 +1,51 @@
/*
* Copyright (c) 2012, salesforce.com, inc.
* All rights reserved.
* Redistribution and use of this software in source and binary forms, with or
* without modification, are permitted provided that the following conditions
* are met:
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of salesforce.com, inc. nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission of salesforce.com, inc.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package com.salesforce.androidsdk.phonegap;
import java.util.List;
import android.test.InstrumentationTestCase;
/**
* Tests for SDKInfoPlugin
*
*/
public class SDKInfoPluginTest extends InstrumentationTestCase {
/**
* Test for getForcePluginsFromXML
*/
public void testGetForcePluginsFromXML() {
List<String> plugins = SDKInfoPlugin.getForcePluginsFromXML(getInstrumentation().getTargetContext());
assertEquals("Wrong number of force plugins", 3, plugins.size());
assertTrue("oauth plugin should have been returned", plugins.contains("com.salesforce.oauth"));
assertTrue("sdkinfo plugin should have been returned", plugins.contains("com.salesforce.sdkinfo"));
+ assertTrue("sfaccountmanager plugin should have been returned", plugins.contains("com.salesforce.sfaccountmanager"));
}
}
| true | true | public void testGetForcePluginsFromXML() {
List<String> plugins = SDKInfoPlugin.getForcePluginsFromXML(getInstrumentation().getTargetContext());
assertEquals("Wrong number of force plugins", 3, plugins.size());
assertTrue("oauth plugin should have been returned", plugins.contains("com.salesforce.oauth"));
assertTrue("sdkinfo plugin should have been returned", plugins.contains("com.salesforce.sdkinfo"));
}
| public void testGetForcePluginsFromXML() {
List<String> plugins = SDKInfoPlugin.getForcePluginsFromXML(getInstrumentation().getTargetContext());
assertEquals("Wrong number of force plugins", 3, plugins.size());
assertTrue("oauth plugin should have been returned", plugins.contains("com.salesforce.oauth"));
assertTrue("sdkinfo plugin should have been returned", plugins.contains("com.salesforce.sdkinfo"));
assertTrue("sfaccountmanager plugin should have been returned", plugins.contains("com.salesforce.sfaccountmanager"));
}
|
diff --git a/patientview/src/main/java/com/worthsoln/patientview/user/UserUtils.java b/patientview/src/main/java/com/worthsoln/patientview/user/UserUtils.java
index 1ec8103f..c4243d3e 100644
--- a/patientview/src/main/java/com/worthsoln/patientview/user/UserUtils.java
+++ b/patientview/src/main/java/com/worthsoln/patientview/user/UserUtils.java
@@ -1,128 +1,128 @@
/*
* PatientView
*
* Copyright (c) Worth Solutions Limited 2004-2013
*
* This file is part of PatientView.
*
* PatientView is free software: you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
* PatientView is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along with PatientView in a file
* titled COPYING. If not, see <http://www.gnu.org/licenses/>.
*
* @package PatientView
* @link http://www.patientview.org
* @author PatientView <[email protected]>
* @copyright Copyright (c) 2004-2013, Worth Solutions Limited
* @license http://www.gnu.org/licenses/gpl-3.0.html The GNU General Public License V3.0
*/
package com.worthsoln.patientview.user;
import com.worthsoln.patientview.model.User;
import com.worthsoln.patientview.model.UserMapping;
import com.worthsoln.utils.LegacySpringUtils;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
public final class UserUtils {
private static final int NHSNO_LENGTH = 10;
private static final int LAST_MAIN_DIGIT_POSITION = 8;
private static final int CHECKSUM_DIGIT_POSITION = 9;
private static final int CHECKSUM_MODULUS = 11;
private UserUtils() {
}
public static User retrieveUser(HttpServletRequest request) {
String username = null;
if (!LegacySpringUtils.getSecurityUserManager().isRolePresent("patient")) {
username = (String) request.getSession().getAttribute("userBeingViewedUsername");
}
if (username == null || "".equals(username)) {
username = LegacySpringUtils.getSecurityUserManager().getLoggedInUsername();
}
return LegacySpringUtils.getUserManager().get(username);
}
public static List<UserMapping> retrieveUserMappings(User user) {
return LegacySpringUtils.getUserManager().getUserMappings(user.getUsername());
}
public static String retrieveUsersRealUnitcodeBestGuess(String username) {
return LegacySpringUtils.getUserManager().getUsersRealUnitcodeBestGuess(username);
}
public static String retrieveUsersRealNhsnoBestGuess(String username) {
return LegacySpringUtils.getUserManager().getUsersRealNhsNoBestGuess(username);
}
public static UserMapping retrieveUserMappingsPatientEntered(User user) {
return LegacySpringUtils.getUserManager().getUserMappingPatientEntered(user);
}
public static void removePatientFromSystem(String nhsno, String unitcode) {
LegacySpringUtils.getPatientManager().removePatientFromSystem(nhsno, unitcode);
}
public static boolean isNhsNumberValid(String nhsNumber) {
return isNhsNumberValid(nhsNumber, false);
}
public static boolean isNhsNumberValid(String nhsNumber, boolean ignoreUppercaseLetters) {
// Remove all whitespace and non-visible characters such as tab, new line etc
nhsNumber = nhsNumber.replaceAll("\\s", "");
// Only permit 10 characters
if (nhsNumber.length() != NHSNO_LENGTH) {
return false;
}
boolean nhsNoContainsOnlyNumbers = nhsNumber.matches("[0-9]+");
boolean nhsNoContainsLowercaseLetters = !nhsNumber.equals(nhsNumber.toUpperCase());
if (!nhsNoContainsOnlyNumbers && ignoreUppercaseLetters && !nhsNoContainsLowercaseLetters) {
return true;
}
return isNhsChecksumValid(nhsNumber);
}
private static boolean isNhsChecksumValid(String nhsNumber) {
/**
* Generate the checksum using modulus 11 algorithm
*/
int checksum = 0;
try {
// Multiply each of the first 9 digits by 10-character position (where the left character is in position 0)
for (int i = 0; i <= LAST_MAIN_DIGIT_POSITION; i++) {
- int value = Integer.parseInt(nhsNumber.charAt(i) + "") * (10 - i);
+ int value = Integer.parseInt(nhsNumber.charAt(i) + "") * (NHSNO_LENGTH - i);
checksum += value;
}
//(modulus 11)
checksum = CHECKSUM_MODULUS - checksum % CHECKSUM_MODULUS;
if (checksum == CHECKSUM_MODULUS) {
checksum = 0;
}
// Does checksum match the 10th digit?
return checksum == Integer.parseInt(nhsNumber.substring(CHECKSUM_DIGIT_POSITION));
} catch (NumberFormatException e) {
return false; // nhsNumber contains letters
}
}
}
| true | true | private static boolean isNhsChecksumValid(String nhsNumber) {
/**
* Generate the checksum using modulus 11 algorithm
*/
int checksum = 0;
try {
// Multiply each of the first 9 digits by 10-character position (where the left character is in position 0)
for (int i = 0; i <= LAST_MAIN_DIGIT_POSITION; i++) {
int value = Integer.parseInt(nhsNumber.charAt(i) + "") * (10 - i);
checksum += value;
}
//(modulus 11)
checksum = CHECKSUM_MODULUS - checksum % CHECKSUM_MODULUS;
if (checksum == CHECKSUM_MODULUS) {
checksum = 0;
}
// Does checksum match the 10th digit?
return checksum == Integer.parseInt(nhsNumber.substring(CHECKSUM_DIGIT_POSITION));
} catch (NumberFormatException e) {
return false; // nhsNumber contains letters
}
}
| private static boolean isNhsChecksumValid(String nhsNumber) {
/**
* Generate the checksum using modulus 11 algorithm
*/
int checksum = 0;
try {
// Multiply each of the first 9 digits by 10-character position (where the left character is in position 0)
for (int i = 0; i <= LAST_MAIN_DIGIT_POSITION; i++) {
int value = Integer.parseInt(nhsNumber.charAt(i) + "") * (NHSNO_LENGTH - i);
checksum += value;
}
//(modulus 11)
checksum = CHECKSUM_MODULUS - checksum % CHECKSUM_MODULUS;
if (checksum == CHECKSUM_MODULUS) {
checksum = 0;
}
// Does checksum match the 10th digit?
return checksum == Integer.parseInt(nhsNumber.substring(CHECKSUM_DIGIT_POSITION));
} catch (NumberFormatException e) {
return false; // nhsNumber contains letters
}
}
|
diff --git a/src/de/ueller/midlet/gps/Trace.java b/src/de/ueller/midlet/gps/Trace.java
index c919663d..3a5b38b0 100644
--- a/src/de/ueller/midlet/gps/Trace.java
+++ b/src/de/ueller/midlet/gps/Trace.java
@@ -1,3429 +1,3429 @@
/*
* GpsMid - Copyright (c) 2007 Harald Mueller james22 at users dot sourceforge dot net
* See file COPYING.
*/
package de.ueller.midlet.gps;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
//#if polish.api.fileconnection
import javax.microedition.io.file.FileConnection;
//#endif
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Choice;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.List;
//#if polish.android
import android.view.WindowManager;
//#else
import javax.microedition.lcdui.game.GameCanvas;
//#endif
import javax.microedition.midlet.MIDlet;
import de.enough.polish.util.Locale;
import de.ueller.gps.SECellID;
import de.ueller.gps.GetCompass;
import de.ueller.gps.data.Legend;
import de.ueller.gps.data.Configuration;
import de.ueller.gps.data.Position;
import de.ueller.gps.data.Satellite;
import de.ueller.gps.nmea.NmeaInput;
import de.ueller.gps.sirf.SirfInput;
import de.ueller.gps.tools.DateTimeTools;
import de.ueller.gps.tools.HelperRoutines;
import de.ueller.gps.tools.IconActionPerformer;
import de.ueller.gps.tools.LayoutElement;
import de.ueller.gps.urls.Urls;
import de.ueller.gpsMid.mapData.DictReader;
//#if polish.api.osm-editing
import de.ueller.gpsMid.GUIosmWayDisplay;
import de.ueller.midlet.gps.data.EditableWay;
//#endif
import de.ueller.gpsMid.CancelMonitorInterface;
import de.ueller.gpsMid.mapData.QueueDataReader;
import de.ueller.gpsMid.mapData.QueueDictReader;
import de.ueller.gpsMid.mapData.Tile;
import de.ueller.midlet.gps.data.CellIdProvider;
import de.ueller.midlet.gps.data.CompassProvider;
import de.ueller.midlet.gps.data.Compass;
import de.ueller.midlet.gps.data.GSMCell;
import de.ueller.midlet.gps.data.Proj2D;
import de.ueller.midlet.gps.data.ProjFactory;
import de.ueller.midlet.gps.data.ProjMath;
import de.ueller.midlet.gps.data.Gpx;
import de.ueller.midlet.gps.data.IntPoint;
import de.ueller.midlet.gps.data.MoreMath;
import de.ueller.midlet.gps.data.Node;
import de.ueller.midlet.gps.data.PositionMark;
import de.ueller.midlet.gps.data.Projection;
import de.ueller.midlet.gps.data.Proj3D;
import de.ueller.midlet.gps.data.RoutePositionMark;
import de.ueller.midlet.gps.data.SECellLocLogger;
import de.ueller.midlet.gps.data.Way;
import de.ueller.midlet.gps.names.Names;
import de.ueller.midlet.gps.routing.RouteNode;
import de.ueller.midlet.gps.routing.Routing;
import de.ueller.midlet.gps.GuiMapFeatures;
import de.ueller.midlet.gps.tile.Images;
import de.ueller.midlet.gps.tile.PaintContext;
import de.ueller.midlet.gps.GpsMidDisplayable;
import de.ueller.midlet.screens.GuiWaypointPredefined;
//#if polish.android
import de.enough.polish.android.midlet.MidletBridge;
//#endif
/**
* Implements the main "Map" screen which displays the map, offers track recording etc.
* @author Harald Mueller
*
*/
public class Trace extends KeyCommandCanvas implements LocationMsgReceiver,
CompassReceiver, Runnable , GpsMidDisplayable, CompletionListener, IconActionPerformer {
/** Soft button for exiting the map screen */
protected static final int EXIT_CMD = 1;
protected static final int CONNECT_GPS_CMD = 2;
protected static final int DISCONNECT_GPS_CMD = 3;
protected static final int START_RECORD_CMD = 4;
protected static final int STOP_RECORD_CMD = 5;
protected static final int MANAGE_TRACKS_CMD = 6;
protected static final int SAVE_WAYP_CMD = 7;
protected static final int ENTER_WAYP_CMD = 8;
protected static final int MAN_WAYP_CMD = 9;
protected static final int ROUTING_TOGGLE_CMD = 10;
protected static final int CAMERA_CMD = 11;
protected static final int CLEAR_DEST_CMD = 12;
protected static final int SET_DEST_CMD = 13;
protected static final int MAPFEATURES_CMD = 14;
protected static final int RECORDINGS_CMD = 16;
protected static final int ROUTINGS_CMD = 17;
protected static final int OK_CMD =18;
protected static final int BACK_CMD = 19;
protected static final int ZOOM_IN_CMD = 20;
protected static final int ZOOM_OUT_CMD = 21;
protected static final int MANUAL_ROTATION_MODE_CMD = 22;
protected static final int TOGGLE_OVERLAY_CMD = 23;
protected static final int TOGGLE_BACKLIGHT_CMD = 24;
protected static final int TOGGLE_FULLSCREEN_CMD = 25;
protected static final int TOGGLE_MAP_PROJ_CMD = 26;
protected static final int TOGGLE_KEY_LOCK_CMD = 27;
protected static final int TOGGLE_RECORDING_CMD = 28;
protected static final int TOGGLE_RECORDING_SUSP_CMD = 29;
protected static final int RECENTER_GPS_CMD = 30;
protected static final int DATASCREEN_CMD = 31;
protected static final int OVERVIEW_MAP_CMD = 32;
protected static final int RETRIEVE_XML = 33;
protected static final int PAN_LEFT25_CMD = 34;
protected static final int PAN_RIGHT25_CMD = 35;
protected static final int PAN_UP25_CMD = 36;
protected static final int PAN_DOWN25_CMD = 37;
protected static final int PAN_LEFT2_CMD = 38;
protected static final int PAN_RIGHT2_CMD = 39;
protected static final int PAN_UP2_CMD = 40;
protected static final int PAN_DOWN2_CMD = 41;
protected static final int REFRESH_CMD = 42;
protected static final int SEARCH_CMD = 43;
protected static final int TOGGLE_AUDIO_REC = 44;
protected static final int ROUTING_START_CMD = 45;
protected static final int ROUTING_STOP_CMD = 46;
protected static final int ONLINE_INFO_CMD = 47;
protected static final int ROUTING_START_WITH_MODE_SELECT_CMD = 48;
protected static final int RETRIEVE_NODE = 49;
protected static final int ICON_MENU = 50;
protected static final int ABOUT_CMD = 51;
protected static final int SETUP_CMD = 52;
protected static final int SEND_MESSAGE_CMD = 53;
protected static final int SHOW_DEST_CMD = 54;
protected static final int EDIT_ADDR_CMD = 55;
protected static final int OPEN_URL_CMD = 56;
protected static final int SHOW_PREVIOUS_POSITION_CMD = 57;
protected static final int TOGGLE_GPS_CMD = 58;
protected static final int CELLID_LOCATION_CMD = 59;
protected static final int MANUAL_LOCATION_CMD = 60;
private final Command [] CMDS = new Command[61];
public static final int DATASCREEN_NONE = 0;
public static final int DATASCREEN_TACHO = 1;
public static final int DATASCREEN_TRIP = 2;
public static final int DATASCREEN_SATS = 3;
public final static int DISTANCE_GENERIC = 1;
public final static int DISTANCE_ALTITUDE = 2;
public final static int DISTANCE_ROAD = 3;
public final static int DISTANCE_AIR = 4;
public final static int DISTANCE_UNKNOWN = 5;
// private SirfInput si;
private LocationMsgProducer locationProducer;
private LocationMsgProducer cellIDLocationProducer = null;
private CompassProducer compassProducer = null;
private volatile int compassDirection = 0;
private volatile int compassDeviation = 0;
private volatile int compassDeviated = 0;
public byte solution = LocationMsgReceiver.STATUS_OFF;
public String solutionStr = Locale.get("solution.Off");
/** Flag if the user requested to be centered to the current GPS position (true)
* or if the user moved the map away from this position (false).
*/
public boolean gpsRecenter = true;
/** Flag if the gps position is not yet valid after recenter request
*/
public volatile boolean gpsRecenterInvalid = true;
/** Flag if the gps position is stale (last known position instead of current) after recenter request
*/
public volatile boolean gpsRecenterStale = true;
/** Flag if the map is autoZoomed
*/
public boolean autoZoomed = true;
private Position pos = new Position(0.0f, 0.0f,
PositionMark.INVALID_ELEVATION, 0.0f, 0.0f, 1,
System.currentTimeMillis());
/**
* this node contains actually RAD coordinates
* although the constructor for Node(lat, lon) requires parameters in DEC format
* - e. g. "new Node(49.328010f, 11.352556f)"
*/
public Node center = new Node(49.328010f, 11.352556f);
private Node prevPositionNode = null;
// Projection projection;
private final GpsMid parent;
public static TraceLayout tl = null;
private String lastTitleMsg;
private String currentTitleMsg;
private volatile int currentTitleMsgOpenCount = 0;
private volatile int setTitleMsgTimeout = 0;
private String lastTitleMsgClock;
private String currentAlertTitle;
private String currentAlertMessage;
private volatile int currentAlertsOpenCount = 0;
private volatile int setAlertTimeout = 0;
private long lastBackLightOnTime = 0;
private volatile static long lastUserActionTime = 0;
private long collected = 0;
public PaintContext pc;
public float scale = Configuration.getRealBaseScale();
int showAddons = 0;
/** x position display was touched last time (on pointerPressed() ) */
private static int touchX = 0;
/** y position display was touched last time (on pointerPressed() ) */
private static int touchY = 0;
/** x position display was released last time (on pointerReleased() ) */
private static int touchReleaseX = 0;
/** y position display was released last time (on pointerReleased() ) */
private static int touchReleaseY = 0;
/** center when display was touched last time (on pointerReleased() ) */
private static Node centerPointerPressedN = new Node();
private static Node pickPointStart = new Node();
private static Node pickPointEnd = new Node();
/**
* time at which a pointer press occured to determine
* single / double / long taps
*/
private long pressedPointerTime;
/**
* indicates if the next release event is valid or the corresponding pointer pressing has already been handled
*/
private volatile boolean pointerActionDone;
/** timer checking for single tap */
private volatile TimerTask singleTapTimerTask = null;
/** timer checking for long tap */
private volatile TimerTask longTapTimerTask = null;
/** timer for returning to small buttons */
private volatile TimerTask bigButtonTimerTask = null;
/**
* Indicates that there was any drag event since the last pointerPressed
*/
private static volatile boolean pointerDragged = false;
/**
* Indicates that there was a rather far drag event since the last pointerPressed
*/
private static volatile boolean pointerDraggedMuch = false;
/** indicates whether we already are checking for a single tap in the TimerTask */
private static volatile boolean checkingForSingleTap = false;
private final int DOUBLETAP_MAXDELAY = 300;
private final int LONGTAP_DELAY = 1500;
public volatile boolean routeCalc=false;
public Tile tiles[] = new Tile[6];
public Way actualSpeedLimitWay;
// this is only for visual debugging of the routing engine
Vector routeNodes = new Vector();
private long oldRecalculationTime;
private List recordingsMenu = null;
private List routingsMenu = null;
private GuiTacho guiTacho = null;
private GuiTrip guiTrip = null;
private GuiSatellites guiSatellites = null;
private GuiWaypointSave guiWaypointSave = null;
private final GuiWaypointPredefined guiWaypointPredefined = null;
private static TraceIconMenu traceIconMenu = null;
private final static Logger logger = Logger.getInstance(Trace.class, Logger.DEBUG);
//#mdebug info
public static final String statMsg[] = { "no Start1:", "no Start2:",
"to long :", "interrupt:", "checksum :", "no End1 :",
"no End2 :" };
//#enddebug
/**
* Quality of Bluetooth reception, 0..100.
*/
private byte btquality;
private int[] statRecord;
/**
* Current speed from GPS in km/h.
*/
public volatile int speed;
public volatile float fspeed;
/**
* variables for setting course from GPS movement
* TODO: make speed threshold (currently courseMinSpeed)
* user-settable by transfer mode in the style file
* and/or in user menu
*/
// was three until release 0.7; less than three allows
// for course setting even with slow walking, while
// the heuristics filter away erratic courses
// I've even tested with 0.5f with good results --jkpj
private final float courseMinSpeed = 1.5f;
private volatile int prevCourse = -1;
private volatile int secondPrevCourse = -1;
private volatile int thirdPrevCourse = -1;
/**
* Current altitude from GPS in m.
*/
public volatile int altitude;
/**
* Flag if we're speeding
*/
private volatile boolean speeding = false;
private long lastTimeOfSpeedingSound = 0;
private long startTimeOfSpeedingSign = 0;
private int speedingSpeedLimit = 0;
/**
* Current course from GPS in compass degrees, 0..359.
*/
private int course = 0;
private int coursegps = 0;
public boolean atDest = false;
public boolean movedAwayFromDest = true;
private Names namesThread;
private Urls urlsThread;
private ImageCollector imageCollector;
private QueueDataReader tileReader;
private QueueDictReader dictReader;
private final Runtime runtime = Runtime.getRuntime();
private RoutePositionMark dest = null;
public Vector route = null;
private RouteInstructions ri = null;
private boolean running = false;
private static final int CENTERPOS = Graphics.HCENTER | Graphics.VCENTER;
public Gpx gpx;
public AudioRecorder audioRec;
private static volatile Trace traceInstance = null;
private Routing routeEngine;
/*
private static Font smallBoldFont;
private static int smallBoldFontHeight;
*/
public boolean manualRotationMode = false;
public Vector locationUpdateListeners;
private Projection panProjection;
private Trace() throws Exception {
//#debug
logger.info("init Trace");
this.parent = GpsMid.getInstance();
Configuration.setHasPointerEvents(hasPointerEvents());
CMDS[EXIT_CMD] = new Command(Locale.get("generic.Exit")/*Exit*/, Command.EXIT, 2);
CMDS[REFRESH_CMD] = new Command(Locale.get("trace.Refresh")/*Refresh*/, Command.ITEM, 4);
CMDS[SEARCH_CMD] = new Command(Locale.get("generic.Search")/*Search*/, Command.OK, 1);
CMDS[CONNECT_GPS_CMD] = new Command(Locale.get("trace.StartGPS")/*Start GPS*/,Command.ITEM, 2);
CMDS[DISCONNECT_GPS_CMD] = new Command(Locale.get("trace.StopGPS")/*Stop GPS*/,Command.ITEM, 2);
CMDS[TOGGLE_GPS_CMD] = new Command(Locale.get("trace.ToggleGPS")/*Toggle GPS*/,Command.ITEM, 2);
CMDS[START_RECORD_CMD] = new Command(Locale.get("trace.StartRecord")/*Start record*/,Command.ITEM, 4);
CMDS[STOP_RECORD_CMD] = new Command(Locale.get("trace.StopRecord")/*Stop record*/,Command.ITEM, 4);
CMDS[MANAGE_TRACKS_CMD] = new Command(Locale.get("trace.ManageTracks")/*Manage tracks*/,Command.ITEM, 5);
CMDS[SAVE_WAYP_CMD] = new Command(Locale.get("trace.SaveWaypoint")/*Save waypoint*/,Command.ITEM, 7);
CMDS[ENTER_WAYP_CMD] = new Command(Locale.get("trace.EnterWaypoint")/*Enter waypoint*/,Command.ITEM, 7);
CMDS[MAN_WAYP_CMD] = new Command(Locale.get("trace.ManageWaypoints")/*Manage waypoints*/,Command.ITEM, 7);
CMDS[ROUTING_TOGGLE_CMD] = new Command(Locale.get("trace.ToggleRouting")/*Toggle routing*/,Command.ITEM, 3);
CMDS[CAMERA_CMD] = new Command(Locale.get("trace.Camera")/*Camera*/,Command.ITEM, 9);
CMDS[CLEAR_DEST_CMD] = new Command(Locale.get("trace.ClearDestination")/*Clear destination*/,Command.ITEM, 10);
CMDS[SET_DEST_CMD] = new Command(Locale.get("trace.AsDestination")/*As destination*/,Command.ITEM, 11);
CMDS[MAPFEATURES_CMD] = new Command(Locale.get("trace.MapFeatures")/*Map Features*/,Command.ITEM, 12);
CMDS[RECORDINGS_CMD] = new Command(Locale.get("trace.Recordings")/*Recordings...*/,Command.ITEM, 4);
CMDS[ROUTINGS_CMD] = new Command(Locale.get("trace.Routing3")/*Routing...*/,Command.ITEM, 3);
CMDS[OK_CMD] = new Command(Locale.get("generic.OK")/*OK*/,Command.OK, 14);
CMDS[BACK_CMD] = new Command(Locale.get("generic.Back")/*Back*/,Command.BACK, 15);
CMDS[ZOOM_IN_CMD] = new Command(Locale.get("trace.ZoomIn")/*Zoom in*/,Command.ITEM, 100);
CMDS[ZOOM_OUT_CMD] = new Command(Locale.get("trace.ZoomOut")/*Zoom out*/,Command.ITEM, 100);
CMDS[MANUAL_ROTATION_MODE_CMD] = new Command(Locale.get("trace.ManualRotation2")/*Manual rotation mode*/,Command.ITEM, 100);
CMDS[TOGGLE_OVERLAY_CMD] = new Command(Locale.get("trace.NextOverlay")/*Next overlay*/,Command.ITEM, 100);
CMDS[TOGGLE_BACKLIGHT_CMD] = new Command(Locale.get("trace.KeepBacklight")/*Keep backlight on/off*/,Command.ITEM, 100);
CMDS[TOGGLE_FULLSCREEN_CMD] = new Command(Locale.get("trace.SwitchToFullscreen")/*Switch to fullscreen*/,Command.ITEM, 100);
CMDS[TOGGLE_MAP_PROJ_CMD] = new Command(Locale.get("trace.NextMapProjection")/*Next map projection*/,Command.ITEM, 100);
CMDS[TOGGLE_KEY_LOCK_CMD] = new Command(Locale.get("trace.ToggleKeylock")/*(De)Activate Keylock*/,Command.ITEM, 100);
CMDS[TOGGLE_RECORDING_CMD] = new Command(Locale.get("trace.ToggleRecording")/*(De)Activate recording*/,Command.ITEM, 100);
CMDS[TOGGLE_RECORDING_SUSP_CMD] = new Command(Locale.get("trace.SuspendRecording")/*Suspend recording*/,Command.ITEM, 100);
CMDS[RECENTER_GPS_CMD] = new Command(Locale.get("trace.RecenterOnGPS")/*Recenter on GPS*/,Command.ITEM, 100);
CMDS[SHOW_DEST_CMD] = new Command(Locale.get("trace.ShowDestination")/*Show destination*/,Command.ITEM, 100);
CMDS[SHOW_PREVIOUS_POSITION_CMD] = new Command(Locale.get("trace.ShowPreviousPosition")/*Previous position*/,Command.ITEM, 100);
CMDS[DATASCREEN_CMD] = new Command(Locale.get("trace.Tacho")/*Tacho*/, Command.ITEM, 15);
CMDS[OVERVIEW_MAP_CMD] = new Command(Locale.get("trace.OverviewFilterMap")/*Overview/Filter map*/, Command.ITEM, 20);
CMDS[RETRIEVE_XML] = new Command(Locale.get("trace.RetrieveXML")/*Retrieve XML*/,Command.ITEM, 200);
CMDS[PAN_LEFT25_CMD] = new Command(Locale.get("trace.left25")/*left 25%*/,Command.ITEM, 100);
CMDS[PAN_RIGHT25_CMD] = new Command(Locale.get("trace.right25")/*right 25%*/,Command.ITEM, 100);
CMDS[PAN_UP25_CMD] = new Command(Locale.get("trace.up25")/*up 25%*/,Command.ITEM, 100);
CMDS[PAN_DOWN25_CMD] = new Command(Locale.get("trace.down25")/*down 25%*/,Command.ITEM, 100);
CMDS[PAN_LEFT2_CMD] = new Command(Locale.get("trace.left2")/*left 2*/,Command.ITEM, 100);
CMDS[PAN_RIGHT2_CMD] = new Command(Locale.get("trace.right2")/*right 2*/,Command.ITEM, 100);
CMDS[PAN_UP2_CMD] = new Command(Locale.get("trace.up2")/*up 2*/,Command.ITEM, 100);
CMDS[PAN_DOWN2_CMD] = new Command(Locale.get("trace.down2")/*down 2*/,Command.ITEM, 100);
CMDS[TOGGLE_AUDIO_REC] = new Command(Locale.get("trace.AudioRecording")/*Audio recording*/,Command.ITEM, 100);
CMDS[ROUTING_START_CMD] = new Command(Locale.get("trace.CalculateRoute")/*Calculate route*/,Command.ITEM, 100);
CMDS[ROUTING_STOP_CMD] = new Command(Locale.get("trace.StopRouting")/*Stop routing*/,Command.ITEM, 100);
CMDS[ONLINE_INFO_CMD] = new Command(Locale.get("trace.OnlineInfo")/*Online info*/,Command.ITEM, 100);
CMDS[ROUTING_START_WITH_MODE_SELECT_CMD] = new Command(Locale.get("trace.CalculateRoute2")/*Calculate route...*/,Command.ITEM, 100);
CMDS[RETRIEVE_NODE] = new Command(Locale.get("trace.AddPOI")/*Add POI to OSM...*/,Command.ITEM, 100);
CMDS[ICON_MENU] = new Command(Locale.get("trace.Menu")/*Menu*/,Command.OK, 100);
CMDS[SETUP_CMD] = new Command(Locale.get("trace.Setup")/*Setup*/, Command.ITEM, 25);
CMDS[ABOUT_CMD] = new Command(Locale.get("generic.About")/*About*/, Command.ITEM, 30);
//#if polish.api.wmapi
CMDS[SEND_MESSAGE_CMD] = new Command(Locale.get("trace.SendSMSMapPos")/*Send SMS (map pos)*/,Command.ITEM, 20);
//#endif
CMDS[EDIT_ADDR_CMD] = new Command(Locale.get("trace.AddAddrNode")/*Add Addr node*/,Command.ITEM,100);
CMDS[CELLID_LOCATION_CMD] = new Command(Locale.get("trace.CellidLocation")/*Set location from CellID*/,Command.ITEM,100);
CMDS[MANUAL_LOCATION_CMD] = new Command(Locale.get("trace.ManualLocation")/*Set location manually*/,Command.ITEM,100);
addAllCommands();
Configuration.loadKeyShortcuts(gameKeyCommand, singleKeyPressCommand,
repeatableKeyPressCommand, doubleKeyPressCommand, longKeyPressCommand,
nonReleasableKeyPressCommand, CMDS);
if (!Configuration.getCfgBitState(Configuration.CFGBIT_DISPLAYSIZE_SPECIFIC_DEFAULTS_DONE)) {
if (getWidth() > 219) {
// if the map display is wide enough, show the clock in the map screen by default
Configuration.setCfgBitSavedState(Configuration.CFGBIT_SHOW_CLOCK_IN_MAP, true);
// if the map display is wide enough, use big tab buttons by default
Configuration.setCfgBitSavedState(Configuration.CFGBIT_ICONMENUS_BIG_TAB_BUTTONS, true);
}
Configuration.setCfgBitSavedState(Configuration.CFGBIT_DISPLAYSIZE_SPECIFIC_DEFAULTS_DONE, true);
}
try {
startup();
} catch (Exception e) {
logger.fatal(Locale.get("trace.GotExceptionDuringStartup")/*Got an exception during startup: */ + e.getMessage());
e.printStackTrace();
return;
}
// setTitle("initTrace ready");
locationUpdateListeners = new Vector();
traceInstance = this;
}
/**
* Returns the instance of the map screen. If none exists yet,
* a new instance is generated
* @return Reference to singleton instance
*/
public static synchronized Trace getInstance() {
if (traceInstance == null) {
try {
traceInstance = new Trace();
} catch (Exception e) {
logger.exception(Locale.get("trace.FailedToInitialiseMapScreen")/*Failed to initialise Map screen*/, e);
}
}
return traceInstance;
}
public void stopCompass() {
if (compassProducer != null) {
compassProducer.close();
}
compassProducer = null;
}
public void startCompass() {
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer == null) {
compassProducer = new GetCompass();
if (!compassProducer.init(this)) {
logger.info("Failed to init compass producer");
compassProducer = null;
} else if (!compassProducer.activate(this)) {
logger.info("Failed to activate compass producer");
compassProducer = null;
}
}
}
/**
* Starts the LocationProvider in the background
*/
public void run() {
try {
if (running) {
receiveMessage(Locale.get("trace.GpsStarterRunning")/*GPS starter already running*/);
return;
}
//#debug info
logger.info("start thread init locationprovider");
if (locationProducer != null) {
receiveMessage(Locale.get("trace.LocProvRunning")/*Location provider already running*/);
return;
}
if (Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_NONE) {
receiveMessage(Locale.get("trace.NoLocProv")/*"No location provider*/);
return;
}
running=true;
startCompass();
int locprov = Configuration.getLocationProvider();
receiveMessage(Locale.get("trace.ConnectTo")/*Connect to */ + Configuration.LOCATIONPROVIDER[locprov]);
if (Configuration.getCfgBitSavedState(Configuration.CFGBIT_CELLID_STARTUP)) {
// Don't do initial lookup if we're going to start primary cellid location provider anyway
if (Configuration.getLocationProvider() != Configuration.LOCATIONPROVIDER_SECELL || !Configuration.getCfgBitState(Configuration.CFGBIT_AUTO_START_GPS)) {
commandAction(CELLID_LOCATION_CMD);
}
}
switch (locprov) {
case Configuration.LOCATIONPROVIDER_SIRF:
locationProducer = new SirfInput();
break;
case Configuration.LOCATIONPROVIDER_NMEA:
locationProducer = new NmeaInput();
break;
case Configuration.LOCATIONPROVIDER_SECELL:
if (cellIDLocationProducer != null) {
cellIDLocationProducer.close();
}
locationProducer = new SECellID();
break;
case Configuration.LOCATIONPROVIDER_JSR179:
//#if polish.api.locationapi
try {
String jsr179Version = null;
try {
jsr179Version = System.getProperty("microedition.location.version");
} catch (RuntimeException re) {
// Some phones throw exceptions if trying to access properties that don't
// exist, so we have to catch these and just ignore them.
} catch (Exception e) {
// As above
}
//#if polish.android
// FIXME current (2010-06) android j2mepolish doesn't give this info
//#else
if (jsr179Version != null && jsr179Version.length() > 0) {
//#endif
Class jsr179Class = Class.forName("de.ueller.gps.location.JSR179Input");
locationProducer = (LocationMsgProducer) jsr179Class.newInstance();
//#if polish.android
//#else
}
//#endif
} catch (ClassNotFoundException cnfe) {
locationDecoderEnd();
logger.exception(Locale.get("trace.NoJSR179Support")/*Your phone does not support JSR179, please use a different location provider*/, cnfe);
running = false;
return;
}
//#else
// keep Eclipse happy
if (true) {
logger.error(Locale.get("trace.JSR179NotCompiledIn")/*JSR179 is not compiled in this version of GpsMid*/);
running = false;
return;
}
//#endif
break;
}
//#if polish.api.fileconnection
/**
* Allow for logging the raw data coming from the gps
*/
String url = Configuration.getGpsRawLoggerUrl();
//logger.error("Raw logging url: " + url);
if (url != null) {
try {
if (Configuration.getGpsRawLoggerEnable()) {
logger.info("Raw Location logging to: " + url);
url += "rawGpsLog" + HelperRoutines.formatSimpleDateNow() + ".txt";
//#if polish.android
de.enough.polish.android.io.Connection logCon = Connector.open(url);
//#else
javax.microedition.io.Connection logCon = Connector.open(url);
//#endif
if (logCon instanceof FileConnection) {
FileConnection fileCon = (FileConnection)logCon;
if (!fileCon.exists()) {
fileCon.create();
}
locationProducer.enableRawLogging(((FileConnection)logCon).openOutputStream());
} else {
logger.info("Raw logging of NMEA is only to filesystem supported");
}
}
/**
* Help out the OpenCellId.org project by gathering and logging
* data of cell ids together with current Gps location. This information
* can then be uploaded to their web site to determine the position of the
* cell towers. It currently only works for SE phones
*/
if (Configuration.getCfgBitState(Configuration.CFGBIT_CELLID_LOGGING)) {
SECellLocLogger secl = new SECellLocLogger();
if (secl.init()) {
locationProducer.addLocationMsgReceiver(secl);
}
}
} catch (IOException ioe) {
logger.exception(Locale.get("trace.CouldntOpenFileForRawLogging")/*Could not open file for raw logging of Gps data*/,ioe);
} catch (SecurityException se) {
logger.error(Locale.get("trace.PermissionWritingDataDenied")/*Permission to write data for NMEA raw logging was denied*/);
}
}
//#endif
if (locationProducer == null) {
logger.error(Locale.get("trace.ChooseDiffLocMethod")/*Your phone does not seem to support this method of location input, please choose a different one*/);
running = false;
return;
}
if (!locationProducer.init(this)) {
logger.info("Failed to initialise location producer");
running = false;
return;
}
if (!locationProducer.activate(this)) {
logger.info("Failed to activate location producer");
running = false;
return;
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_SND_CONNECT)) {
GpsMid.mNoiseMaker.playSound("CONNECT");
}
//#debug debug
logger.debug("rm connect, add disconnect");
removeCommand(CMDS[CONNECT_GPS_CMD]);
addCommand(CMDS[DISCONNECT_GPS_CMD]);
//#debug info
logger.info("end startLocationPovider thread");
// setTitle("lp="+Configuration.getLocationProvider() + " " + Configuration.getBtUrl());
} catch (SecurityException se) {
/**
* The application was not permitted to connect to the required resources
* Not much we can do here other than gracefully shutdown the thread *
*/
} catch (OutOfMemoryError oome) {
logger.fatal(Locale.get("trace.TraceThreadCrashOOM")/*Trace thread crashed as out of memory: */ + oome.getMessage());
oome.printStackTrace();
} catch (Exception e) {
logger.fatal(Locale.get("trace.TraceThreadCrashWith")/*Trace thread crashed unexpectedly with error */ + e.getMessage());
e.printStackTrace();
} finally {
running = false;
}
running = false;
}
// add the command only if icon menus are not used
public void addCommand(Command c) {
if (!Configuration.getCfgBitState(Configuration.CFGBIT_ICONMENUS)) {
super.addCommand(c);
}
}
public RoutePositionMark getDest() {
return dest;
}
// remove the command only if icon menus are not used
public void removeCommand(Command c) {
if (!Configuration.getCfgBitState(Configuration.CFGBIT_ICONMENUS)) {
super.removeCommand(c);
}
}
public synchronized void pause() {
logger.debug("Pausing application");
if (imageCollector != null) {
imageCollector.suspend();
}
if (locationProducer != null) {
locationProducer.close();
} else {
return;
}
int polling = 0;
while ((locationProducer != null) && (polling < 7)) {
polling++;
try {
wait(200);
} catch (InterruptedException e) {
break;
}
}
if (locationProducer != null) {
logger.error(Locale.get("trace.LocationProducerTookTooLong")/*LocationProducer took too long to close, giving up*/);
}
}
public void resume() {
logger.debug("resuming application");
if (imageCollector != null) {
imageCollector.resume();
}
Thread thread = new Thread(this,"LocationProducer init");
thread.start();
}
public void autoRouteRecalculate() {
if ( gpsRecenter && Configuration.getCfgBitState(Configuration.CFGBIT_ROUTE_AUTO_RECALC) ) {
if (Math.abs(System.currentTimeMillis()-oldRecalculationTime) >= 7000 ) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_SND_ROUTINGINSTRUCTIONS)) {
GpsMid.mNoiseMaker.playSound(RouteSyntax.getInstance().getRecalculationSound(), (byte) 5, (byte) 1 );
}
//#debug debug
logger.debug("autoRouteRecalculate");
// recalculate route
commandAction(ROUTING_START_CMD);
}
}
}
public boolean isGpsConnected() {
return (locationProducer != null && solution != LocationMsgReceiver.STATUS_OFF);
}
/**
* Adds all commands for a normal menu.
*/
public void addAllCommands() {
addCommand(CMDS[EXIT_CMD]);
addCommand(CMDS[SEARCH_CMD]);
if (isGpsConnected()) {
addCommand(CMDS[DISCONNECT_GPS_CMD]);
} else {
addCommand(CMDS[CONNECT_GPS_CMD]);
}
addCommand(CMDS[MANAGE_TRACKS_CMD]);
addCommand(CMDS[MAN_WAYP_CMD]);
addCommand(CMDS[ROUTINGS_CMD]);
addCommand(CMDS[RECORDINGS_CMD]);
addCommand(CMDS[MAPFEATURES_CMD]);
addCommand(CMDS[DATASCREEN_CMD]);
addCommand(CMDS[OVERVIEW_MAP_CMD]);
//#if polish.api.online
addCommand(CMDS[ONLINE_INFO_CMD]);
//#if polish.api.osm-editing
addCommand(CMDS[RETRIEVE_XML]);
addCommand(CMDS[RETRIEVE_NODE]);
addCommand(CMDS[EDIT_ADDR_CMD]);
//#endif
//#endif
addCommand(CMDS[SETUP_CMD]);
addCommand(CMDS[ABOUT_CMD]);
if (Configuration.getCfgBitState(Configuration.CFGBIT_ICONMENUS)) {
if (!Configuration.getCfgBitState(Configuration.CFGBIT_FULLSCREEN)) {
super.addCommand(CMDS[ICON_MENU]);
}
}
setCommandListener(this);
}
/**
* This method must remove all commands that were added by addAllCommands().
*/
public void removeAllCommands() {
//setCommandListener(null);
/* Although j2me documentation says removeCommand for a non-attached command is allowed
* this would crash MicroEmulator. Thus we only remove the commands attached.
*/
removeCommand(CMDS[EXIT_CMD]);
removeCommand(CMDS[SEARCH_CMD]);
if (isGpsConnected()) {
removeCommand(CMDS[DISCONNECT_GPS_CMD]);
} else {
removeCommand(CMDS[CONNECT_GPS_CMD]);
}
removeCommand(CMDS[MANAGE_TRACKS_CMD]);
removeCommand(CMDS[MAN_WAYP_CMD]);
removeCommand(CMDS[MAPFEATURES_CMD]);
removeCommand(CMDS[RECORDINGS_CMD]);
removeCommand(CMDS[ROUTINGS_CMD]);
removeCommand(CMDS[DATASCREEN_CMD]);
removeCommand(CMDS[OVERVIEW_MAP_CMD]);
//#if polish.api.online
removeCommand(CMDS[ONLINE_INFO_CMD]);
//#if polish.api.osm-editing
removeCommand(CMDS[RETRIEVE_XML]);
removeCommand(CMDS[RETRIEVE_NODE]);
removeCommand(CMDS[EDIT_ADDR_CMD]);
//#endif
//#endif
removeCommand(CMDS[SETUP_CMD]);
removeCommand(CMDS[ABOUT_CMD]);
removeCommand(CMDS[CELLID_LOCATION_CMD]);
removeCommand(CMDS[MANUAL_LOCATION_CMD]);
if (Configuration.getCfgBitState(Configuration.CFGBIT_ICONMENUS)) {
if (!Configuration.getCfgBitState(Configuration.CFGBIT_FULLSCREEN)) {
super.removeCommand(CMDS[ICON_MENU]);
}
}
}
/** Sets the Canvas to fullScreen or windowed mode
* when icon menus are active the Menu command gets removed
* so the Canvas will not unhide the menu bar first when pressing fire (e.g. on SE mobiles)
*/
public void setFullScreenMode(boolean fullScreen) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_ICONMENUS)) {
//#ifndef polish.android
if (fullScreen) {
super.removeCommand(CMDS[ICON_MENU]);
} else
//#endif
{
super.addCommand(CMDS[ICON_MENU]);
}
}
//#if polish.android
if (fullScreen) {
MidletBridge.instance.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
} else {
MidletBridge.instance.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
//#else
super.setFullScreenMode(fullScreen);
//#endif
}
private void commandAction(int actionId) {
commandAction(CMDS[actionId], null);
}
public void commandAction(Command c, Displayable d) {
updateLastUserActionTime();
try {
if((keyboardLocked) && (d != null)) {
// show alert in keypressed() that keyboard is locked
keyPressed(0);
return;
}
if ((c == CMDS[PAN_LEFT25_CMD]) || (c == CMDS[PAN_RIGHT25_CMD])
|| (c == CMDS[PAN_UP25_CMD]) || (c == CMDS[PAN_DOWN25_CMD])
|| (c == CMDS[PAN_LEFT2_CMD]) || (c == CMDS[PAN_RIGHT2_CMD])
|| (c == CMDS[PAN_UP2_CMD]) || (c == CMDS[PAN_DOWN2_CMD])) {
int panX = 0; int panY = 0;
int courseDiff = 0;
int backLightLevelDiff = 0;
if (c == CMDS[PAN_LEFT25_CMD]) {
panX = -25;
} else if (c == CMDS[PAN_RIGHT25_CMD]) {
panX = 25;
} else if (c == CMDS[PAN_UP25_CMD]) {
panY = -25;
} else if (c == CMDS[PAN_DOWN25_CMD]) {
panY = 25;
} else if (c == CMDS[PAN_LEFT2_CMD]) {
if (TrackPlayer.isPlaying) {
TrackPlayer.slower();
} else if (manualRotationMode) {
courseDiff=-5;
} else {
panX = -2;
}
backLightLevelDiff = -25;
} else if (c == CMDS[PAN_RIGHT2_CMD]) {
if (TrackPlayer.isPlaying) {
TrackPlayer.faster();
} else if (manualRotationMode) {
courseDiff=5;
} else {
panX = 2;
}
backLightLevelDiff = 25;
} else if (c == CMDS[PAN_UP2_CMD]) {
if (route!=null && Configuration.getCfgBitState(Configuration.CFGBIT_ROUTE_BROWSING)) {
RouteInstructions.toNextInstruction(1);
} else {
panY = -2;
}
} else if (c == CMDS[PAN_DOWN2_CMD]) {
if (route!=null && Configuration.getCfgBitState(Configuration.CFGBIT_ROUTE_BROWSING)) {
RouteInstructions.toNextInstruction(-1);
} else {
panY = 2;
}
}
if (backLightLevelDiff !=0 && System.currentTimeMillis() < (lastBackLightOnTime + 2500)) {
// turn backlight always on when dimming
Configuration.setCfgBitState(Configuration.CFGBIT_BACKLIGHT_ON, true, false);
lastBackLightOnTime = System.currentTimeMillis();
Configuration.addToBackLightLevel(backLightLevelDiff);
parent.showBackLightLevel();
} else if (imageCollector != null) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null) {
// set compass compassDeviation
if (compassDeviation == 360) {
compassDeviation = 0;
} else {
compassDeviation += courseDiff;
compassDeviation %= 360;
if (course < 0) {
course += 360;
}
}
imageCollector.getCurrentProjection().pan(center, panX, panY);
} else {
// manual rotation
if (courseDiff == 360) {
course = 0; //N
} else {
course += courseDiff;
course %= 360;
if (course < 0) {
course += 360;
}
}
if (panX != 0 || panY != 0) {
gpsRecenter = false;
}
imageCollector.getCurrentProjection().pan(center, panX, panY);
}
}
gpsRecenter = false;
return;
}
if (c == CMDS[EXIT_CMD]) {
// FIXME: This is a workaround. It would be better if recording
// would not be stopped when leaving the map.
if (Legend.isValid && gpx.isRecordingTrk()) {
alert(Locale.get("trace.RecordMode")/*Record Mode*/, Locale.get("trace.PleaseStopRecording")/*Please stop recording before exit.*/ , 2500);
return;
}
if (Legend.isValid) {
pause();
}
parent.exit();
return;
}
if (c == CMDS[START_RECORD_CMD]) {
try {
gpx.newTrk(false);
alert(Locale.get("trace.GpsRecording")/*Gps track recording*/, Locale.get("trace.StartingToRecord")/*Starting to record*/, 1250);
} catch (RuntimeException e) {
receiveMessage(e.getMessage());
}
recordingsMenu = null; // refresh recordings menu
return;
}
if (c == CMDS[STOP_RECORD_CMD]) {
gpx.saveTrk(false);
alert(Locale.get("trace.GpsRecording")/*Gps track recording*/, Locale.get("trace.StoppingToRecord")/*Stopping to record*/, 1250);
recordingsMenu = null; // refresh recordings menu
return;
}
if (c == CMDS[MANAGE_TRACKS_CMD]) {
if (gpx.isRecordingTrk() && !gpx.isRecordingTrkSuspended()) {
// FIXME it's not strictly necessary to stop, after there are translation for the pause
// message, change to Locale.get("trace.YouNeedStopPauseRecording")
alert(Locale.get("trace.RecordMode")/*Record Mode*/, Locale.get("trace.YouNeedStopRecording")/*You need to stop recording before managing tracks.*/ , 4000);
return;
}
GuiGpx guiGpx = new GuiGpx(this);
guiGpx.show();
return;
}
if (c == CMDS[REFRESH_CMD]) {
repaint();
return;
}
if (c == CMDS[CONNECT_GPS_CMD]) {
if (locationProducer == null) {
if (TrackPlayer.isPlaying) {
TrackPlayer.getInstance().stop();
alert(Locale.get("trace.Trackplayer")/*Trackplayer*/, Locale.get("trace.PlayingStopped")/*Playing stopped for connecting to GPS*/, 2500);
}
Thread thread = new Thread(this,"LocationProducer init");
thread.start();
}
return;
}
if (c == CMDS[DISCONNECT_GPS_CMD]) {
if (locationProducer != null) {
locationProducer.close();
}
return;
}
if (c == CMDS[TOGGLE_GPS_CMD]) {
if (isGpsConnected()) {
commandAction(DISCONNECT_GPS_CMD);
} else {
commandAction(CONNECT_GPS_CMD);
}
return;
}
if (c == CMDS[SEARCH_CMD]) {
GuiSearch guiSearch = new GuiSearch(this);
guiSearch.show();
return;
}
if (c == CMDS[ENTER_WAYP_CMD]) {
if (gpx.isLoadingWaypoints()) {
showAlertLoadingWpt();
} else {
GuiWaypointEnter gwpe = new GuiWaypointEnter(this);
gwpe.show();
}
return;
}
if (c == CMDS[MAN_WAYP_CMD]) {
if (gpx.isLoadingWaypoints()) {
showAlertLoadingWpt();
} else {
GuiWaypoint gwp = new GuiWaypoint(this);
gwp.show();
}
return;
}
if (c == CMDS[MAPFEATURES_CMD]) {
GuiMapFeatures gmf = new GuiMapFeatures(this);
gmf.show();
repaint();
return;
}
if (c == CMDS[OVERVIEW_MAP_CMD]) {
GuiOverviewElements ovEl = new GuiOverviewElements(this);
ovEl.show();
repaint();
return;
}
//#if polish.api.wmapi
if (c == CMDS[SEND_MESSAGE_CMD]) {
GuiSendMessage sendMsg = new GuiSendMessage(this);
sendMsg.show();
repaint();
return;
}
//#endif
if (c == CMDS[RECORDINGS_CMD]) {
if (recordingsMenu == null) {
boolean hasJSR120 = Configuration.hasDeviceJSR120();
int noElements = 3;
//#if polish.api.mmapi
noElements += 2;
//#endif
//#if polish.api.wmapi
if (hasJSR120) {
noElements++;
}
//#endif
int idx = 0;
String[] elements = new String[noElements];
if (gpx.isRecordingTrk()) {
elements[idx++] = Locale.get("trace.StopGpxTracklog")/*Stop Gpx tracklog*/;
} else {
elements[idx++] = Locale.get("trace.StartGpxTracklog")/*Start Gpx tracklog*/;
}
elements[idx++] = Locale.get("trace.SaveWaypoint")/*Save waypoint*/;
elements[idx++] = Locale.get("trace.EnterWaypoint")/*Enter waypoint*/;
//#if polish.api.mmapi
elements[idx++] = Locale.get("trace.TakePictures")/*Take pictures*/;
if (audioRec.isRecording()) {
elements[idx++] = Locale.get("trace.StopAudioRecording")/*Stop audio recording*/;
} else {
elements[idx++] = Locale.get("trace.StartAudioRecording")/*Start audio recording*/;
}
//#endif
//#if polish.api.wmapi
if (hasJSR120) {
elements[idx++] = Locale.get("trace.SendSMSMapPos")/*Send SMS (map pos)*/;
}
//#endif
recordingsMenu = new List(Locale.get("trace.Recordings")/*Recordings...*/,Choice.IMPLICIT,elements,null);
recordingsMenu.addCommand(CMDS[OK_CMD]);
recordingsMenu.addCommand(CMDS[BACK_CMD]);
recordingsMenu.setSelectCommand(CMDS[OK_CMD]);
parent.show(recordingsMenu);
recordingsMenu.setCommandListener(this);
}
if (recordingsMenu != null) {
recordingsMenu.setSelectedIndex(0, true);
parent.show(recordingsMenu);
}
return;
}
if (c == CMDS[ROUTINGS_CMD]) {
if (routingsMenu == null) {
String[] elements = new String[4];
if (routeCalc || route != null) {
elements[0] = Locale.get("trace.StopRouting")/*Stop routing*/;
} else {
elements[0] = Locale.get("trace.CalculateRoute")/*Calculate route*/;
}
elements[1] = Locale.get("trace.SetDestination")/*Set destination*/;
elements[2] = Locale.get("trace.ShowDestination")/*Show destination*/;
elements[3] = Locale.get("trace.ClearDestination")/*Clear destination*/;
routingsMenu = new List(Locale.get("trace.Routing2")/*Routing..*/, Choice.IMPLICIT, elements, null);
routingsMenu.addCommand(CMDS[OK_CMD]);
routingsMenu.addCommand(CMDS[BACK_CMD]);
routingsMenu.setSelectCommand(CMDS[OK_CMD]);
routingsMenu.setCommandListener(this);
}
if (routingsMenu != null) {
routingsMenu.setSelectedIndex(0, true);
parent.show(routingsMenu);
}
return;
}
if (c == CMDS[SAVE_WAYP_CMD]) {
if (gpx.isLoadingWaypoints()) {
showAlertLoadingWpt();
} else {
PositionMark posMark = null;
if (gpsRecenter) {
// TODO: If we lose the fix the old position and height
// will be used silently -> we should inform the user
// here that we have no fix - he may not know what's going on.
posMark = new PositionMark(center.radlat, center.radlon,
(int)pos.altitude, pos.timeMillis,
/* fix */ (byte)-1, /* sats */ (byte)-1,
/* sym */ (byte)-1, /* type */ (byte)-1);
} else {
// Cursor does not point to current position
// -> it does not make sense to add elevation and GPS fix info.
posMark = new PositionMark(center.radlat, center.radlon,
PositionMark.INVALID_ELEVATION,
pos.timeMillis, /* fix */ (byte)-1,
/* sats */ (byte)-1, /* sym */ (byte)-1,
/* type */ (byte)-1);
}
/*
if (Configuration.getCfgBitState(Configuration.CFGBIT_WAYPT_OFFER_PREDEF)) {
if (guiWaypointPredefined == null) {
guiWaypointPredefined = new GuiWaypointPredefined(this);
}
if (guiWaypointPredefined != null) {
guiWaypointPredefined.setData(posMark);
guiWaypointPredefined.show();
}
} else {
*/
showGuiWaypointSave(posMark);
//}
}
return;
}
if (c == CMDS[ONLINE_INFO_CMD]) {
//#if polish.api.online
Position oPos = new Position(center.radlat, center.radlon,
0.0f, 0.0f, 0.0f, 0, 0);
GuiWebInfo gWeb = new GuiWebInfo(this, oPos, pc);
gWeb.show();
//#else
alert(Locale.get("trace.NoOnlineCapa")/*No online capabilites*/,
Locale.get("trace.SetAppGeneric")/*Set app=GpsMid-Generic-editing and enableEditing=true in*/ +
Locale.get("trace.PropertiesFile")/*.properties file and recreate GpsMid with Osm2GpsMid.*/,
Alert.FOREVER);
//#endif
}
if (c == CMDS[BACK_CMD]) {
show();
return;
}
if (c == CMDS[OK_CMD]) {
if (d == recordingsMenu) {
switch (recordingsMenu.getSelectedIndex()) {
case 0: {
if ( gpx.isRecordingTrk() ) {
commandAction(STOP_RECORD_CMD);
if (! Configuration.getCfgBitState(Configuration.CFGBIT_GPX_ASK_TRACKNAME_STOP)) {
show();
}
} else {
commandAction(START_RECORD_CMD);
if (! Configuration.getCfgBitState(Configuration.CFGBIT_GPX_ASK_TRACKNAME_START)) {
show();
}
}
break;
}
case 1: {
commandAction(SAVE_WAYP_CMD);
break;
}
case 2: {
commandAction(ENTER_WAYP_CMD);
break;
}
//#if polish.api.mmapi
case 3: {
commandAction(CAMERA_CMD);
break;
}
case 4: {
show();
commandAction(TOGGLE_AUDIO_REC);
break;
}
//#endif
//#if polish.api.mmapi && polish.api.wmapi
case 5: {
commandAction(SEND_MESSAGE_CMD);
break;
}
//#elif polish.api.wmapi
case 3: {
commandAction(SEND_MESSAGE_CMD);
break;
}
//#endif
}
}
if (d == routingsMenu) {
show();
switch (routingsMenu.getSelectedIndex()) {
case 0: {
if (routeCalc || route != null) {
commandAction(ROUTING_STOP_CMD);
} else {
commandAction(ROUTING_START_WITH_MODE_SELECT_CMD);
}
break;
}
case 1: {
commandAction(SET_DEST_CMD);
break;
}
case 2: {
commandAction(SHOW_DEST_CMD);
break;
}
case 3: {
commandAction(CLEAR_DEST_CMD);
break;
}
}
}
return;
}
//#if polish.api.mmapi
if (c == CMDS[CAMERA_CMD]) {
try {
Class GuiCameraClass = Class.forName("de.ueller.midlet.gps.GuiCamera");
Object GuiCameraObject = GuiCameraClass.newInstance();
GuiCameraInterface cam = (GuiCameraInterface)GuiCameraObject;
cam.init(this);
cam.show();
} catch (ClassNotFoundException cnfe) {
logger.exception(Locale.get("trace.YourPhoneNoCamSupport")/*Your phone does not support the necessary JSRs to use the camera*/, cnfe);
}
return;
}
if (c == CMDS[TOGGLE_AUDIO_REC]) {
if (audioRec.isRecording()) {
audioRec.stopRecord();
} else {
audioRec.startRecorder();
}
recordingsMenu = null; // refresh recordings menu
return;
}
//#endif
if (c == CMDS[ROUTING_TOGGLE_CMD]) {
if (routeCalc || route != null) {
commandAction(ROUTING_STOP_CMD);
} else {
commandAction(ROUTING_START_WITH_MODE_SELECT_CMD);
}
return;
}
if (c == CMDS[ROUTING_START_WITH_MODE_SELECT_CMD]) {
gpsRecenter = true;
gpsRecenterInvalid = true;
gpsRecenterStale = true;
GuiRoute guiRoute = new GuiRoute(this, false);
if (Configuration.getCfgBitSavedState(Configuration.CFGBIT_DONT_ASK_FOR_ROUTING_OPTIONS)) {
commandAction(ROUTING_START_CMD);
} else {
guiRoute.show();
}
return;
}
if (c == CMDS[ROUTING_START_CMD]) {
if (! routeCalc || RouteLineProducer.isRunning()) {
routeCalc = true;
if (Configuration.getContinueMapWhileRouteing() != Configuration.continueMap_Always ) {
stopImageCollector();
}
RouteInstructions.resetOffRoute(route, center);
// center of the map is the route source
RoutePositionMark routeSource = new RoutePositionMark(center.radlat, center.radlon);
logger.info("Routing source: " + routeSource);
routeNodes=new Vector();
routeEngine = new Routing(tiles, this);
routeEngine.solve(routeSource, dest);
// resume();
}
routingsMenu = null; // refresh routingsMenu
return;
}
if (c == CMDS[ROUTING_STOP_CMD]) {
NoiseMaker.stopPlayer();
if (routeCalc) {
if (routeEngine != null) {
routeEngine.cancelRouting();
}
alert(Locale.get("trace.RouteCalculation")/*Route Calculation*/, Locale.get("trace.Cancelled")/*Cancelled*/, 1500);
} else {
alert(Locale.get("trace.Routing")/*Routing*/, Locale.get("generic.Off")/*Off*/, 750);
}
endRouting();
routingsMenu = null; // refresh routingsMenu
// redraw immediately
synchronized (this) {
if (imageCollector != null) {
imageCollector.newDataReady();
}
}
routingsMenu = null; // refresh routingsMenu
return;
}
if (c == CMDS[ZOOM_IN_CMD]) {
scale = scale / 1.5f;
autoZoomed = false;
return;
}
if (c == CMDS[ZOOM_OUT_CMD]) {
scale = scale * 1.5f;
autoZoomed = false;
return;
}
if (c == CMDS[MANUAL_ROTATION_MODE_CMD]) {
manualRotationMode = !manualRotationMode;
if (manualRotationMode) {
if (hasPointerEvents()) {
alert(Locale.get("trace.ManualRotation")/*Manual Rotation*/, Locale.get("trace.ChangeCourse")/*Change course with zoom buttons*/, 3000);
} else {
alert(Locale.get("trace.ManualRotation")/*Manual Rotation*/, Locale.get("trace.ChangeCourseWithLeftRightKeys")/*Change course with left/right keys*/, 3000);
}
} else {
alert(Locale.get("trace.ManualRotation")/*Manual Rotation*/, Locale.get("generic.Off")/*Off*/, 750);
}
return;
}
if (c == CMDS[TOGGLE_OVERLAY_CMD]) {
showAddons++;
repaint();
return;
}
if (c == CMDS[TOGGLE_BACKLIGHT_CMD]) {
// toggle Backlight
Configuration.setCfgBitState(Configuration.CFGBIT_BACKLIGHT_ON,
!(Configuration.getCfgBitState(Configuration.CFGBIT_BACKLIGHT_ON)),
false);
lastBackLightOnTime = System.currentTimeMillis();
parent.showBackLightLevel();
return;
}
if (c == CMDS[TOGGLE_FULLSCREEN_CMD]) {
boolean fullScreen = !Configuration.getCfgBitState(Configuration.CFGBIT_FULLSCREEN);
Configuration.setCfgBitState(Configuration.CFGBIT_FULLSCREEN, fullScreen, false);
setFullScreenMode(fullScreen);
return;
}
if (c == CMDS[TOGGLE_MAP_PROJ_CMD]) {
if (manualRotationMode) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null) {
compassDeviation = 0;
} else {
course = 0;
}
alert(Locale.get("trace.ManualRotation"), Locale.get("trace.ManualToNorth"), 750);
} else {
// FIXME rename string to generic
alert(Locale.get("guidiscover.MapProjection")/*Map Projection*/, ProjFactory.nextProj(), 750);
}
// redraw immediately
synchronized (this) {
if (imageCollector != null) {
imageCollector.newDataReady();
}
}
return;
}
if (c == CMDS[TOGGLE_KEY_LOCK_CMD]) {
keyboardLocked = !keyboardLocked;
if (keyboardLocked) {
// show alert that keys are locked
keyPressed(0);
} else {
alert(Locale.get("trace.GpsMid")/*GpsMid*/, hasPointerEvents() ? Locale.get("trace.KeysAndTouchscreenUnlocked")/*Keys and touch screen unlocked*/ : Locale.get("trace.KeysUnlocked")/*Keys unlocked*/, 1000);
}
return;
}
if (c == CMDS[TOGGLE_RECORDING_CMD]) {
if ( gpx.isRecordingTrk() ) {
commandAction(STOP_RECORD_CMD);
} else {
commandAction(START_RECORD_CMD);
}
return;
}
if (c == CMDS[TOGGLE_RECORDING_SUSP_CMD]) {
if (gpx.isRecordingTrk()) {
if ( gpx.isRecordingTrkSuspended() ) {
alert(Locale.get("trace.GpsRecording")/*Gps track recording*/, Locale.get("trace.ResumingRecording")/*Resuming recording*/, 1000);
gpx.resumeTrk();
} else {
alert(Locale.get("trace.GpsRecording")/*Gps track recording*/, Locale.get("trace.SuspendingRecording")/*Suspending recording*/, 1000);
gpx.suspendTrk();
}
}
return;
}
if (c == CMDS[RECENTER_GPS_CMD]) {
gpsRecenter = true;
gpsRecenterInvalid = true;
gpsRecenterStale = true;
autoZoomed = true;
if (pos.latitude != 0.0f) {
receivePosition(pos);
}
newDataReady();
return;
}
if (c == CMDS[SHOW_DEST_CMD]) {
if (dest != null) {
//We are explicitly setting the map to this position, so we probably don't
//want it to be recentered on the GPS immediately.
gpsRecenter = false;
prevPositionNode = center.copy();
center.setLatLonRad(dest.lat, dest.lon);
movedAwayFromDest = false;
updatePosition();
}
else {
alert(Locale.get("trace.ShowDestination")/*Show destination*/, Locale.get("trace.DestinationNotSpecifiedYet")/*Destination is not specified yet*/, 3000);
}
return;
}
if (c == CMDS[SHOW_PREVIOUS_POSITION_CMD]) {
if (prevPositionNode != null) {
//We are explicitly setting the map to this position, so we probably don't
//want it to be recentered on the GPS immediately.
gpsRecenter = false;
center.setLatLon(prevPositionNode);
updatePosition();
}
}
if (c == CMDS[DATASCREEN_CMD]) {
showNextDataScreen(DATASCREEN_NONE);
return;
}
if (c == CMDS[ICON_MENU] && Configuration.getCfgBitState(Configuration.CFGBIT_ICONMENUS)) {
showIconMenu();
return;
}
if (c == CMDS[SETUP_CMD]) {
new GuiDiscover(parent);
return;
}
if (c == CMDS[ABOUT_CMD]) {
new Splash(parent, GpsMid.initDone);
return;
}
if (c == CMDS[CELLID_LOCATION_CMD]) {
if (Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_SECELL && locationProducer != null) {
locationProducer.triggerPositionUpdate();
newDataReady();
} else {
if (cellIDLocationProducer == null) {
// init sleeping cellid location provider if cellid is not primary
cellIDLocationProducer = new SECellID();
if (cellIDLocationProducer != null && !cellIDLocationProducer.init(this)) {
logger.info("Failed to initialise CellID location producer");
}
}
if (cellIDLocationProducer != null) {
cellIDLocationProducer.triggerPositionUpdate();
newDataReady();
}
}
return;
}
if (c == CMDS[MANUAL_LOCATION_CMD]) {
Position setpos = new Position(center.radlat / MoreMath.FAC_DECTORAD,
center.radlon / MoreMath.FAC_DECTORAD,
PositionMark.INVALID_ELEVATION, 0.0f, 0.0f, 1,
System.currentTimeMillis(), Position.TYPE_MANUAL);
// implies center to gps, to give feedback as the gps rectangle
gpsRecenter = true;
// gpsRecenterInvalid = true;
// gpsRecenterStale = true;
autoZoomed = true;
receivePosition(setpos);
receiveStatus(LocationMsgReceiver.STATUS_MANUAL, 0);
newDataReady();
return;
}
if (! routeCalc) {
//#if polish.api.osm-editing
if (c == CMDS[RETRIEVE_XML]) {
if (Legend.enableEdits) {
// -1 alert ("Editing", "Urlidx: " + pc.actualWay.urlIdx, Alert.FOREVER);
if ((pc.actualWay != null) && (getUrl(pc.actualWay.urlIdx) != null)) {
parent.alert ("Url", "Url: " + getUrl(pc.actualWay.urlIdx), Alert.FOREVER);
}
if ((pc.actualWay != null) && (pc.actualWay instanceof EditableWay)) {
EditableWay eway = (EditableWay)pc.actualWay;
GUIosmWayDisplay guiWay = new GUIosmWayDisplay(eway, pc.actualSingleTile, this);
guiWay.show();
guiWay.refresh();
}
} else {
parent.alert("Editing", "Editing support was not enabled in Osm2GpsMid", Alert.FOREVER);
}
}
if (c == CMDS[RETRIEVE_NODE]) {
if (Legend.enableEdits) {
GuiOSMPOIDisplay guiNode = new GuiOSMPOIDisplay(-1, null,
center.radlat, center.radlon, this);
guiNode.show();
guiNode.refresh();
} else {
logger.error(Locale.get("trace.EditingIsNotEnabled")/*Editing is not enabled in this map*/);
}
}
if (c == CMDS[EDIT_ADDR_CMD]) {
if (Legend.enableEdits) {
String streetName = "";
if ((pc != null) && (pc.actualWay != null)) {
streetName = getName(pc.actualWay.nameIdx);
}
GuiOSMAddrDisplay guiAddr = new GuiOSMAddrDisplay(-1, streetName, null,
center.radlat, center.radlon, this);
guiAddr.show();
} else {
logger.error(Locale.get("trace.EditingIsNotEnabled")/*Editing is not enabled in this map*/);
}
}
//#else
if (c == CMDS[RETRIEVE_XML] || c == CMDS[RETRIEVE_NODE] || c == CMDS[EDIT_ADDR_CMD]) {
alert("No online capabilites",
Locale.get("trace.SetAppGeneric")/*Set app=GpsMid-Generic-editing and enableEditing=true in*/ +
Locale.get("trace.PropertiesFile")/*.properties file and recreate GpsMid with Osm2GpsMid.*/,
Alert.FOREVER);
}
//#endif
if (c == CMDS[SET_DEST_CMD]) {
RoutePositionMark pm1 = new RoutePositionMark(center.radlat, center.radlon);
setDestination(pm1);
return;
}
if (c == CMDS[CLEAR_DEST_CMD]) {
setDestination(null);
return;
}
} else {
alert(Locale.get("trace.Error")/*Error*/, Locale.get("trace.CurrentlyInRouteCalculation")/*Currently in route calculation*/, 2000);
}
} catch (Exception e) {
logger.exception(Locale.get("trace.InTraceCommandAction")/*In Trace.commandAction*/, e);
}
}
private void startImageCollector() throws Exception {
//#debug info
logger.info("Starting ImageCollector");
Images images = new Images();
pc = new PaintContext(this, images);
/* move responsibility for overscan to ImageCollector
int w = (this.getWidth() * 125) / 100;
int h = (this.getHeight() * 125) / 100;
*/
imageCollector = new ImageCollector(tiles, this.getWidth(), this.getHeight(), this, images);
// projection = ProjFactory.getInstance(center,course, scale, getWidth(), getHeight());
// pc.setP(projection);
pc.center = center.copy();
pc.scale = scale;
pc.xSize = this.getWidth();
pc.ySize = this.getHeight();
}
private void stopImageCollector(){
//#debug info
logger.info("Stopping ImageCollector");
cleanup();
if (imageCollector != null ) {
imageCollector.stop();
imageCollector=null;
}
System.gc();
}
public void startup() throws Exception {
// logger.info("reading Data ...");
namesThread = new Names();
urlsThread = new Urls();
new DictReader(this);
if (Configuration.getCfgBitState(Configuration.CFGBIT_AUTO_START_GPS)) {
Thread thread = new Thread(this, "Trace");
thread.start();
}
// logger.info("Create queueDataReader");
tileReader = new QueueDataReader(this);
// logger.info("create imageCollector");
dictReader = new QueueDictReader(this);
this.gpx = new Gpx();
this.audioRec = new AudioRecorder();
setDict(gpx, (byte)5);
startImageCollector();
recreateTraceLayout();
}
public void shutdown() {
if (gpx != null) {
// change to "false" to ask for track name if configure to
// currently "true" to not ask for name to ensure fast
// quit & try to avoid loss of data which might result from
// waiting for user to type the name
gpx.saveTrk(true);
}
//#debug debug
logger.debug("Shutdown: stopImageCollector");
stopImageCollector();
if (namesThread != null) {
//#debug debug
logger.debug("Shutdown: namesThread");
namesThread.stop();
namesThread = null;
}
if (urlsThread != null) {
urlsThread.stop();
urlsThread = null;
}
if (dictReader != null) {
//#debug debug
logger.debug("Shutdown: dictReader");
dictReader.shutdown();
dictReader = null;
}
if (tileReader != null) {
//#debug debug
logger.debug("Shutdown: tileReader");
tileReader.shutdown();
tileReader = null;
}
if (locationProducer != null) {
//#debug debug
logger.debug("Shutdown: locationProducer");
locationProducer.close();
}
if (TrackPlayer.isPlaying) {
//#debug debug
logger.debug("Shutdown: TrackPlayer");
TrackPlayer.getInstance().stop();
}
}
public void sizeChanged(int w, int h) {
updateLastUserActionTime();
if (imageCollector != null) {
logger.info("Size of Canvas changed to " + w + "|" + h);
stopImageCollector();
try {
startImageCollector();
imageCollector.resume();
imageCollector.newDataReady();
} catch (Exception e) {
logger.exception(Locale.get("trace.CouldNotReinitialiseImageCollector")/*Could not reinitialise Image Collector after size change*/, e);
}
/**
* Recalculate the projection, as it may depends on the size of the screen
*/
updatePosition();
}
tl = new TraceLayout(0, 0, w, h);
}
protected void paint(Graphics g) {
//#debug debug
logger.debug("Drawing Map screen");
try {
int yc = 1;
int la = 18;
getPC();
// cleans the screen
g.setColor(Legend.COLORS[Legend.COLOR_MAP_BACKGROUND]);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
pc.g = g;
if (imageCollector != null) {
/*
* When painting we receive a copy of the center coordinates
* where the imageCollector has drawn last
* as we need to base the routing instructions on the information
* determined during the way drawing (e.g. the current routePathConnection)
*/
Node drawnCenter = imageCollector.paint(pc);
if (route != null && ri != null && pc.lineP2 != null) {
pc.getP().forward(drawnCenter.radlat, drawnCenter.radlon, pc.lineP2);
/*
* we also need to make sure the current way for the real position
* has really been detected by the imageCollector which happens when drawing the ways
* So we check if we just painted an image that did not cover
* the center of the display because it was too far painted off from
* the display center position and in this case we don't give route instructions
* Thus e.g. after leaving a long tunnel without gps fix there will not be given an
* obsolete instruction from inside the tunnel
*/
int maxAllowedMapMoveOffs = Math.min(pc.xSize/2, pc.ySize/2);
if ( Math.abs(pc.lineP2.x - pc.getP().getImageCenter().x) < maxAllowedMapMoveOffs
&&
Math.abs(pc.lineP2.y - pc.getP().getImageCenter().y) < maxAllowedMapMoveOffs
) {
/*
* we need to synchronize the route instructions on the informations determined during way painting
* so we give the route instructions right after drawing the image with the map
* and use the center of the last drawn image for the route instructions
*/
ri.showRoute(pc, drawnCenter,imageCollector.xScreenOverscan,imageCollector.yScreenOverscan);
}
}
} else {
// show the way bar even if ImageCollector is not running because it's necessary on touch screens to get to the icon menu
tl.ele[TraceLayout.WAYNAME].setText(" ");
}
/* Beginning of voice instructions started from overlay code (besides showRoute above)
*/
// Determine if we are at the destination
if (dest != null) {
float distance = ProjMath.getDistance(dest.lat, dest.lon, center.radlat, center.radlon);
atDest = (distance < 25);
if (atDest) {
if (movedAwayFromDest && Configuration.getCfgBitState(Configuration.CFGBIT_SND_DESTREACHED)) {
GpsMid.mNoiseMaker.playSound(RouteSyntax.getInstance().getDestReachedSound(), (byte) 7, (byte) 1);
}
} else if (!movedAwayFromDest) {
movedAwayFromDest = true;
}
}
// determine if we are currently speeding
speeding = false;
int maxSpeed = 0;
// only detect speeding when gpsRecentered and there is a current way
if (gpsRecenter && actualSpeedLimitWay != null) {
maxSpeed = actualSpeedLimitWay.getMaxSpeed();
// check for winter speed limit if configured
if (Configuration.getCfgBitState(Configuration.CFGBIT_MAXSPEED_WINTER)
&& (actualSpeedLimitWay.getMaxSpeedWinter() > 0)) {
maxSpeed = actualSpeedLimitWay.getMaxSpeedWinter();
}
if (maxSpeed != 0 && speed > (maxSpeed + Configuration.getSpeedTolerance()) ) {
speeding = true;
}
}
if (speeding && Configuration.getCfgBitState(Configuration.CFGBIT_SPEEDALERT_SND)) {
// give speeding alert only every 10 seconds
if ( (System.currentTimeMillis() - lastTimeOfSpeedingSound) > 10000 ) {
lastTimeOfSpeedingSound = System.currentTimeMillis();
GpsMid.mNoiseMaker.immediateSound(RouteSyntax.getInstance().getSpeedLimitSound());
}
}
/*
* end of voice instructions started from overlay code
*/
/*
* the final part of the overlay should not give any voice instructions
*/
g.setColor(Legend.COLOR_MAP_TEXT);
switch (showAddons) {
case 1:
yc = showMemory(g, yc, la);
break;
case 2:
yc = showConnectStatistics(g, yc, la);
break;
default:
showAddons = 0;
if (Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_SCALE_BAR)) {
if (pc != null) {
tl.calcScaleBarWidth(pc);
tl.ele[TraceLayout.SCALEBAR].setText(" ");
}
}
setPointOfTheCompass();
}
showMovement(g);
// Show gpx track recording status
LayoutElement eSolution = tl.ele[TraceLayout.SOLUTION];
LayoutElement eRecorded = tl.ele[TraceLayout.RECORDED_COUNT];
if (gpx.isRecordingTrk()) {
// we are recording tracklogs
if (gpx.isRecordingTrkSuspended()) {
eRecorded.setColor(Legend.COLORS[Legend.COLOR_RECORDING_SUSPENDED_TEXT]); // blue
} else {
eRecorded.setColor(Legend.COLORS[Legend.COLOR_RECORDING_ON_TEXT]); // red
}
eRecorded.setText(gpx.getTrkPointCount() + Locale.get("trace.r")/*r*/);
}
if (TrackPlayer.isPlaying) {
eSolution.setText(Locale.get("trace.Replay")/*Replay*/);
} else {
if (locationProducer == null && !(solution == LocationMsgReceiver.STATUS_CELLID ||
solution == LocationMsgReceiver.STATUS_MANUAL)) {
eSolution.setText(Locale.get("solution.Off")/*Off*/);
} else {
eSolution.setText(solutionStr);
}
}
LayoutElement e = tl.ele[TraceLayout.CELLID];
// show if we are logging cellIDs
if (SECellLocLogger.isCellIDLogging() > 0) {
if (SECellLocLogger.isCellIDLogging() == 2) {
e.setColor(Legend.COLORS[Legend.COLOR_CELLID_LOG_ON_TEXT]); // yellow
} else {
//Attempting to log, but currently no valid info available
e.setColor(Legend.COLORS[Legend.COLOR_CELLID_LOG_ON_ATTEMPTING_TEXT]); // red
}
e.setText(Locale.get("trace.cellIDs")/*cellIDs*/);
}
// show audio recording status
e = tl.ele[TraceLayout.AUDIOREC];
if (audioRec.isRecording()) {
e.setColor(Legend.COLORS[Legend.COLOR_AUDIOREC_TEXT]); // red
e.setText(Locale.get("trace.AudioRec")/*AudioRec*/);
}
if (pc != null) {
showDestination(pc);
}
if (speed > 0 &&
Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_SPEED_IN_MAP)) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_METRIC)) {
tl.ele[TraceLayout.SPEED_CURRENT].setText(" " + Integer.toString(speed) + Locale.get("trace.kmh")/* km/h*/);
} else {
tl.ele[TraceLayout.SPEED_CURRENT].setText(" " + Integer.toString((int)(speed / 1.609344f)) + " mph");
}
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_ALTITUDE_IN_MAP)
&& locationProducer != null
&& LocationMsgReceiverList.isPosValid(solution)
) {
tl.ele[TraceLayout.ALTITUDE].setText(showDistance(altitude, DISTANCE_ALTITUDE));
}
if (dest != null && (route == null || (!RouteLineProducer.isRouteLineProduced() && !RouteLineProducer.isRunning()) )
&& Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_AIR_DISTANCE_IN_MAP)) {
e = Trace.tl.ele[TraceLayout.ROUTE_DISTANCE];
e.setBackgroundColor(Legend.COLORS[Legend.COLOR_RI_DISTANCE_BACKGROUND]);
double distLine = ProjMath.getDistance(center.radlat, center.radlon, dest.lat, dest.lon);
e.setText(Locale.get("trace.Air")/*Air:*/ + showDistance((int) distLine, DISTANCE_AIR));
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_CLOCK_IN_MAP)) {
e = tl.ele[TraceLayout.CURRENT_TIME]; // e is used *twice* below (also as vRelative)
e.setText(DateTimeTools.getClock(System.currentTimeMillis(), true));
/*
don't use new Date() - it is very slow on some Nokia devices
currentTime.setTime( new Date( System.currentTimeMillis() ) );
e.setText(
currentTime.get(Calendar.HOUR_OF_DAY) + ":"
+ HelperRoutines.formatInt2(currentTime.get(Calendar.MINUTE)));
*/
// if current time is visible, positioning OFFROUTE above current time will work
tl.ele[TraceLayout.ROUTE_OFFROUTE].setVRelative(e);
}
setSpeedingSign(maxSpeed);
if (hasPointerEvents()) {
tl.ele[TraceLayout.ZOOM_IN].setText("+");
tl.ele[TraceLayout.ZOOM_OUT].setText("-");
tl.ele[TraceLayout.RECENTER_GPS].setText("|");
e = tl.ele[TraceLayout.SHOW_DEST];
if (atDest && prevPositionNode != null) {
e.setText("<");
e.setActionID(SHOW_PREVIOUS_POSITION_CMD);
} else {
e.setText(">");
- e.setActionID(SHOW_DEST_CMD + + (Trace.SET_DEST_CMD << 16) );
+ e.setActionID(SHOW_DEST_CMD + (Trace.SET_DEST_CMD << 16) );
}
}
e = tl.ele[TraceLayout.TITLEBAR];
if (currentTitleMsgOpenCount != 0) {
e.setText(currentTitleMsg);
// setTitleMsgTimeOut can be changed in receiveMessage()
synchronized (this) {
if (setTitleMsgTimeout != 0) {
TimerTask timerT = new TimerTask() {
public synchronized void run() {
currentTitleMsgOpenCount--;
lastTitleMsg = currentTitleMsg;
if (currentTitleMsgOpenCount == 0) {
//#debug debug
logger.debug("clearing title");
repaint();
}
}
};
GpsMid.getTimer().schedule(timerT, setTitleMsgTimeout);
setTitleMsgTimeout = 0;
}
}
}
tl.paint(g);
if (currentAlertsOpenCount > 0) {
showCurrentAlert(g);
}
} catch (Exception e) {
logger.silentexception("Unhandled exception in the paint code", e);
}
}
public void showGuiWaypointSave(PositionMark posMark) {
if (guiWaypointSave == null) {
guiWaypointSave = new GuiWaypointSave(this);
}
if (guiWaypointSave != null) {
guiWaypointSave.setData(posMark);
guiWaypointSave.show();
}
}
/** Show an alert telling the user that waypoints are not ready yet.
*/
private void showAlertLoadingWpt() {
alert("Way points", "Way points are not ready yet.", 3000);
}
private void showCurrentAlert(Graphics g) {
Font font = g.getFont();
// request same font in bold for title
Font titleFont = Font.getFont(font.getFace(), Font.STYLE_BOLD, font.getSize());
int fontHeight = font.getHeight();
// add alert title height plus extra space of one line for calculation of alertHeight
int y = titleFont.getHeight() + 2 + fontHeight;
// extra width for alert
int extraWidth = font.charWidth('W');
// alert is at least as wide as alert title
int alertWidth = titleFont.stringWidth(currentAlertTitle);
// width each alert message line must fit in
int maxWidth = getWidth() - extraWidth;
// Two passes: 1st pass calculates placement and necessary size of alert,
// 2nd pass actually does the drawing
for (int i = 0; i <= 1; i++) {
int nextSpaceAt = 0;
int prevSpaceAt = 0;
int start = 0;
// word wrap
do {
int width = 0;
// add word by word until string part is too wide for screen
while (width < maxWidth && nextSpaceAt <= currentAlertMessage.length() ) {
prevSpaceAt = nextSpaceAt;
nextSpaceAt = currentAlertMessage.indexOf(' ', nextSpaceAt);
if (nextSpaceAt == -1) {
nextSpaceAt = currentAlertMessage.length();
}
width = font.substringWidth(currentAlertMessage, start, nextSpaceAt - start);
nextSpaceAt++;
}
nextSpaceAt--;
// Reduce line word by word or if not possible char by char until the
// remaining string part fits to display width
while (width > maxWidth) {
if (prevSpaceAt > start && nextSpaceAt > prevSpaceAt) {
nextSpaceAt = prevSpaceAt;
} else {
nextSpaceAt--;
}
width = font.substringWidth(currentAlertMessage, start, nextSpaceAt - start);
}
// determine maximum alert width
if (alertWidth < width ) {
alertWidth = width;
}
// during the second pass draw the message text lines
if (i==1) {
g.drawSubstring(currentAlertMessage, start, nextSpaceAt - start,
getWidth()/2, y, Graphics.TOP|Graphics.HCENTER);
}
y += fontHeight;
start = nextSpaceAt;
} while (nextSpaceAt < currentAlertMessage.length() );
// at the end of the first pass draw the alert box and the alert title
if (i == 0) {
alertWidth += extraWidth;
int alertHeight = y;
int alertTop = (getHeight() - alertHeight) /2;
//alertHeight += fontHeight/2;
int alertLeft = (getWidth() - alertWidth) / 2;
// alert background color
g.setColor(Legend.COLORS[Legend.COLOR_ALERT_BACKGROUND]);
g.fillRect(alertLeft, alertTop, alertWidth, alertHeight);
// background color for alert title
g.setColor(Legend.COLORS[Legend.COLOR_ALERT_TITLE_BACKGROUND]);
g.fillRect(alertLeft, alertTop, alertWidth, fontHeight + 3);
// alert border
g.setColor(Legend.COLORS[Legend.COLOR_ALERT_BORDER]);
g.setStrokeStyle(Graphics.SOLID);
g.drawRect(alertLeft, alertTop, alertWidth, fontHeight + 3); // title border
g.drawRect(alertLeft, alertTop, alertWidth, alertHeight); // alert border
// draw alert title
y = alertTop + 2; // output position of alert title
g.setFont(titleFont);
g.setColor(Legend.COLORS[Legend.COLOR_ALERT_TEXT]);
g.drawString(currentAlertTitle, getWidth()/2, y , Graphics.TOP|Graphics.HCENTER);
g.setFont(font);
// output alert message 1.5 lines below alert title in the next pass
y += (fontHeight * 3 / 2);
}
} // end for
// setAlertTimeOut can be changed in receiveMessage()
synchronized (this) {
if (setAlertTimeout != 0) {
TimerTask timerT = new TimerTask() {
public synchronized void run() {
currentAlertsOpenCount--;
if (currentAlertsOpenCount == 0) {
//#debug debug
logger.debug("clearing alert");
repaint();
}
}
};
GpsMid.getTimer().schedule(timerT, setAlertTimeout);
setAlertTimeout = 0;
}
}
}
private void setSpeedingSign(int maxSpeed) {
// speeding = true;
if (Configuration.getCfgBitState(Configuration.CFGBIT_SPEEDALERT_VISUAL)
&&
(
speeding
||
(System.currentTimeMillis() - startTimeOfSpeedingSign) < 3000
)
) {
if (speeding) {
speedingSpeedLimit = maxSpeed;
startTimeOfSpeedingSign = System.currentTimeMillis();
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_METRIC)) {
tl.ele[TraceLayout.SPEEDING_SIGN].setText(Integer.toString(speedingSpeedLimit));
} else {
tl.ele[TraceLayout.SPEEDING_SIGN].setText(Integer.toString((int)(speedingSpeedLimit / 1.609344f)));
}
} else {
startTimeOfSpeedingSign = 0;
}
}
/**
*
*/
private void getPC() {
pc.course = course;
pc.scale = scale;
pc.center = center.copy();
// pc.setP( projection);
// projection.inverse(pc.xSize, 0, pc.screenRU);
// projection.inverse(0, pc.ySize, pc.screenLD);
pc.dest = dest;
}
public void cleanup() {
namesThread.cleanup();
urlsThread.cleanup();
tileReader.incUnusedCounter();
dictReader.incUnusedCounter();
}
// public void searchElement(PositionMark pm) throws Exception {
// PaintContext pc = new PaintContext(this, null);
// // take a bigger angle for lon because of positions near to the poles.
// Node nld = new Node(pm.lat - 0.0001f, pm.lon - 0.0005f, true);
// Node nru = new Node(pm.lat + 0.0001f, pm.lon + 0.0005f, true);
// pc.searchLD = nld;
// pc.searchRU = nru;
// pc.dest = pm;
// pc.setP(new Proj2D(new Node(pm.lat, pm.lon, true), 5000, 100, 100));
// for (int i = 0; i < 4; i++) {
// tiles[i].walk(pc, Tile.OPT_WAIT_FOR_LOAD);
// }
// }
public void searchNextRoutableWay(RoutePositionMark pm) throws Exception {
PaintContext pc = new PaintContext(this, null);
// take a bigger angle for lon because of positions near to the pols.
// Node nld=new Node(pm.lat - 0.0001f,pm.lon - 0.0005f,true);
// Node nru=new Node(pm.lat + 0.0001f,pm.lon + 0.0005f,true);
// pc.searchLD=nld;
// pc.searchRU=nru;
pc.squareDstToActualRoutableWay = Float.MAX_VALUE;
pc.xSize = 100;
pc.ySize = 100;
// retry searching an expanding region at the position mark
Projection p;
do {
p = new Proj2D(new Node(pm.lat,pm.lon, true),5000,pc.xSize,pc.ySize);
pc.setP(p);
for (int i=0; i<4; i++) {
tiles[i].walk(pc, Tile.OPT_WAIT_FOR_LOAD | Tile.OPT_FIND_CURRENT);
}
// stop the search when a routable way is found
if (pc.actualRoutableWay != null) {
break;
}
// expand the region that gets searched for a routable way
pc.xSize += 100;
pc.ySize += 100;
// System.out.println(pc.xSize);
} while(MoreMath.dist(p.getMinLat(), p.getMinLon(), p.getMinLat(), p.getMaxLon()) < 500); // until we searched at least 500 m edge length
Way w = pc.actualRoutableWay;
pm.setEntity(w, pc.currentPos.nodeLat, pc.currentPos.nodeLon);
}
private void setPointOfTheCompass() {
String c = "";
if (ProjFactory.getProj() != ProjFactory.NORTH_UP
&& Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_POINT_OF_COMPASS)) {
c = Configuration.getCompassDirection(course);
}
// if tl shows big onscreen buttons add spaces to compass directions consisting of only one char or not shown
if (tl.bigOnScreenButtons && c.length() <= 1) {
if (ProjFactory.getProj() == ProjFactory.NORTH_UP) {
c = "(" + Configuration.getCompassDirection(0) + ")";
} else {
c = " " + c + " ";
}
}
tl.ele[TraceLayout.POINT_OF_COMPASS].setText(c);
}
private int showConnectStatistics(Graphics g, int yc, int la) {
g.setColor(Legend.COLORS[Legend.COLOR_MAP_TEXT]);
// only try to show compass id and cell id if user has somehow switched them on
GSMCell cell = null;
if (cellIDLocationProducer != null || Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_SECELL) {
cell = CellIdProvider.getInstance().obtainCachedCellID();
}
Compass compass = null;
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION)) {
compass = CompassProvider.getInstance().obtainCachedCompass();
}
if (cell == null) {
g.drawString("No Cell ID available", 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
} else {
g.drawString("Cell: MCC=" + cell.mcc + " MNC=" + cell.mnc, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString("LAC=" + cell.lac, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString("cellID=" + cell.cellID, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
}
if (compass == null) {
g.drawString("No compass direction available", 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
} else {
g.drawString("Compass direction: " + compass.direction, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
}
if (statRecord == null) {
g.drawString("No stats yet", 0, yc, Graphics.TOP
| Graphics.LEFT);
return yc+la;
}
//#mdebug info
for (byte i = 0; i < LocationMsgReceiver.SIRF_FAIL_COUNT; i++) {
g.drawString(statMsg[i] + statRecord[i], 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
}
//#enddebug
g.drawString("BtQual : " + btquality, 0, yc, Graphics.TOP | Graphics.LEFT);
yc += la;
g.drawString("Count : " + collected, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
return yc;
}
public void showDestination(PaintContext pc) {
try {
if (dest != null) {
pc.getP().forward(dest.lat, dest.lon, pc.lineP2);
// System.out.println(dest.toString());
int x = pc.lineP2.x - imageCollector.xScreenOverscan;
int y = pc.lineP2.y - imageCollector.yScreenOverscan;
pc.g.drawImage(pc.images.IMG_DEST, x, y, CENTERPOS);
pc.g.setColor(Legend.COLORS[Legend.COLOR_DEST_TEXT]);
if (dest.displayName != null) {
pc.g.drawString(dest.displayName, x, y+8,
Graphics.TOP | Graphics.HCENTER);
}
pc.g.setColor(Legend.COLORS[Legend.COLOR_DEST_LINE]);
pc.g.setStrokeStyle(Graphics.SOLID);
pc.g.drawLine(x, y, pc.getP().getImageCenter().x - imageCollector.xScreenOverscan,
pc.getP().getImageCenter().y - imageCollector.yScreenOverscan);
}
} catch (Exception e) {
if (imageCollector == null) {
logger.silentexception("No ImageCollector", e);
}
e.printStackTrace();
}
}
/**
* Draws the position square, the movement line and the center cross.
*
* @param g Graphics context for drawing
*/
public void showMovement(Graphics g) {
IntPoint centerP = null;
try {
if (imageCollector != null) {
g.setColor(Legend.COLORS[Legend.COLOR_MAP_CURSOR]);
centerP = pc.getP().getImageCenter();
int centerX = centerP.x - imageCollector.xScreenOverscan;
int centerY = centerP.y - imageCollector.yScreenOverscan;
int posX, posY;
if (!gpsRecenter) {
IntPoint p1 = new IntPoint(0, 0);
pc.getP().forward((pos.latitude * MoreMath.FAC_DECTORAD),
(pos.longitude * MoreMath.FAC_DECTORAD), p1);
posX = p1.getX()-imageCollector.xScreenOverscan;
posY = p1.getY()-imageCollector.yScreenOverscan;
} else {
posX = centerX;
posY = centerY;
}
g.setColor(Legend.COLORS[Legend.COLOR_MAP_POSINDICATOR]);
float radc = course * MoreMath.FAC_DECTORAD;
int px = posX + (int) (Math.sin(radc) * 20);
int py = posY - (int) (Math.cos(radc) * 20);
// crosshair center cursor
if (!gpsRecenter || gpsRecenterInvalid) {
g.drawLine(centerX, centerY - 12, centerX, centerY + 12);
g.drawLine(centerX - 12, centerY, centerX + 12, centerY);
g.drawArc(centerX - 5, centerY - 5, 10, 10, 0, 360);
}
if (! gpsRecenterInvalid) {
// gps position spot
pc.g.drawImage(gpsRecenterStale ? pc.images.IMG_POS_BG_STALE : pc.images.IMG_POS_BG, posX, posY, CENTERPOS);
// gps position rectangle
g.drawRect(posX - 4, posY - 4, 8, 8);
g.drawLine(posX, posY, px, py);
}
}
} catch (Exception e) {
if (imageCollector == null) {
logger.silentexception("No ImageCollector", e);
}
if (centerP == null) {
logger.silentexception("No centerP", e);
}
e.printStackTrace();
}
}
/**
* Show next screen in the sequence of data screens
* (tacho, trip, satellites).
* @param currentScreen Data screen currently shown, use the DATASCREEN_XXX
* constants from this class. Use DATASCREEN_NONE if none of them
* is on screen i.e. the first one should be shown.
*/
public void showNextDataScreen(int currentScreen) {
switch (currentScreen)
{
case DATASCREEN_TACHO:
// Tacho is followed by Trip.
if (guiTrip == null) {
guiTrip = new GuiTrip(this);
}
if (guiTrip != null) {
guiTrip.show();
}
break;
case DATASCREEN_TRIP:
// Trip is followed by Satellites.
if (guiSatellites == null) {
guiSatellites = new GuiSatellites(this, locationProducer);
}
if (guiSatellites != null) {
guiSatellites.show();
}
break;
case DATASCREEN_SATS:
// After Satellites, go back to map.
this.show();
break;
case DATASCREEN_NONE:
default:
// Tacho is first data screen
if (guiTacho == null) {
guiTacho = new GuiTacho(this);
}
if (guiTacho != null) {
guiTacho.show();
}
break;
}
}
public int showMemory(Graphics g, int yc, int la) {
g.setColor(0);
g.drawString(Locale.get("trace.Freemem")/*Freemem: */ + runtime.freeMemory(), 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.Totmem")/*Totmem: */ + runtime.totalMemory(), 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.Percent")/*Percent: */
+ (100f * runtime.freeMemory() / runtime.totalMemory()), 0, yc,
Graphics.TOP | Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.ThreadsRunning")/*Threads running: */
+ Thread.activeCount(), 0, yc,
Graphics.TOP | Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.Names")/*Names: */ + namesThread.getNameCount(), 0, yc,
Graphics.TOP | Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.SingleT")/*Single T: */ + tileReader.getLivingTilesCount() + "/"
+ tileReader.getRequestQueueSize(), 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.FileT")/*File T: */ + dictReader.getLivingTilesCount() + "/"
+ dictReader.getRequestQueueSize() + " Map: " + ImageCollector.icDuration + " ms", 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.LastMsg")/*LastMsg: */ + lastTitleMsg, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString( Locale.get("trace.at")/*at */ + lastTitleMsgClock, 0, yc,
Graphics.TOP | Graphics.LEFT );
return (yc);
}
private void updatePosition() {
if (pc != null) {
pc.center = center.copy();
pc.scale = scale;
pc.course=course;
repaint();
if (locationUpdateListeners != null && !TrackPlayer.isPlaying) {
synchronized (locationUpdateListeners) {
for (int i = 0; i < locationUpdateListeners.size(); i++) {
((LocationUpdateListener)locationUpdateListeners.elementAt(i)).loctionUpdated();
}
}
}
}
}
public synchronized void receivePosition(float lat, float lon, float scale) {
//#debug debug
logger.debug("Now displaying: " + (lat * MoreMath.FAC_RADTODEC) + " | " +
(lon * MoreMath.FAC_RADTODEC));
//We are explicitly setting the map to this position, so we probably don't
//want it to be recentered on the GPS immediately.
gpsRecenter = false;
center.setLatLonRad(lat, lon);
this.scale = scale;
updatePosition();
}
public synchronized void receiveCompassStatus(int status) {
}
public synchronized void receiveCompass(float direction) {
//#debug debug
logger.debug("Got compass reading: " + direction);
compassDirection = (int) direction;
compassDeviated = ((int) direction + compassDeviation + 360) % 360;
// TODO: allow for user to use compass for turning the map in panning mode
// (gpsRenter test below switchable by user setting)
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null && gpsRecenter) {
updateCourse(compassDeviated);
//repaint();
}
// course = compassDeviated;
//}
}
public static void updateLastUserActionTime() {
lastUserActionTime = System.currentTimeMillis();
}
public static long getDurationSinceLastUserActionTime() {
return System.currentTimeMillis() - lastUserActionTime;
}
public void updateCourse(int newcourse) {
coursegps = newcourse;
/* don't rotate too fast
*/
if ((newcourse - course)> 180) {
course = course + 360;
}
if ((course-newcourse)> 180) {
newcourse = newcourse + 360;
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null) {
course = newcourse;
} else {
// FIXME I think this is too slow a turn at least when course is
// of good quality, turning should be faster. This probably alleviates
// the trouble caused by unreliable gps course. However,
// some kind of heuristic, averaging course or evaluating the
// quality of course and fast or instant rotation with a known good GPS fix
// should be implemented instead of assuming course is always unreliable.
// The course fluctuations are lesser in faster speeds, so if we're constantly
// (for three consecutive locations) above say 5 km/h, a reasonable approach
// could be to use direct course change in thet case, and for speed below
// 5 km/h use the slow turning below.
// jkpj 2010-01-17
course = course + ((newcourse - course)*1)/4 + 360;
}
while (course > 360) {
course -= 360;
}
}
public synchronized void receivePosition(Position pos) {
// FIXME signal on location gained
//#debug info
logger.info("New position: " + pos);
collected++;
if (Configuration.getAutoRecenterToGpsMilliSecs() !=0 &&
getDurationSinceLastUserActionTime() > Configuration.getAutoRecenterToGpsMilliSecs()
&& isShown()
) {
gpsRecenter = true;
//autoZoomed = true;
}
if (Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_JSR179) {
if (pos.type == Position.TYPE_GPS_LASTKNOWN) {
// if we have a current cell id fix from cellid location,
// don't overwrite it with a stale GPS location, but ignore the position
// FIXME perhaps compare timestamps here in case the last known gps is later
if (this.pos.type == Position.TYPE_CELLID) {
return;
}
gpsRecenterInvalid = false;
gpsRecenterStale = true;
}
}
this.pos = pos;
if (pos.type == Position.TYPE_GPS || pos.type == Position.TYPE_CELLID || pos.type == Position.TYPE_MANUAL) {
gpsRecenterInvalid = false;
gpsRecenterStale = false;
}
if (gpsRecenter) {
center.setLatLonDeg(pos.latitude, pos.longitude);
speed = (int) (pos.speed * 3.6f);
fspeed = pos.speed * 3.6f;
// FIXME add auto-fallback mode where course is from GPS at high speeds and from compass
// at low speeds
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null) {
updateCourse(compassDeviated);
} else if (fspeed >= courseMinSpeed && pos.course != Float.NaN ) {
// Problem: resolve issue erratic course due to GPS fluctuation
// when GPS reception is poor (maybe 3..7S),
// causes unnecessary and disturbing map rotation when device is in one location
// Heuristic for solving: After being still, require
// three consecutive over-the-limit speed readings with roughly the
// same course
if (thirdPrevCourse != -1) {
// first check for normal flow of things, we've had three valid courses after movement start
updateCourse((int) pos.course);
} else if (prevCourse == -1) {
// previous course was invalid,
// don't set course yet, but set the first tentatively good course
prevCourse = (int) pos.course;
} else if (secondPrevCourse == -1) {
// the previous course was the first good one.
// If this course is in the same 60-degree
// sector as the first course, we have two valid courses
if (Math.abs(prevCourse - (int)pos.course) < 30 || Math.abs(prevCourse - (int)pos.course) > 330) {
secondPrevCourse = prevCourse;
}
prevCourse = (int) pos.course;
} else {
// we have received two previous valid curses, check for this one
if (Math.abs(prevCourse - (int)pos.course) < 30 || Math.abs(prevCourse - (int)pos.course) > 330) {
thirdPrevCourse = secondPrevCourse;
//No need to set these as we'll now trust courses until speed goes below limit
// - unless we'll later add averaging of recent courses for poor GPS reception
//secondPrevCourse = prevCourse;
//prevCourse = (int) pos.course;
updateCourse((int) pos.course);
} else {
prevCourse = (int) pos.course;
secondPrevCourse = -1;
}
}
} else {
// speed under the minimum, invalidate all prev courses
prevCourse = -1;
secondPrevCourse = -1;
thirdPrevCourse = -1;
}
}
if (gpx.isRecordingTrk()) {
try {
// don't tracklog manual cellid position or gps start/stop last known position
if ((Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_JSR179
&& pos.type == Position.TYPE_CELLID) || pos.type == Position.TYPE_GPS_LASTKNOWN) {
} else {
gpx.addTrkPt(pos);
}
} catch (Exception e) {
receiveMessage(e.getMessage());
}
}
altitude = (int) (pos.altitude);
if (Configuration.getCfgBitState(Configuration.CFGBIT_AUTOZOOM)
&& gpsRecenter
&& (isGpsConnected() || TrackPlayer.isPlaying)
&& autoZoomed
&& pc.getP() != null
&& pos.speed != Float.NaN // if speed is unknown do not autozoom
) {
// the minimumScale at 20km/h and below is equivalent to having zoomed in manually once from the startup zoom level
final float minimumScale = Configuration.getRealBaseScale() / 1.5f;
final int minimumSpeed = 20;
// the maximumScale at 160km/h and above is equivalent to having zoomed out manually once from the startup zoom level
final float maximumScale = Configuration.getRealBaseScale() * 1.5f;
final int maximumSpeed = 160;
int speedForScale = speed;
float newScale = minimumScale + (maximumScale - minimumScale) * (speedForScale - minimumSpeed) / (maximumSpeed - minimumSpeed);
// make sure the new scale is within the minimum / maximum scale values
if (newScale < minimumScale) {
newScale = minimumScale;
} else if (newScale > maximumScale) {
newScale = maximumScale;
}
scale = newScale;
// // calculate meters to top of screen
// float topLat = pc.getP().getMaxLat();
// float topLon = (pc.getP().getMinLon() + pc.getP().getMaxLon()) / 2f;
// float distance = MoreMath.dist(center.radlat, center.radlon, topLat, topLon );
// System.out.println("current distance to top of screen: " + distance);
//
// // avoid zooming in or out too far
// int speedForScale = course;
// if (speedForScale < 30) {
// speedForScale = 30;
// } else if (speedForScale > 160) {
// speedForScale = 160;
// }
//
// final float SECONDS_TO_PREVIEW = 45f;
// float metersToPreview = (float) speedForScale / 3.6f * SECONDS_TO_PREVIEW;
// System.out.println(metersToPreview + "meters to preview at " + speedForScale + "km/h");
//
// if (metersToPreview < 2000) {
// // calculate top position that needs to be visible to preview the metersToPreview
// topLat = center.radlat + (topLat - center.radlat) * metersToPreview / distance;
// topLon = center.radlon + (topLon - center.radlon) * metersToPreview / distance;
// System.out.println("new distance to top:" + MoreMath.dist(center.radlat, center.radlon, topLat, topLon ));
//
// /*
// * calculate scale factor, we multiply this again with 2 * 1.2 = 2.4 to take into account we calculated half the screen height
// * and 1.2f is probably the factor the PaintContext is larger than the display size
// * (new scale is calculated similiar to GuiWaypoint)
// */
// IntPoint intPoint1 = new IntPoint(0, 0);
// IntPoint intPoint2 = new IntPoint(getWidth(), getHeight());
// Node n1 = new Node(center.radlat, center.radlon, true);
// Node n2 = new Node(topLat, topLon, true);
// scale = pc.getP().getScale(n1, n2, intPoint1, intPoint2) * 2.4f;
// }
}
updatePosition();
}
public synchronized Position getCurrentPosition() {
return this.pos;
}
public synchronized void receiveMessage(String s) {
// #debug info
logger.info("Setting title: " + s);
currentTitleMsg = s;
synchronized (this) {
/*
* only increase the number of current title messages
* if the timer already has been set in the display code
*/
if (setTitleMsgTimeout == 0) {
currentTitleMsgOpenCount++;
}
setTitleMsgTimeout = 3000;
}
lastTitleMsgClock = DateTimeTools.getClock(System.currentTimeMillis(), false);
repaint();
}
public void receiveSatellites(Satellite[] sats) {
// Not interested
}
/** Shows an alert message
*
* @param title The title of the alert
* @param message The message text
* @param timeout Timeout in ms. Please reserve enough time so the user can
* actually read the message. Use Alert.FOREVER if you want no timeout.
*/
public synchronized void alert(String title, String message, int timeout) {
// #debug info
logger.info("Showing trace alert: " + title + ": " + message);
if (timeout == Alert.FOREVER) {
timeout = 10000;
}
currentAlertTitle = title;
currentAlertMessage = message;
synchronized (this) {
/*
* only increase the number of current open alerts
* if the timer already has been set in the display code
*/
if (setAlertTimeout == 0) {
currentAlertsOpenCount++;
}
setAlertTimeout = timeout;
}
repaint();
}
public MIDlet getParent() {
return parent;
}
protected void pointerPressed(int x, int y) {
updateLastUserActionTime();
long currTime = System.currentTimeMillis();
pointerDragged = false;
pointerDraggedMuch = false;
pointerActionDone = false;
// remember center when the pointer was pressed for dragging
centerPointerPressedN = center.copy();
if (imageCollector != null) {
panProjection=imageCollector.getCurrentProjection();
pickPointStart=panProjection.inverse(x,y, pickPointStart);
} else {
panProjection = null;
}
// remember the LayoutElement the pointer is pressed down at, this will also highlight it on the display
int touchedElementId = tl.getElementIdAtPointer(x, y);
if (touchedElementId >= 0 && (!keyboardLocked || tl.getActionIdAtPointer(x, y) == Trace.ICON_MENU)
&&
tl.isAnyActionIdAtPointer(x, y)
) {
tl.setTouchedElement((LayoutElement) tl.elementAt(touchedElementId));
repaint();
}
// check for double press
if (!keyboardLocked && currTime - pressedPointerTime < DOUBLETAP_MAXDELAY) {
doubleTap(x, y);
}
// Remember the time and position the pointer was pressed after the check for double tap,
// so the double tap code will check for the position of the first of the two taps
pressedPointerTime = currTime;
Trace.touchX = x;
Trace.touchY = y;
// Give a message if keyboard/user interface is locked.
// This must be done after remembering the touchX/Y positions as they are needed to unlock
if (keyboardLocked) {
keyPressed(0);
return;
}
// // when these statements are reached, no double tap action has been executed,
// // so check here if there's currently already a TimerTask waiting for a single tap.
// // If yes, perform the current single tap action immediately before starting the next TimerTask
// if (checkingForSingleTap && !pointerDraggedMuch) {
// singleTap();
// pointerActionDone = false;
// }
//
longTapTimerTask = new TimerTask() {
public void run() {
// if no action (e.g. from double tap) is already done
// and the pointer did not move or if it was pressed on a control and not moved much
if (!pointerActionDone && !pointerDraggedMuch) {
if (System.currentTimeMillis() - pressedPointerTime >= LONGTAP_DELAY){
longTap();
}
}
}
};
try {
// set timer to continue check if this is a long tap
GpsMid.getTimer().schedule(longTapTimerTask, LONGTAP_DELAY);
} catch (Exception e) {
logger.error(Locale.get("trace.NoLongTapTimerTask")/*No LongTap TimerTask: */ + e.toString());
}
}
protected void pointerReleased(int x, int y) {
// releasing the pointer cancels the check for long tap
if (longTapTimerTask != null) {
longTapTimerTask.cancel();
}
// releasing the pointer will clear the highlighting of the touched element
if (tl.getTouchedElement() != null) {
tl.clearTouchedElement();
repaint();
}
if (!pointerActionDone && !keyboardLocked) {
touchReleaseX = x;
touchReleaseY = y;
// check for a single tap in a timer started after the maximum double tap delay
// if the timer will not be cancelled by a double tap, the timer will execute the single tap command
singleTapTimerTask = new TimerTask() {
public void run() {
if (!keyboardLocked) {
singleTap(touchReleaseX, touchReleaseY);
}
}
};
try {
// set timer to check if this is a single tap
GpsMid.getTimer().schedule(singleTapTimerTask, DOUBLETAP_MAXDELAY);
} catch (Exception e) {
logger.error(Locale.get("trace.NoSingleTapTimerTask")/*No SingleTap TimerTask: */ + e.toString());
}
if (pointerDragged) {
pointerDragged(x , y);
return;
}
}
}
protected void pointerDragged (int x, int y) {
updateLastUserActionTime();
LayoutElement e = tl.getElementAtPointer(x, y);
if (tl.getTouchedElement() != e) {
// leaving the touched element cancels the check for long tap
if (longTapTimerTask != null) {
longTapTimerTask.cancel();
}
tl.clearTouchedElement();
repaint();
}
// If the initially touched element is reached again during dragging, highlight it
if (tl.getElementAtPointer(touchX, touchY) == e && tl.isAnyActionIdAtPointer(x, y)) {
tl.setTouchedElement(e);
repaint();
}
if (pointerActionDone) {
return;
}
// check if there's been much movement, do this before the slide lock/unlock
// to avoid a single tap action when not sliding enough
if (Math.abs(x - Trace.touchX) > 8
||
Math.abs(y - Trace.touchY) > 8
) {
pointerDraggedMuch = true;
// avoid double tap triggering on fast consecutive drag actions starting at almost the same position
pressedPointerTime = 0;
}
// slide at least 1/4 display width to lock / unlock GpsMid
if (tl.getActionIdAtPointer(touchX, touchY) == Trace.ICON_MENU) {
if ( tl.getActionIdAtPointer(x, y) == Trace.ICON_MENU
&&
x - touchX > getWidth() / 4
) {
commandAction(TOGGLE_KEY_LOCK_CMD);
pointerActionDone = true;
}
return;
}
if (keyboardLocked) {
return;
}
pointerDragged = true;
// do not start map dragging on a touch control if only dragged slightly
if (!pointerDraggedMuch && tl.getElementIdAtPointer(touchX, touchY) >= 0) {
return;
}
if (tl.getElementIdAtPointer(touchX, touchY) < 0 && imageCollector != null && panProjection != null) {
// difference between where the pointer was pressed and is currently dragged
// int diffX = Trace.touchX - x;
// int diffY = Trace.touchY - y;
//
// IntPoint centerPointerPressedP = new IntPoint();
pickPointEnd=panProjection.inverse(x,y, pickPointEnd);
center.radlat=centerPointerPressedN.radlat-(pickPointEnd.radlat-pickPointStart.radlat);
center.radlon=centerPointerPressedN.radlon-(pickPointEnd.radlon-pickPointStart.radlon);
// System.out.println("diff " + diffX + "/" + diffY + " " + (pickPointEnd.radlat-pickPointStart.radlat) + "/" + (pickPointEnd.radlon-pickPointStart.radlon) );
imageCollector.newDataReady();
gpsRecenter = false;
}
}
private void singleTap(int x, int y) {
pointerActionDone = true;
// if not tapping a control, then the map area must be tapped so we set the touchable button sizes
if (tl.getElementIdAtPointer(touchX, touchY) < 0) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_MAPTAP_SINGLE)) {
// if pointer was dragged much, do not recognize a single tap on the map
if (pointerDraggedMuch) {
return;
}
// #debug debug
logger.debug("single tap map");
if (!tl.bigOnScreenButtons) {
tl.setOnScreenButtonSize(true);
// set timer to continuously check if the last user interaction is old enough to make the buttons small again
final long BIGBUTTON_DURATION = 5000;
bigButtonTimerTask = new TimerTask() {
public void run() {
if (System.currentTimeMillis() - lastUserActionTime > BIGBUTTON_DURATION ) {
// make the on screen touch buttons small again
tl.setOnScreenButtonSize(false);
requestRedraw();
bigButtonTimerTask.cancel();
}
}
};
try {
GpsMid.getTimer().schedule(bigButtonTimerTask, BIGBUTTON_DURATION, 500);
} catch (Exception e) {
logger.error("Error scheduling bigButtonTimerTask: " + e.toString());
}
}
}
repaint();
} else if (tl.getElementIdAtPointer(x, y) == tl.getElementIdAtPointer(touchX, touchY)) {
tl.clearTouchedElement();
int actionId = tl.getActionIdAtPointer(x, y);
if (actionId > 0) {
// #debug debug
logger.debug("single tap button: " + actionId + " x: " + touchX + " y: " + touchY);
if (System.currentTimeMillis() < (lastBackLightOnTime + 2500)) {
if (actionId == ZOOM_IN_CMD) {
actionId = PAN_RIGHT2_CMD;
} else if (actionId == ZOOM_OUT_CMD) {
actionId = PAN_LEFT2_CMD;
}
} else if (manualRotationMode) {
if (actionId == ZOOM_IN_CMD) {
actionId = PAN_LEFT2_CMD;
} else if (actionId == ZOOM_OUT_CMD) {
actionId = PAN_RIGHT2_CMD;
}
} else if (TrackPlayer.isPlaying) {
if (actionId == ZOOM_IN_CMD) {
actionId = PAN_RIGHT2_CMD;
} else if (actionId == ZOOM_OUT_CMD) {
actionId = PAN_LEFT2_CMD;
}
}
commandAction(actionId);
repaint();
}
}
}
private void doubleTap(int x, int y) {
// if not double tapping a control, then the map area must be double tapped and we zoom in
if (tl.getElementIdAtPointer(touchX, touchY) < 0) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_MAPTAP_DOUBLE)) {
// if this is a double press on the map, cancel the timer checking for a single press
if (singleTapTimerTask != null) {
singleTapTimerTask.cancel();
}
// if pointer was dragged much, do not recognize a double tap on the map
if (pointerDraggedMuch) {
return;
}
//#debug debug
logger.debug("double tap map");
pointerActionDone = true;
commandAction(ZOOM_IN_CMD);
}
repaint();
return;
} else if (tl.getTouchedElement() == tl.getElementAtPointer(x, y) ){
// double tapping a control
int actionId = tl.getActionIdDoubleAtPointer(x, y);
//#debug debug
logger.debug("double tap button: " + actionId + " x: " + x + " y: " + x);
if (actionId > 0) {
// if this is a double press on a control, cancel the timer checking for a single press
if (singleTapTimerTask != null) {
singleTapTimerTask.cancel();
}
pointerActionDone = true;
commandAction(actionId);
tl.clearTouchedElement();
repaint();
return;
} else {
singleTap(x, y);
}
}
}
private void longTap() {
pointerActionDone = true;
// if not tapping a control, then the map area must be tapped so we do the long tap action for the map area
if (tl.getElementIdAtPointer(touchX, touchY) < 0 && panProjection != null) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_MAPTAP_LONG)) {
//#debug debug
logger.debug("long tap map");
//#if polish.api.online
// long tap map to open a place-related menu
// use the place of touch instead of old center as position,
// set as new center
pickPointEnd=panProjection.inverse(touchX,touchY, pickPointEnd);
center.radlat=centerPointerPressedN.radlat-(pickPointEnd.radlat-pickPointStart.radlat);
center.radlon=centerPointerPressedN.radlon-(pickPointEnd.radlon-pickPointStart.radlon);
Position oPos = new Position(center.radlat, center.radlon,
0.0f, 0.0f, 0.0f, 0, 0);
imageCollector.newDataReady();
gpsRecenter = false;
commandAction(ONLINE_INFO_CMD);
//#endif
}
return;
// long tapping a control
} else {
int actionId = tl.getActionIdLongAtPointer(touchX, touchY);
if (actionId > 0) {
tl.clearTouchedElement();
//#debug debug
logger.debug("long tap button: " + actionId + " x: " + touchX + " y: " + touchY);
commandAction(actionId);
repaint();
}
}
}
/**
* Returns the command used to go to the data screens.
* Needed by the data screens so they can find the key codes used for this
* as they have to use them too.
* @return Command
*/
public Command getDataScreenCommand() {
return CMDS[DATASCREEN_CMD];
}
public Tile getDict(byte zl) {
return tiles[zl];
}
public void setDict(Tile dict, byte zl) {
tiles[zl] = dict;
// Tile.trace=this;
//addCommand(REFRESH_CMD);
// if (zl == 3) {
// setTitle(null);
// } else {
// setTitle("dict " + zl + "ready");
// }
if (zl == 0) {
// read saved position from Configuration
Configuration.getStartupPos(center);
if (center.radlat == 0.0f && center.radlon == 0.0f) {
// if no saved position use center of map
dict.getCenter(center);
}
// read saved destination position from Configuration
if (Configuration.getCfgBitState(Configuration.CFGBIT_SAVED_DESTPOS_VALID)) {
Node destNode = new Node();
Configuration.getDestPos(destNode);
setDestination(new RoutePositionMark(destNode.radlat, destNode.radlon));
}
if (pc != null) {
pc.center = center.copy();
pc.scale = scale;
pc.course = course;
}
}
updatePosition();
}
public void receiveStatistics(int[] statRecord, byte quality) {
this.btquality = quality;
this.statRecord = statRecord;
repaint();
}
public synchronized void locationDecoderEnd() {
//#debug info
logger.info("enter locationDecoderEnd");
if (Configuration.getCfgBitState(Configuration.CFGBIT_SND_DISCONNECT)) {
// some fault tolerance - will crash without a map
if (Legend.isValid) {
GpsMid.mNoiseMaker.playSound("DISCONNECT");
}
}
//if (gpx != null) {
// /**
// * Close and Save the gpx recording, to ensure we don't loose data
// */
// gpx.saveTrk(false);
//}
removeCommand(CMDS[DISCONNECT_GPS_CMD]);
if (locationProducer == null) {
//#debug info
logger.info("leave locationDecoderEnd no producer");
return;
}
locationProducer = null;
notify();
addCommand(CMDS[CONNECT_GPS_CMD]);
// addCommand(START_RECORD_CMD);
//#debug info
logger.info("end locationDecoderEnd");
}
public void receiveStatus(byte status, int satsReceived) {
// FIXME signal a sound on location gained or lost
solution = status;
solutionStr = LocationMsgReceiverList.getCurrentStatusString(status, satsReceived);
repaint();
}
public String getName(int idx) {
if (idx < 0) {
return null;
}
return namesThread.getName(idx);
}
public String getUrl(int idx) {
if (idx < 0) {
return null;
}
return urlsThread.getUrl(idx);
}
public Vector fulltextSearch (String snippet, CancelMonitorInterface cmi) {
return namesThread.fulltextSearch(snippet, cmi);
}
// this is called by ImageCollector
public void requestRedraw() {
repaint();
}
public void newDataReady() {
if (imageCollector != null) {
imageCollector.newDataReady();
}
}
public void show() {
//Display.getDisplay(parent).setCurrent(this);
Legend.freeDrawnWayAndAreaSearchImages();
GpsMid.getInstance().show(this);
setFullScreenMode(Configuration.getCfgBitState(Configuration.CFGBIT_FULLSCREEN));
updateLastUserActionTime();
repaint();
}
public void recreateTraceLayout() {
tl = new TraceLayout(0, 0, getWidth(), getHeight());
}
public void locationDecoderEnd(String msg) {
receiveMessage(msg);
locationDecoderEnd();
}
public PositionMark getDestination() {
return dest;
}
public void setDestination(RoutePositionMark dest) {
endRouting();
this.dest = dest;
pc.dest = dest;
if (dest != null) {
//#debug info
logger.info("Setting destination to " + dest.toString());
// move map only to the destination, if GUI is not optimized for routing
if (! Configuration.getCfgBitState(Configuration.CFGBIT_ICONMENUS_ROUTING_OPTIMIZED)) {
commandAction(SHOW_DEST_CMD);
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_AUTOSAVE_DESTPOS)) {
Configuration.setDestPos(new Node(dest.lat, dest.lon, true));
Configuration.setCfgBitSavedState(Configuration.CFGBIT_SAVED_DESTPOS_VALID, true);
}
movedAwayFromDest = false;
} else {
Configuration.setCfgBitSavedState(Configuration.CFGBIT_SAVED_DESTPOS_VALID, false);
//#debug info
logger.info("Setting destination to null");
}
}
public void endRouting() {
RouteInstructions.initialRecalcDone = false;
RouteInstructions.icCountOffRouteDetected = 0;
RouteInstructions.routeInstructionsHeight = 0;
RouteInstructions.abortRouteLineProduction();
setRoute(null);
setRouteNodes(null);
}
/**
* This is the callback routine if RouteCalculation is ready
* @param route
*/
public void setRoute(Vector route) {
synchronized(this) {
this.route = route;
}
if (this.route != null) {
// reset off-route as soon as first route connection is known
RouteInstructions.resetOffRoute(this.route, center);
if (ri == null) {
ri = new RouteInstructions(this);
}
// show map during route line production
if (Configuration.getContinueMapWhileRouteing() == Configuration.continueMap_At_Route_Line_Creation) {
resumeImageCollectorAfterRouteCalc();
}
ri.newRoute(this.route);
oldRecalculationTime = System.currentTimeMillis();
}
// show map always after route calculation
resumeImageCollectorAfterRouteCalc();
routeCalc=false;
routeEngine=null;
}
private void resumeImageCollectorAfterRouteCalc() {
try {
if (imageCollector == null) {
startImageCollector();
// imageCollector thread starts up suspended,
// so we need to resume it
imageCollector.resume();
} else if (imageCollector != null) {
imageCollector.newDataReady();
}
repaint();
} catch (Exception e) {
logger.exception(Locale.get("trace.InTraceResumeImageCollector")/*In Trace.resumeImageCollector*/, e);
}
}
/**
* If we are running out of memory, try
* dropping all the caches in order to try
* and recover from out of memory errors.
* Not guaranteed to work, as it needs
* to allocate some memory for dropping
* caches.
*/
public void dropCache() {
tileReader.dropCache();
dictReader.dropCache();
System.gc();
namesThread.dropCache();
urlsThread.dropCache();
System.gc();
if (gpx != null) {
gpx.dropCache();
}
}
public QueueDataReader getDataReader() {
return tileReader;
}
public QueueDictReader getDictReader() {
return dictReader;
}
public Vector getRouteNodes() {
return routeNodes;
}
public void setRouteNodes(Vector routeNodes) {
this.routeNodes = routeNodes;
}
protected void hideNotify() {
//#debug debug
logger.debug("Hide notify has been called, screen will no longer be updated");
if (imageCollector != null) {
imageCollector.suspend();
}
}
protected void showNotify() {
//#debug debug
logger.debug("Show notify has been called, screen will be updated again");
if (imageCollector != null) {
imageCollector.resume();
imageCollector.newDataReady();
}
}
public Vector getRoute() {
return route;
}
public void actionCompleted() {
boolean reAddCommands = true;
if (reAddCommands && Configuration.getCfgBitState(Configuration.CFGBIT_FULLSCREEN)) {
addAllCommands();
}
}
public void showIconMenu() {
if (traceIconMenu == null) {
traceIconMenu = new TraceIconMenu(this, this);
}
traceIconMenu.show();
}
/** uncache the icon menu to reflect changes in the setup or save memory */
public static void uncacheIconMenu() {
//#mdebug trace
if (traceIconMenu != null) {
logger.trace("uncaching TraceIconMenu");
}
//#enddebug
traceIconMenu = null;
}
/** interface for IconMenuWithPages: recreate the icon menu from scratch and show it (introduced for reflecting size change of the Canvas) */
public void recreateAndShowIconMenu() {
uncacheIconMenu();
showIconMenu();
}
/** interface for received actions from the IconMenu GUI */
public void performIconAction(int actionId) {
updateLastUserActionTime();
// when we are low on memory or during route calculation do not cache the icon menu (including scaled images)
if (routeCalc || GpsMid.getInstance().needsFreeingMemory()) {
//#debug info
logger.info("low mem: Uncaching traceIconMenu");
uncacheIconMenu();
}
if (actionId != IconActionPerformer.BACK_ACTIONID) {
commandAction(actionId);
}
}
/** convert distance to string based on user preferences */
// The default way to show a distance is "10km" for
// distances 10km or more, "2,6km" for distances under 10, and
// "600m" for distances under 1km.
public static String showDistance(int meters) {
return showDistance(meters, DISTANCE_GENERIC);
}
public static String showDistance(int meters, int type) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_METRIC)) {
if (type == DISTANCE_UNKNOWN) {
return "???m";
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_DISTANCE_VIEW) && (type != DISTANCE_ALTITUDE)) {
if (meters >= 10000) {
return meters / 1000 + "km";
} else if (meters < 1000) {
return meters + "m";
} else {
// FIXME use e.g. getDecimalSeparator() for decimal comma/point selection
return meters / 1000 + "." + (meters % 1000) / 100 + "km";
}
} else {
return meters + "m";
}
} else {
if (type == DISTANCE_UNKNOWN) {
return "???yd";
} else if (type == DISTANCE_ALTITUDE) {
return Integer.toString((int)(meters / 0.30480 + 0.5)) + "ft";
} else {
return Integer.toString((int)(meters / 0.9144 + 0.5)) + "yd";
}
}
}
}
| true | true | public void commandAction(Command c, Displayable d) {
updateLastUserActionTime();
try {
if((keyboardLocked) && (d != null)) {
// show alert in keypressed() that keyboard is locked
keyPressed(0);
return;
}
if ((c == CMDS[PAN_LEFT25_CMD]) || (c == CMDS[PAN_RIGHT25_CMD])
|| (c == CMDS[PAN_UP25_CMD]) || (c == CMDS[PAN_DOWN25_CMD])
|| (c == CMDS[PAN_LEFT2_CMD]) || (c == CMDS[PAN_RIGHT2_CMD])
|| (c == CMDS[PAN_UP2_CMD]) || (c == CMDS[PAN_DOWN2_CMD])) {
int panX = 0; int panY = 0;
int courseDiff = 0;
int backLightLevelDiff = 0;
if (c == CMDS[PAN_LEFT25_CMD]) {
panX = -25;
} else if (c == CMDS[PAN_RIGHT25_CMD]) {
panX = 25;
} else if (c == CMDS[PAN_UP25_CMD]) {
panY = -25;
} else if (c == CMDS[PAN_DOWN25_CMD]) {
panY = 25;
} else if (c == CMDS[PAN_LEFT2_CMD]) {
if (TrackPlayer.isPlaying) {
TrackPlayer.slower();
} else if (manualRotationMode) {
courseDiff=-5;
} else {
panX = -2;
}
backLightLevelDiff = -25;
} else if (c == CMDS[PAN_RIGHT2_CMD]) {
if (TrackPlayer.isPlaying) {
TrackPlayer.faster();
} else if (manualRotationMode) {
courseDiff=5;
} else {
panX = 2;
}
backLightLevelDiff = 25;
} else if (c == CMDS[PAN_UP2_CMD]) {
if (route!=null && Configuration.getCfgBitState(Configuration.CFGBIT_ROUTE_BROWSING)) {
RouteInstructions.toNextInstruction(1);
} else {
panY = -2;
}
} else if (c == CMDS[PAN_DOWN2_CMD]) {
if (route!=null && Configuration.getCfgBitState(Configuration.CFGBIT_ROUTE_BROWSING)) {
RouteInstructions.toNextInstruction(-1);
} else {
panY = 2;
}
}
if (backLightLevelDiff !=0 && System.currentTimeMillis() < (lastBackLightOnTime + 2500)) {
// turn backlight always on when dimming
Configuration.setCfgBitState(Configuration.CFGBIT_BACKLIGHT_ON, true, false);
lastBackLightOnTime = System.currentTimeMillis();
Configuration.addToBackLightLevel(backLightLevelDiff);
parent.showBackLightLevel();
} else if (imageCollector != null) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null) {
// set compass compassDeviation
if (compassDeviation == 360) {
compassDeviation = 0;
} else {
compassDeviation += courseDiff;
compassDeviation %= 360;
if (course < 0) {
course += 360;
}
}
imageCollector.getCurrentProjection().pan(center, panX, panY);
} else {
// manual rotation
if (courseDiff == 360) {
course = 0; //N
} else {
course += courseDiff;
course %= 360;
if (course < 0) {
course += 360;
}
}
if (panX != 0 || panY != 0) {
gpsRecenter = false;
}
imageCollector.getCurrentProjection().pan(center, panX, panY);
}
}
gpsRecenter = false;
return;
}
if (c == CMDS[EXIT_CMD]) {
// FIXME: This is a workaround. It would be better if recording
// would not be stopped when leaving the map.
if (Legend.isValid && gpx.isRecordingTrk()) {
alert(Locale.get("trace.RecordMode")/*Record Mode*/, Locale.get("trace.PleaseStopRecording")/*Please stop recording before exit.*/ , 2500);
return;
}
if (Legend.isValid) {
pause();
}
parent.exit();
return;
}
if (c == CMDS[START_RECORD_CMD]) {
try {
gpx.newTrk(false);
alert(Locale.get("trace.GpsRecording")/*Gps track recording*/, Locale.get("trace.StartingToRecord")/*Starting to record*/, 1250);
} catch (RuntimeException e) {
receiveMessage(e.getMessage());
}
recordingsMenu = null; // refresh recordings menu
return;
}
if (c == CMDS[STOP_RECORD_CMD]) {
gpx.saveTrk(false);
alert(Locale.get("trace.GpsRecording")/*Gps track recording*/, Locale.get("trace.StoppingToRecord")/*Stopping to record*/, 1250);
recordingsMenu = null; // refresh recordings menu
return;
}
if (c == CMDS[MANAGE_TRACKS_CMD]) {
if (gpx.isRecordingTrk() && !gpx.isRecordingTrkSuspended()) {
// FIXME it's not strictly necessary to stop, after there are translation for the pause
// message, change to Locale.get("trace.YouNeedStopPauseRecording")
alert(Locale.get("trace.RecordMode")/*Record Mode*/, Locale.get("trace.YouNeedStopRecording")/*You need to stop recording before managing tracks.*/ , 4000);
return;
}
GuiGpx guiGpx = new GuiGpx(this);
guiGpx.show();
return;
}
if (c == CMDS[REFRESH_CMD]) {
repaint();
return;
}
if (c == CMDS[CONNECT_GPS_CMD]) {
if (locationProducer == null) {
if (TrackPlayer.isPlaying) {
TrackPlayer.getInstance().stop();
alert(Locale.get("trace.Trackplayer")/*Trackplayer*/, Locale.get("trace.PlayingStopped")/*Playing stopped for connecting to GPS*/, 2500);
}
Thread thread = new Thread(this,"LocationProducer init");
thread.start();
}
return;
}
if (c == CMDS[DISCONNECT_GPS_CMD]) {
if (locationProducer != null) {
locationProducer.close();
}
return;
}
if (c == CMDS[TOGGLE_GPS_CMD]) {
if (isGpsConnected()) {
commandAction(DISCONNECT_GPS_CMD);
} else {
commandAction(CONNECT_GPS_CMD);
}
return;
}
if (c == CMDS[SEARCH_CMD]) {
GuiSearch guiSearch = new GuiSearch(this);
guiSearch.show();
return;
}
if (c == CMDS[ENTER_WAYP_CMD]) {
if (gpx.isLoadingWaypoints()) {
showAlertLoadingWpt();
} else {
GuiWaypointEnter gwpe = new GuiWaypointEnter(this);
gwpe.show();
}
return;
}
if (c == CMDS[MAN_WAYP_CMD]) {
if (gpx.isLoadingWaypoints()) {
showAlertLoadingWpt();
} else {
GuiWaypoint gwp = new GuiWaypoint(this);
gwp.show();
}
return;
}
if (c == CMDS[MAPFEATURES_CMD]) {
GuiMapFeatures gmf = new GuiMapFeatures(this);
gmf.show();
repaint();
return;
}
if (c == CMDS[OVERVIEW_MAP_CMD]) {
GuiOverviewElements ovEl = new GuiOverviewElements(this);
ovEl.show();
repaint();
return;
}
//#if polish.api.wmapi
if (c == CMDS[SEND_MESSAGE_CMD]) {
GuiSendMessage sendMsg = new GuiSendMessage(this);
sendMsg.show();
repaint();
return;
}
//#endif
if (c == CMDS[RECORDINGS_CMD]) {
if (recordingsMenu == null) {
boolean hasJSR120 = Configuration.hasDeviceJSR120();
int noElements = 3;
//#if polish.api.mmapi
noElements += 2;
//#endif
//#if polish.api.wmapi
if (hasJSR120) {
noElements++;
}
//#endif
int idx = 0;
String[] elements = new String[noElements];
if (gpx.isRecordingTrk()) {
elements[idx++] = Locale.get("trace.StopGpxTracklog")/*Stop Gpx tracklog*/;
} else {
elements[idx++] = Locale.get("trace.StartGpxTracklog")/*Start Gpx tracklog*/;
}
elements[idx++] = Locale.get("trace.SaveWaypoint")/*Save waypoint*/;
elements[idx++] = Locale.get("trace.EnterWaypoint")/*Enter waypoint*/;
//#if polish.api.mmapi
elements[idx++] = Locale.get("trace.TakePictures")/*Take pictures*/;
if (audioRec.isRecording()) {
elements[idx++] = Locale.get("trace.StopAudioRecording")/*Stop audio recording*/;
} else {
elements[idx++] = Locale.get("trace.StartAudioRecording")/*Start audio recording*/;
}
//#endif
//#if polish.api.wmapi
if (hasJSR120) {
elements[idx++] = Locale.get("trace.SendSMSMapPos")/*Send SMS (map pos)*/;
}
//#endif
recordingsMenu = new List(Locale.get("trace.Recordings")/*Recordings...*/,Choice.IMPLICIT,elements,null);
recordingsMenu.addCommand(CMDS[OK_CMD]);
recordingsMenu.addCommand(CMDS[BACK_CMD]);
recordingsMenu.setSelectCommand(CMDS[OK_CMD]);
parent.show(recordingsMenu);
recordingsMenu.setCommandListener(this);
}
if (recordingsMenu != null) {
recordingsMenu.setSelectedIndex(0, true);
parent.show(recordingsMenu);
}
return;
}
if (c == CMDS[ROUTINGS_CMD]) {
if (routingsMenu == null) {
String[] elements = new String[4];
if (routeCalc || route != null) {
elements[0] = Locale.get("trace.StopRouting")/*Stop routing*/;
} else {
elements[0] = Locale.get("trace.CalculateRoute")/*Calculate route*/;
}
elements[1] = Locale.get("trace.SetDestination")/*Set destination*/;
elements[2] = Locale.get("trace.ShowDestination")/*Show destination*/;
elements[3] = Locale.get("trace.ClearDestination")/*Clear destination*/;
routingsMenu = new List(Locale.get("trace.Routing2")/*Routing..*/, Choice.IMPLICIT, elements, null);
routingsMenu.addCommand(CMDS[OK_CMD]);
routingsMenu.addCommand(CMDS[BACK_CMD]);
routingsMenu.setSelectCommand(CMDS[OK_CMD]);
routingsMenu.setCommandListener(this);
}
if (routingsMenu != null) {
routingsMenu.setSelectedIndex(0, true);
parent.show(routingsMenu);
}
return;
}
if (c == CMDS[SAVE_WAYP_CMD]) {
if (gpx.isLoadingWaypoints()) {
showAlertLoadingWpt();
} else {
PositionMark posMark = null;
if (gpsRecenter) {
// TODO: If we lose the fix the old position and height
// will be used silently -> we should inform the user
// here that we have no fix - he may not know what's going on.
posMark = new PositionMark(center.radlat, center.radlon,
(int)pos.altitude, pos.timeMillis,
/* fix */ (byte)-1, /* sats */ (byte)-1,
/* sym */ (byte)-1, /* type */ (byte)-1);
} else {
// Cursor does not point to current position
// -> it does not make sense to add elevation and GPS fix info.
posMark = new PositionMark(center.radlat, center.radlon,
PositionMark.INVALID_ELEVATION,
pos.timeMillis, /* fix */ (byte)-1,
/* sats */ (byte)-1, /* sym */ (byte)-1,
/* type */ (byte)-1);
}
/*
if (Configuration.getCfgBitState(Configuration.CFGBIT_WAYPT_OFFER_PREDEF)) {
if (guiWaypointPredefined == null) {
guiWaypointPredefined = new GuiWaypointPredefined(this);
}
if (guiWaypointPredefined != null) {
guiWaypointPredefined.setData(posMark);
guiWaypointPredefined.show();
}
} else {
*/
showGuiWaypointSave(posMark);
//}
}
return;
}
if (c == CMDS[ONLINE_INFO_CMD]) {
//#if polish.api.online
Position oPos = new Position(center.radlat, center.radlon,
0.0f, 0.0f, 0.0f, 0, 0);
GuiWebInfo gWeb = new GuiWebInfo(this, oPos, pc);
gWeb.show();
//#else
alert(Locale.get("trace.NoOnlineCapa")/*No online capabilites*/,
Locale.get("trace.SetAppGeneric")/*Set app=GpsMid-Generic-editing and enableEditing=true in*/ +
Locale.get("trace.PropertiesFile")/*.properties file and recreate GpsMid with Osm2GpsMid.*/,
Alert.FOREVER);
//#endif
}
if (c == CMDS[BACK_CMD]) {
show();
return;
}
if (c == CMDS[OK_CMD]) {
if (d == recordingsMenu) {
switch (recordingsMenu.getSelectedIndex()) {
case 0: {
if ( gpx.isRecordingTrk() ) {
commandAction(STOP_RECORD_CMD);
if (! Configuration.getCfgBitState(Configuration.CFGBIT_GPX_ASK_TRACKNAME_STOP)) {
show();
}
} else {
commandAction(START_RECORD_CMD);
if (! Configuration.getCfgBitState(Configuration.CFGBIT_GPX_ASK_TRACKNAME_START)) {
show();
}
}
break;
}
case 1: {
commandAction(SAVE_WAYP_CMD);
break;
}
case 2: {
commandAction(ENTER_WAYP_CMD);
break;
}
//#if polish.api.mmapi
case 3: {
commandAction(CAMERA_CMD);
break;
}
case 4: {
show();
commandAction(TOGGLE_AUDIO_REC);
break;
}
//#endif
//#if polish.api.mmapi && polish.api.wmapi
case 5: {
commandAction(SEND_MESSAGE_CMD);
break;
}
//#elif polish.api.wmapi
case 3: {
commandAction(SEND_MESSAGE_CMD);
break;
}
//#endif
}
}
if (d == routingsMenu) {
show();
switch (routingsMenu.getSelectedIndex()) {
case 0: {
if (routeCalc || route != null) {
commandAction(ROUTING_STOP_CMD);
} else {
commandAction(ROUTING_START_WITH_MODE_SELECT_CMD);
}
break;
}
case 1: {
commandAction(SET_DEST_CMD);
break;
}
case 2: {
commandAction(SHOW_DEST_CMD);
break;
}
case 3: {
commandAction(CLEAR_DEST_CMD);
break;
}
}
}
return;
}
//#if polish.api.mmapi
if (c == CMDS[CAMERA_CMD]) {
try {
Class GuiCameraClass = Class.forName("de.ueller.midlet.gps.GuiCamera");
Object GuiCameraObject = GuiCameraClass.newInstance();
GuiCameraInterface cam = (GuiCameraInterface)GuiCameraObject;
cam.init(this);
cam.show();
} catch (ClassNotFoundException cnfe) {
logger.exception(Locale.get("trace.YourPhoneNoCamSupport")/*Your phone does not support the necessary JSRs to use the camera*/, cnfe);
}
return;
}
if (c == CMDS[TOGGLE_AUDIO_REC]) {
if (audioRec.isRecording()) {
audioRec.stopRecord();
} else {
audioRec.startRecorder();
}
recordingsMenu = null; // refresh recordings menu
return;
}
//#endif
if (c == CMDS[ROUTING_TOGGLE_CMD]) {
if (routeCalc || route != null) {
commandAction(ROUTING_STOP_CMD);
} else {
commandAction(ROUTING_START_WITH_MODE_SELECT_CMD);
}
return;
}
if (c == CMDS[ROUTING_START_WITH_MODE_SELECT_CMD]) {
gpsRecenter = true;
gpsRecenterInvalid = true;
gpsRecenterStale = true;
GuiRoute guiRoute = new GuiRoute(this, false);
if (Configuration.getCfgBitSavedState(Configuration.CFGBIT_DONT_ASK_FOR_ROUTING_OPTIONS)) {
commandAction(ROUTING_START_CMD);
} else {
guiRoute.show();
}
return;
}
if (c == CMDS[ROUTING_START_CMD]) {
if (! routeCalc || RouteLineProducer.isRunning()) {
routeCalc = true;
if (Configuration.getContinueMapWhileRouteing() != Configuration.continueMap_Always ) {
stopImageCollector();
}
RouteInstructions.resetOffRoute(route, center);
// center of the map is the route source
RoutePositionMark routeSource = new RoutePositionMark(center.radlat, center.radlon);
logger.info("Routing source: " + routeSource);
routeNodes=new Vector();
routeEngine = new Routing(tiles, this);
routeEngine.solve(routeSource, dest);
// resume();
}
routingsMenu = null; // refresh routingsMenu
return;
}
if (c == CMDS[ROUTING_STOP_CMD]) {
NoiseMaker.stopPlayer();
if (routeCalc) {
if (routeEngine != null) {
routeEngine.cancelRouting();
}
alert(Locale.get("trace.RouteCalculation")/*Route Calculation*/, Locale.get("trace.Cancelled")/*Cancelled*/, 1500);
} else {
alert(Locale.get("trace.Routing")/*Routing*/, Locale.get("generic.Off")/*Off*/, 750);
}
endRouting();
routingsMenu = null; // refresh routingsMenu
// redraw immediately
synchronized (this) {
if (imageCollector != null) {
imageCollector.newDataReady();
}
}
routingsMenu = null; // refresh routingsMenu
return;
}
if (c == CMDS[ZOOM_IN_CMD]) {
scale = scale / 1.5f;
autoZoomed = false;
return;
}
if (c == CMDS[ZOOM_OUT_CMD]) {
scale = scale * 1.5f;
autoZoomed = false;
return;
}
if (c == CMDS[MANUAL_ROTATION_MODE_CMD]) {
manualRotationMode = !manualRotationMode;
if (manualRotationMode) {
if (hasPointerEvents()) {
alert(Locale.get("trace.ManualRotation")/*Manual Rotation*/, Locale.get("trace.ChangeCourse")/*Change course with zoom buttons*/, 3000);
} else {
alert(Locale.get("trace.ManualRotation")/*Manual Rotation*/, Locale.get("trace.ChangeCourseWithLeftRightKeys")/*Change course with left/right keys*/, 3000);
}
} else {
alert(Locale.get("trace.ManualRotation")/*Manual Rotation*/, Locale.get("generic.Off")/*Off*/, 750);
}
return;
}
if (c == CMDS[TOGGLE_OVERLAY_CMD]) {
showAddons++;
repaint();
return;
}
if (c == CMDS[TOGGLE_BACKLIGHT_CMD]) {
// toggle Backlight
Configuration.setCfgBitState(Configuration.CFGBIT_BACKLIGHT_ON,
!(Configuration.getCfgBitState(Configuration.CFGBIT_BACKLIGHT_ON)),
false);
lastBackLightOnTime = System.currentTimeMillis();
parent.showBackLightLevel();
return;
}
if (c == CMDS[TOGGLE_FULLSCREEN_CMD]) {
boolean fullScreen = !Configuration.getCfgBitState(Configuration.CFGBIT_FULLSCREEN);
Configuration.setCfgBitState(Configuration.CFGBIT_FULLSCREEN, fullScreen, false);
setFullScreenMode(fullScreen);
return;
}
if (c == CMDS[TOGGLE_MAP_PROJ_CMD]) {
if (manualRotationMode) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null) {
compassDeviation = 0;
} else {
course = 0;
}
alert(Locale.get("trace.ManualRotation"), Locale.get("trace.ManualToNorth"), 750);
} else {
// FIXME rename string to generic
alert(Locale.get("guidiscover.MapProjection")/*Map Projection*/, ProjFactory.nextProj(), 750);
}
// redraw immediately
synchronized (this) {
if (imageCollector != null) {
imageCollector.newDataReady();
}
}
return;
}
if (c == CMDS[TOGGLE_KEY_LOCK_CMD]) {
keyboardLocked = !keyboardLocked;
if (keyboardLocked) {
// show alert that keys are locked
keyPressed(0);
} else {
alert(Locale.get("trace.GpsMid")/*GpsMid*/, hasPointerEvents() ? Locale.get("trace.KeysAndTouchscreenUnlocked")/*Keys and touch screen unlocked*/ : Locale.get("trace.KeysUnlocked")/*Keys unlocked*/, 1000);
}
return;
}
if (c == CMDS[TOGGLE_RECORDING_CMD]) {
if ( gpx.isRecordingTrk() ) {
commandAction(STOP_RECORD_CMD);
} else {
commandAction(START_RECORD_CMD);
}
return;
}
if (c == CMDS[TOGGLE_RECORDING_SUSP_CMD]) {
if (gpx.isRecordingTrk()) {
if ( gpx.isRecordingTrkSuspended() ) {
alert(Locale.get("trace.GpsRecording")/*Gps track recording*/, Locale.get("trace.ResumingRecording")/*Resuming recording*/, 1000);
gpx.resumeTrk();
} else {
alert(Locale.get("trace.GpsRecording")/*Gps track recording*/, Locale.get("trace.SuspendingRecording")/*Suspending recording*/, 1000);
gpx.suspendTrk();
}
}
return;
}
if (c == CMDS[RECENTER_GPS_CMD]) {
gpsRecenter = true;
gpsRecenterInvalid = true;
gpsRecenterStale = true;
autoZoomed = true;
if (pos.latitude != 0.0f) {
receivePosition(pos);
}
newDataReady();
return;
}
if (c == CMDS[SHOW_DEST_CMD]) {
if (dest != null) {
//We are explicitly setting the map to this position, so we probably don't
//want it to be recentered on the GPS immediately.
gpsRecenter = false;
prevPositionNode = center.copy();
center.setLatLonRad(dest.lat, dest.lon);
movedAwayFromDest = false;
updatePosition();
}
else {
alert(Locale.get("trace.ShowDestination")/*Show destination*/, Locale.get("trace.DestinationNotSpecifiedYet")/*Destination is not specified yet*/, 3000);
}
return;
}
if (c == CMDS[SHOW_PREVIOUS_POSITION_CMD]) {
if (prevPositionNode != null) {
//We are explicitly setting the map to this position, so we probably don't
//want it to be recentered on the GPS immediately.
gpsRecenter = false;
center.setLatLon(prevPositionNode);
updatePosition();
}
}
if (c == CMDS[DATASCREEN_CMD]) {
showNextDataScreen(DATASCREEN_NONE);
return;
}
if (c == CMDS[ICON_MENU] && Configuration.getCfgBitState(Configuration.CFGBIT_ICONMENUS)) {
showIconMenu();
return;
}
if (c == CMDS[SETUP_CMD]) {
new GuiDiscover(parent);
return;
}
if (c == CMDS[ABOUT_CMD]) {
new Splash(parent, GpsMid.initDone);
return;
}
if (c == CMDS[CELLID_LOCATION_CMD]) {
if (Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_SECELL && locationProducer != null) {
locationProducer.triggerPositionUpdate();
newDataReady();
} else {
if (cellIDLocationProducer == null) {
// init sleeping cellid location provider if cellid is not primary
cellIDLocationProducer = new SECellID();
if (cellIDLocationProducer != null && !cellIDLocationProducer.init(this)) {
logger.info("Failed to initialise CellID location producer");
}
}
if (cellIDLocationProducer != null) {
cellIDLocationProducer.triggerPositionUpdate();
newDataReady();
}
}
return;
}
if (c == CMDS[MANUAL_LOCATION_CMD]) {
Position setpos = new Position(center.radlat / MoreMath.FAC_DECTORAD,
center.radlon / MoreMath.FAC_DECTORAD,
PositionMark.INVALID_ELEVATION, 0.0f, 0.0f, 1,
System.currentTimeMillis(), Position.TYPE_MANUAL);
// implies center to gps, to give feedback as the gps rectangle
gpsRecenter = true;
// gpsRecenterInvalid = true;
// gpsRecenterStale = true;
autoZoomed = true;
receivePosition(setpos);
receiveStatus(LocationMsgReceiver.STATUS_MANUAL, 0);
newDataReady();
return;
}
if (! routeCalc) {
//#if polish.api.osm-editing
if (c == CMDS[RETRIEVE_XML]) {
if (Legend.enableEdits) {
// -1 alert ("Editing", "Urlidx: " + pc.actualWay.urlIdx, Alert.FOREVER);
if ((pc.actualWay != null) && (getUrl(pc.actualWay.urlIdx) != null)) {
parent.alert ("Url", "Url: " + getUrl(pc.actualWay.urlIdx), Alert.FOREVER);
}
if ((pc.actualWay != null) && (pc.actualWay instanceof EditableWay)) {
EditableWay eway = (EditableWay)pc.actualWay;
GUIosmWayDisplay guiWay = new GUIosmWayDisplay(eway, pc.actualSingleTile, this);
guiWay.show();
guiWay.refresh();
}
} else {
parent.alert("Editing", "Editing support was not enabled in Osm2GpsMid", Alert.FOREVER);
}
}
if (c == CMDS[RETRIEVE_NODE]) {
if (Legend.enableEdits) {
GuiOSMPOIDisplay guiNode = new GuiOSMPOIDisplay(-1, null,
center.radlat, center.radlon, this);
guiNode.show();
guiNode.refresh();
} else {
logger.error(Locale.get("trace.EditingIsNotEnabled")/*Editing is not enabled in this map*/);
}
}
if (c == CMDS[EDIT_ADDR_CMD]) {
if (Legend.enableEdits) {
String streetName = "";
if ((pc != null) && (pc.actualWay != null)) {
streetName = getName(pc.actualWay.nameIdx);
}
GuiOSMAddrDisplay guiAddr = new GuiOSMAddrDisplay(-1, streetName, null,
center.radlat, center.radlon, this);
guiAddr.show();
} else {
logger.error(Locale.get("trace.EditingIsNotEnabled")/*Editing is not enabled in this map*/);
}
}
//#else
if (c == CMDS[RETRIEVE_XML] || c == CMDS[RETRIEVE_NODE] || c == CMDS[EDIT_ADDR_CMD]) {
alert("No online capabilites",
Locale.get("trace.SetAppGeneric")/*Set app=GpsMid-Generic-editing and enableEditing=true in*/ +
Locale.get("trace.PropertiesFile")/*.properties file and recreate GpsMid with Osm2GpsMid.*/,
Alert.FOREVER);
}
//#endif
if (c == CMDS[SET_DEST_CMD]) {
RoutePositionMark pm1 = new RoutePositionMark(center.radlat, center.radlon);
setDestination(pm1);
return;
}
if (c == CMDS[CLEAR_DEST_CMD]) {
setDestination(null);
return;
}
} else {
alert(Locale.get("trace.Error")/*Error*/, Locale.get("trace.CurrentlyInRouteCalculation")/*Currently in route calculation*/, 2000);
}
} catch (Exception e) {
logger.exception(Locale.get("trace.InTraceCommandAction")/*In Trace.commandAction*/, e);
}
}
private void startImageCollector() throws Exception {
//#debug info
logger.info("Starting ImageCollector");
Images images = new Images();
pc = new PaintContext(this, images);
/* move responsibility for overscan to ImageCollector
int w = (this.getWidth() * 125) / 100;
int h = (this.getHeight() * 125) / 100;
*/
imageCollector = new ImageCollector(tiles, this.getWidth(), this.getHeight(), this, images);
// projection = ProjFactory.getInstance(center,course, scale, getWidth(), getHeight());
// pc.setP(projection);
pc.center = center.copy();
pc.scale = scale;
pc.xSize = this.getWidth();
pc.ySize = this.getHeight();
}
private void stopImageCollector(){
//#debug info
logger.info("Stopping ImageCollector");
cleanup();
if (imageCollector != null ) {
imageCollector.stop();
imageCollector=null;
}
System.gc();
}
public void startup() throws Exception {
// logger.info("reading Data ...");
namesThread = new Names();
urlsThread = new Urls();
new DictReader(this);
if (Configuration.getCfgBitState(Configuration.CFGBIT_AUTO_START_GPS)) {
Thread thread = new Thread(this, "Trace");
thread.start();
}
// logger.info("Create queueDataReader");
tileReader = new QueueDataReader(this);
// logger.info("create imageCollector");
dictReader = new QueueDictReader(this);
this.gpx = new Gpx();
this.audioRec = new AudioRecorder();
setDict(gpx, (byte)5);
startImageCollector();
recreateTraceLayout();
}
public void shutdown() {
if (gpx != null) {
// change to "false" to ask for track name if configure to
// currently "true" to not ask for name to ensure fast
// quit & try to avoid loss of data which might result from
// waiting for user to type the name
gpx.saveTrk(true);
}
//#debug debug
logger.debug("Shutdown: stopImageCollector");
stopImageCollector();
if (namesThread != null) {
//#debug debug
logger.debug("Shutdown: namesThread");
namesThread.stop();
namesThread = null;
}
if (urlsThread != null) {
urlsThread.stop();
urlsThread = null;
}
if (dictReader != null) {
//#debug debug
logger.debug("Shutdown: dictReader");
dictReader.shutdown();
dictReader = null;
}
if (tileReader != null) {
//#debug debug
logger.debug("Shutdown: tileReader");
tileReader.shutdown();
tileReader = null;
}
if (locationProducer != null) {
//#debug debug
logger.debug("Shutdown: locationProducer");
locationProducer.close();
}
if (TrackPlayer.isPlaying) {
//#debug debug
logger.debug("Shutdown: TrackPlayer");
TrackPlayer.getInstance().stop();
}
}
public void sizeChanged(int w, int h) {
updateLastUserActionTime();
if (imageCollector != null) {
logger.info("Size of Canvas changed to " + w + "|" + h);
stopImageCollector();
try {
startImageCollector();
imageCollector.resume();
imageCollector.newDataReady();
} catch (Exception e) {
logger.exception(Locale.get("trace.CouldNotReinitialiseImageCollector")/*Could not reinitialise Image Collector after size change*/, e);
}
/**
* Recalculate the projection, as it may depends on the size of the screen
*/
updatePosition();
}
tl = new TraceLayout(0, 0, w, h);
}
protected void paint(Graphics g) {
//#debug debug
logger.debug("Drawing Map screen");
try {
int yc = 1;
int la = 18;
getPC();
// cleans the screen
g.setColor(Legend.COLORS[Legend.COLOR_MAP_BACKGROUND]);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
pc.g = g;
if (imageCollector != null) {
/*
* When painting we receive a copy of the center coordinates
* where the imageCollector has drawn last
* as we need to base the routing instructions on the information
* determined during the way drawing (e.g. the current routePathConnection)
*/
Node drawnCenter = imageCollector.paint(pc);
if (route != null && ri != null && pc.lineP2 != null) {
pc.getP().forward(drawnCenter.radlat, drawnCenter.radlon, pc.lineP2);
/*
* we also need to make sure the current way for the real position
* has really been detected by the imageCollector which happens when drawing the ways
* So we check if we just painted an image that did not cover
* the center of the display because it was too far painted off from
* the display center position and in this case we don't give route instructions
* Thus e.g. after leaving a long tunnel without gps fix there will not be given an
* obsolete instruction from inside the tunnel
*/
int maxAllowedMapMoveOffs = Math.min(pc.xSize/2, pc.ySize/2);
if ( Math.abs(pc.lineP2.x - pc.getP().getImageCenter().x) < maxAllowedMapMoveOffs
&&
Math.abs(pc.lineP2.y - pc.getP().getImageCenter().y) < maxAllowedMapMoveOffs
) {
/*
* we need to synchronize the route instructions on the informations determined during way painting
* so we give the route instructions right after drawing the image with the map
* and use the center of the last drawn image for the route instructions
*/
ri.showRoute(pc, drawnCenter,imageCollector.xScreenOverscan,imageCollector.yScreenOverscan);
}
}
} else {
// show the way bar even if ImageCollector is not running because it's necessary on touch screens to get to the icon menu
tl.ele[TraceLayout.WAYNAME].setText(" ");
}
/* Beginning of voice instructions started from overlay code (besides showRoute above)
*/
// Determine if we are at the destination
if (dest != null) {
float distance = ProjMath.getDistance(dest.lat, dest.lon, center.radlat, center.radlon);
atDest = (distance < 25);
if (atDest) {
if (movedAwayFromDest && Configuration.getCfgBitState(Configuration.CFGBIT_SND_DESTREACHED)) {
GpsMid.mNoiseMaker.playSound(RouteSyntax.getInstance().getDestReachedSound(), (byte) 7, (byte) 1);
}
} else if (!movedAwayFromDest) {
movedAwayFromDest = true;
}
}
// determine if we are currently speeding
speeding = false;
int maxSpeed = 0;
// only detect speeding when gpsRecentered and there is a current way
if (gpsRecenter && actualSpeedLimitWay != null) {
maxSpeed = actualSpeedLimitWay.getMaxSpeed();
// check for winter speed limit if configured
if (Configuration.getCfgBitState(Configuration.CFGBIT_MAXSPEED_WINTER)
&& (actualSpeedLimitWay.getMaxSpeedWinter() > 0)) {
maxSpeed = actualSpeedLimitWay.getMaxSpeedWinter();
}
if (maxSpeed != 0 && speed > (maxSpeed + Configuration.getSpeedTolerance()) ) {
speeding = true;
}
}
if (speeding && Configuration.getCfgBitState(Configuration.CFGBIT_SPEEDALERT_SND)) {
// give speeding alert only every 10 seconds
if ( (System.currentTimeMillis() - lastTimeOfSpeedingSound) > 10000 ) {
lastTimeOfSpeedingSound = System.currentTimeMillis();
GpsMid.mNoiseMaker.immediateSound(RouteSyntax.getInstance().getSpeedLimitSound());
}
}
/*
* end of voice instructions started from overlay code
*/
/*
* the final part of the overlay should not give any voice instructions
*/
g.setColor(Legend.COLOR_MAP_TEXT);
switch (showAddons) {
case 1:
yc = showMemory(g, yc, la);
break;
case 2:
yc = showConnectStatistics(g, yc, la);
break;
default:
showAddons = 0;
if (Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_SCALE_BAR)) {
if (pc != null) {
tl.calcScaleBarWidth(pc);
tl.ele[TraceLayout.SCALEBAR].setText(" ");
}
}
setPointOfTheCompass();
}
showMovement(g);
// Show gpx track recording status
LayoutElement eSolution = tl.ele[TraceLayout.SOLUTION];
LayoutElement eRecorded = tl.ele[TraceLayout.RECORDED_COUNT];
if (gpx.isRecordingTrk()) {
// we are recording tracklogs
if (gpx.isRecordingTrkSuspended()) {
eRecorded.setColor(Legend.COLORS[Legend.COLOR_RECORDING_SUSPENDED_TEXT]); // blue
} else {
eRecorded.setColor(Legend.COLORS[Legend.COLOR_RECORDING_ON_TEXT]); // red
}
eRecorded.setText(gpx.getTrkPointCount() + Locale.get("trace.r")/*r*/);
}
if (TrackPlayer.isPlaying) {
eSolution.setText(Locale.get("trace.Replay")/*Replay*/);
} else {
if (locationProducer == null && !(solution == LocationMsgReceiver.STATUS_CELLID ||
solution == LocationMsgReceiver.STATUS_MANUAL)) {
eSolution.setText(Locale.get("solution.Off")/*Off*/);
} else {
eSolution.setText(solutionStr);
}
}
LayoutElement e = tl.ele[TraceLayout.CELLID];
// show if we are logging cellIDs
if (SECellLocLogger.isCellIDLogging() > 0) {
if (SECellLocLogger.isCellIDLogging() == 2) {
e.setColor(Legend.COLORS[Legend.COLOR_CELLID_LOG_ON_TEXT]); // yellow
} else {
//Attempting to log, but currently no valid info available
e.setColor(Legend.COLORS[Legend.COLOR_CELLID_LOG_ON_ATTEMPTING_TEXT]); // red
}
e.setText(Locale.get("trace.cellIDs")/*cellIDs*/);
}
// show audio recording status
e = tl.ele[TraceLayout.AUDIOREC];
if (audioRec.isRecording()) {
e.setColor(Legend.COLORS[Legend.COLOR_AUDIOREC_TEXT]); // red
e.setText(Locale.get("trace.AudioRec")/*AudioRec*/);
}
if (pc != null) {
showDestination(pc);
}
if (speed > 0 &&
Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_SPEED_IN_MAP)) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_METRIC)) {
tl.ele[TraceLayout.SPEED_CURRENT].setText(" " + Integer.toString(speed) + Locale.get("trace.kmh")/* km/h*/);
} else {
tl.ele[TraceLayout.SPEED_CURRENT].setText(" " + Integer.toString((int)(speed / 1.609344f)) + " mph");
}
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_ALTITUDE_IN_MAP)
&& locationProducer != null
&& LocationMsgReceiverList.isPosValid(solution)
) {
tl.ele[TraceLayout.ALTITUDE].setText(showDistance(altitude, DISTANCE_ALTITUDE));
}
if (dest != null && (route == null || (!RouteLineProducer.isRouteLineProduced() && !RouteLineProducer.isRunning()) )
&& Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_AIR_DISTANCE_IN_MAP)) {
e = Trace.tl.ele[TraceLayout.ROUTE_DISTANCE];
e.setBackgroundColor(Legend.COLORS[Legend.COLOR_RI_DISTANCE_BACKGROUND]);
double distLine = ProjMath.getDistance(center.radlat, center.radlon, dest.lat, dest.lon);
e.setText(Locale.get("trace.Air")/*Air:*/ + showDistance((int) distLine, DISTANCE_AIR));
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_CLOCK_IN_MAP)) {
e = tl.ele[TraceLayout.CURRENT_TIME]; // e is used *twice* below (also as vRelative)
e.setText(DateTimeTools.getClock(System.currentTimeMillis(), true));
/*
don't use new Date() - it is very slow on some Nokia devices
currentTime.setTime( new Date( System.currentTimeMillis() ) );
e.setText(
currentTime.get(Calendar.HOUR_OF_DAY) + ":"
+ HelperRoutines.formatInt2(currentTime.get(Calendar.MINUTE)));
*/
// if current time is visible, positioning OFFROUTE above current time will work
tl.ele[TraceLayout.ROUTE_OFFROUTE].setVRelative(e);
}
setSpeedingSign(maxSpeed);
if (hasPointerEvents()) {
tl.ele[TraceLayout.ZOOM_IN].setText("+");
tl.ele[TraceLayout.ZOOM_OUT].setText("-");
tl.ele[TraceLayout.RECENTER_GPS].setText("|");
e = tl.ele[TraceLayout.SHOW_DEST];
if (atDest && prevPositionNode != null) {
e.setText("<");
e.setActionID(SHOW_PREVIOUS_POSITION_CMD);
} else {
e.setText(">");
e.setActionID(SHOW_DEST_CMD + + (Trace.SET_DEST_CMD << 16) );
}
}
e = tl.ele[TraceLayout.TITLEBAR];
if (currentTitleMsgOpenCount != 0) {
e.setText(currentTitleMsg);
// setTitleMsgTimeOut can be changed in receiveMessage()
synchronized (this) {
if (setTitleMsgTimeout != 0) {
TimerTask timerT = new TimerTask() {
public synchronized void run() {
currentTitleMsgOpenCount--;
lastTitleMsg = currentTitleMsg;
if (currentTitleMsgOpenCount == 0) {
//#debug debug
logger.debug("clearing title");
repaint();
}
}
};
GpsMid.getTimer().schedule(timerT, setTitleMsgTimeout);
setTitleMsgTimeout = 0;
}
}
}
tl.paint(g);
if (currentAlertsOpenCount > 0) {
showCurrentAlert(g);
}
} catch (Exception e) {
logger.silentexception("Unhandled exception in the paint code", e);
}
}
public void showGuiWaypointSave(PositionMark posMark) {
if (guiWaypointSave == null) {
guiWaypointSave = new GuiWaypointSave(this);
}
if (guiWaypointSave != null) {
guiWaypointSave.setData(posMark);
guiWaypointSave.show();
}
}
/** Show an alert telling the user that waypoints are not ready yet.
*/
private void showAlertLoadingWpt() {
alert("Way points", "Way points are not ready yet.", 3000);
}
private void showCurrentAlert(Graphics g) {
Font font = g.getFont();
// request same font in bold for title
Font titleFont = Font.getFont(font.getFace(), Font.STYLE_BOLD, font.getSize());
int fontHeight = font.getHeight();
// add alert title height plus extra space of one line for calculation of alertHeight
int y = titleFont.getHeight() + 2 + fontHeight;
// extra width for alert
int extraWidth = font.charWidth('W');
// alert is at least as wide as alert title
int alertWidth = titleFont.stringWidth(currentAlertTitle);
// width each alert message line must fit in
int maxWidth = getWidth() - extraWidth;
// Two passes: 1st pass calculates placement and necessary size of alert,
// 2nd pass actually does the drawing
for (int i = 0; i <= 1; i++) {
int nextSpaceAt = 0;
int prevSpaceAt = 0;
int start = 0;
// word wrap
do {
int width = 0;
// add word by word until string part is too wide for screen
while (width < maxWidth && nextSpaceAt <= currentAlertMessage.length() ) {
prevSpaceAt = nextSpaceAt;
nextSpaceAt = currentAlertMessage.indexOf(' ', nextSpaceAt);
if (nextSpaceAt == -1) {
nextSpaceAt = currentAlertMessage.length();
}
width = font.substringWidth(currentAlertMessage, start, nextSpaceAt - start);
nextSpaceAt++;
}
nextSpaceAt--;
// Reduce line word by word or if not possible char by char until the
// remaining string part fits to display width
while (width > maxWidth) {
if (prevSpaceAt > start && nextSpaceAt > prevSpaceAt) {
nextSpaceAt = prevSpaceAt;
} else {
nextSpaceAt--;
}
width = font.substringWidth(currentAlertMessage, start, nextSpaceAt - start);
}
// determine maximum alert width
if (alertWidth < width ) {
alertWidth = width;
}
// during the second pass draw the message text lines
if (i==1) {
g.drawSubstring(currentAlertMessage, start, nextSpaceAt - start,
getWidth()/2, y, Graphics.TOP|Graphics.HCENTER);
}
y += fontHeight;
start = nextSpaceAt;
} while (nextSpaceAt < currentAlertMessage.length() );
// at the end of the first pass draw the alert box and the alert title
if (i == 0) {
alertWidth += extraWidth;
int alertHeight = y;
int alertTop = (getHeight() - alertHeight) /2;
//alertHeight += fontHeight/2;
int alertLeft = (getWidth() - alertWidth) / 2;
// alert background color
g.setColor(Legend.COLORS[Legend.COLOR_ALERT_BACKGROUND]);
g.fillRect(alertLeft, alertTop, alertWidth, alertHeight);
// background color for alert title
g.setColor(Legend.COLORS[Legend.COLOR_ALERT_TITLE_BACKGROUND]);
g.fillRect(alertLeft, alertTop, alertWidth, fontHeight + 3);
// alert border
g.setColor(Legend.COLORS[Legend.COLOR_ALERT_BORDER]);
g.setStrokeStyle(Graphics.SOLID);
g.drawRect(alertLeft, alertTop, alertWidth, fontHeight + 3); // title border
g.drawRect(alertLeft, alertTop, alertWidth, alertHeight); // alert border
// draw alert title
y = alertTop + 2; // output position of alert title
g.setFont(titleFont);
g.setColor(Legend.COLORS[Legend.COLOR_ALERT_TEXT]);
g.drawString(currentAlertTitle, getWidth()/2, y , Graphics.TOP|Graphics.HCENTER);
g.setFont(font);
// output alert message 1.5 lines below alert title in the next pass
y += (fontHeight * 3 / 2);
}
} // end for
// setAlertTimeOut can be changed in receiveMessage()
synchronized (this) {
if (setAlertTimeout != 0) {
TimerTask timerT = new TimerTask() {
public synchronized void run() {
currentAlertsOpenCount--;
if (currentAlertsOpenCount == 0) {
//#debug debug
logger.debug("clearing alert");
repaint();
}
}
};
GpsMid.getTimer().schedule(timerT, setAlertTimeout);
setAlertTimeout = 0;
}
}
}
private void setSpeedingSign(int maxSpeed) {
// speeding = true;
if (Configuration.getCfgBitState(Configuration.CFGBIT_SPEEDALERT_VISUAL)
&&
(
speeding
||
(System.currentTimeMillis() - startTimeOfSpeedingSign) < 3000
)
) {
if (speeding) {
speedingSpeedLimit = maxSpeed;
startTimeOfSpeedingSign = System.currentTimeMillis();
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_METRIC)) {
tl.ele[TraceLayout.SPEEDING_SIGN].setText(Integer.toString(speedingSpeedLimit));
} else {
tl.ele[TraceLayout.SPEEDING_SIGN].setText(Integer.toString((int)(speedingSpeedLimit / 1.609344f)));
}
} else {
startTimeOfSpeedingSign = 0;
}
}
/**
*
*/
private void getPC() {
pc.course = course;
pc.scale = scale;
pc.center = center.copy();
// pc.setP( projection);
// projection.inverse(pc.xSize, 0, pc.screenRU);
// projection.inverse(0, pc.ySize, pc.screenLD);
pc.dest = dest;
}
public void cleanup() {
namesThread.cleanup();
urlsThread.cleanup();
tileReader.incUnusedCounter();
dictReader.incUnusedCounter();
}
// public void searchElement(PositionMark pm) throws Exception {
// PaintContext pc = new PaintContext(this, null);
// // take a bigger angle for lon because of positions near to the poles.
// Node nld = new Node(pm.lat - 0.0001f, pm.lon - 0.0005f, true);
// Node nru = new Node(pm.lat + 0.0001f, pm.lon + 0.0005f, true);
// pc.searchLD = nld;
// pc.searchRU = nru;
// pc.dest = pm;
// pc.setP(new Proj2D(new Node(pm.lat, pm.lon, true), 5000, 100, 100));
// for (int i = 0; i < 4; i++) {
// tiles[i].walk(pc, Tile.OPT_WAIT_FOR_LOAD);
// }
// }
public void searchNextRoutableWay(RoutePositionMark pm) throws Exception {
PaintContext pc = new PaintContext(this, null);
// take a bigger angle for lon because of positions near to the pols.
// Node nld=new Node(pm.lat - 0.0001f,pm.lon - 0.0005f,true);
// Node nru=new Node(pm.lat + 0.0001f,pm.lon + 0.0005f,true);
// pc.searchLD=nld;
// pc.searchRU=nru;
pc.squareDstToActualRoutableWay = Float.MAX_VALUE;
pc.xSize = 100;
pc.ySize = 100;
// retry searching an expanding region at the position mark
Projection p;
do {
p = new Proj2D(new Node(pm.lat,pm.lon, true),5000,pc.xSize,pc.ySize);
pc.setP(p);
for (int i=0; i<4; i++) {
tiles[i].walk(pc, Tile.OPT_WAIT_FOR_LOAD | Tile.OPT_FIND_CURRENT);
}
// stop the search when a routable way is found
if (pc.actualRoutableWay != null) {
break;
}
// expand the region that gets searched for a routable way
pc.xSize += 100;
pc.ySize += 100;
// System.out.println(pc.xSize);
} while(MoreMath.dist(p.getMinLat(), p.getMinLon(), p.getMinLat(), p.getMaxLon()) < 500); // until we searched at least 500 m edge length
Way w = pc.actualRoutableWay;
pm.setEntity(w, pc.currentPos.nodeLat, pc.currentPos.nodeLon);
}
private void setPointOfTheCompass() {
String c = "";
if (ProjFactory.getProj() != ProjFactory.NORTH_UP
&& Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_POINT_OF_COMPASS)) {
c = Configuration.getCompassDirection(course);
}
// if tl shows big onscreen buttons add spaces to compass directions consisting of only one char or not shown
if (tl.bigOnScreenButtons && c.length() <= 1) {
if (ProjFactory.getProj() == ProjFactory.NORTH_UP) {
c = "(" + Configuration.getCompassDirection(0) + ")";
} else {
c = " " + c + " ";
}
}
tl.ele[TraceLayout.POINT_OF_COMPASS].setText(c);
}
private int showConnectStatistics(Graphics g, int yc, int la) {
g.setColor(Legend.COLORS[Legend.COLOR_MAP_TEXT]);
// only try to show compass id and cell id if user has somehow switched them on
GSMCell cell = null;
if (cellIDLocationProducer != null || Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_SECELL) {
cell = CellIdProvider.getInstance().obtainCachedCellID();
}
Compass compass = null;
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION)) {
compass = CompassProvider.getInstance().obtainCachedCompass();
}
if (cell == null) {
g.drawString("No Cell ID available", 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
} else {
g.drawString("Cell: MCC=" + cell.mcc + " MNC=" + cell.mnc, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString("LAC=" + cell.lac, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString("cellID=" + cell.cellID, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
}
if (compass == null) {
g.drawString("No compass direction available", 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
} else {
g.drawString("Compass direction: " + compass.direction, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
}
if (statRecord == null) {
g.drawString("No stats yet", 0, yc, Graphics.TOP
| Graphics.LEFT);
return yc+la;
}
//#mdebug info
for (byte i = 0; i < LocationMsgReceiver.SIRF_FAIL_COUNT; i++) {
g.drawString(statMsg[i] + statRecord[i], 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
}
//#enddebug
g.drawString("BtQual : " + btquality, 0, yc, Graphics.TOP | Graphics.LEFT);
yc += la;
g.drawString("Count : " + collected, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
return yc;
}
public void showDestination(PaintContext pc) {
try {
if (dest != null) {
pc.getP().forward(dest.lat, dest.lon, pc.lineP2);
// System.out.println(dest.toString());
int x = pc.lineP2.x - imageCollector.xScreenOverscan;
int y = pc.lineP2.y - imageCollector.yScreenOverscan;
pc.g.drawImage(pc.images.IMG_DEST, x, y, CENTERPOS);
pc.g.setColor(Legend.COLORS[Legend.COLOR_DEST_TEXT]);
if (dest.displayName != null) {
pc.g.drawString(dest.displayName, x, y+8,
Graphics.TOP | Graphics.HCENTER);
}
pc.g.setColor(Legend.COLORS[Legend.COLOR_DEST_LINE]);
pc.g.setStrokeStyle(Graphics.SOLID);
pc.g.drawLine(x, y, pc.getP().getImageCenter().x - imageCollector.xScreenOverscan,
pc.getP().getImageCenter().y - imageCollector.yScreenOverscan);
}
} catch (Exception e) {
if (imageCollector == null) {
logger.silentexception("No ImageCollector", e);
}
e.printStackTrace();
}
}
/**
* Draws the position square, the movement line and the center cross.
*
* @param g Graphics context for drawing
*/
public void showMovement(Graphics g) {
IntPoint centerP = null;
try {
if (imageCollector != null) {
g.setColor(Legend.COLORS[Legend.COLOR_MAP_CURSOR]);
centerP = pc.getP().getImageCenter();
int centerX = centerP.x - imageCollector.xScreenOverscan;
int centerY = centerP.y - imageCollector.yScreenOverscan;
int posX, posY;
if (!gpsRecenter) {
IntPoint p1 = new IntPoint(0, 0);
pc.getP().forward((pos.latitude * MoreMath.FAC_DECTORAD),
(pos.longitude * MoreMath.FAC_DECTORAD), p1);
posX = p1.getX()-imageCollector.xScreenOverscan;
posY = p1.getY()-imageCollector.yScreenOverscan;
} else {
posX = centerX;
posY = centerY;
}
g.setColor(Legend.COLORS[Legend.COLOR_MAP_POSINDICATOR]);
float radc = course * MoreMath.FAC_DECTORAD;
int px = posX + (int) (Math.sin(radc) * 20);
int py = posY - (int) (Math.cos(radc) * 20);
// crosshair center cursor
if (!gpsRecenter || gpsRecenterInvalid) {
g.drawLine(centerX, centerY - 12, centerX, centerY + 12);
g.drawLine(centerX - 12, centerY, centerX + 12, centerY);
g.drawArc(centerX - 5, centerY - 5, 10, 10, 0, 360);
}
if (! gpsRecenterInvalid) {
// gps position spot
pc.g.drawImage(gpsRecenterStale ? pc.images.IMG_POS_BG_STALE : pc.images.IMG_POS_BG, posX, posY, CENTERPOS);
// gps position rectangle
g.drawRect(posX - 4, posY - 4, 8, 8);
g.drawLine(posX, posY, px, py);
}
}
} catch (Exception e) {
if (imageCollector == null) {
logger.silentexception("No ImageCollector", e);
}
if (centerP == null) {
logger.silentexception("No centerP", e);
}
e.printStackTrace();
}
}
/**
* Show next screen in the sequence of data screens
* (tacho, trip, satellites).
* @param currentScreen Data screen currently shown, use the DATASCREEN_XXX
* constants from this class. Use DATASCREEN_NONE if none of them
* is on screen i.e. the first one should be shown.
*/
public void showNextDataScreen(int currentScreen) {
switch (currentScreen)
{
case DATASCREEN_TACHO:
// Tacho is followed by Trip.
if (guiTrip == null) {
guiTrip = new GuiTrip(this);
}
if (guiTrip != null) {
guiTrip.show();
}
break;
case DATASCREEN_TRIP:
// Trip is followed by Satellites.
if (guiSatellites == null) {
guiSatellites = new GuiSatellites(this, locationProducer);
}
if (guiSatellites != null) {
guiSatellites.show();
}
break;
case DATASCREEN_SATS:
// After Satellites, go back to map.
this.show();
break;
case DATASCREEN_NONE:
default:
// Tacho is first data screen
if (guiTacho == null) {
guiTacho = new GuiTacho(this);
}
if (guiTacho != null) {
guiTacho.show();
}
break;
}
}
public int showMemory(Graphics g, int yc, int la) {
g.setColor(0);
g.drawString(Locale.get("trace.Freemem")/*Freemem: */ + runtime.freeMemory(), 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.Totmem")/*Totmem: */ + runtime.totalMemory(), 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.Percent")/*Percent: */
+ (100f * runtime.freeMemory() / runtime.totalMemory()), 0, yc,
Graphics.TOP | Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.ThreadsRunning")/*Threads running: */
+ Thread.activeCount(), 0, yc,
Graphics.TOP | Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.Names")/*Names: */ + namesThread.getNameCount(), 0, yc,
Graphics.TOP | Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.SingleT")/*Single T: */ + tileReader.getLivingTilesCount() + "/"
+ tileReader.getRequestQueueSize(), 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.FileT")/*File T: */ + dictReader.getLivingTilesCount() + "/"
+ dictReader.getRequestQueueSize() + " Map: " + ImageCollector.icDuration + " ms", 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.LastMsg")/*LastMsg: */ + lastTitleMsg, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString( Locale.get("trace.at")/*at */ + lastTitleMsgClock, 0, yc,
Graphics.TOP | Graphics.LEFT );
return (yc);
}
private void updatePosition() {
if (pc != null) {
pc.center = center.copy();
pc.scale = scale;
pc.course=course;
repaint();
if (locationUpdateListeners != null && !TrackPlayer.isPlaying) {
synchronized (locationUpdateListeners) {
for (int i = 0; i < locationUpdateListeners.size(); i++) {
((LocationUpdateListener)locationUpdateListeners.elementAt(i)).loctionUpdated();
}
}
}
}
}
public synchronized void receivePosition(float lat, float lon, float scale) {
//#debug debug
logger.debug("Now displaying: " + (lat * MoreMath.FAC_RADTODEC) + " | " +
(lon * MoreMath.FAC_RADTODEC));
//We are explicitly setting the map to this position, so we probably don't
//want it to be recentered on the GPS immediately.
gpsRecenter = false;
center.setLatLonRad(lat, lon);
this.scale = scale;
updatePosition();
}
public synchronized void receiveCompassStatus(int status) {
}
public synchronized void receiveCompass(float direction) {
//#debug debug
logger.debug("Got compass reading: " + direction);
compassDirection = (int) direction;
compassDeviated = ((int) direction + compassDeviation + 360) % 360;
// TODO: allow for user to use compass for turning the map in panning mode
// (gpsRenter test below switchable by user setting)
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null && gpsRecenter) {
updateCourse(compassDeviated);
//repaint();
}
// course = compassDeviated;
//}
}
public static void updateLastUserActionTime() {
lastUserActionTime = System.currentTimeMillis();
}
public static long getDurationSinceLastUserActionTime() {
return System.currentTimeMillis() - lastUserActionTime;
}
public void updateCourse(int newcourse) {
coursegps = newcourse;
/* don't rotate too fast
*/
if ((newcourse - course)> 180) {
course = course + 360;
}
if ((course-newcourse)> 180) {
newcourse = newcourse + 360;
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null) {
course = newcourse;
} else {
// FIXME I think this is too slow a turn at least when course is
// of good quality, turning should be faster. This probably alleviates
// the trouble caused by unreliable gps course. However,
// some kind of heuristic, averaging course or evaluating the
// quality of course and fast or instant rotation with a known good GPS fix
// should be implemented instead of assuming course is always unreliable.
// The course fluctuations are lesser in faster speeds, so if we're constantly
// (for three consecutive locations) above say 5 km/h, a reasonable approach
// could be to use direct course change in thet case, and for speed below
// 5 km/h use the slow turning below.
// jkpj 2010-01-17
course = course + ((newcourse - course)*1)/4 + 360;
}
while (course > 360) {
course -= 360;
}
}
public synchronized void receivePosition(Position pos) {
// FIXME signal on location gained
//#debug info
logger.info("New position: " + pos);
collected++;
if (Configuration.getAutoRecenterToGpsMilliSecs() !=0 &&
getDurationSinceLastUserActionTime() > Configuration.getAutoRecenterToGpsMilliSecs()
&& isShown()
) {
gpsRecenter = true;
//autoZoomed = true;
}
if (Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_JSR179) {
if (pos.type == Position.TYPE_GPS_LASTKNOWN) {
// if we have a current cell id fix from cellid location,
// don't overwrite it with a stale GPS location, but ignore the position
// FIXME perhaps compare timestamps here in case the last known gps is later
if (this.pos.type == Position.TYPE_CELLID) {
return;
}
gpsRecenterInvalid = false;
gpsRecenterStale = true;
}
}
this.pos = pos;
if (pos.type == Position.TYPE_GPS || pos.type == Position.TYPE_CELLID || pos.type == Position.TYPE_MANUAL) {
gpsRecenterInvalid = false;
gpsRecenterStale = false;
}
if (gpsRecenter) {
center.setLatLonDeg(pos.latitude, pos.longitude);
speed = (int) (pos.speed * 3.6f);
fspeed = pos.speed * 3.6f;
// FIXME add auto-fallback mode where course is from GPS at high speeds and from compass
// at low speeds
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null) {
updateCourse(compassDeviated);
} else if (fspeed >= courseMinSpeed && pos.course != Float.NaN ) {
// Problem: resolve issue erratic course due to GPS fluctuation
// when GPS reception is poor (maybe 3..7S),
// causes unnecessary and disturbing map rotation when device is in one location
// Heuristic for solving: After being still, require
// three consecutive over-the-limit speed readings with roughly the
// same course
if (thirdPrevCourse != -1) {
// first check for normal flow of things, we've had three valid courses after movement start
updateCourse((int) pos.course);
} else if (prevCourse == -1) {
// previous course was invalid,
// don't set course yet, but set the first tentatively good course
prevCourse = (int) pos.course;
} else if (secondPrevCourse == -1) {
// the previous course was the first good one.
// If this course is in the same 60-degree
// sector as the first course, we have two valid courses
if (Math.abs(prevCourse - (int)pos.course) < 30 || Math.abs(prevCourse - (int)pos.course) > 330) {
secondPrevCourse = prevCourse;
}
prevCourse = (int) pos.course;
} else {
// we have received two previous valid curses, check for this one
if (Math.abs(prevCourse - (int)pos.course) < 30 || Math.abs(prevCourse - (int)pos.course) > 330) {
thirdPrevCourse = secondPrevCourse;
//No need to set these as we'll now trust courses until speed goes below limit
// - unless we'll later add averaging of recent courses for poor GPS reception
//secondPrevCourse = prevCourse;
//prevCourse = (int) pos.course;
updateCourse((int) pos.course);
} else {
prevCourse = (int) pos.course;
secondPrevCourse = -1;
}
}
} else {
// speed under the minimum, invalidate all prev courses
prevCourse = -1;
secondPrevCourse = -1;
thirdPrevCourse = -1;
}
}
if (gpx.isRecordingTrk()) {
try {
// don't tracklog manual cellid position or gps start/stop last known position
if ((Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_JSR179
&& pos.type == Position.TYPE_CELLID) || pos.type == Position.TYPE_GPS_LASTKNOWN) {
} else {
gpx.addTrkPt(pos);
}
} catch (Exception e) {
receiveMessage(e.getMessage());
}
}
altitude = (int) (pos.altitude);
if (Configuration.getCfgBitState(Configuration.CFGBIT_AUTOZOOM)
&& gpsRecenter
&& (isGpsConnected() || TrackPlayer.isPlaying)
&& autoZoomed
&& pc.getP() != null
&& pos.speed != Float.NaN // if speed is unknown do not autozoom
) {
// the minimumScale at 20km/h and below is equivalent to having zoomed in manually once from the startup zoom level
final float minimumScale = Configuration.getRealBaseScale() / 1.5f;
final int minimumSpeed = 20;
// the maximumScale at 160km/h and above is equivalent to having zoomed out manually once from the startup zoom level
final float maximumScale = Configuration.getRealBaseScale() * 1.5f;
final int maximumSpeed = 160;
int speedForScale = speed;
float newScale = minimumScale + (maximumScale - minimumScale) * (speedForScale - minimumSpeed) / (maximumSpeed - minimumSpeed);
// make sure the new scale is within the minimum / maximum scale values
if (newScale < minimumScale) {
newScale = minimumScale;
} else if (newScale > maximumScale) {
newScale = maximumScale;
}
scale = newScale;
// // calculate meters to top of screen
// float topLat = pc.getP().getMaxLat();
// float topLon = (pc.getP().getMinLon() + pc.getP().getMaxLon()) / 2f;
// float distance = MoreMath.dist(center.radlat, center.radlon, topLat, topLon );
// System.out.println("current distance to top of screen: " + distance);
//
// // avoid zooming in or out too far
// int speedForScale = course;
// if (speedForScale < 30) {
// speedForScale = 30;
// } else if (speedForScale > 160) {
// speedForScale = 160;
// }
//
// final float SECONDS_TO_PREVIEW = 45f;
// float metersToPreview = (float) speedForScale / 3.6f * SECONDS_TO_PREVIEW;
// System.out.println(metersToPreview + "meters to preview at " + speedForScale + "km/h");
//
// if (metersToPreview < 2000) {
// // calculate top position that needs to be visible to preview the metersToPreview
// topLat = center.radlat + (topLat - center.radlat) * metersToPreview / distance;
// topLon = center.radlon + (topLon - center.radlon) * metersToPreview / distance;
// System.out.println("new distance to top:" + MoreMath.dist(center.radlat, center.radlon, topLat, topLon ));
//
// /*
// * calculate scale factor, we multiply this again with 2 * 1.2 = 2.4 to take into account we calculated half the screen height
// * and 1.2f is probably the factor the PaintContext is larger than the display size
// * (new scale is calculated similiar to GuiWaypoint)
// */
// IntPoint intPoint1 = new IntPoint(0, 0);
// IntPoint intPoint2 = new IntPoint(getWidth(), getHeight());
// Node n1 = new Node(center.radlat, center.radlon, true);
// Node n2 = new Node(topLat, topLon, true);
// scale = pc.getP().getScale(n1, n2, intPoint1, intPoint2) * 2.4f;
// }
}
updatePosition();
}
public synchronized Position getCurrentPosition() {
return this.pos;
}
public synchronized void receiveMessage(String s) {
// #debug info
logger.info("Setting title: " + s);
currentTitleMsg = s;
synchronized (this) {
/*
* only increase the number of current title messages
* if the timer already has been set in the display code
*/
if (setTitleMsgTimeout == 0) {
currentTitleMsgOpenCount++;
}
setTitleMsgTimeout = 3000;
}
lastTitleMsgClock = DateTimeTools.getClock(System.currentTimeMillis(), false);
repaint();
}
public void receiveSatellites(Satellite[] sats) {
// Not interested
}
/** Shows an alert message
*
* @param title The title of the alert
* @param message The message text
* @param timeout Timeout in ms. Please reserve enough time so the user can
* actually read the message. Use Alert.FOREVER if you want no timeout.
*/
public synchronized void alert(String title, String message, int timeout) {
// #debug info
logger.info("Showing trace alert: " + title + ": " + message);
if (timeout == Alert.FOREVER) {
timeout = 10000;
}
currentAlertTitle = title;
currentAlertMessage = message;
synchronized (this) {
/*
* only increase the number of current open alerts
* if the timer already has been set in the display code
*/
if (setAlertTimeout == 0) {
currentAlertsOpenCount++;
}
setAlertTimeout = timeout;
}
repaint();
}
public MIDlet getParent() {
return parent;
}
protected void pointerPressed(int x, int y) {
updateLastUserActionTime();
long currTime = System.currentTimeMillis();
pointerDragged = false;
pointerDraggedMuch = false;
pointerActionDone = false;
// remember center when the pointer was pressed for dragging
centerPointerPressedN = center.copy();
if (imageCollector != null) {
panProjection=imageCollector.getCurrentProjection();
pickPointStart=panProjection.inverse(x,y, pickPointStart);
} else {
panProjection = null;
}
// remember the LayoutElement the pointer is pressed down at, this will also highlight it on the display
int touchedElementId = tl.getElementIdAtPointer(x, y);
if (touchedElementId >= 0 && (!keyboardLocked || tl.getActionIdAtPointer(x, y) == Trace.ICON_MENU)
&&
tl.isAnyActionIdAtPointer(x, y)
) {
tl.setTouchedElement((LayoutElement) tl.elementAt(touchedElementId));
repaint();
}
// check for double press
if (!keyboardLocked && currTime - pressedPointerTime < DOUBLETAP_MAXDELAY) {
doubleTap(x, y);
}
// Remember the time and position the pointer was pressed after the check for double tap,
// so the double tap code will check for the position of the first of the two taps
pressedPointerTime = currTime;
Trace.touchX = x;
Trace.touchY = y;
// Give a message if keyboard/user interface is locked.
// This must be done after remembering the touchX/Y positions as they are needed to unlock
if (keyboardLocked) {
keyPressed(0);
return;
}
// // when these statements are reached, no double tap action has been executed,
// // so check here if there's currently already a TimerTask waiting for a single tap.
// // If yes, perform the current single tap action immediately before starting the next TimerTask
// if (checkingForSingleTap && !pointerDraggedMuch) {
// singleTap();
// pointerActionDone = false;
// }
//
longTapTimerTask = new TimerTask() {
public void run() {
// if no action (e.g. from double tap) is already done
// and the pointer did not move or if it was pressed on a control and not moved much
if (!pointerActionDone && !pointerDraggedMuch) {
if (System.currentTimeMillis() - pressedPointerTime >= LONGTAP_DELAY){
longTap();
}
}
}
};
try {
// set timer to continue check if this is a long tap
GpsMid.getTimer().schedule(longTapTimerTask, LONGTAP_DELAY);
} catch (Exception e) {
logger.error(Locale.get("trace.NoLongTapTimerTask")/*No LongTap TimerTask: */ + e.toString());
}
}
protected void pointerReleased(int x, int y) {
// releasing the pointer cancels the check for long tap
if (longTapTimerTask != null) {
longTapTimerTask.cancel();
}
// releasing the pointer will clear the highlighting of the touched element
if (tl.getTouchedElement() != null) {
tl.clearTouchedElement();
repaint();
}
if (!pointerActionDone && !keyboardLocked) {
touchReleaseX = x;
touchReleaseY = y;
// check for a single tap in a timer started after the maximum double tap delay
// if the timer will not be cancelled by a double tap, the timer will execute the single tap command
singleTapTimerTask = new TimerTask() {
public void run() {
if (!keyboardLocked) {
singleTap(touchReleaseX, touchReleaseY);
}
}
};
try {
// set timer to check if this is a single tap
GpsMid.getTimer().schedule(singleTapTimerTask, DOUBLETAP_MAXDELAY);
} catch (Exception e) {
logger.error(Locale.get("trace.NoSingleTapTimerTask")/*No SingleTap TimerTask: */ + e.toString());
}
if (pointerDragged) {
pointerDragged(x , y);
return;
}
}
}
protected void pointerDragged (int x, int y) {
updateLastUserActionTime();
LayoutElement e = tl.getElementAtPointer(x, y);
if (tl.getTouchedElement() != e) {
// leaving the touched element cancels the check for long tap
if (longTapTimerTask != null) {
longTapTimerTask.cancel();
}
tl.clearTouchedElement();
repaint();
}
// If the initially touched element is reached again during dragging, highlight it
if (tl.getElementAtPointer(touchX, touchY) == e && tl.isAnyActionIdAtPointer(x, y)) {
tl.setTouchedElement(e);
repaint();
}
if (pointerActionDone) {
return;
}
// check if there's been much movement, do this before the slide lock/unlock
// to avoid a single tap action when not sliding enough
if (Math.abs(x - Trace.touchX) > 8
||
Math.abs(y - Trace.touchY) > 8
) {
pointerDraggedMuch = true;
// avoid double tap triggering on fast consecutive drag actions starting at almost the same position
pressedPointerTime = 0;
}
// slide at least 1/4 display width to lock / unlock GpsMid
if (tl.getActionIdAtPointer(touchX, touchY) == Trace.ICON_MENU) {
if ( tl.getActionIdAtPointer(x, y) == Trace.ICON_MENU
&&
x - touchX > getWidth() / 4
) {
commandAction(TOGGLE_KEY_LOCK_CMD);
pointerActionDone = true;
}
return;
}
if (keyboardLocked) {
return;
}
pointerDragged = true;
// do not start map dragging on a touch control if only dragged slightly
if (!pointerDraggedMuch && tl.getElementIdAtPointer(touchX, touchY) >= 0) {
return;
}
if (tl.getElementIdAtPointer(touchX, touchY) < 0 && imageCollector != null && panProjection != null) {
// difference between where the pointer was pressed and is currently dragged
// int diffX = Trace.touchX - x;
// int diffY = Trace.touchY - y;
//
// IntPoint centerPointerPressedP = new IntPoint();
pickPointEnd=panProjection.inverse(x,y, pickPointEnd);
center.radlat=centerPointerPressedN.radlat-(pickPointEnd.radlat-pickPointStart.radlat);
center.radlon=centerPointerPressedN.radlon-(pickPointEnd.radlon-pickPointStart.radlon);
// System.out.println("diff " + diffX + "/" + diffY + " " + (pickPointEnd.radlat-pickPointStart.radlat) + "/" + (pickPointEnd.radlon-pickPointStart.radlon) );
imageCollector.newDataReady();
gpsRecenter = false;
}
}
private void singleTap(int x, int y) {
pointerActionDone = true;
// if not tapping a control, then the map area must be tapped so we set the touchable button sizes
if (tl.getElementIdAtPointer(touchX, touchY) < 0) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_MAPTAP_SINGLE)) {
// if pointer was dragged much, do not recognize a single tap on the map
if (pointerDraggedMuch) {
return;
}
// #debug debug
logger.debug("single tap map");
if (!tl.bigOnScreenButtons) {
tl.setOnScreenButtonSize(true);
// set timer to continuously check if the last user interaction is old enough to make the buttons small again
final long BIGBUTTON_DURATION = 5000;
bigButtonTimerTask = new TimerTask() {
public void run() {
if (System.currentTimeMillis() - lastUserActionTime > BIGBUTTON_DURATION ) {
// make the on screen touch buttons small again
tl.setOnScreenButtonSize(false);
requestRedraw();
bigButtonTimerTask.cancel();
}
}
};
try {
GpsMid.getTimer().schedule(bigButtonTimerTask, BIGBUTTON_DURATION, 500);
} catch (Exception e) {
logger.error("Error scheduling bigButtonTimerTask: " + e.toString());
}
}
}
repaint();
} else if (tl.getElementIdAtPointer(x, y) == tl.getElementIdAtPointer(touchX, touchY)) {
tl.clearTouchedElement();
int actionId = tl.getActionIdAtPointer(x, y);
if (actionId > 0) {
// #debug debug
logger.debug("single tap button: " + actionId + " x: " + touchX + " y: " + touchY);
if (System.currentTimeMillis() < (lastBackLightOnTime + 2500)) {
if (actionId == ZOOM_IN_CMD) {
actionId = PAN_RIGHT2_CMD;
} else if (actionId == ZOOM_OUT_CMD) {
actionId = PAN_LEFT2_CMD;
}
} else if (manualRotationMode) {
if (actionId == ZOOM_IN_CMD) {
actionId = PAN_LEFT2_CMD;
} else if (actionId == ZOOM_OUT_CMD) {
actionId = PAN_RIGHT2_CMD;
}
} else if (TrackPlayer.isPlaying) {
if (actionId == ZOOM_IN_CMD) {
actionId = PAN_RIGHT2_CMD;
} else if (actionId == ZOOM_OUT_CMD) {
actionId = PAN_LEFT2_CMD;
}
}
commandAction(actionId);
repaint();
}
}
}
private void doubleTap(int x, int y) {
// if not double tapping a control, then the map area must be double tapped and we zoom in
if (tl.getElementIdAtPointer(touchX, touchY) < 0) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_MAPTAP_DOUBLE)) {
// if this is a double press on the map, cancel the timer checking for a single press
if (singleTapTimerTask != null) {
singleTapTimerTask.cancel();
}
// if pointer was dragged much, do not recognize a double tap on the map
if (pointerDraggedMuch) {
return;
}
//#debug debug
logger.debug("double tap map");
pointerActionDone = true;
commandAction(ZOOM_IN_CMD);
}
repaint();
return;
} else if (tl.getTouchedElement() == tl.getElementAtPointer(x, y) ){
// double tapping a control
int actionId = tl.getActionIdDoubleAtPointer(x, y);
//#debug debug
logger.debug("double tap button: " + actionId + " x: " + x + " y: " + x);
if (actionId > 0) {
// if this is a double press on a control, cancel the timer checking for a single press
if (singleTapTimerTask != null) {
singleTapTimerTask.cancel();
}
pointerActionDone = true;
commandAction(actionId);
tl.clearTouchedElement();
repaint();
return;
} else {
singleTap(x, y);
}
}
}
private void longTap() {
pointerActionDone = true;
// if not tapping a control, then the map area must be tapped so we do the long tap action for the map area
if (tl.getElementIdAtPointer(touchX, touchY) < 0 && panProjection != null) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_MAPTAP_LONG)) {
//#debug debug
logger.debug("long tap map");
//#if polish.api.online
// long tap map to open a place-related menu
// use the place of touch instead of old center as position,
// set as new center
pickPointEnd=panProjection.inverse(touchX,touchY, pickPointEnd);
center.radlat=centerPointerPressedN.radlat-(pickPointEnd.radlat-pickPointStart.radlat);
center.radlon=centerPointerPressedN.radlon-(pickPointEnd.radlon-pickPointStart.radlon);
Position oPos = new Position(center.radlat, center.radlon,
0.0f, 0.0f, 0.0f, 0, 0);
imageCollector.newDataReady();
gpsRecenter = false;
commandAction(ONLINE_INFO_CMD);
//#endif
}
return;
// long tapping a control
} else {
int actionId = tl.getActionIdLongAtPointer(touchX, touchY);
if (actionId > 0) {
tl.clearTouchedElement();
//#debug debug
logger.debug("long tap button: " + actionId + " x: " + touchX + " y: " + touchY);
commandAction(actionId);
repaint();
}
}
}
/**
* Returns the command used to go to the data screens.
* Needed by the data screens so they can find the key codes used for this
* as they have to use them too.
* @return Command
*/
public Command getDataScreenCommand() {
return CMDS[DATASCREEN_CMD];
}
public Tile getDict(byte zl) {
return tiles[zl];
}
public void setDict(Tile dict, byte zl) {
tiles[zl] = dict;
// Tile.trace=this;
//addCommand(REFRESH_CMD);
// if (zl == 3) {
// setTitle(null);
// } else {
// setTitle("dict " + zl + "ready");
// }
if (zl == 0) {
// read saved position from Configuration
Configuration.getStartupPos(center);
if (center.radlat == 0.0f && center.radlon == 0.0f) {
// if no saved position use center of map
dict.getCenter(center);
}
// read saved destination position from Configuration
if (Configuration.getCfgBitState(Configuration.CFGBIT_SAVED_DESTPOS_VALID)) {
Node destNode = new Node();
Configuration.getDestPos(destNode);
setDestination(new RoutePositionMark(destNode.radlat, destNode.radlon));
}
if (pc != null) {
pc.center = center.copy();
pc.scale = scale;
pc.course = course;
}
}
updatePosition();
}
public void receiveStatistics(int[] statRecord, byte quality) {
this.btquality = quality;
this.statRecord = statRecord;
repaint();
}
public synchronized void locationDecoderEnd() {
//#debug info
logger.info("enter locationDecoderEnd");
if (Configuration.getCfgBitState(Configuration.CFGBIT_SND_DISCONNECT)) {
// some fault tolerance - will crash without a map
if (Legend.isValid) {
GpsMid.mNoiseMaker.playSound("DISCONNECT");
}
}
//if (gpx != null) {
// /**
// * Close and Save the gpx recording, to ensure we don't loose data
// */
// gpx.saveTrk(false);
//}
removeCommand(CMDS[DISCONNECT_GPS_CMD]);
if (locationProducer == null) {
//#debug info
logger.info("leave locationDecoderEnd no producer");
return;
}
locationProducer = null;
notify();
addCommand(CMDS[CONNECT_GPS_CMD]);
// addCommand(START_RECORD_CMD);
//#debug info
logger.info("end locationDecoderEnd");
}
public void receiveStatus(byte status, int satsReceived) {
// FIXME signal a sound on location gained or lost
solution = status;
solutionStr = LocationMsgReceiverList.getCurrentStatusString(status, satsReceived);
repaint();
}
public String getName(int idx) {
if (idx < 0) {
return null;
}
return namesThread.getName(idx);
}
public String getUrl(int idx) {
if (idx < 0) {
return null;
}
return urlsThread.getUrl(idx);
}
public Vector fulltextSearch (String snippet, CancelMonitorInterface cmi) {
return namesThread.fulltextSearch(snippet, cmi);
}
// this is called by ImageCollector
public void requestRedraw() {
repaint();
}
public void newDataReady() {
if (imageCollector != null) {
imageCollector.newDataReady();
}
}
public void show() {
//Display.getDisplay(parent).setCurrent(this);
Legend.freeDrawnWayAndAreaSearchImages();
GpsMid.getInstance().show(this);
setFullScreenMode(Configuration.getCfgBitState(Configuration.CFGBIT_FULLSCREEN));
updateLastUserActionTime();
repaint();
}
public void recreateTraceLayout() {
tl = new TraceLayout(0, 0, getWidth(), getHeight());
}
public void locationDecoderEnd(String msg) {
receiveMessage(msg);
locationDecoderEnd();
}
public PositionMark getDestination() {
return dest;
}
public void setDestination(RoutePositionMark dest) {
endRouting();
this.dest = dest;
pc.dest = dest;
if (dest != null) {
//#debug info
logger.info("Setting destination to " + dest.toString());
// move map only to the destination, if GUI is not optimized for routing
if (! Configuration.getCfgBitState(Configuration.CFGBIT_ICONMENUS_ROUTING_OPTIMIZED)) {
commandAction(SHOW_DEST_CMD);
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_AUTOSAVE_DESTPOS)) {
Configuration.setDestPos(new Node(dest.lat, dest.lon, true));
Configuration.setCfgBitSavedState(Configuration.CFGBIT_SAVED_DESTPOS_VALID, true);
}
movedAwayFromDest = false;
} else {
Configuration.setCfgBitSavedState(Configuration.CFGBIT_SAVED_DESTPOS_VALID, false);
//#debug info
logger.info("Setting destination to null");
}
}
public void endRouting() {
RouteInstructions.initialRecalcDone = false;
RouteInstructions.icCountOffRouteDetected = 0;
RouteInstructions.routeInstructionsHeight = 0;
RouteInstructions.abortRouteLineProduction();
setRoute(null);
setRouteNodes(null);
}
/**
* This is the callback routine if RouteCalculation is ready
* @param route
*/
public void setRoute(Vector route) {
synchronized(this) {
this.route = route;
}
if (this.route != null) {
// reset off-route as soon as first route connection is known
RouteInstructions.resetOffRoute(this.route, center);
if (ri == null) {
ri = new RouteInstructions(this);
}
// show map during route line production
if (Configuration.getContinueMapWhileRouteing() == Configuration.continueMap_At_Route_Line_Creation) {
resumeImageCollectorAfterRouteCalc();
}
ri.newRoute(this.route);
oldRecalculationTime = System.currentTimeMillis();
}
// show map always after route calculation
resumeImageCollectorAfterRouteCalc();
routeCalc=false;
routeEngine=null;
}
private void resumeImageCollectorAfterRouteCalc() {
try {
if (imageCollector == null) {
startImageCollector();
// imageCollector thread starts up suspended,
// so we need to resume it
imageCollector.resume();
} else if (imageCollector != null) {
imageCollector.newDataReady();
}
repaint();
} catch (Exception e) {
logger.exception(Locale.get("trace.InTraceResumeImageCollector")/*In Trace.resumeImageCollector*/, e);
}
}
/**
* If we are running out of memory, try
* dropping all the caches in order to try
* and recover from out of memory errors.
* Not guaranteed to work, as it needs
* to allocate some memory for dropping
* caches.
*/
public void dropCache() {
tileReader.dropCache();
dictReader.dropCache();
System.gc();
namesThread.dropCache();
urlsThread.dropCache();
System.gc();
if (gpx != null) {
gpx.dropCache();
}
}
public QueueDataReader getDataReader() {
return tileReader;
}
public QueueDictReader getDictReader() {
return dictReader;
}
public Vector getRouteNodes() {
return routeNodes;
}
public void setRouteNodes(Vector routeNodes) {
this.routeNodes = routeNodes;
}
protected void hideNotify() {
//#debug debug
logger.debug("Hide notify has been called, screen will no longer be updated");
if (imageCollector != null) {
imageCollector.suspend();
}
}
protected void showNotify() {
//#debug debug
logger.debug("Show notify has been called, screen will be updated again");
if (imageCollector != null) {
imageCollector.resume();
imageCollector.newDataReady();
}
}
public Vector getRoute() {
return route;
}
public void actionCompleted() {
boolean reAddCommands = true;
if (reAddCommands && Configuration.getCfgBitState(Configuration.CFGBIT_FULLSCREEN)) {
addAllCommands();
}
}
public void showIconMenu() {
if (traceIconMenu == null) {
traceIconMenu = new TraceIconMenu(this, this);
}
traceIconMenu.show();
}
/** uncache the icon menu to reflect changes in the setup or save memory */
public static void uncacheIconMenu() {
//#mdebug trace
if (traceIconMenu != null) {
logger.trace("uncaching TraceIconMenu");
}
//#enddebug
traceIconMenu = null;
}
/** interface for IconMenuWithPages: recreate the icon menu from scratch and show it (introduced for reflecting size change of the Canvas) */
public void recreateAndShowIconMenu() {
uncacheIconMenu();
showIconMenu();
}
/** interface for received actions from the IconMenu GUI */
public void performIconAction(int actionId) {
updateLastUserActionTime();
// when we are low on memory or during route calculation do not cache the icon menu (including scaled images)
if (routeCalc || GpsMid.getInstance().needsFreeingMemory()) {
//#debug info
logger.info("low mem: Uncaching traceIconMenu");
uncacheIconMenu();
}
if (actionId != IconActionPerformer.BACK_ACTIONID) {
commandAction(actionId);
}
}
/** convert distance to string based on user preferences */
// The default way to show a distance is "10km" for
// distances 10km or more, "2,6km" for distances under 10, and
// "600m" for distances under 1km.
public static String showDistance(int meters) {
return showDistance(meters, DISTANCE_GENERIC);
}
public static String showDistance(int meters, int type) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_METRIC)) {
if (type == DISTANCE_UNKNOWN) {
return "???m";
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_DISTANCE_VIEW) && (type != DISTANCE_ALTITUDE)) {
if (meters >= 10000) {
return meters / 1000 + "km";
} else if (meters < 1000) {
return meters + "m";
} else {
// FIXME use e.g. getDecimalSeparator() for decimal comma/point selection
return meters / 1000 + "." + (meters % 1000) / 100 + "km";
}
} else {
return meters + "m";
}
} else {
if (type == DISTANCE_UNKNOWN) {
return "???yd";
} else if (type == DISTANCE_ALTITUDE) {
return Integer.toString((int)(meters / 0.30480 + 0.5)) + "ft";
} else {
return Integer.toString((int)(meters / 0.9144 + 0.5)) + "yd";
}
}
}
}
| public void commandAction(Command c, Displayable d) {
updateLastUserActionTime();
try {
if((keyboardLocked) && (d != null)) {
// show alert in keypressed() that keyboard is locked
keyPressed(0);
return;
}
if ((c == CMDS[PAN_LEFT25_CMD]) || (c == CMDS[PAN_RIGHT25_CMD])
|| (c == CMDS[PAN_UP25_CMD]) || (c == CMDS[PAN_DOWN25_CMD])
|| (c == CMDS[PAN_LEFT2_CMD]) || (c == CMDS[PAN_RIGHT2_CMD])
|| (c == CMDS[PAN_UP2_CMD]) || (c == CMDS[PAN_DOWN2_CMD])) {
int panX = 0; int panY = 0;
int courseDiff = 0;
int backLightLevelDiff = 0;
if (c == CMDS[PAN_LEFT25_CMD]) {
panX = -25;
} else if (c == CMDS[PAN_RIGHT25_CMD]) {
panX = 25;
} else if (c == CMDS[PAN_UP25_CMD]) {
panY = -25;
} else if (c == CMDS[PAN_DOWN25_CMD]) {
panY = 25;
} else if (c == CMDS[PAN_LEFT2_CMD]) {
if (TrackPlayer.isPlaying) {
TrackPlayer.slower();
} else if (manualRotationMode) {
courseDiff=-5;
} else {
panX = -2;
}
backLightLevelDiff = -25;
} else if (c == CMDS[PAN_RIGHT2_CMD]) {
if (TrackPlayer.isPlaying) {
TrackPlayer.faster();
} else if (manualRotationMode) {
courseDiff=5;
} else {
panX = 2;
}
backLightLevelDiff = 25;
} else if (c == CMDS[PAN_UP2_CMD]) {
if (route!=null && Configuration.getCfgBitState(Configuration.CFGBIT_ROUTE_BROWSING)) {
RouteInstructions.toNextInstruction(1);
} else {
panY = -2;
}
} else if (c == CMDS[PAN_DOWN2_CMD]) {
if (route!=null && Configuration.getCfgBitState(Configuration.CFGBIT_ROUTE_BROWSING)) {
RouteInstructions.toNextInstruction(-1);
} else {
panY = 2;
}
}
if (backLightLevelDiff !=0 && System.currentTimeMillis() < (lastBackLightOnTime + 2500)) {
// turn backlight always on when dimming
Configuration.setCfgBitState(Configuration.CFGBIT_BACKLIGHT_ON, true, false);
lastBackLightOnTime = System.currentTimeMillis();
Configuration.addToBackLightLevel(backLightLevelDiff);
parent.showBackLightLevel();
} else if (imageCollector != null) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null) {
// set compass compassDeviation
if (compassDeviation == 360) {
compassDeviation = 0;
} else {
compassDeviation += courseDiff;
compassDeviation %= 360;
if (course < 0) {
course += 360;
}
}
imageCollector.getCurrentProjection().pan(center, panX, panY);
} else {
// manual rotation
if (courseDiff == 360) {
course = 0; //N
} else {
course += courseDiff;
course %= 360;
if (course < 0) {
course += 360;
}
}
if (panX != 0 || panY != 0) {
gpsRecenter = false;
}
imageCollector.getCurrentProjection().pan(center, panX, panY);
}
}
gpsRecenter = false;
return;
}
if (c == CMDS[EXIT_CMD]) {
// FIXME: This is a workaround. It would be better if recording
// would not be stopped when leaving the map.
if (Legend.isValid && gpx.isRecordingTrk()) {
alert(Locale.get("trace.RecordMode")/*Record Mode*/, Locale.get("trace.PleaseStopRecording")/*Please stop recording before exit.*/ , 2500);
return;
}
if (Legend.isValid) {
pause();
}
parent.exit();
return;
}
if (c == CMDS[START_RECORD_CMD]) {
try {
gpx.newTrk(false);
alert(Locale.get("trace.GpsRecording")/*Gps track recording*/, Locale.get("trace.StartingToRecord")/*Starting to record*/, 1250);
} catch (RuntimeException e) {
receiveMessage(e.getMessage());
}
recordingsMenu = null; // refresh recordings menu
return;
}
if (c == CMDS[STOP_RECORD_CMD]) {
gpx.saveTrk(false);
alert(Locale.get("trace.GpsRecording")/*Gps track recording*/, Locale.get("trace.StoppingToRecord")/*Stopping to record*/, 1250);
recordingsMenu = null; // refresh recordings menu
return;
}
if (c == CMDS[MANAGE_TRACKS_CMD]) {
if (gpx.isRecordingTrk() && !gpx.isRecordingTrkSuspended()) {
// FIXME it's not strictly necessary to stop, after there are translation for the pause
// message, change to Locale.get("trace.YouNeedStopPauseRecording")
alert(Locale.get("trace.RecordMode")/*Record Mode*/, Locale.get("trace.YouNeedStopRecording")/*You need to stop recording before managing tracks.*/ , 4000);
return;
}
GuiGpx guiGpx = new GuiGpx(this);
guiGpx.show();
return;
}
if (c == CMDS[REFRESH_CMD]) {
repaint();
return;
}
if (c == CMDS[CONNECT_GPS_CMD]) {
if (locationProducer == null) {
if (TrackPlayer.isPlaying) {
TrackPlayer.getInstance().stop();
alert(Locale.get("trace.Trackplayer")/*Trackplayer*/, Locale.get("trace.PlayingStopped")/*Playing stopped for connecting to GPS*/, 2500);
}
Thread thread = new Thread(this,"LocationProducer init");
thread.start();
}
return;
}
if (c == CMDS[DISCONNECT_GPS_CMD]) {
if (locationProducer != null) {
locationProducer.close();
}
return;
}
if (c == CMDS[TOGGLE_GPS_CMD]) {
if (isGpsConnected()) {
commandAction(DISCONNECT_GPS_CMD);
} else {
commandAction(CONNECT_GPS_CMD);
}
return;
}
if (c == CMDS[SEARCH_CMD]) {
GuiSearch guiSearch = new GuiSearch(this);
guiSearch.show();
return;
}
if (c == CMDS[ENTER_WAYP_CMD]) {
if (gpx.isLoadingWaypoints()) {
showAlertLoadingWpt();
} else {
GuiWaypointEnter gwpe = new GuiWaypointEnter(this);
gwpe.show();
}
return;
}
if (c == CMDS[MAN_WAYP_CMD]) {
if (gpx.isLoadingWaypoints()) {
showAlertLoadingWpt();
} else {
GuiWaypoint gwp = new GuiWaypoint(this);
gwp.show();
}
return;
}
if (c == CMDS[MAPFEATURES_CMD]) {
GuiMapFeatures gmf = new GuiMapFeatures(this);
gmf.show();
repaint();
return;
}
if (c == CMDS[OVERVIEW_MAP_CMD]) {
GuiOverviewElements ovEl = new GuiOverviewElements(this);
ovEl.show();
repaint();
return;
}
//#if polish.api.wmapi
if (c == CMDS[SEND_MESSAGE_CMD]) {
GuiSendMessage sendMsg = new GuiSendMessage(this);
sendMsg.show();
repaint();
return;
}
//#endif
if (c == CMDS[RECORDINGS_CMD]) {
if (recordingsMenu == null) {
boolean hasJSR120 = Configuration.hasDeviceJSR120();
int noElements = 3;
//#if polish.api.mmapi
noElements += 2;
//#endif
//#if polish.api.wmapi
if (hasJSR120) {
noElements++;
}
//#endif
int idx = 0;
String[] elements = new String[noElements];
if (gpx.isRecordingTrk()) {
elements[idx++] = Locale.get("trace.StopGpxTracklog")/*Stop Gpx tracklog*/;
} else {
elements[idx++] = Locale.get("trace.StartGpxTracklog")/*Start Gpx tracklog*/;
}
elements[idx++] = Locale.get("trace.SaveWaypoint")/*Save waypoint*/;
elements[idx++] = Locale.get("trace.EnterWaypoint")/*Enter waypoint*/;
//#if polish.api.mmapi
elements[idx++] = Locale.get("trace.TakePictures")/*Take pictures*/;
if (audioRec.isRecording()) {
elements[idx++] = Locale.get("trace.StopAudioRecording")/*Stop audio recording*/;
} else {
elements[idx++] = Locale.get("trace.StartAudioRecording")/*Start audio recording*/;
}
//#endif
//#if polish.api.wmapi
if (hasJSR120) {
elements[idx++] = Locale.get("trace.SendSMSMapPos")/*Send SMS (map pos)*/;
}
//#endif
recordingsMenu = new List(Locale.get("trace.Recordings")/*Recordings...*/,Choice.IMPLICIT,elements,null);
recordingsMenu.addCommand(CMDS[OK_CMD]);
recordingsMenu.addCommand(CMDS[BACK_CMD]);
recordingsMenu.setSelectCommand(CMDS[OK_CMD]);
parent.show(recordingsMenu);
recordingsMenu.setCommandListener(this);
}
if (recordingsMenu != null) {
recordingsMenu.setSelectedIndex(0, true);
parent.show(recordingsMenu);
}
return;
}
if (c == CMDS[ROUTINGS_CMD]) {
if (routingsMenu == null) {
String[] elements = new String[4];
if (routeCalc || route != null) {
elements[0] = Locale.get("trace.StopRouting")/*Stop routing*/;
} else {
elements[0] = Locale.get("trace.CalculateRoute")/*Calculate route*/;
}
elements[1] = Locale.get("trace.SetDestination")/*Set destination*/;
elements[2] = Locale.get("trace.ShowDestination")/*Show destination*/;
elements[3] = Locale.get("trace.ClearDestination")/*Clear destination*/;
routingsMenu = new List(Locale.get("trace.Routing2")/*Routing..*/, Choice.IMPLICIT, elements, null);
routingsMenu.addCommand(CMDS[OK_CMD]);
routingsMenu.addCommand(CMDS[BACK_CMD]);
routingsMenu.setSelectCommand(CMDS[OK_CMD]);
routingsMenu.setCommandListener(this);
}
if (routingsMenu != null) {
routingsMenu.setSelectedIndex(0, true);
parent.show(routingsMenu);
}
return;
}
if (c == CMDS[SAVE_WAYP_CMD]) {
if (gpx.isLoadingWaypoints()) {
showAlertLoadingWpt();
} else {
PositionMark posMark = null;
if (gpsRecenter) {
// TODO: If we lose the fix the old position and height
// will be used silently -> we should inform the user
// here that we have no fix - he may not know what's going on.
posMark = new PositionMark(center.radlat, center.radlon,
(int)pos.altitude, pos.timeMillis,
/* fix */ (byte)-1, /* sats */ (byte)-1,
/* sym */ (byte)-1, /* type */ (byte)-1);
} else {
// Cursor does not point to current position
// -> it does not make sense to add elevation and GPS fix info.
posMark = new PositionMark(center.radlat, center.radlon,
PositionMark.INVALID_ELEVATION,
pos.timeMillis, /* fix */ (byte)-1,
/* sats */ (byte)-1, /* sym */ (byte)-1,
/* type */ (byte)-1);
}
/*
if (Configuration.getCfgBitState(Configuration.CFGBIT_WAYPT_OFFER_PREDEF)) {
if (guiWaypointPredefined == null) {
guiWaypointPredefined = new GuiWaypointPredefined(this);
}
if (guiWaypointPredefined != null) {
guiWaypointPredefined.setData(posMark);
guiWaypointPredefined.show();
}
} else {
*/
showGuiWaypointSave(posMark);
//}
}
return;
}
if (c == CMDS[ONLINE_INFO_CMD]) {
//#if polish.api.online
Position oPos = new Position(center.radlat, center.radlon,
0.0f, 0.0f, 0.0f, 0, 0);
GuiWebInfo gWeb = new GuiWebInfo(this, oPos, pc);
gWeb.show();
//#else
alert(Locale.get("trace.NoOnlineCapa")/*No online capabilites*/,
Locale.get("trace.SetAppGeneric")/*Set app=GpsMid-Generic-editing and enableEditing=true in*/ +
Locale.get("trace.PropertiesFile")/*.properties file and recreate GpsMid with Osm2GpsMid.*/,
Alert.FOREVER);
//#endif
}
if (c == CMDS[BACK_CMD]) {
show();
return;
}
if (c == CMDS[OK_CMD]) {
if (d == recordingsMenu) {
switch (recordingsMenu.getSelectedIndex()) {
case 0: {
if ( gpx.isRecordingTrk() ) {
commandAction(STOP_RECORD_CMD);
if (! Configuration.getCfgBitState(Configuration.CFGBIT_GPX_ASK_TRACKNAME_STOP)) {
show();
}
} else {
commandAction(START_RECORD_CMD);
if (! Configuration.getCfgBitState(Configuration.CFGBIT_GPX_ASK_TRACKNAME_START)) {
show();
}
}
break;
}
case 1: {
commandAction(SAVE_WAYP_CMD);
break;
}
case 2: {
commandAction(ENTER_WAYP_CMD);
break;
}
//#if polish.api.mmapi
case 3: {
commandAction(CAMERA_CMD);
break;
}
case 4: {
show();
commandAction(TOGGLE_AUDIO_REC);
break;
}
//#endif
//#if polish.api.mmapi && polish.api.wmapi
case 5: {
commandAction(SEND_MESSAGE_CMD);
break;
}
//#elif polish.api.wmapi
case 3: {
commandAction(SEND_MESSAGE_CMD);
break;
}
//#endif
}
}
if (d == routingsMenu) {
show();
switch (routingsMenu.getSelectedIndex()) {
case 0: {
if (routeCalc || route != null) {
commandAction(ROUTING_STOP_CMD);
} else {
commandAction(ROUTING_START_WITH_MODE_SELECT_CMD);
}
break;
}
case 1: {
commandAction(SET_DEST_CMD);
break;
}
case 2: {
commandAction(SHOW_DEST_CMD);
break;
}
case 3: {
commandAction(CLEAR_DEST_CMD);
break;
}
}
}
return;
}
//#if polish.api.mmapi
if (c == CMDS[CAMERA_CMD]) {
try {
Class GuiCameraClass = Class.forName("de.ueller.midlet.gps.GuiCamera");
Object GuiCameraObject = GuiCameraClass.newInstance();
GuiCameraInterface cam = (GuiCameraInterface)GuiCameraObject;
cam.init(this);
cam.show();
} catch (ClassNotFoundException cnfe) {
logger.exception(Locale.get("trace.YourPhoneNoCamSupport")/*Your phone does not support the necessary JSRs to use the camera*/, cnfe);
}
return;
}
if (c == CMDS[TOGGLE_AUDIO_REC]) {
if (audioRec.isRecording()) {
audioRec.stopRecord();
} else {
audioRec.startRecorder();
}
recordingsMenu = null; // refresh recordings menu
return;
}
//#endif
if (c == CMDS[ROUTING_TOGGLE_CMD]) {
if (routeCalc || route != null) {
commandAction(ROUTING_STOP_CMD);
} else {
commandAction(ROUTING_START_WITH_MODE_SELECT_CMD);
}
return;
}
if (c == CMDS[ROUTING_START_WITH_MODE_SELECT_CMD]) {
gpsRecenter = true;
gpsRecenterInvalid = true;
gpsRecenterStale = true;
GuiRoute guiRoute = new GuiRoute(this, false);
if (Configuration.getCfgBitSavedState(Configuration.CFGBIT_DONT_ASK_FOR_ROUTING_OPTIONS)) {
commandAction(ROUTING_START_CMD);
} else {
guiRoute.show();
}
return;
}
if (c == CMDS[ROUTING_START_CMD]) {
if (! routeCalc || RouteLineProducer.isRunning()) {
routeCalc = true;
if (Configuration.getContinueMapWhileRouteing() != Configuration.continueMap_Always ) {
stopImageCollector();
}
RouteInstructions.resetOffRoute(route, center);
// center of the map is the route source
RoutePositionMark routeSource = new RoutePositionMark(center.radlat, center.radlon);
logger.info("Routing source: " + routeSource);
routeNodes=new Vector();
routeEngine = new Routing(tiles, this);
routeEngine.solve(routeSource, dest);
// resume();
}
routingsMenu = null; // refresh routingsMenu
return;
}
if (c == CMDS[ROUTING_STOP_CMD]) {
NoiseMaker.stopPlayer();
if (routeCalc) {
if (routeEngine != null) {
routeEngine.cancelRouting();
}
alert(Locale.get("trace.RouteCalculation")/*Route Calculation*/, Locale.get("trace.Cancelled")/*Cancelled*/, 1500);
} else {
alert(Locale.get("trace.Routing")/*Routing*/, Locale.get("generic.Off")/*Off*/, 750);
}
endRouting();
routingsMenu = null; // refresh routingsMenu
// redraw immediately
synchronized (this) {
if (imageCollector != null) {
imageCollector.newDataReady();
}
}
routingsMenu = null; // refresh routingsMenu
return;
}
if (c == CMDS[ZOOM_IN_CMD]) {
scale = scale / 1.5f;
autoZoomed = false;
return;
}
if (c == CMDS[ZOOM_OUT_CMD]) {
scale = scale * 1.5f;
autoZoomed = false;
return;
}
if (c == CMDS[MANUAL_ROTATION_MODE_CMD]) {
manualRotationMode = !manualRotationMode;
if (manualRotationMode) {
if (hasPointerEvents()) {
alert(Locale.get("trace.ManualRotation")/*Manual Rotation*/, Locale.get("trace.ChangeCourse")/*Change course with zoom buttons*/, 3000);
} else {
alert(Locale.get("trace.ManualRotation")/*Manual Rotation*/, Locale.get("trace.ChangeCourseWithLeftRightKeys")/*Change course with left/right keys*/, 3000);
}
} else {
alert(Locale.get("trace.ManualRotation")/*Manual Rotation*/, Locale.get("generic.Off")/*Off*/, 750);
}
return;
}
if (c == CMDS[TOGGLE_OVERLAY_CMD]) {
showAddons++;
repaint();
return;
}
if (c == CMDS[TOGGLE_BACKLIGHT_CMD]) {
// toggle Backlight
Configuration.setCfgBitState(Configuration.CFGBIT_BACKLIGHT_ON,
!(Configuration.getCfgBitState(Configuration.CFGBIT_BACKLIGHT_ON)),
false);
lastBackLightOnTime = System.currentTimeMillis();
parent.showBackLightLevel();
return;
}
if (c == CMDS[TOGGLE_FULLSCREEN_CMD]) {
boolean fullScreen = !Configuration.getCfgBitState(Configuration.CFGBIT_FULLSCREEN);
Configuration.setCfgBitState(Configuration.CFGBIT_FULLSCREEN, fullScreen, false);
setFullScreenMode(fullScreen);
return;
}
if (c == CMDS[TOGGLE_MAP_PROJ_CMD]) {
if (manualRotationMode) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null) {
compassDeviation = 0;
} else {
course = 0;
}
alert(Locale.get("trace.ManualRotation"), Locale.get("trace.ManualToNorth"), 750);
} else {
// FIXME rename string to generic
alert(Locale.get("guidiscover.MapProjection")/*Map Projection*/, ProjFactory.nextProj(), 750);
}
// redraw immediately
synchronized (this) {
if (imageCollector != null) {
imageCollector.newDataReady();
}
}
return;
}
if (c == CMDS[TOGGLE_KEY_LOCK_CMD]) {
keyboardLocked = !keyboardLocked;
if (keyboardLocked) {
// show alert that keys are locked
keyPressed(0);
} else {
alert(Locale.get("trace.GpsMid")/*GpsMid*/, hasPointerEvents() ? Locale.get("trace.KeysAndTouchscreenUnlocked")/*Keys and touch screen unlocked*/ : Locale.get("trace.KeysUnlocked")/*Keys unlocked*/, 1000);
}
return;
}
if (c == CMDS[TOGGLE_RECORDING_CMD]) {
if ( gpx.isRecordingTrk() ) {
commandAction(STOP_RECORD_CMD);
} else {
commandAction(START_RECORD_CMD);
}
return;
}
if (c == CMDS[TOGGLE_RECORDING_SUSP_CMD]) {
if (gpx.isRecordingTrk()) {
if ( gpx.isRecordingTrkSuspended() ) {
alert(Locale.get("trace.GpsRecording")/*Gps track recording*/, Locale.get("trace.ResumingRecording")/*Resuming recording*/, 1000);
gpx.resumeTrk();
} else {
alert(Locale.get("trace.GpsRecording")/*Gps track recording*/, Locale.get("trace.SuspendingRecording")/*Suspending recording*/, 1000);
gpx.suspendTrk();
}
}
return;
}
if (c == CMDS[RECENTER_GPS_CMD]) {
gpsRecenter = true;
gpsRecenterInvalid = true;
gpsRecenterStale = true;
autoZoomed = true;
if (pos.latitude != 0.0f) {
receivePosition(pos);
}
newDataReady();
return;
}
if (c == CMDS[SHOW_DEST_CMD]) {
if (dest != null) {
//We are explicitly setting the map to this position, so we probably don't
//want it to be recentered on the GPS immediately.
gpsRecenter = false;
prevPositionNode = center.copy();
center.setLatLonRad(dest.lat, dest.lon);
movedAwayFromDest = false;
updatePosition();
}
else {
alert(Locale.get("trace.ShowDestination")/*Show destination*/, Locale.get("trace.DestinationNotSpecifiedYet")/*Destination is not specified yet*/, 3000);
}
return;
}
if (c == CMDS[SHOW_PREVIOUS_POSITION_CMD]) {
if (prevPositionNode != null) {
//We are explicitly setting the map to this position, so we probably don't
//want it to be recentered on the GPS immediately.
gpsRecenter = false;
center.setLatLon(prevPositionNode);
updatePosition();
}
}
if (c == CMDS[DATASCREEN_CMD]) {
showNextDataScreen(DATASCREEN_NONE);
return;
}
if (c == CMDS[ICON_MENU] && Configuration.getCfgBitState(Configuration.CFGBIT_ICONMENUS)) {
showIconMenu();
return;
}
if (c == CMDS[SETUP_CMD]) {
new GuiDiscover(parent);
return;
}
if (c == CMDS[ABOUT_CMD]) {
new Splash(parent, GpsMid.initDone);
return;
}
if (c == CMDS[CELLID_LOCATION_CMD]) {
if (Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_SECELL && locationProducer != null) {
locationProducer.triggerPositionUpdate();
newDataReady();
} else {
if (cellIDLocationProducer == null) {
// init sleeping cellid location provider if cellid is not primary
cellIDLocationProducer = new SECellID();
if (cellIDLocationProducer != null && !cellIDLocationProducer.init(this)) {
logger.info("Failed to initialise CellID location producer");
}
}
if (cellIDLocationProducer != null) {
cellIDLocationProducer.triggerPositionUpdate();
newDataReady();
}
}
return;
}
if (c == CMDS[MANUAL_LOCATION_CMD]) {
Position setpos = new Position(center.radlat / MoreMath.FAC_DECTORAD,
center.radlon / MoreMath.FAC_DECTORAD,
PositionMark.INVALID_ELEVATION, 0.0f, 0.0f, 1,
System.currentTimeMillis(), Position.TYPE_MANUAL);
// implies center to gps, to give feedback as the gps rectangle
gpsRecenter = true;
// gpsRecenterInvalid = true;
// gpsRecenterStale = true;
autoZoomed = true;
receivePosition(setpos);
receiveStatus(LocationMsgReceiver.STATUS_MANUAL, 0);
newDataReady();
return;
}
if (! routeCalc) {
//#if polish.api.osm-editing
if (c == CMDS[RETRIEVE_XML]) {
if (Legend.enableEdits) {
// -1 alert ("Editing", "Urlidx: " + pc.actualWay.urlIdx, Alert.FOREVER);
if ((pc.actualWay != null) && (getUrl(pc.actualWay.urlIdx) != null)) {
parent.alert ("Url", "Url: " + getUrl(pc.actualWay.urlIdx), Alert.FOREVER);
}
if ((pc.actualWay != null) && (pc.actualWay instanceof EditableWay)) {
EditableWay eway = (EditableWay)pc.actualWay;
GUIosmWayDisplay guiWay = new GUIosmWayDisplay(eway, pc.actualSingleTile, this);
guiWay.show();
guiWay.refresh();
}
} else {
parent.alert("Editing", "Editing support was not enabled in Osm2GpsMid", Alert.FOREVER);
}
}
if (c == CMDS[RETRIEVE_NODE]) {
if (Legend.enableEdits) {
GuiOSMPOIDisplay guiNode = new GuiOSMPOIDisplay(-1, null,
center.radlat, center.radlon, this);
guiNode.show();
guiNode.refresh();
} else {
logger.error(Locale.get("trace.EditingIsNotEnabled")/*Editing is not enabled in this map*/);
}
}
if (c == CMDS[EDIT_ADDR_CMD]) {
if (Legend.enableEdits) {
String streetName = "";
if ((pc != null) && (pc.actualWay != null)) {
streetName = getName(pc.actualWay.nameIdx);
}
GuiOSMAddrDisplay guiAddr = new GuiOSMAddrDisplay(-1, streetName, null,
center.radlat, center.radlon, this);
guiAddr.show();
} else {
logger.error(Locale.get("trace.EditingIsNotEnabled")/*Editing is not enabled in this map*/);
}
}
//#else
if (c == CMDS[RETRIEVE_XML] || c == CMDS[RETRIEVE_NODE] || c == CMDS[EDIT_ADDR_CMD]) {
alert("No online capabilites",
Locale.get("trace.SetAppGeneric")/*Set app=GpsMid-Generic-editing and enableEditing=true in*/ +
Locale.get("trace.PropertiesFile")/*.properties file and recreate GpsMid with Osm2GpsMid.*/,
Alert.FOREVER);
}
//#endif
if (c == CMDS[SET_DEST_CMD]) {
RoutePositionMark pm1 = new RoutePositionMark(center.radlat, center.radlon);
setDestination(pm1);
return;
}
if (c == CMDS[CLEAR_DEST_CMD]) {
setDestination(null);
return;
}
} else {
alert(Locale.get("trace.Error")/*Error*/, Locale.get("trace.CurrentlyInRouteCalculation")/*Currently in route calculation*/, 2000);
}
} catch (Exception e) {
logger.exception(Locale.get("trace.InTraceCommandAction")/*In Trace.commandAction*/, e);
}
}
private void startImageCollector() throws Exception {
//#debug info
logger.info("Starting ImageCollector");
Images images = new Images();
pc = new PaintContext(this, images);
/* move responsibility for overscan to ImageCollector
int w = (this.getWidth() * 125) / 100;
int h = (this.getHeight() * 125) / 100;
*/
imageCollector = new ImageCollector(tiles, this.getWidth(), this.getHeight(), this, images);
// projection = ProjFactory.getInstance(center,course, scale, getWidth(), getHeight());
// pc.setP(projection);
pc.center = center.copy();
pc.scale = scale;
pc.xSize = this.getWidth();
pc.ySize = this.getHeight();
}
private void stopImageCollector(){
//#debug info
logger.info("Stopping ImageCollector");
cleanup();
if (imageCollector != null ) {
imageCollector.stop();
imageCollector=null;
}
System.gc();
}
public void startup() throws Exception {
// logger.info("reading Data ...");
namesThread = new Names();
urlsThread = new Urls();
new DictReader(this);
if (Configuration.getCfgBitState(Configuration.CFGBIT_AUTO_START_GPS)) {
Thread thread = new Thread(this, "Trace");
thread.start();
}
// logger.info("Create queueDataReader");
tileReader = new QueueDataReader(this);
// logger.info("create imageCollector");
dictReader = new QueueDictReader(this);
this.gpx = new Gpx();
this.audioRec = new AudioRecorder();
setDict(gpx, (byte)5);
startImageCollector();
recreateTraceLayout();
}
public void shutdown() {
if (gpx != null) {
// change to "false" to ask for track name if configure to
// currently "true" to not ask for name to ensure fast
// quit & try to avoid loss of data which might result from
// waiting for user to type the name
gpx.saveTrk(true);
}
//#debug debug
logger.debug("Shutdown: stopImageCollector");
stopImageCollector();
if (namesThread != null) {
//#debug debug
logger.debug("Shutdown: namesThread");
namesThread.stop();
namesThread = null;
}
if (urlsThread != null) {
urlsThread.stop();
urlsThread = null;
}
if (dictReader != null) {
//#debug debug
logger.debug("Shutdown: dictReader");
dictReader.shutdown();
dictReader = null;
}
if (tileReader != null) {
//#debug debug
logger.debug("Shutdown: tileReader");
tileReader.shutdown();
tileReader = null;
}
if (locationProducer != null) {
//#debug debug
logger.debug("Shutdown: locationProducer");
locationProducer.close();
}
if (TrackPlayer.isPlaying) {
//#debug debug
logger.debug("Shutdown: TrackPlayer");
TrackPlayer.getInstance().stop();
}
}
public void sizeChanged(int w, int h) {
updateLastUserActionTime();
if (imageCollector != null) {
logger.info("Size of Canvas changed to " + w + "|" + h);
stopImageCollector();
try {
startImageCollector();
imageCollector.resume();
imageCollector.newDataReady();
} catch (Exception e) {
logger.exception(Locale.get("trace.CouldNotReinitialiseImageCollector")/*Could not reinitialise Image Collector after size change*/, e);
}
/**
* Recalculate the projection, as it may depends on the size of the screen
*/
updatePosition();
}
tl = new TraceLayout(0, 0, w, h);
}
protected void paint(Graphics g) {
//#debug debug
logger.debug("Drawing Map screen");
try {
int yc = 1;
int la = 18;
getPC();
// cleans the screen
g.setColor(Legend.COLORS[Legend.COLOR_MAP_BACKGROUND]);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
pc.g = g;
if (imageCollector != null) {
/*
* When painting we receive a copy of the center coordinates
* where the imageCollector has drawn last
* as we need to base the routing instructions on the information
* determined during the way drawing (e.g. the current routePathConnection)
*/
Node drawnCenter = imageCollector.paint(pc);
if (route != null && ri != null && pc.lineP2 != null) {
pc.getP().forward(drawnCenter.radlat, drawnCenter.radlon, pc.lineP2);
/*
* we also need to make sure the current way for the real position
* has really been detected by the imageCollector which happens when drawing the ways
* So we check if we just painted an image that did not cover
* the center of the display because it was too far painted off from
* the display center position and in this case we don't give route instructions
* Thus e.g. after leaving a long tunnel without gps fix there will not be given an
* obsolete instruction from inside the tunnel
*/
int maxAllowedMapMoveOffs = Math.min(pc.xSize/2, pc.ySize/2);
if ( Math.abs(pc.lineP2.x - pc.getP().getImageCenter().x) < maxAllowedMapMoveOffs
&&
Math.abs(pc.lineP2.y - pc.getP().getImageCenter().y) < maxAllowedMapMoveOffs
) {
/*
* we need to synchronize the route instructions on the informations determined during way painting
* so we give the route instructions right after drawing the image with the map
* and use the center of the last drawn image for the route instructions
*/
ri.showRoute(pc, drawnCenter,imageCollector.xScreenOverscan,imageCollector.yScreenOverscan);
}
}
} else {
// show the way bar even if ImageCollector is not running because it's necessary on touch screens to get to the icon menu
tl.ele[TraceLayout.WAYNAME].setText(" ");
}
/* Beginning of voice instructions started from overlay code (besides showRoute above)
*/
// Determine if we are at the destination
if (dest != null) {
float distance = ProjMath.getDistance(dest.lat, dest.lon, center.radlat, center.radlon);
atDest = (distance < 25);
if (atDest) {
if (movedAwayFromDest && Configuration.getCfgBitState(Configuration.CFGBIT_SND_DESTREACHED)) {
GpsMid.mNoiseMaker.playSound(RouteSyntax.getInstance().getDestReachedSound(), (byte) 7, (byte) 1);
}
} else if (!movedAwayFromDest) {
movedAwayFromDest = true;
}
}
// determine if we are currently speeding
speeding = false;
int maxSpeed = 0;
// only detect speeding when gpsRecentered and there is a current way
if (gpsRecenter && actualSpeedLimitWay != null) {
maxSpeed = actualSpeedLimitWay.getMaxSpeed();
// check for winter speed limit if configured
if (Configuration.getCfgBitState(Configuration.CFGBIT_MAXSPEED_WINTER)
&& (actualSpeedLimitWay.getMaxSpeedWinter() > 0)) {
maxSpeed = actualSpeedLimitWay.getMaxSpeedWinter();
}
if (maxSpeed != 0 && speed > (maxSpeed + Configuration.getSpeedTolerance()) ) {
speeding = true;
}
}
if (speeding && Configuration.getCfgBitState(Configuration.CFGBIT_SPEEDALERT_SND)) {
// give speeding alert only every 10 seconds
if ( (System.currentTimeMillis() - lastTimeOfSpeedingSound) > 10000 ) {
lastTimeOfSpeedingSound = System.currentTimeMillis();
GpsMid.mNoiseMaker.immediateSound(RouteSyntax.getInstance().getSpeedLimitSound());
}
}
/*
* end of voice instructions started from overlay code
*/
/*
* the final part of the overlay should not give any voice instructions
*/
g.setColor(Legend.COLOR_MAP_TEXT);
switch (showAddons) {
case 1:
yc = showMemory(g, yc, la);
break;
case 2:
yc = showConnectStatistics(g, yc, la);
break;
default:
showAddons = 0;
if (Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_SCALE_BAR)) {
if (pc != null) {
tl.calcScaleBarWidth(pc);
tl.ele[TraceLayout.SCALEBAR].setText(" ");
}
}
setPointOfTheCompass();
}
showMovement(g);
// Show gpx track recording status
LayoutElement eSolution = tl.ele[TraceLayout.SOLUTION];
LayoutElement eRecorded = tl.ele[TraceLayout.RECORDED_COUNT];
if (gpx.isRecordingTrk()) {
// we are recording tracklogs
if (gpx.isRecordingTrkSuspended()) {
eRecorded.setColor(Legend.COLORS[Legend.COLOR_RECORDING_SUSPENDED_TEXT]); // blue
} else {
eRecorded.setColor(Legend.COLORS[Legend.COLOR_RECORDING_ON_TEXT]); // red
}
eRecorded.setText(gpx.getTrkPointCount() + Locale.get("trace.r")/*r*/);
}
if (TrackPlayer.isPlaying) {
eSolution.setText(Locale.get("trace.Replay")/*Replay*/);
} else {
if (locationProducer == null && !(solution == LocationMsgReceiver.STATUS_CELLID ||
solution == LocationMsgReceiver.STATUS_MANUAL)) {
eSolution.setText(Locale.get("solution.Off")/*Off*/);
} else {
eSolution.setText(solutionStr);
}
}
LayoutElement e = tl.ele[TraceLayout.CELLID];
// show if we are logging cellIDs
if (SECellLocLogger.isCellIDLogging() > 0) {
if (SECellLocLogger.isCellIDLogging() == 2) {
e.setColor(Legend.COLORS[Legend.COLOR_CELLID_LOG_ON_TEXT]); // yellow
} else {
//Attempting to log, but currently no valid info available
e.setColor(Legend.COLORS[Legend.COLOR_CELLID_LOG_ON_ATTEMPTING_TEXT]); // red
}
e.setText(Locale.get("trace.cellIDs")/*cellIDs*/);
}
// show audio recording status
e = tl.ele[TraceLayout.AUDIOREC];
if (audioRec.isRecording()) {
e.setColor(Legend.COLORS[Legend.COLOR_AUDIOREC_TEXT]); // red
e.setText(Locale.get("trace.AudioRec")/*AudioRec*/);
}
if (pc != null) {
showDestination(pc);
}
if (speed > 0 &&
Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_SPEED_IN_MAP)) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_METRIC)) {
tl.ele[TraceLayout.SPEED_CURRENT].setText(" " + Integer.toString(speed) + Locale.get("trace.kmh")/* km/h*/);
} else {
tl.ele[TraceLayout.SPEED_CURRENT].setText(" " + Integer.toString((int)(speed / 1.609344f)) + " mph");
}
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_ALTITUDE_IN_MAP)
&& locationProducer != null
&& LocationMsgReceiverList.isPosValid(solution)
) {
tl.ele[TraceLayout.ALTITUDE].setText(showDistance(altitude, DISTANCE_ALTITUDE));
}
if (dest != null && (route == null || (!RouteLineProducer.isRouteLineProduced() && !RouteLineProducer.isRunning()) )
&& Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_AIR_DISTANCE_IN_MAP)) {
e = Trace.tl.ele[TraceLayout.ROUTE_DISTANCE];
e.setBackgroundColor(Legend.COLORS[Legend.COLOR_RI_DISTANCE_BACKGROUND]);
double distLine = ProjMath.getDistance(center.radlat, center.radlon, dest.lat, dest.lon);
e.setText(Locale.get("trace.Air")/*Air:*/ + showDistance((int) distLine, DISTANCE_AIR));
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_CLOCK_IN_MAP)) {
e = tl.ele[TraceLayout.CURRENT_TIME]; // e is used *twice* below (also as vRelative)
e.setText(DateTimeTools.getClock(System.currentTimeMillis(), true));
/*
don't use new Date() - it is very slow on some Nokia devices
currentTime.setTime( new Date( System.currentTimeMillis() ) );
e.setText(
currentTime.get(Calendar.HOUR_OF_DAY) + ":"
+ HelperRoutines.formatInt2(currentTime.get(Calendar.MINUTE)));
*/
// if current time is visible, positioning OFFROUTE above current time will work
tl.ele[TraceLayout.ROUTE_OFFROUTE].setVRelative(e);
}
setSpeedingSign(maxSpeed);
if (hasPointerEvents()) {
tl.ele[TraceLayout.ZOOM_IN].setText("+");
tl.ele[TraceLayout.ZOOM_OUT].setText("-");
tl.ele[TraceLayout.RECENTER_GPS].setText("|");
e = tl.ele[TraceLayout.SHOW_DEST];
if (atDest && prevPositionNode != null) {
e.setText("<");
e.setActionID(SHOW_PREVIOUS_POSITION_CMD);
} else {
e.setText(">");
e.setActionID(SHOW_DEST_CMD + (Trace.SET_DEST_CMD << 16) );
}
}
e = tl.ele[TraceLayout.TITLEBAR];
if (currentTitleMsgOpenCount != 0) {
e.setText(currentTitleMsg);
// setTitleMsgTimeOut can be changed in receiveMessage()
synchronized (this) {
if (setTitleMsgTimeout != 0) {
TimerTask timerT = new TimerTask() {
public synchronized void run() {
currentTitleMsgOpenCount--;
lastTitleMsg = currentTitleMsg;
if (currentTitleMsgOpenCount == 0) {
//#debug debug
logger.debug("clearing title");
repaint();
}
}
};
GpsMid.getTimer().schedule(timerT, setTitleMsgTimeout);
setTitleMsgTimeout = 0;
}
}
}
tl.paint(g);
if (currentAlertsOpenCount > 0) {
showCurrentAlert(g);
}
} catch (Exception e) {
logger.silentexception("Unhandled exception in the paint code", e);
}
}
public void showGuiWaypointSave(PositionMark posMark) {
if (guiWaypointSave == null) {
guiWaypointSave = new GuiWaypointSave(this);
}
if (guiWaypointSave != null) {
guiWaypointSave.setData(posMark);
guiWaypointSave.show();
}
}
/** Show an alert telling the user that waypoints are not ready yet.
*/
private void showAlertLoadingWpt() {
alert("Way points", "Way points are not ready yet.", 3000);
}
private void showCurrentAlert(Graphics g) {
Font font = g.getFont();
// request same font in bold for title
Font titleFont = Font.getFont(font.getFace(), Font.STYLE_BOLD, font.getSize());
int fontHeight = font.getHeight();
// add alert title height plus extra space of one line for calculation of alertHeight
int y = titleFont.getHeight() + 2 + fontHeight;
// extra width for alert
int extraWidth = font.charWidth('W');
// alert is at least as wide as alert title
int alertWidth = titleFont.stringWidth(currentAlertTitle);
// width each alert message line must fit in
int maxWidth = getWidth() - extraWidth;
// Two passes: 1st pass calculates placement and necessary size of alert,
// 2nd pass actually does the drawing
for (int i = 0; i <= 1; i++) {
int nextSpaceAt = 0;
int prevSpaceAt = 0;
int start = 0;
// word wrap
do {
int width = 0;
// add word by word until string part is too wide for screen
while (width < maxWidth && nextSpaceAt <= currentAlertMessage.length() ) {
prevSpaceAt = nextSpaceAt;
nextSpaceAt = currentAlertMessage.indexOf(' ', nextSpaceAt);
if (nextSpaceAt == -1) {
nextSpaceAt = currentAlertMessage.length();
}
width = font.substringWidth(currentAlertMessage, start, nextSpaceAt - start);
nextSpaceAt++;
}
nextSpaceAt--;
// Reduce line word by word or if not possible char by char until the
// remaining string part fits to display width
while (width > maxWidth) {
if (prevSpaceAt > start && nextSpaceAt > prevSpaceAt) {
nextSpaceAt = prevSpaceAt;
} else {
nextSpaceAt--;
}
width = font.substringWidth(currentAlertMessage, start, nextSpaceAt - start);
}
// determine maximum alert width
if (alertWidth < width ) {
alertWidth = width;
}
// during the second pass draw the message text lines
if (i==1) {
g.drawSubstring(currentAlertMessage, start, nextSpaceAt - start,
getWidth()/2, y, Graphics.TOP|Graphics.HCENTER);
}
y += fontHeight;
start = nextSpaceAt;
} while (nextSpaceAt < currentAlertMessage.length() );
// at the end of the first pass draw the alert box and the alert title
if (i == 0) {
alertWidth += extraWidth;
int alertHeight = y;
int alertTop = (getHeight() - alertHeight) /2;
//alertHeight += fontHeight/2;
int alertLeft = (getWidth() - alertWidth) / 2;
// alert background color
g.setColor(Legend.COLORS[Legend.COLOR_ALERT_BACKGROUND]);
g.fillRect(alertLeft, alertTop, alertWidth, alertHeight);
// background color for alert title
g.setColor(Legend.COLORS[Legend.COLOR_ALERT_TITLE_BACKGROUND]);
g.fillRect(alertLeft, alertTop, alertWidth, fontHeight + 3);
// alert border
g.setColor(Legend.COLORS[Legend.COLOR_ALERT_BORDER]);
g.setStrokeStyle(Graphics.SOLID);
g.drawRect(alertLeft, alertTop, alertWidth, fontHeight + 3); // title border
g.drawRect(alertLeft, alertTop, alertWidth, alertHeight); // alert border
// draw alert title
y = alertTop + 2; // output position of alert title
g.setFont(titleFont);
g.setColor(Legend.COLORS[Legend.COLOR_ALERT_TEXT]);
g.drawString(currentAlertTitle, getWidth()/2, y , Graphics.TOP|Graphics.HCENTER);
g.setFont(font);
// output alert message 1.5 lines below alert title in the next pass
y += (fontHeight * 3 / 2);
}
} // end for
// setAlertTimeOut can be changed in receiveMessage()
synchronized (this) {
if (setAlertTimeout != 0) {
TimerTask timerT = new TimerTask() {
public synchronized void run() {
currentAlertsOpenCount--;
if (currentAlertsOpenCount == 0) {
//#debug debug
logger.debug("clearing alert");
repaint();
}
}
};
GpsMid.getTimer().schedule(timerT, setAlertTimeout);
setAlertTimeout = 0;
}
}
}
private void setSpeedingSign(int maxSpeed) {
// speeding = true;
if (Configuration.getCfgBitState(Configuration.CFGBIT_SPEEDALERT_VISUAL)
&&
(
speeding
||
(System.currentTimeMillis() - startTimeOfSpeedingSign) < 3000
)
) {
if (speeding) {
speedingSpeedLimit = maxSpeed;
startTimeOfSpeedingSign = System.currentTimeMillis();
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_METRIC)) {
tl.ele[TraceLayout.SPEEDING_SIGN].setText(Integer.toString(speedingSpeedLimit));
} else {
tl.ele[TraceLayout.SPEEDING_SIGN].setText(Integer.toString((int)(speedingSpeedLimit / 1.609344f)));
}
} else {
startTimeOfSpeedingSign = 0;
}
}
/**
*
*/
private void getPC() {
pc.course = course;
pc.scale = scale;
pc.center = center.copy();
// pc.setP( projection);
// projection.inverse(pc.xSize, 0, pc.screenRU);
// projection.inverse(0, pc.ySize, pc.screenLD);
pc.dest = dest;
}
public void cleanup() {
namesThread.cleanup();
urlsThread.cleanup();
tileReader.incUnusedCounter();
dictReader.incUnusedCounter();
}
// public void searchElement(PositionMark pm) throws Exception {
// PaintContext pc = new PaintContext(this, null);
// // take a bigger angle for lon because of positions near to the poles.
// Node nld = new Node(pm.lat - 0.0001f, pm.lon - 0.0005f, true);
// Node nru = new Node(pm.lat + 0.0001f, pm.lon + 0.0005f, true);
// pc.searchLD = nld;
// pc.searchRU = nru;
// pc.dest = pm;
// pc.setP(new Proj2D(new Node(pm.lat, pm.lon, true), 5000, 100, 100));
// for (int i = 0; i < 4; i++) {
// tiles[i].walk(pc, Tile.OPT_WAIT_FOR_LOAD);
// }
// }
public void searchNextRoutableWay(RoutePositionMark pm) throws Exception {
PaintContext pc = new PaintContext(this, null);
// take a bigger angle for lon because of positions near to the pols.
// Node nld=new Node(pm.lat - 0.0001f,pm.lon - 0.0005f,true);
// Node nru=new Node(pm.lat + 0.0001f,pm.lon + 0.0005f,true);
// pc.searchLD=nld;
// pc.searchRU=nru;
pc.squareDstToActualRoutableWay = Float.MAX_VALUE;
pc.xSize = 100;
pc.ySize = 100;
// retry searching an expanding region at the position mark
Projection p;
do {
p = new Proj2D(new Node(pm.lat,pm.lon, true),5000,pc.xSize,pc.ySize);
pc.setP(p);
for (int i=0; i<4; i++) {
tiles[i].walk(pc, Tile.OPT_WAIT_FOR_LOAD | Tile.OPT_FIND_CURRENT);
}
// stop the search when a routable way is found
if (pc.actualRoutableWay != null) {
break;
}
// expand the region that gets searched for a routable way
pc.xSize += 100;
pc.ySize += 100;
// System.out.println(pc.xSize);
} while(MoreMath.dist(p.getMinLat(), p.getMinLon(), p.getMinLat(), p.getMaxLon()) < 500); // until we searched at least 500 m edge length
Way w = pc.actualRoutableWay;
pm.setEntity(w, pc.currentPos.nodeLat, pc.currentPos.nodeLon);
}
private void setPointOfTheCompass() {
String c = "";
if (ProjFactory.getProj() != ProjFactory.NORTH_UP
&& Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_POINT_OF_COMPASS)) {
c = Configuration.getCompassDirection(course);
}
// if tl shows big onscreen buttons add spaces to compass directions consisting of only one char or not shown
if (tl.bigOnScreenButtons && c.length() <= 1) {
if (ProjFactory.getProj() == ProjFactory.NORTH_UP) {
c = "(" + Configuration.getCompassDirection(0) + ")";
} else {
c = " " + c + " ";
}
}
tl.ele[TraceLayout.POINT_OF_COMPASS].setText(c);
}
private int showConnectStatistics(Graphics g, int yc, int la) {
g.setColor(Legend.COLORS[Legend.COLOR_MAP_TEXT]);
// only try to show compass id and cell id if user has somehow switched them on
GSMCell cell = null;
if (cellIDLocationProducer != null || Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_SECELL) {
cell = CellIdProvider.getInstance().obtainCachedCellID();
}
Compass compass = null;
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION)) {
compass = CompassProvider.getInstance().obtainCachedCompass();
}
if (cell == null) {
g.drawString("No Cell ID available", 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
} else {
g.drawString("Cell: MCC=" + cell.mcc + " MNC=" + cell.mnc, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString("LAC=" + cell.lac, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString("cellID=" + cell.cellID, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
}
if (compass == null) {
g.drawString("No compass direction available", 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
} else {
g.drawString("Compass direction: " + compass.direction, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
}
if (statRecord == null) {
g.drawString("No stats yet", 0, yc, Graphics.TOP
| Graphics.LEFT);
return yc+la;
}
//#mdebug info
for (byte i = 0; i < LocationMsgReceiver.SIRF_FAIL_COUNT; i++) {
g.drawString(statMsg[i] + statRecord[i], 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
}
//#enddebug
g.drawString("BtQual : " + btquality, 0, yc, Graphics.TOP | Graphics.LEFT);
yc += la;
g.drawString("Count : " + collected, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
return yc;
}
public void showDestination(PaintContext pc) {
try {
if (dest != null) {
pc.getP().forward(dest.lat, dest.lon, pc.lineP2);
// System.out.println(dest.toString());
int x = pc.lineP2.x - imageCollector.xScreenOverscan;
int y = pc.lineP2.y - imageCollector.yScreenOverscan;
pc.g.drawImage(pc.images.IMG_DEST, x, y, CENTERPOS);
pc.g.setColor(Legend.COLORS[Legend.COLOR_DEST_TEXT]);
if (dest.displayName != null) {
pc.g.drawString(dest.displayName, x, y+8,
Graphics.TOP | Graphics.HCENTER);
}
pc.g.setColor(Legend.COLORS[Legend.COLOR_DEST_LINE]);
pc.g.setStrokeStyle(Graphics.SOLID);
pc.g.drawLine(x, y, pc.getP().getImageCenter().x - imageCollector.xScreenOverscan,
pc.getP().getImageCenter().y - imageCollector.yScreenOverscan);
}
} catch (Exception e) {
if (imageCollector == null) {
logger.silentexception("No ImageCollector", e);
}
e.printStackTrace();
}
}
/**
* Draws the position square, the movement line and the center cross.
*
* @param g Graphics context for drawing
*/
public void showMovement(Graphics g) {
IntPoint centerP = null;
try {
if (imageCollector != null) {
g.setColor(Legend.COLORS[Legend.COLOR_MAP_CURSOR]);
centerP = pc.getP().getImageCenter();
int centerX = centerP.x - imageCollector.xScreenOverscan;
int centerY = centerP.y - imageCollector.yScreenOverscan;
int posX, posY;
if (!gpsRecenter) {
IntPoint p1 = new IntPoint(0, 0);
pc.getP().forward((pos.latitude * MoreMath.FAC_DECTORAD),
(pos.longitude * MoreMath.FAC_DECTORAD), p1);
posX = p1.getX()-imageCollector.xScreenOverscan;
posY = p1.getY()-imageCollector.yScreenOverscan;
} else {
posX = centerX;
posY = centerY;
}
g.setColor(Legend.COLORS[Legend.COLOR_MAP_POSINDICATOR]);
float radc = course * MoreMath.FAC_DECTORAD;
int px = posX + (int) (Math.sin(radc) * 20);
int py = posY - (int) (Math.cos(radc) * 20);
// crosshair center cursor
if (!gpsRecenter || gpsRecenterInvalid) {
g.drawLine(centerX, centerY - 12, centerX, centerY + 12);
g.drawLine(centerX - 12, centerY, centerX + 12, centerY);
g.drawArc(centerX - 5, centerY - 5, 10, 10, 0, 360);
}
if (! gpsRecenterInvalid) {
// gps position spot
pc.g.drawImage(gpsRecenterStale ? pc.images.IMG_POS_BG_STALE : pc.images.IMG_POS_BG, posX, posY, CENTERPOS);
// gps position rectangle
g.drawRect(posX - 4, posY - 4, 8, 8);
g.drawLine(posX, posY, px, py);
}
}
} catch (Exception e) {
if (imageCollector == null) {
logger.silentexception("No ImageCollector", e);
}
if (centerP == null) {
logger.silentexception("No centerP", e);
}
e.printStackTrace();
}
}
/**
* Show next screen in the sequence of data screens
* (tacho, trip, satellites).
* @param currentScreen Data screen currently shown, use the DATASCREEN_XXX
* constants from this class. Use DATASCREEN_NONE if none of them
* is on screen i.e. the first one should be shown.
*/
public void showNextDataScreen(int currentScreen) {
switch (currentScreen)
{
case DATASCREEN_TACHO:
// Tacho is followed by Trip.
if (guiTrip == null) {
guiTrip = new GuiTrip(this);
}
if (guiTrip != null) {
guiTrip.show();
}
break;
case DATASCREEN_TRIP:
// Trip is followed by Satellites.
if (guiSatellites == null) {
guiSatellites = new GuiSatellites(this, locationProducer);
}
if (guiSatellites != null) {
guiSatellites.show();
}
break;
case DATASCREEN_SATS:
// After Satellites, go back to map.
this.show();
break;
case DATASCREEN_NONE:
default:
// Tacho is first data screen
if (guiTacho == null) {
guiTacho = new GuiTacho(this);
}
if (guiTacho != null) {
guiTacho.show();
}
break;
}
}
public int showMemory(Graphics g, int yc, int la) {
g.setColor(0);
g.drawString(Locale.get("trace.Freemem")/*Freemem: */ + runtime.freeMemory(), 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.Totmem")/*Totmem: */ + runtime.totalMemory(), 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.Percent")/*Percent: */
+ (100f * runtime.freeMemory() / runtime.totalMemory()), 0, yc,
Graphics.TOP | Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.ThreadsRunning")/*Threads running: */
+ Thread.activeCount(), 0, yc,
Graphics.TOP | Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.Names")/*Names: */ + namesThread.getNameCount(), 0, yc,
Graphics.TOP | Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.SingleT")/*Single T: */ + tileReader.getLivingTilesCount() + "/"
+ tileReader.getRequestQueueSize(), 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.FileT")/*File T: */ + dictReader.getLivingTilesCount() + "/"
+ dictReader.getRequestQueueSize() + " Map: " + ImageCollector.icDuration + " ms", 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.LastMsg")/*LastMsg: */ + lastTitleMsg, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString( Locale.get("trace.at")/*at */ + lastTitleMsgClock, 0, yc,
Graphics.TOP | Graphics.LEFT );
return (yc);
}
private void updatePosition() {
if (pc != null) {
pc.center = center.copy();
pc.scale = scale;
pc.course=course;
repaint();
if (locationUpdateListeners != null && !TrackPlayer.isPlaying) {
synchronized (locationUpdateListeners) {
for (int i = 0; i < locationUpdateListeners.size(); i++) {
((LocationUpdateListener)locationUpdateListeners.elementAt(i)).loctionUpdated();
}
}
}
}
}
public synchronized void receivePosition(float lat, float lon, float scale) {
//#debug debug
logger.debug("Now displaying: " + (lat * MoreMath.FAC_RADTODEC) + " | " +
(lon * MoreMath.FAC_RADTODEC));
//We are explicitly setting the map to this position, so we probably don't
//want it to be recentered on the GPS immediately.
gpsRecenter = false;
center.setLatLonRad(lat, lon);
this.scale = scale;
updatePosition();
}
public synchronized void receiveCompassStatus(int status) {
}
public synchronized void receiveCompass(float direction) {
//#debug debug
logger.debug("Got compass reading: " + direction);
compassDirection = (int) direction;
compassDeviated = ((int) direction + compassDeviation + 360) % 360;
// TODO: allow for user to use compass for turning the map in panning mode
// (gpsRenter test below switchable by user setting)
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null && gpsRecenter) {
updateCourse(compassDeviated);
//repaint();
}
// course = compassDeviated;
//}
}
public static void updateLastUserActionTime() {
lastUserActionTime = System.currentTimeMillis();
}
public static long getDurationSinceLastUserActionTime() {
return System.currentTimeMillis() - lastUserActionTime;
}
public void updateCourse(int newcourse) {
coursegps = newcourse;
/* don't rotate too fast
*/
if ((newcourse - course)> 180) {
course = course + 360;
}
if ((course-newcourse)> 180) {
newcourse = newcourse + 360;
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null) {
course = newcourse;
} else {
// FIXME I think this is too slow a turn at least when course is
// of good quality, turning should be faster. This probably alleviates
// the trouble caused by unreliable gps course. However,
// some kind of heuristic, averaging course or evaluating the
// quality of course and fast or instant rotation with a known good GPS fix
// should be implemented instead of assuming course is always unreliable.
// The course fluctuations are lesser in faster speeds, so if we're constantly
// (for three consecutive locations) above say 5 km/h, a reasonable approach
// could be to use direct course change in thet case, and for speed below
// 5 km/h use the slow turning below.
// jkpj 2010-01-17
course = course + ((newcourse - course)*1)/4 + 360;
}
while (course > 360) {
course -= 360;
}
}
public synchronized void receivePosition(Position pos) {
// FIXME signal on location gained
//#debug info
logger.info("New position: " + pos);
collected++;
if (Configuration.getAutoRecenterToGpsMilliSecs() !=0 &&
getDurationSinceLastUserActionTime() > Configuration.getAutoRecenterToGpsMilliSecs()
&& isShown()
) {
gpsRecenter = true;
//autoZoomed = true;
}
if (Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_JSR179) {
if (pos.type == Position.TYPE_GPS_LASTKNOWN) {
// if we have a current cell id fix from cellid location,
// don't overwrite it with a stale GPS location, but ignore the position
// FIXME perhaps compare timestamps here in case the last known gps is later
if (this.pos.type == Position.TYPE_CELLID) {
return;
}
gpsRecenterInvalid = false;
gpsRecenterStale = true;
}
}
this.pos = pos;
if (pos.type == Position.TYPE_GPS || pos.type == Position.TYPE_CELLID || pos.type == Position.TYPE_MANUAL) {
gpsRecenterInvalid = false;
gpsRecenterStale = false;
}
if (gpsRecenter) {
center.setLatLonDeg(pos.latitude, pos.longitude);
speed = (int) (pos.speed * 3.6f);
fspeed = pos.speed * 3.6f;
// FIXME add auto-fallback mode where course is from GPS at high speeds and from compass
// at low speeds
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null) {
updateCourse(compassDeviated);
} else if (fspeed >= courseMinSpeed && pos.course != Float.NaN ) {
// Problem: resolve issue erratic course due to GPS fluctuation
// when GPS reception is poor (maybe 3..7S),
// causes unnecessary and disturbing map rotation when device is in one location
// Heuristic for solving: After being still, require
// three consecutive over-the-limit speed readings with roughly the
// same course
if (thirdPrevCourse != -1) {
// first check for normal flow of things, we've had three valid courses after movement start
updateCourse((int) pos.course);
} else if (prevCourse == -1) {
// previous course was invalid,
// don't set course yet, but set the first tentatively good course
prevCourse = (int) pos.course;
} else if (secondPrevCourse == -1) {
// the previous course was the first good one.
// If this course is in the same 60-degree
// sector as the first course, we have two valid courses
if (Math.abs(prevCourse - (int)pos.course) < 30 || Math.abs(prevCourse - (int)pos.course) > 330) {
secondPrevCourse = prevCourse;
}
prevCourse = (int) pos.course;
} else {
// we have received two previous valid curses, check for this one
if (Math.abs(prevCourse - (int)pos.course) < 30 || Math.abs(prevCourse - (int)pos.course) > 330) {
thirdPrevCourse = secondPrevCourse;
//No need to set these as we'll now trust courses until speed goes below limit
// - unless we'll later add averaging of recent courses for poor GPS reception
//secondPrevCourse = prevCourse;
//prevCourse = (int) pos.course;
updateCourse((int) pos.course);
} else {
prevCourse = (int) pos.course;
secondPrevCourse = -1;
}
}
} else {
// speed under the minimum, invalidate all prev courses
prevCourse = -1;
secondPrevCourse = -1;
thirdPrevCourse = -1;
}
}
if (gpx.isRecordingTrk()) {
try {
// don't tracklog manual cellid position or gps start/stop last known position
if ((Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_JSR179
&& pos.type == Position.TYPE_CELLID) || pos.type == Position.TYPE_GPS_LASTKNOWN) {
} else {
gpx.addTrkPt(pos);
}
} catch (Exception e) {
receiveMessage(e.getMessage());
}
}
altitude = (int) (pos.altitude);
if (Configuration.getCfgBitState(Configuration.CFGBIT_AUTOZOOM)
&& gpsRecenter
&& (isGpsConnected() || TrackPlayer.isPlaying)
&& autoZoomed
&& pc.getP() != null
&& pos.speed != Float.NaN // if speed is unknown do not autozoom
) {
// the minimumScale at 20km/h and below is equivalent to having zoomed in manually once from the startup zoom level
final float minimumScale = Configuration.getRealBaseScale() / 1.5f;
final int minimumSpeed = 20;
// the maximumScale at 160km/h and above is equivalent to having zoomed out manually once from the startup zoom level
final float maximumScale = Configuration.getRealBaseScale() * 1.5f;
final int maximumSpeed = 160;
int speedForScale = speed;
float newScale = minimumScale + (maximumScale - minimumScale) * (speedForScale - minimumSpeed) / (maximumSpeed - minimumSpeed);
// make sure the new scale is within the minimum / maximum scale values
if (newScale < minimumScale) {
newScale = minimumScale;
} else if (newScale > maximumScale) {
newScale = maximumScale;
}
scale = newScale;
// // calculate meters to top of screen
// float topLat = pc.getP().getMaxLat();
// float topLon = (pc.getP().getMinLon() + pc.getP().getMaxLon()) / 2f;
// float distance = MoreMath.dist(center.radlat, center.radlon, topLat, topLon );
// System.out.println("current distance to top of screen: " + distance);
//
// // avoid zooming in or out too far
// int speedForScale = course;
// if (speedForScale < 30) {
// speedForScale = 30;
// } else if (speedForScale > 160) {
// speedForScale = 160;
// }
//
// final float SECONDS_TO_PREVIEW = 45f;
// float metersToPreview = (float) speedForScale / 3.6f * SECONDS_TO_PREVIEW;
// System.out.println(metersToPreview + "meters to preview at " + speedForScale + "km/h");
//
// if (metersToPreview < 2000) {
// // calculate top position that needs to be visible to preview the metersToPreview
// topLat = center.radlat + (topLat - center.radlat) * metersToPreview / distance;
// topLon = center.radlon + (topLon - center.radlon) * metersToPreview / distance;
// System.out.println("new distance to top:" + MoreMath.dist(center.radlat, center.radlon, topLat, topLon ));
//
// /*
// * calculate scale factor, we multiply this again with 2 * 1.2 = 2.4 to take into account we calculated half the screen height
// * and 1.2f is probably the factor the PaintContext is larger than the display size
// * (new scale is calculated similiar to GuiWaypoint)
// */
// IntPoint intPoint1 = new IntPoint(0, 0);
// IntPoint intPoint2 = new IntPoint(getWidth(), getHeight());
// Node n1 = new Node(center.radlat, center.radlon, true);
// Node n2 = new Node(topLat, topLon, true);
// scale = pc.getP().getScale(n1, n2, intPoint1, intPoint2) * 2.4f;
// }
}
updatePosition();
}
public synchronized Position getCurrentPosition() {
return this.pos;
}
public synchronized void receiveMessage(String s) {
// #debug info
logger.info("Setting title: " + s);
currentTitleMsg = s;
synchronized (this) {
/*
* only increase the number of current title messages
* if the timer already has been set in the display code
*/
if (setTitleMsgTimeout == 0) {
currentTitleMsgOpenCount++;
}
setTitleMsgTimeout = 3000;
}
lastTitleMsgClock = DateTimeTools.getClock(System.currentTimeMillis(), false);
repaint();
}
public void receiveSatellites(Satellite[] sats) {
// Not interested
}
/** Shows an alert message
*
* @param title The title of the alert
* @param message The message text
* @param timeout Timeout in ms. Please reserve enough time so the user can
* actually read the message. Use Alert.FOREVER if you want no timeout.
*/
public synchronized void alert(String title, String message, int timeout) {
// #debug info
logger.info("Showing trace alert: " + title + ": " + message);
if (timeout == Alert.FOREVER) {
timeout = 10000;
}
currentAlertTitle = title;
currentAlertMessage = message;
synchronized (this) {
/*
* only increase the number of current open alerts
* if the timer already has been set in the display code
*/
if (setAlertTimeout == 0) {
currentAlertsOpenCount++;
}
setAlertTimeout = timeout;
}
repaint();
}
public MIDlet getParent() {
return parent;
}
protected void pointerPressed(int x, int y) {
updateLastUserActionTime();
long currTime = System.currentTimeMillis();
pointerDragged = false;
pointerDraggedMuch = false;
pointerActionDone = false;
// remember center when the pointer was pressed for dragging
centerPointerPressedN = center.copy();
if (imageCollector != null) {
panProjection=imageCollector.getCurrentProjection();
pickPointStart=panProjection.inverse(x,y, pickPointStart);
} else {
panProjection = null;
}
// remember the LayoutElement the pointer is pressed down at, this will also highlight it on the display
int touchedElementId = tl.getElementIdAtPointer(x, y);
if (touchedElementId >= 0 && (!keyboardLocked || tl.getActionIdAtPointer(x, y) == Trace.ICON_MENU)
&&
tl.isAnyActionIdAtPointer(x, y)
) {
tl.setTouchedElement((LayoutElement) tl.elementAt(touchedElementId));
repaint();
}
// check for double press
if (!keyboardLocked && currTime - pressedPointerTime < DOUBLETAP_MAXDELAY) {
doubleTap(x, y);
}
// Remember the time and position the pointer was pressed after the check for double tap,
// so the double tap code will check for the position of the first of the two taps
pressedPointerTime = currTime;
Trace.touchX = x;
Trace.touchY = y;
// Give a message if keyboard/user interface is locked.
// This must be done after remembering the touchX/Y positions as they are needed to unlock
if (keyboardLocked) {
keyPressed(0);
return;
}
// // when these statements are reached, no double tap action has been executed,
// // so check here if there's currently already a TimerTask waiting for a single tap.
// // If yes, perform the current single tap action immediately before starting the next TimerTask
// if (checkingForSingleTap && !pointerDraggedMuch) {
// singleTap();
// pointerActionDone = false;
// }
//
longTapTimerTask = new TimerTask() {
public void run() {
// if no action (e.g. from double tap) is already done
// and the pointer did not move or if it was pressed on a control and not moved much
if (!pointerActionDone && !pointerDraggedMuch) {
if (System.currentTimeMillis() - pressedPointerTime >= LONGTAP_DELAY){
longTap();
}
}
}
};
try {
// set timer to continue check if this is a long tap
GpsMid.getTimer().schedule(longTapTimerTask, LONGTAP_DELAY);
} catch (Exception e) {
logger.error(Locale.get("trace.NoLongTapTimerTask")/*No LongTap TimerTask: */ + e.toString());
}
}
protected void pointerReleased(int x, int y) {
// releasing the pointer cancels the check for long tap
if (longTapTimerTask != null) {
longTapTimerTask.cancel();
}
// releasing the pointer will clear the highlighting of the touched element
if (tl.getTouchedElement() != null) {
tl.clearTouchedElement();
repaint();
}
if (!pointerActionDone && !keyboardLocked) {
touchReleaseX = x;
touchReleaseY = y;
// check for a single tap in a timer started after the maximum double tap delay
// if the timer will not be cancelled by a double tap, the timer will execute the single tap command
singleTapTimerTask = new TimerTask() {
public void run() {
if (!keyboardLocked) {
singleTap(touchReleaseX, touchReleaseY);
}
}
};
try {
// set timer to check if this is a single tap
GpsMid.getTimer().schedule(singleTapTimerTask, DOUBLETAP_MAXDELAY);
} catch (Exception e) {
logger.error(Locale.get("trace.NoSingleTapTimerTask")/*No SingleTap TimerTask: */ + e.toString());
}
if (pointerDragged) {
pointerDragged(x , y);
return;
}
}
}
protected void pointerDragged (int x, int y) {
updateLastUserActionTime();
LayoutElement e = tl.getElementAtPointer(x, y);
if (tl.getTouchedElement() != e) {
// leaving the touched element cancels the check for long tap
if (longTapTimerTask != null) {
longTapTimerTask.cancel();
}
tl.clearTouchedElement();
repaint();
}
// If the initially touched element is reached again during dragging, highlight it
if (tl.getElementAtPointer(touchX, touchY) == e && tl.isAnyActionIdAtPointer(x, y)) {
tl.setTouchedElement(e);
repaint();
}
if (pointerActionDone) {
return;
}
// check if there's been much movement, do this before the slide lock/unlock
// to avoid a single tap action when not sliding enough
if (Math.abs(x - Trace.touchX) > 8
||
Math.abs(y - Trace.touchY) > 8
) {
pointerDraggedMuch = true;
// avoid double tap triggering on fast consecutive drag actions starting at almost the same position
pressedPointerTime = 0;
}
// slide at least 1/4 display width to lock / unlock GpsMid
if (tl.getActionIdAtPointer(touchX, touchY) == Trace.ICON_MENU) {
if ( tl.getActionIdAtPointer(x, y) == Trace.ICON_MENU
&&
x - touchX > getWidth() / 4
) {
commandAction(TOGGLE_KEY_LOCK_CMD);
pointerActionDone = true;
}
return;
}
if (keyboardLocked) {
return;
}
pointerDragged = true;
// do not start map dragging on a touch control if only dragged slightly
if (!pointerDraggedMuch && tl.getElementIdAtPointer(touchX, touchY) >= 0) {
return;
}
if (tl.getElementIdAtPointer(touchX, touchY) < 0 && imageCollector != null && panProjection != null) {
// difference between where the pointer was pressed and is currently dragged
// int diffX = Trace.touchX - x;
// int diffY = Trace.touchY - y;
//
// IntPoint centerPointerPressedP = new IntPoint();
pickPointEnd=panProjection.inverse(x,y, pickPointEnd);
center.radlat=centerPointerPressedN.radlat-(pickPointEnd.radlat-pickPointStart.radlat);
center.radlon=centerPointerPressedN.radlon-(pickPointEnd.radlon-pickPointStart.radlon);
// System.out.println("diff " + diffX + "/" + diffY + " " + (pickPointEnd.radlat-pickPointStart.radlat) + "/" + (pickPointEnd.radlon-pickPointStart.radlon) );
imageCollector.newDataReady();
gpsRecenter = false;
}
}
private void singleTap(int x, int y) {
pointerActionDone = true;
// if not tapping a control, then the map area must be tapped so we set the touchable button sizes
if (tl.getElementIdAtPointer(touchX, touchY) < 0) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_MAPTAP_SINGLE)) {
// if pointer was dragged much, do not recognize a single tap on the map
if (pointerDraggedMuch) {
return;
}
// #debug debug
logger.debug("single tap map");
if (!tl.bigOnScreenButtons) {
tl.setOnScreenButtonSize(true);
// set timer to continuously check if the last user interaction is old enough to make the buttons small again
final long BIGBUTTON_DURATION = 5000;
bigButtonTimerTask = new TimerTask() {
public void run() {
if (System.currentTimeMillis() - lastUserActionTime > BIGBUTTON_DURATION ) {
// make the on screen touch buttons small again
tl.setOnScreenButtonSize(false);
requestRedraw();
bigButtonTimerTask.cancel();
}
}
};
try {
GpsMid.getTimer().schedule(bigButtonTimerTask, BIGBUTTON_DURATION, 500);
} catch (Exception e) {
logger.error("Error scheduling bigButtonTimerTask: " + e.toString());
}
}
}
repaint();
} else if (tl.getElementIdAtPointer(x, y) == tl.getElementIdAtPointer(touchX, touchY)) {
tl.clearTouchedElement();
int actionId = tl.getActionIdAtPointer(x, y);
if (actionId > 0) {
// #debug debug
logger.debug("single tap button: " + actionId + " x: " + touchX + " y: " + touchY);
if (System.currentTimeMillis() < (lastBackLightOnTime + 2500)) {
if (actionId == ZOOM_IN_CMD) {
actionId = PAN_RIGHT2_CMD;
} else if (actionId == ZOOM_OUT_CMD) {
actionId = PAN_LEFT2_CMD;
}
} else if (manualRotationMode) {
if (actionId == ZOOM_IN_CMD) {
actionId = PAN_LEFT2_CMD;
} else if (actionId == ZOOM_OUT_CMD) {
actionId = PAN_RIGHT2_CMD;
}
} else if (TrackPlayer.isPlaying) {
if (actionId == ZOOM_IN_CMD) {
actionId = PAN_RIGHT2_CMD;
} else if (actionId == ZOOM_OUT_CMD) {
actionId = PAN_LEFT2_CMD;
}
}
commandAction(actionId);
repaint();
}
}
}
private void doubleTap(int x, int y) {
// if not double tapping a control, then the map area must be double tapped and we zoom in
if (tl.getElementIdAtPointer(touchX, touchY) < 0) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_MAPTAP_DOUBLE)) {
// if this is a double press on the map, cancel the timer checking for a single press
if (singleTapTimerTask != null) {
singleTapTimerTask.cancel();
}
// if pointer was dragged much, do not recognize a double tap on the map
if (pointerDraggedMuch) {
return;
}
//#debug debug
logger.debug("double tap map");
pointerActionDone = true;
commandAction(ZOOM_IN_CMD);
}
repaint();
return;
} else if (tl.getTouchedElement() == tl.getElementAtPointer(x, y) ){
// double tapping a control
int actionId = tl.getActionIdDoubleAtPointer(x, y);
//#debug debug
logger.debug("double tap button: " + actionId + " x: " + x + " y: " + x);
if (actionId > 0) {
// if this is a double press on a control, cancel the timer checking for a single press
if (singleTapTimerTask != null) {
singleTapTimerTask.cancel();
}
pointerActionDone = true;
commandAction(actionId);
tl.clearTouchedElement();
repaint();
return;
} else {
singleTap(x, y);
}
}
}
private void longTap() {
pointerActionDone = true;
// if not tapping a control, then the map area must be tapped so we do the long tap action for the map area
if (tl.getElementIdAtPointer(touchX, touchY) < 0 && panProjection != null) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_MAPTAP_LONG)) {
//#debug debug
logger.debug("long tap map");
//#if polish.api.online
// long tap map to open a place-related menu
// use the place of touch instead of old center as position,
// set as new center
pickPointEnd=panProjection.inverse(touchX,touchY, pickPointEnd);
center.radlat=centerPointerPressedN.radlat-(pickPointEnd.radlat-pickPointStart.radlat);
center.radlon=centerPointerPressedN.radlon-(pickPointEnd.radlon-pickPointStart.radlon);
Position oPos = new Position(center.radlat, center.radlon,
0.0f, 0.0f, 0.0f, 0, 0);
imageCollector.newDataReady();
gpsRecenter = false;
commandAction(ONLINE_INFO_CMD);
//#endif
}
return;
// long tapping a control
} else {
int actionId = tl.getActionIdLongAtPointer(touchX, touchY);
if (actionId > 0) {
tl.clearTouchedElement();
//#debug debug
logger.debug("long tap button: " + actionId + " x: " + touchX + " y: " + touchY);
commandAction(actionId);
repaint();
}
}
}
/**
* Returns the command used to go to the data screens.
* Needed by the data screens so they can find the key codes used for this
* as they have to use them too.
* @return Command
*/
public Command getDataScreenCommand() {
return CMDS[DATASCREEN_CMD];
}
public Tile getDict(byte zl) {
return tiles[zl];
}
public void setDict(Tile dict, byte zl) {
tiles[zl] = dict;
// Tile.trace=this;
//addCommand(REFRESH_CMD);
// if (zl == 3) {
// setTitle(null);
// } else {
// setTitle("dict " + zl + "ready");
// }
if (zl == 0) {
// read saved position from Configuration
Configuration.getStartupPos(center);
if (center.radlat == 0.0f && center.radlon == 0.0f) {
// if no saved position use center of map
dict.getCenter(center);
}
// read saved destination position from Configuration
if (Configuration.getCfgBitState(Configuration.CFGBIT_SAVED_DESTPOS_VALID)) {
Node destNode = new Node();
Configuration.getDestPos(destNode);
setDestination(new RoutePositionMark(destNode.radlat, destNode.radlon));
}
if (pc != null) {
pc.center = center.copy();
pc.scale = scale;
pc.course = course;
}
}
updatePosition();
}
public void receiveStatistics(int[] statRecord, byte quality) {
this.btquality = quality;
this.statRecord = statRecord;
repaint();
}
public synchronized void locationDecoderEnd() {
//#debug info
logger.info("enter locationDecoderEnd");
if (Configuration.getCfgBitState(Configuration.CFGBIT_SND_DISCONNECT)) {
// some fault tolerance - will crash without a map
if (Legend.isValid) {
GpsMid.mNoiseMaker.playSound("DISCONNECT");
}
}
//if (gpx != null) {
// /**
// * Close and Save the gpx recording, to ensure we don't loose data
// */
// gpx.saveTrk(false);
//}
removeCommand(CMDS[DISCONNECT_GPS_CMD]);
if (locationProducer == null) {
//#debug info
logger.info("leave locationDecoderEnd no producer");
return;
}
locationProducer = null;
notify();
addCommand(CMDS[CONNECT_GPS_CMD]);
// addCommand(START_RECORD_CMD);
//#debug info
logger.info("end locationDecoderEnd");
}
public void receiveStatus(byte status, int satsReceived) {
// FIXME signal a sound on location gained or lost
solution = status;
solutionStr = LocationMsgReceiverList.getCurrentStatusString(status, satsReceived);
repaint();
}
public String getName(int idx) {
if (idx < 0) {
return null;
}
return namesThread.getName(idx);
}
public String getUrl(int idx) {
if (idx < 0) {
return null;
}
return urlsThread.getUrl(idx);
}
public Vector fulltextSearch (String snippet, CancelMonitorInterface cmi) {
return namesThread.fulltextSearch(snippet, cmi);
}
// this is called by ImageCollector
public void requestRedraw() {
repaint();
}
public void newDataReady() {
if (imageCollector != null) {
imageCollector.newDataReady();
}
}
public void show() {
//Display.getDisplay(parent).setCurrent(this);
Legend.freeDrawnWayAndAreaSearchImages();
GpsMid.getInstance().show(this);
setFullScreenMode(Configuration.getCfgBitState(Configuration.CFGBIT_FULLSCREEN));
updateLastUserActionTime();
repaint();
}
public void recreateTraceLayout() {
tl = new TraceLayout(0, 0, getWidth(), getHeight());
}
public void locationDecoderEnd(String msg) {
receiveMessage(msg);
locationDecoderEnd();
}
public PositionMark getDestination() {
return dest;
}
public void setDestination(RoutePositionMark dest) {
endRouting();
this.dest = dest;
pc.dest = dest;
if (dest != null) {
//#debug info
logger.info("Setting destination to " + dest.toString());
// move map only to the destination, if GUI is not optimized for routing
if (! Configuration.getCfgBitState(Configuration.CFGBIT_ICONMENUS_ROUTING_OPTIMIZED)) {
commandAction(SHOW_DEST_CMD);
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_AUTOSAVE_DESTPOS)) {
Configuration.setDestPos(new Node(dest.lat, dest.lon, true));
Configuration.setCfgBitSavedState(Configuration.CFGBIT_SAVED_DESTPOS_VALID, true);
}
movedAwayFromDest = false;
} else {
Configuration.setCfgBitSavedState(Configuration.CFGBIT_SAVED_DESTPOS_VALID, false);
//#debug info
logger.info("Setting destination to null");
}
}
public void endRouting() {
RouteInstructions.initialRecalcDone = false;
RouteInstructions.icCountOffRouteDetected = 0;
RouteInstructions.routeInstructionsHeight = 0;
RouteInstructions.abortRouteLineProduction();
setRoute(null);
setRouteNodes(null);
}
/**
* This is the callback routine if RouteCalculation is ready
* @param route
*/
public void setRoute(Vector route) {
synchronized(this) {
this.route = route;
}
if (this.route != null) {
// reset off-route as soon as first route connection is known
RouteInstructions.resetOffRoute(this.route, center);
if (ri == null) {
ri = new RouteInstructions(this);
}
// show map during route line production
if (Configuration.getContinueMapWhileRouteing() == Configuration.continueMap_At_Route_Line_Creation) {
resumeImageCollectorAfterRouteCalc();
}
ri.newRoute(this.route);
oldRecalculationTime = System.currentTimeMillis();
}
// show map always after route calculation
resumeImageCollectorAfterRouteCalc();
routeCalc=false;
routeEngine=null;
}
private void resumeImageCollectorAfterRouteCalc() {
try {
if (imageCollector == null) {
startImageCollector();
// imageCollector thread starts up suspended,
// so we need to resume it
imageCollector.resume();
} else if (imageCollector != null) {
imageCollector.newDataReady();
}
repaint();
} catch (Exception e) {
logger.exception(Locale.get("trace.InTraceResumeImageCollector")/*In Trace.resumeImageCollector*/, e);
}
}
/**
* If we are running out of memory, try
* dropping all the caches in order to try
* and recover from out of memory errors.
* Not guaranteed to work, as it needs
* to allocate some memory for dropping
* caches.
*/
public void dropCache() {
tileReader.dropCache();
dictReader.dropCache();
System.gc();
namesThread.dropCache();
urlsThread.dropCache();
System.gc();
if (gpx != null) {
gpx.dropCache();
}
}
public QueueDataReader getDataReader() {
return tileReader;
}
public QueueDictReader getDictReader() {
return dictReader;
}
public Vector getRouteNodes() {
return routeNodes;
}
public void setRouteNodes(Vector routeNodes) {
this.routeNodes = routeNodes;
}
protected void hideNotify() {
//#debug debug
logger.debug("Hide notify has been called, screen will no longer be updated");
if (imageCollector != null) {
imageCollector.suspend();
}
}
protected void showNotify() {
//#debug debug
logger.debug("Show notify has been called, screen will be updated again");
if (imageCollector != null) {
imageCollector.resume();
imageCollector.newDataReady();
}
}
public Vector getRoute() {
return route;
}
public void actionCompleted() {
boolean reAddCommands = true;
if (reAddCommands && Configuration.getCfgBitState(Configuration.CFGBIT_FULLSCREEN)) {
addAllCommands();
}
}
public void showIconMenu() {
if (traceIconMenu == null) {
traceIconMenu = new TraceIconMenu(this, this);
}
traceIconMenu.show();
}
/** uncache the icon menu to reflect changes in the setup or save memory */
public static void uncacheIconMenu() {
//#mdebug trace
if (traceIconMenu != null) {
logger.trace("uncaching TraceIconMenu");
}
//#enddebug
traceIconMenu = null;
}
/** interface for IconMenuWithPages: recreate the icon menu from scratch and show it (introduced for reflecting size change of the Canvas) */
public void recreateAndShowIconMenu() {
uncacheIconMenu();
showIconMenu();
}
/** interface for received actions from the IconMenu GUI */
public void performIconAction(int actionId) {
updateLastUserActionTime();
// when we are low on memory or during route calculation do not cache the icon menu (including scaled images)
if (routeCalc || GpsMid.getInstance().needsFreeingMemory()) {
//#debug info
logger.info("low mem: Uncaching traceIconMenu");
uncacheIconMenu();
}
if (actionId != IconActionPerformer.BACK_ACTIONID) {
commandAction(actionId);
}
}
/** convert distance to string based on user preferences */
// The default way to show a distance is "10km" for
// distances 10km or more, "2,6km" for distances under 10, and
// "600m" for distances under 1km.
public static String showDistance(int meters) {
return showDistance(meters, DISTANCE_GENERIC);
}
public static String showDistance(int meters, int type) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_METRIC)) {
if (type == DISTANCE_UNKNOWN) {
return "???m";
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_DISTANCE_VIEW) && (type != DISTANCE_ALTITUDE)) {
if (meters >= 10000) {
return meters / 1000 + "km";
} else if (meters < 1000) {
return meters + "m";
} else {
// FIXME use e.g. getDecimalSeparator() for decimal comma/point selection
return meters / 1000 + "." + (meters % 1000) / 100 + "km";
}
} else {
return meters + "m";
}
} else {
if (type == DISTANCE_UNKNOWN) {
return "???yd";
} else if (type == DISTANCE_ALTITUDE) {
return Integer.toString((int)(meters / 0.30480 + 0.5)) + "ft";
} else {
return Integer.toString((int)(meters / 0.9144 + 0.5)) + "yd";
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.