answer
stringlengths 17
10.2M
|
|---|
package seedu.unburden.model.task;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import seedu.unburden.commons.exceptions.*;
import seedu.unburden.commons.util.CollectionUtil;
import java.util.*;
/**
* A list of persons that enforces uniqueness between its elements and does not allow nulls.
*
* Supports a minimal set of list operations.
*
* @see Task#equals(Object)
* @see CollectionUtil#elementsAreUnique(Collection)
*/
public class UniqueTaskList implements Iterable<Task> {
/**
* Signals that an operation would have violated the 'no duplicates' property of the list.
*/
public static class DuplicateTaskException extends DuplicateDataException {
protected DuplicateTaskException() {
super("Operation would result in duplicate tasks");
}
}
/**
* Signals that an operation targeting a specified person in the list would fail because
* there is no such matching person in the list.
*/
public static class TaskNotFoundException extends Exception {}
private final ObservableList<Task> internalList = FXCollections.observableArrayList();
/**
* Constructs empty PersonList.
*/
public UniqueTaskList() {}
/**
* Returns true if the list contains an equivalent person as the given argument.
*/
public boolean contains(ReadOnlyTask toCheck) {
assert toCheck != null;
return internalList.contains(toCheck);
}
/**
* Adds a person to the list.
*
* @throws DuplicatePersonException if the person to add is a duplicate of an existing person in the list.
*/
public void add(Task toAdd) throws DuplicateTaskException {
assert toAdd != null;
if (contains(toAdd)) {
throw new DuplicateTaskException();
}
internalList.add(toAdd);
FXCollections.sort(internalList);
}
/**
* Removes the equivalent person from the list.
*
* @throws PersonNotFoundException if no such person could be found in the list.
*/
public boolean remove(ReadOnlyTask toRemove) throws TaskNotFoundException {
assert toRemove != null;
final boolean taskFoundAndDeleted = internalList.remove(toRemove);
if (!taskFoundAndDeleted) {
throw new TaskNotFoundException();
}
FXCollections.sort(internalList);
return taskFoundAndDeleted;
}
//@@Gary Goh A0139714B
public boolean edit(ReadOnlyTask key, Task toEdit)
throws TaskNotFoundException, IllegalValueException {
assert toEdit != null;
assert key != null;
int taskIndex = internalList.indexOf(key);
Task updatedTask = toEdit;
Task oldTask = internalList.get(taskIndex);
if (updatedTask.getName().getFullName() == "") {
updatedTask.setName(oldTask.getName());
}
if (updatedTask.getTaskDescription().getFullTaskDescription() == "") {
updatedTask.setTaskDescription(oldTask.getTaskDescription());
}
if (updatedTask.getDate().getFullDate() == "") {
updatedTask.setDate(oldTask.getDate());
}
if (updatedTask.getStartTime().getFullTime() == "") {
updatedTask.setStartTime(oldTask.getStartTime());
}
if (updatedTask.getEndTime().getFullTime() == "") {
updatedTask.setEndTime(oldTask.getEndTime());
}
updatedTask.setTags(oldTask.getTags());
internalList.set(taskIndex, updatedTask);
FXCollections.sort(internalList);
return true;
}
public ObservableList<Task> getInternalList() {
return internalList;
}
@Override
public Iterator<Task> iterator() {
return internalList.iterator();
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof UniqueTaskList // instanceof handles nulls
&& this.internalList.equals(
((UniqueTaskList) other).internalList));
}
@Override
public int hashCode() {
return internalList.hashCode();
}
//@@ Gauri Joshi A0139714B
public void done(ReadOnlyTask key, boolean isDone) {
assert key != null;
int taskIndex = internalList.indexOf(key);
Task newTask = internalList.get(taskIndex);
newTask.setDone(isDone);
internalList.set(taskIndex, newTask);
}
public void undone(ReadOnlyTask key, boolean isDone) {
assert key != null;
int taskIndex = internalList.indexOf(key);
Task newTask = internalList.get(taskIndex);
newTask.setDone(isDone);
internalList.set(taskIndex, newTask);
}
}
|
package uk.ac.ic.wlgitbridge.server;
import com.google.api.client.auth.oauth2.*;
import com.google.api.client.http.GenericUrl;
import org.apache.commons.codec.binary.Base64;
import org.eclipse.jetty.server.Request;
import uk.ac.ic.wlgitbridge.application.config.Oauth2;
import uk.ac.ic.wlgitbridge.bridge.snapshot.SnapshotApi;
import uk.ac.ic.wlgitbridge.snapshot.base.MissingRepositoryException;
import uk.ac.ic.wlgitbridge.snapshot.base.ForbiddenException;
import uk.ac.ic.wlgitbridge.snapshot.getdoc.GetDocRequest;
import uk.ac.ic.wlgitbridge.util.Instance;
import uk.ac.ic.wlgitbridge.util.Log;
import uk.ac.ic.wlgitbridge.util.Util;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.*;
public class Oauth2Filter implements Filter {
public static final String ATTRIBUTE_KEY = "oauth2";
private final SnapshotApi snapshotApi;
private final Oauth2 oauth2;
public Oauth2Filter(SnapshotApi snapshotApi, Oauth2 oauth2) {
this.snapshotApi = snapshotApi;
this.oauth2 = oauth2;
}
@Override
public void init(FilterConfig filterConfig) {}
private void sendResponse(ServletResponse servletResponse, int code, List<String> lines) throws IOException {
HttpServletResponse response = ((HttpServletResponse) servletResponse);
response.setContentType("text/plain");
response.setStatus(code);
PrintWriter w = response.getWriter();
for (String line : lines) {
w.println(line);
}
w.close();
return;
}
/**
* The original request from git will not contain the Authorization header.
*
* So, for projects that need auth, we return 401. Git will swallow this
* and prompt the user for user/pass, and then make a brand new request.
* @param servletRequest
* @param servletResponse
* @param filterChain
* @throws IOException
* @throws ServletException
*/
@Override
public void doFilter(
ServletRequest servletRequest,
ServletResponse servletResponse,
FilterChain filterChain
) throws IOException, ServletException {
String requestUri = ((Request) servletRequest).getRequestURI();
if (requestUri.startsWith("/project")) {
Log.info("[{}] Invalid request URI", requestUri);
sendResponse(servletResponse,400, Arrays.asList(
"Invalid Project ID (must not have a '/project' prefix)"
));
return;
}
String project = Util.removeAllSuffixes(
requestUri.split("/")[1],
".git"
);
// Reject v1 ids, the request will be rejected by v1 anyway
if (project.matches("^[0-9]+[bcdfghjklmnpqrstvwxyz]{6,12}$") && !project.matches("^[0-9a-f]{24}$")) {
Log.info("[{}] Request for v1 project, refusing", project);
sendResponse(servletResponse, 404, Arrays.asList(
"This project has not yet been moved into the new version",
"of Overleaf. You will need to move it in order to continue working on it.",
"Please visit this project online on www.overleaf.com to do this.",
"",
"You can find the new git remote url by selecting \"Git\" from",
"the left sidebar in the project view.",
"",
"If this is unexpected, please contact us at support@overleaf.com, or",
"see https:
));
return;
}
Log.info("[{}] Checking if auth needed", project);
GetDocRequest doc = new GetDocRequest(project);
doc.request();
try {
SnapshotApi.getResult(
snapshotApi.getDoc(Optional.empty(), project));
} catch (ForbiddenException e) {
Log.info("[{}] Auth needed", project);
getAndInjectCredentials(
project,
servletRequest,
servletResponse,
filterChain
);
return;
} catch (MissingRepositoryException e) {
handleMissingRepository(project, e, (HttpServletResponse) servletResponse);
}
Log.info("[{}] Auth not needed", project);
filterChain.doFilter(servletRequest, servletResponse);
}
// TODO: this is ridiculous. Check for error cases first, then return/throw
// TODO: also, use an Optional credential, since we treat it as optional
private void getAndInjectCredentials(
String projectName,
ServletRequest servletRequest,
ServletResponse servletResponse,
FilterChain filterChain
) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
String capturedUsername = "(unknown)";
String authHeader = request.getHeader("Authorization");
if (authHeader != null) {
Log.info("[{}] Authorization header present");
StringTokenizer st = new StringTokenizer(authHeader);
if (st.hasMoreTokens()) {
String basic = st.nextToken();
if (basic.equalsIgnoreCase("Basic")) {
try {
String credentials = new String(
Base64.decodeBase64(st.nextToken()),
"UTF-8"
);
String[] split = credentials.split(":",2);
if (split.length == 2) {
String username = split[0];
String password = split[1];
String accessToken = null;
if (username.length() > 0) {
capturedUsername = username;
}
try {
accessToken = new PasswordTokenRequest(
Instance.httpTransport,
Instance.jsonFactory,
new GenericUrl(
oauth2.getOauth2Server()
+ "/oauth/token"
),
username,
password
).setClientAuthentication(
new ClientParametersAuthentication(
oauth2.getOauth2ClientID(),
oauth2.getOauth2ClientSecret()
)
).execute().getAccessToken();
} catch (TokenResponseException e) {
handleNeedAuthorization(projectName, capturedUsername, e.getStatusCode(), request, response);
return;
}
final Credential cred = new Credential.Builder(
BearerToken.authorizationHeaderAccessMethod(
)
).build();
cred.setAccessToken(accessToken);
servletRequest.setAttribute(ATTRIBUTE_KEY, cred);
filterChain.doFilter(
servletRequest,
servletResponse
);
} else {
handleNeedAuthorization(projectName, capturedUsername, 0, request, response);
}
} catch (UnsupportedEncodingException e) {
throw new Error("Couldn't retrieve authentication", e);
}
}
}
} else {
handleNeedAuthorization(projectName, capturedUsername, 0, request, response);
}
}
@Override
public void destroy() {}
private void handleNeedAuthorization(
String projectName,
String userName,
int statusCode,
HttpServletRequest servletRequest,
HttpServletResponse servletResponse
) throws IOException {
Log.info(
"[{}] Unauthorized, User '{}' status={} ip={}",
projectName,
userName,
statusCode,
servletRequest.getRemoteAddr()
);
HttpServletResponse response = servletResponse;
response.setContentType("text/plain");
response.setHeader("WWW-Authenticate", "Basic realm=\"Git Bridge\"");
response.setStatus(401);
PrintWriter w = response.getWriter();
w.println(
"Please sign in using your email address and Overleaf password."
);
w.println();
w.println(
"*Note*: if you sign in to Overleaf using another provider, "
+ "such "
);
w.println(
"as Google or Twitter, you need to set a password "
+ "on your Overleaf "
);
w.println(
"account first. "
+ "Please see https:
);
w.println("more information.");
w.close();
}
private void handleMissingRepository(
String projectName,
MissingRepositoryException e,
HttpServletResponse response
) throws IOException {
Log.info("[{}] Project missing.", projectName);
response.setContentType("text/plain");
// git special-cases 404 to give "repository '%s' not found",
// rather than displaying the raw status code.
response.setStatus(404);
PrintWriter w = response.getWriter();
for (String line : e.getDescriptionLines()) {
w.println(line);
}
w.close();
}
}
|
package uk.co.optimisticpanda.atom;
import java.util.List;
import org.apache.abdera.model.Entry;
import org.apache.abdera.model.Feed;
import uk.co.optimisticpanda.atom.reader.FeedReader;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
public class FeedTraverser {
private final Predicate<Entry> stopPredicate;
private final EntryVisitor visitor;
private final Predicate<Entry> entriesMatching;
private final FeedReader reader;
private final Ordering<Entry> latestToEarliest;
FeedTraverser(Predicate<Entry> stopPredicate, EntryVisitor visitor, FeedReader reader, Predicate<Entry> entrysMatching, Ordering<Entry> latestToEarliest) {
this.stopPredicate = stopPredicate;
this.visitor = visitor;
this.reader = reader;
this.entriesMatching = entrysMatching;
this.latestToEarliest = latestToEarliest;
}
/**
* Traverse a feed found at location. Location maybe a url, file system
* location, string etc.... The actual meaning of this is determined by the underlying
* {@link FeedReader}.
*/
public void traverse(String location) {
backwardsTraverse(reader.load(location));
}
// Traverse back through the archive from latest to earliest
private void backwardsTraverse(Feed feed) {
boolean stopped = false;
List<Entry> seenEntries = Lists.newArrayList();
for (Entry entry : latestToEarliest.sortedCopy(feed.getEntries())) {
if (stopPredicate.apply(entry)) {
stopped = true;
break;
}
seenEntries.add(entry);
}
if (stopped) {
for (Entry seenEntry : Lists.reverse(seenEntries)) {
if (entriesMatching.apply(seenEntry)) {
visitor.visit(seenEntry);
}
}
Optional<Feed> next = reader.getNextArchive(feed);
if (next.isPresent()) {
forwardsTraverse(next.get());
}
return;
}
Optional<Feed> previous = reader.getPreviousArchive(feed);
if (previous.isPresent()) {
backwardsTraverse(previous.get());
} else {
forwardsTraverse(feed);
}
}
// Traverse forwards through the feed from earliest to latest.
private void forwardsTraverse(Feed feed) {
for (Entry entry : Lists.reverse(latestToEarliest.sortedCopy(feed.getEntries()))) {
if (entriesMatching.apply(entry)) {
visitor.visit(entry);
}
}
Optional<Feed> next = reader.getNextArchive(feed);
if (next.isPresent()) {
forwardsTraverse(next.get());
}
}
}
|
package willitconnect.service.util;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.core.io.support.ResourcePatternUtils;
import willitconnect.model.CheckedEntry;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.IntStream;
import static willitconnect.service.util.HostMatcher.hasPort;
import static willitconnect.service.util.HostMatcher.isHost;
public class EntryConsumer implements Consumer<String> {
private Logger log = Logger.getLogger(EntryConsumer.class);
private final JSONObject vcapServices;
private final List<CheckedEntry> entries;
public EntryConsumer(List<CheckedEntry> entries, JSONObject vcapServices) {
this.entries = entries;
this.vcapServices = vcapServices;
}
@Override
public void accept(String key) {
if (isHost(key)) {
String host = vcapServices.optString(key);
if (hasPort(host))
addNewEntry(host);
else
addNewEntry(host + ":" + getPort());
} else {
if (ResourcePatternUtils.isUrl(vcapServices.optString(key))) {
try {
URL url = new URL(vcapServices.getString(key));
addNewEntry(url.getHost() + ":" + url.getPort());
} catch (MalformedURLException e) {
log.error("Mailformed URL -- How did we get here?");
}
return;
};
//Check over any sub json objects.
if (handleJSONObject(key)) return;
if (handleJSONArray(key)) return;
}
}
private int getPort() {
int port = -1;
if ( vcapServices.has("port") ) {
String sPort = vcapServices.optString("port");
if ( null != sPort ) {
port = Integer.parseInt(sPort);
} else {
vcapServices.optInt("port", -1);
}
}
return port;
}
private boolean handleJSONArray(String key) {
JSONArray array = vcapServices.optJSONArray(key);
if (null == array) return false;
IntStream.range(0, array.length())
.filter(i -> array.optJSONObject(i) != null)
.forEach(i -> array.getJSONObject(i).keys().forEachRemaining(
new EntryConsumer(entries, array.getJSONObject(i))));
return true;
}
private boolean handleJSONObject(String key) {
JSONObject possibleObject = vcapServices.optJSONObject(key);
if ( null != possibleObject ) {
possibleObject.keys().forEachRemaining(
new EntryConsumer(entries, possibleObject));
return true;
}
return false;
}
private void addNewEntry(String host) {
CheckedEntry entry;
log.info("Entry To Add == " + host);
entry = new CheckedEntry(host);
entries.add(entry);
}
}
|
package yokohama.unit.translator;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.Arrays;
import javax.tools.JavaCompiler;
import javax.tools.JavaCompiler.CompilationTask;
import javax.tools.JavaFileObject;
import javax.tools.JavaFileObject.Kind;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;
import lombok.SneakyThrows;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.BaseErrorListener;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.Lexer;
import org.antlr.v4.runtime.RecognitionException;
import org.antlr.v4.runtime.Recognizer;
import yokohama.unit.ast.Group;
import yokohama.unit.ast_junit.CompilationUnit;
import yokohama.unit.ast_junit.OgnlExpressionStrategy;
import yokohama.unit.grammar.YokohamaUnitLexer;
import yokohama.unit.grammar.YokohamaUnitParser;
import yokohama.unit.grammar.YokohamaUnitParser.GroupContext;
public class TranslatorUtils {
public static class TranslationException extends RuntimeException {
}
private static class ErrorListener extends BaseErrorListener {
public int numErrors = 0;
@Override
public void syntaxError(
Recognizer<?, ?> recognizer,
Object offendingSymbol,
int line,
int charPositionInLine,
String msg,
RecognitionException e) {
numErrors++;
}
}
public static Group parseDocy(final String input) {
return parseDocy(input, YokohamaUnitLexer.DEFAULT_MODE);
}
@SneakyThrows(IOException.class)
static Group parseDocy(final String input, final int mode) {
ErrorListener errorListener = new ErrorListener();
InputStream bais = new ByteArrayInputStream(input.getBytes());
CharStream stream = new ANTLRInputStream(bais);
Lexer lex = new YokohamaUnitLexer(stream);
lex.mode(mode);
lex.addErrorListener(errorListener);
CommonTokenStream tokens = new CommonTokenStream(lex);
YokohamaUnitParser parser = new YokohamaUnitParser(tokens);
parser.addErrorListener(errorListener);
GroupContext ctx = parser.group();
if (errorListener.numErrors > 0) {
throw new TranslationException();
}
return new ParseTreeToAstVisitor().visitGroup(ctx);
}
public static String docyToJava(
final String docy,
final String className,
final String packageName) {
// Source to AST
Group ast = parseDocy(docy);
// AST to JUnit AST
CompilationUnit junit =
new AstToJUnitAst().translate(className, ast, packageName);
// JUnit AST to string
return junit.getText(new OgnlExpressionStrategy());
}
public static boolean compileDocy(
final String docy,
final String className,
final String packageName,
final String... options) {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
JavaFileObject source = new SimpleJavaFileObject(
URI.create("string:
+ packageName.replace('.','/') + "/" + className
+ Kind.SOURCE.extension),
Kind.SOURCE
) {
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return docyToJava(docy, className, packageName);
}
};
CompilationTask task = compiler.getTask(
null, /* Writer out */
null, /* JavaFileManager fileManager */
null, /* DiagnosticListener<? super JavaFileObject> diagnosticListener */
Arrays.asList(options),
null, /* Iterable<String> classes */
Arrays.asList(source)
);
return task.call();
}
}
|
package imagej.ij1bridge;
import mpicbg.imglib.container.array.ArrayContainerFactory;
import mpicbg.imglib.container.basictypecontainer.PlanarAccess;
import mpicbg.imglib.container.basictypecontainer.array.ArrayDataAccess;
import mpicbg.imglib.image.Image;
import mpicbg.imglib.type.numeric.RealType;
import imagej.MetaData;
import imagej.UserType;
import imagej.dataset.Dataset;
import imagej.dataset.PlanarDatasetFactory;
import imagej.dataset.RecursiveDataset;
import imagej.imglib.TypeManager;
import imagej.imglib.process.ImageUtils;
import imagej.process.Index;
public class ImgLibDataset<T extends RealType<T>> implements Dataset, RecursiveDataset
{
|
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.AbstractMap.SimpleEntry;
public class HENprocess {
private static boolean debug = false;
private static final byte[] URL_PLACEHOLDER = getArrayOfByte((byte) 'x',256);
private static byte[] getArrayOfByte(byte b,int length) {
byte[] arr = new byte[length];
for (int i=0;i<length; i++) {
arr[i] = b;
}
return arr;
}
public HENprocess() {
super();
}
public static void main(String[] argv)
{
if (argv.length < 3) {
logErr("Usage for write_pkg_url: java HENprocess write_pkg_url filename url");
logErr("Usage for preprocess: java HENprocess preprocess urop.bin output-payload.js");
System.exit(-2);
}
debug = debug || (argv.length > 3);
final String operation = argv[0];
try {
if (operation.equalsIgnoreCase("write_pkg_url")) {
final String srcFile = argv[1];
final String url = argv[2];
writePkgUrl(srcFile, url);
} else if (operation.equalsIgnoreCase("preprocess")) {
final String uropFile = argv[1];
final String outputFile = argv[2];
preprocess(uropFile, outputFile);
} else {
throw new Exception("Unsupported operation: " + operation);
}
} catch (Exception e) {
logErr(e);
System.exit(-2);
}
}
private static void preprocess(String uropFile, String filename) throws Exception {
byte[] urop = read(uropFile);
while (urop.length % 4 != 0) {
final int N = urop.length;
urop = Arrays.copyOf(urop, N + 1);
urop[N] = (byte) 0;
}
int header_size = 0x40;
int dsize = u32(urop, 0x10);
int csize = u32(urop, 0x20);
int reloc_size = u32(urop, 0x30);
int symtab_size = u32(urop, 0x38);
if (csize % 4 != 0) {
final String err = "csize % 4 != 0???";
logErr(err);
throw new Exception(err);
}
log(header_size);
log(dsize);
log(csize);
log(reloc_size);
log(symtab_size);
int reloc_offset = header_size + dsize + csize;
int symtab = reloc_offset + reloc_size;
int strtab = symtab + symtab_size;
int symtab_n = getFloor(symtab_size, 8);
log(reloc_offset);
log(symtab);
log(strtab);
log(symtab_n);
Map<Integer,String> reloc_map = new HashMap<Integer,String>();
for (int x=0; x < symtab_n; x++) {
int sym_id = u32(urop, symtab + 8 * x);
int str_offset = u32(urop, symtab + 8 * x + 4);
int begin = str_offset;
int end = str_offset;
while (urop[end] != 0) {
end += 1;
}
String name = new String(Arrays.copyOfRange(urop, begin, end),"ascii");
reloc_map.put(sym_id,name);
}
// mapping between roptool (symbol_name, reloc_type) and exploit hardcoded types
// note that in exploit type=0 means no relocation
Map<SimpleEntry<String, Integer>,Integer> reloc_type_map = new HashMap<SimpleEntry<String, Integer>,Integer>();
reloc_type_map.put(new SimpleEntry<String, Integer>("rop.data",0),1); // dest += rop_data_base
reloc_type_map.put(new SimpleEntry<String, Integer>("SceWebKit",0),2); // dest += SceWebKit_base
reloc_type_map.put(new SimpleEntry<String, Integer>("SceLibKernel",0),3); // dest += SceLibKernel_base
reloc_type_map.put(new SimpleEntry<String, Integer>("SceLibc",0),4); // dest += SceLibc_base
reloc_type_map.put(new SimpleEntry<String, Integer>("SceLibHttp",0),5); // dest += SceLibHttp_base
reloc_type_map.put(new SimpleEntry<String, Integer>("SceNet",0),6); // dest += SceNet_base
reloc_type_map.put(new SimpleEntry<String, Integer>("SceAppMgr",0),7); // dest += SceAppMgr_base
// we don't need symtab/strtab/relocs
int want_len = 0x40 + dsize + csize;
byte[] relocs = getArrayOfByte((byte)0, getFloor(want_len, 4));
int reloc_n = getFloor(reloc_size, 8);
for (int x=0; x < reloc_n; x++) {
int reloc_type = u16(urop, reloc_offset + 8 * x);
int sym_id = u16(urop, reloc_offset + 8 * x + 2);
int offset = u32(urop, reloc_offset + 8 * x + 4);
String err = null;
//log("type " + reloc_type + " sym " + reloc_map.get(sym_id) + " offset " + offset);
if (offset % 4 != 0) {
err = "offset % 4 != 0???";
}
int relocsIndex = getFloor(offset, 4);
if (relocs[relocsIndex] != 0) {
err = "symbol relocated twice, not supported";
}
Integer wk_reloc_type = reloc_type_map.get(new SimpleEntry<String, Integer>(reloc_map.get(sym_id),reloc_type));
if (wk_reloc_type == null) {
err = "unsupported relocation type";
}
if (err != null) {
logErr("type " + reloc_type + " sym " + reloc_map.get(sym_id) + " offset " + offset);
throw new Exception(err);
}
relocs[relocsIndex] = wk_reloc_type.byteValue();
}
long[] urop_js = new long[want_len/4];
for (int x=0, y=0; x < want_len; x = x+4, y++) {
long val = (long) u32(urop, x);
if (val < 0) {
val = -1*((long) (Integer.MAX_VALUE+1)*2-val);
}
urop_js[y] = val;
}
OutputStream output = null;
try {
output = new BufferedOutputStream(new FileOutputStream(filename));
if (filename.endsWith(".js")) {
output.write('\n');
output.write("payload = [".getBytes());
for (int x=0; x < urop_js.length; x++) {
output.write(Long.toString(urop_js[x]).getBytes());
if (x!= urop_js.length-1) {
output.write(',');
}
}
output.write("];\n".getBytes());
output.write("relocs = [".getBytes());
for (int x=0; x < relocs.length; x++) {
output.write(Long.toString(relocs[x]).getBytes());
if (x!= relocs.length-1) {
output.write(',');
}
}
output.write("];\n".getBytes());
} else {
long pos = 0;
byte[] data = ByteBuffer.allocate(4)
.putInt(getFloor(want_len, 4))
.order(ByteOrder.LITTLE_ENDIAN)
.array();
for(int j = data.length; j > 0; j
output.write(data[j-1]);
}
pos = pos + 4;
for (int x=0; x < urop_js.length; x++) {
data = ByteBuffer.allocate(4)
.putInt((int)urop_js[x])
.order(ByteOrder.LITTLE_ENDIAN)
.array();
for(int j = data.length; j > 0; j
output.write(data[j-1]);
}
pos = pos + 4;
}
for (int x=0; x < relocs.length; x++) {
data = ByteBuffer.allocate(1)
.put(relocs[x])
.array();
output.write(data);
pos = pos + 1;
}
while (pos % 4 != 0 ) {
output.write('\0');
pos = pos +1;
}
}
}
finally {
output.close();
}
}
private static int getFloor(double value, int divider) {
return (int) Math.floor( value / divider );
}
private static int u32(byte[] data,int offset) {
byte[] fourBytes = Arrays.copyOfRange(data,offset,offset+4);
final int anInt = (ByteBuffer.wrap(fourBytes)
.order(ByteOrder.LITTLE_ENDIAN).getInt());
return (int) anInt;
}
private static int u16(byte[] data, int offset) {
byte[] fourBytes = Arrays.copyOfRange(data,offset,offset+2);
final int anInt = (ByteBuffer.wrap(fourBytes)
.order(ByteOrder.LITTLE_ENDIAN).getShort());
return (int) anInt;
}
private static void writePkgUrl(String srcFile, String url) {
if (url.length() >= 255) {
log("url must be at most 255 characters!");
System.exit(-2);
}
byte[] contents = read(srcFile) ;
Integer pos = bytesIndexOf(contents,URL_PLACEHOLDER,0);
if (pos < 0) {
log("URL placeholder not found!");
System.exit(-2);
}
log("Writing binary file...");
try {
OutputStream output = null;
try {
output = new BufferedOutputStream(new FileOutputStream(srcFile));
output.write(Arrays.copyOfRange(contents,0,pos));
output.write(url.getBytes());
byte[] chars = new byte[256 - url.length()];
Arrays.fill(chars, (byte) 0);
output.write(chars);
output.write(Arrays.copyOfRange(contents,pos+256,contents.length));
}
finally {
output.close();
}
}
catch(FileNotFoundException ex){
log("File not found.");
}
catch(IOException ex){
log(ex);
}
}
private static Integer bytesIndexOf(byte[] Source, byte[] Search, int fromIndex) {
boolean Find = false;
int i;
for (i = fromIndex;i<Source.length-Search.length;i++){
if(Source[i]==Search[0]){
Find = true;
for (int j = 0;j<Search.length;j++){
if (Source[i+j]!=Search[j]){
Find = false;
}
}
}
if(Find){
break;
}
}
if(!Find){
return new Integer(-1);
}
return new Integer(i);
}
/**
Read the given binary file, and return its contents as a byte array.
*/
static byte[] read(String aInputFileName){
File file = new File(aInputFileName);
byte[] result = null;
try {
InputStream input = new BufferedInputStream(new FileInputStream(file));
result = readAndClose(input);
}
catch (FileNotFoundException ex){
log(ex);
}
return result;
}
/**
Read an input stream, and return it as a byte array.
*/
static byte[] readAndClose(InputStream aInput){
byte[] bucket = new byte[32*1024];
ByteArrayOutputStream result = null;
try {
try {
result = new ByteArrayOutputStream(bucket.length);
int bytesRead = 0;
while(bytesRead != -1){
bytesRead = aInput.read(bucket);
if(bytesRead > 0){
result.write(bucket, 0, bytesRead);
}
}
}
finally {
aInput.close();
}
}
catch (IOException ex){
log(ex);
}
return result.toByteArray();
}
private static void logErr(Object aThing){
log(aThing,true);
}
private static void log(Object aThing){
log(aThing,false);
}
private static void log(Object aThing, boolean force){
if (debug || force)
System.out.println(String.valueOf(aThing));
}
}
|
package net.mgsx.rainstick.systems;
import org.puredata.core.PdListener;
import com.badlogic.ashley.core.Engine;
import com.badlogic.ashley.core.Entity;
import com.badlogic.ashley.core.Family;
import com.badlogic.ashley.systems.IteratingSystem;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.ai.GdxAI;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.math.MathUtils;
import net.mgsx.game.core.GamePipeline;
import net.mgsx.game.core.GameScreen;
import net.mgsx.game.plugins.box2d.components.Box2DBodyModel;
import net.mgsx.pd.Pd;
import net.mgsx.pd.utils.PdAdapter;
import net.mgsx.rainstick.components.Ball;
public class BallOutlineRender extends IteratingSystem {
private ShapeRenderer batch;
private GameScreen game;
private float feedback;
private PdListener feedbackListener;
public BallOutlineRender(GameScreen game) {
super(Family.all(Ball.class,Box2DBodyModel.class).get(), GamePipeline.RENDER );
this.game = game;
batch = new ShapeRenderer();
feedbackListener = new PdAdapter(){
@Override
public void receiveFloat(String source, float x) {
feedback = x;
}
};
}
@Override
public void addedToEngine(Engine engine) {
super.addedToEngine(engine);
Pd.audio.addListener("feedback", feedbackListener);
}
@Override
public void removedFromEngine(Engine engine) {
Pd.audio.removeListener("feedback", feedbackListener);
super.removedFromEngine(engine);
}
@Override
public void update(float deltaTime) {
// Gdx.gl.glDepthFunc(GL20.GL_GREATER);
batch.setProjectionMatrix(game.camera.combined);
batch.begin(ShapeType.Filled);
Gdx.gl.glEnable(GL20.GL_BLEND);
Gdx.gl.glEnable(GL20.GL_DEPTH_TEST);
Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA,GL20.GL_ONE);
Gdx.gl.glDepthFunc(GL20.GL_LESS );
Gdx.gl.glDepthMask(false);
//Gdx.gl.glClearDepthf(0);
//Gdx.gl.glClear(GL20.GL_DEPTH_BUFFER_BIT);
//Gdx.gl.glColorMask(false, false, false, false); // XXX debug here
super.update(deltaTime);
batch.end();
Gdx.gl.glDisable(GL20.GL_BLEND);
//Gdx.gl.glClearDepthf(1); // restore to default
//Gdx.gl.glColorMask(true, true, true, true);
}
@Override
protected void processEntity(Entity entity, float deltaTime) {
Box2DBodyModel physics = Box2DBodyModel.components.get(entity);
float x = physics.body.getPosition().x;
float y = physics.body.getPosition().y;
Ball ball = Ball.components.get(entity);
float min = getEngine().getSystem(ResonatorPhysicSystem.class).velMin;
float max = getEngine().getSystem(ResonatorPhysicSystem.class).velMax;
float speed =MathUtils.clamp(( physics.body.getLinearVelocity().len() - min) / (max - min), 0, 1) ;
float speed2 = .5f + .5f * (float)Math.sin(GdxAI.getTimepiece().getTime() * 0.3f * speed);
batch.setColor(1f,1f,1f,/*0.05f+ 0.051f*feedback+speed * .05f*/ 10f/255f);
batch.circle(x, y, ball .radius*(0.5f + feedback*0.5f) +(1-speed2)* .025f , 16);
}
}
|
package intentbuilder;
import android.app.Activity;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import java.io.Serializable;
import java.util.ArrayList;
import static intentbuilder.PreConditions.validateContext;
import static intentbuilder.PreConditions.validateNotBlank;
import static intentbuilder.PreConditions.validateNotEmpty;
import static intentbuilder.PreConditions.validateNotNull;
import static intentbuilder.PreConditions.validateNotZero;
public class IntentBuilder {
private Intent mIntent;
private Context mContext;
// Constructors
public IntentBuilder() {
mIntent = new Intent();
}
public IntentBuilder(Intent intent) {
mIntent = intent;
}
public IntentBuilder(String action) {
mIntent = new Intent(action);
}
public IntentBuilder(String action, Uri uri) {
mIntent = new Intent(action, uri);
}
public IntentBuilder(Context packageContext, Class<?> cls) {
mIntent = new Intent(packageContext, cls);
}
public IntentBuilder(String action, Uri uri, Context packageContext, Class<?> cls) {
mIntent = new Intent(action, uri, packageContext, cls);
}
// Builder methods
public IntentBuilder context(Context context) {
mContext = context;
return this;
}
public IntentBuilder action(String action) {
validateNotBlank(action, "Action");
mIntent.setAction(action);
return this;
}
public IntentBuilder service(Class<? extends Service> service) {
return setClass(service);
}
public IntentBuilder activity(Class<? extends Activity> activity) {
return setClass(activity);
}
public IntentBuilder receiver(Class<? extends BroadcastReceiver> receiver) {
return setClass(receiver);
}
public IntentBuilder component(ComponentName component) {
validateNotNull(component, "ComponentName");
mIntent.setComponent(component);
return this;
}
public IntentBuilder className(Context packageCtx, String className) {
validateNotNull(packageCtx, "Context");
validateNotBlank(className, "ClassName");
mIntent.setClassName(packageCtx, className);
return this;
}
public IntentBuilder className(String packageName, String className) {
validateNotBlank(packageName, "PackageName");
validateNotBlank(className, "ClassName");
mIntent.setClassName(packageName, className);
return this;
}
public IntentBuilder flags(int... flags) {
validateNotEmpty(flags, "Flags");
for (int flag : flags) {
mIntent.addFlags(flag);
}
return this;
}
public IntentBuilder extras(Bundle extras) {
validateNotNull(extras, "Extras bundle");
mIntent.putExtras(extras);
return this;
}
public IntentBuilder extras(Intent intent) {
validateNotNull(intent, "Intent");
mIntent.putExtras(intent);
return this;
}
// Primitive extras
public IntentBuilder extra(String name, boolean value) {
validateNotBlank(name, "Name");
mIntent.putExtra(name, value);
return this;
}
public IntentBuilder extra(String name, byte value) {
validateNotBlank(name, "Name");
mIntent.putExtra(name, value);
return this;
}
public IntentBuilder extra(String name, char value) {
validateNotBlank(name, "Name");
mIntent.putExtra(name, value);
return this;
}
public IntentBuilder extra(String name, double value) {
validateNotBlank(name, "Name");
mIntent.putExtra(name, value);
return this;
}
public IntentBuilder extra(String name, float value) {
validateNotBlank(name, "Name");
mIntent.putExtra(name, value);
return this;
}
public IntentBuilder extra(String name, int value) {
validateNotBlank(name, "Name");
mIntent.putExtra(name, value);
return this;
}
public IntentBuilder extra(String name, long value) {
validateNotBlank(name, "Name");
mIntent.putExtra(name, value);
return this;
}
public IntentBuilder extra(String name, short value) {
validateNotBlank(name, "Name");
mIntent.putExtra(name, value);
return this;
}
public IntentBuilder extra(String name, String value) {
validateNotBlank(name, "Name");
validateNotNull(value, "Value");
mIntent.putExtra(name, value);
return this;
}
// Primitive Arrays extras
public IntentBuilder extra(String name, byte[] value) {
validateNotBlank(name, "Name");
validateNotEmpty(value, "Value");
mIntent.putExtra(name, value);
return this;
}
public IntentBuilder extra(String name, boolean[] value) {
validateNotBlank(name, "Name");
validateNotEmpty(value, "Value");
mIntent.putExtra(name, value);
return this;
}
public IntentBuilder extra(String name, char[] value) {
validateNotBlank(name, "Name");
validateNotEmpty(value, "Value");
mIntent.putExtra(name, value);
return this;
}
public IntentBuilder extra(String name, double[] value) {
validateNotBlank(name, "Name");
validateNotEmpty(value, "Value");
mIntent.putExtra(name, value);
return this;
}
public IntentBuilder extra(String name, float[] value) {
validateNotBlank(name, "Name");
validateNotEmpty(value, "Value");
mIntent.putExtra(name, value);
return this;
}
public IntentBuilder extra(String name, int[] value) {
validateNotBlank(name, "Name");
validateNotEmpty(value, "Value");
mIntent.putExtra(name, value);
return this;
}
public IntentBuilder extra(String name, long[] value) {
validateNotBlank(name, "Name");
validateNotEmpty(value, "Value");
mIntent.putExtra(name, value);
return this;
}
public IntentBuilder extra(String name, short[] value) {
validateNotBlank(name, "Name");
validateNotEmpty(value, "Value");
mIntent.putExtra(name, value);
return this;
}
// Object extras
public IntentBuilder extra(String name, Bundle value) {
validateNotBlank(name, "Name");
validateNotNull(value, "Value");
mIntent.putExtra(name, value);
return this;
}
public IntentBuilder extra(String name, CharSequence value) {
validateNotBlank(name, "Name");
validateNotBlank(value, "Value");
mIntent.putExtra(name, value);
return this;
}
public IntentBuilder extra(String name, Parcelable value) {
validateNotBlank(name, "Name");
validateNotNull(value, "Value");
mIntent.putExtra(name, value);
return this;
}
public IntentBuilder extra(String name, Serializable value) {
validateNotBlank(name, "Name");
validateNotNull(value, "Value");
mIntent.putExtra(name, value);
return this;
}
// Object collections extras
public IntentBuilder extra(String name, CharSequence[] value) {
validateNotBlank(name, "Name");
validateNotEmpty(value, "Value");
mIntent.putExtra(name, value);
return this;
}
public IntentBuilder extra(String name, Parcelable[] value) {
validateNotBlank(name, "Name");
validateNotEmpty(value, "Value");
mIntent.putExtra(name, value);
return this;
}
public IntentBuilder extra(String name, String[] value) {
validateNotBlank(name, "Name");
validateNotEmpty(value, "Value");
mIntent.putExtra(name, value);
return this;
}
public IntentBuilder extraCharSequenceList(String name, ArrayList<CharSequence> value) {
validateNotBlank(name, "Name");
validateNotEmpty(value, "Value");
mIntent.putExtra(name, value);
return this;
}
public IntentBuilder extraIntegerList(String name, ArrayList<Integer> value) {
validateNotBlank(name, "Name");
validateNotEmpty(value, "Value");
mIntent.putExtra(name, value);
return this;
}
public IntentBuilder extraParcelableList(String name, ArrayList<? extends Parcelable> value) {
validateNotBlank(name, "Name");
validateNotEmpty(value, "Value");
mIntent.putExtra(name, value);
return this;
}
public IntentBuilder extraStringList(String name, ArrayList<String> value) {
validateNotBlank(name, "Name");
validateNotEmpty(value, "Value");
mIntent.putExtra(name, value);
return this;
}
// Return the intent
public Intent build() {
return mIntent;
}
// Private methods
private IntentBuilder setClass(Class<?> cls) {
validateContext(mContext);
validateNotNull(cls, "Class<?>");
mIntent.setClass(mContext, cls);
return this;
}
}
|
package jade.domain.JADEAgentManagement;
import jade.util.leap.List;
import jade.util.leap.LinkedList;
import jade.util.leap.Map;
import jade.util.leap.HashMap;
import jade.core.AID;
import jade.core.ContainerID;
import jade.content.onto.*;
import jade.content.schema.*;
import jade.domain.FIPAAgentManagement.*;
/**
This class represents the ontology
<code>jade-agent-management</code>, containing all JADE extensions
related to agent management. There is only a single instance of
this class.
<p>
The package contains one class for each element in the ontology.
<p>
@author Giovanni Caire - TILAB
*/
public class JADEManagementOntology extends Ontology {
/**
A symbolic constant, containing the name of this ontology.
*/
public static final String NAME = "JADE-Agent-Management";
public static final String AGENTIDENTIFIER = "agent-identifier";
// Concepts
public static final String CONTAINERID = "container-ID";
public static final String CONTAINERID_NAME = "name";
public static final String CONTAINERID_ADDRESS = "address";
// Actions supported by the ams
public static final String KILLCONTAINER = "kill-container";
public static final String KILLCONTAINER_CONTAINER = "container";
public static final String KILLCONTAINER_PASSWORD = "password";
public static final String CREATEAGENT = "create-agent";
public static final String CREATEAGENT_AGENT_NAME = "agent-name";
public static final String CREATEAGENT_CLASS_NAME = "class-name";
public static final String CREATEAGENT_ARGUMENTS = "arguments";
public static final String CREATEAGENT_CONTAINER = "container";
public static final String CREATEAGENT_DELEGATION = "delegation";
public static final String CREATEAGENT_PASSWORD = "password";
public static final String KILLAGENT = "kill-agent";
public static final String KILLAGENT_AGENT = "agent";
public static final String KILLAGENT_PASSWORD = "password";
public static final String INSTALLMTP = "install-mtp";
public static final String INSTALLMTP_ADDRESS = "address";
public static final String INSTALLMTP_CONTAINER = "container";
public static final String INSTALLMTP_CLASS_NAME = "class-name";
public static final String UNINSTALLMTP = "uninstall-mtp";
public static final String UNINSTALLMTP_ADDRESS = "address";
public static final String UNINSTALLMTP_CONTAINER = "container";
public static final String SNIFFON = "sniff-on";
public static final String SNIFFON_SNIFFER = "sniffer";
public static final String SNIFFON_SNIFFED_AGENTS = "sniffed-agents";
public static final String SNIFFON_PASSWORD = "password";
public static final String SNIFFOFF = "sniff-off";
public static final String SNIFFOFF_SNIFFER = "sniffer";
public static final String SNIFFOFF_SNIFFED_AGENTS = "sniffed-agents";
public static final String SNIFFOFF_PASSWORD = "password";
public static final String DEBUGON = "debug-on";
public static final String DEBUGON_DEBUGGER = "debugger";
public static final String DEBUGON_DEBUGGED_AGENTS = "debugged-agents";
public static final String DEBUGON_PASSWORD = "password";
public static final String DEBUGOFF = "debug-off";
public static final String DEBUGOFF_DEBUGGER = "debugger";
public static final String DEBUGOFF_DEBUGGED_AGENTS = "debugged-agents";
public static final String DEBUGOFF_PASSWORD = "password";
// actions supported by the DF
public static final String SHOWGUI = "showgui";
// Exception Predicates
public static final String NOTREGISTERED = jade.domain.FIPAAgentManagement.FIPAAgentManagementOntology.NOTREGISTERED;
public static final String INTERNALERROR = jade.domain.FIPAAgentManagement.FIPAAgentManagementOntology.INTERNALERROR;
public static final String INTERNALERROR_MESSAGE = "_0";
public static final String UNSUPPORTEDVALUE = jade.domain.FIPAAgentManagement.FIPAAgentManagementOntology.UNSUPPORTEDVALUE;
public static final String UNSUPPORTEDVALUE_VALUE = "_0";
public static final String UNRECOGNISEDVALUE = jade.domain.FIPAAgentManagement.FIPAAgentManagementOntology.UNRECOGNISEDVALUE;
public static final String UNRECOGNISEDVALUE_VALUE = "_0";
public static final String UNSUPPORTEDFUNCTION = jade.domain.FIPAAgentManagement.FIPAAgentManagementOntology.UNSUPPORTEDFUNCTION;
public static final String UNSUPPORTEDFUNCTION_FUNCTION = "_0";
public static final String MISSINGPARAMETER = jade.domain.FIPAAgentManagement.FIPAAgentManagementOntology.MISSINGPARAMETER;
public static final String MISSINGPARAMETER_OBJECT_NAME = "_0";
public static final String MISSINGPARAMETER_PARAMETER_NAME = "_1";
public static final String UNEXPECTEDPARAMETER = jade.domain.FIPAAgentManagement.FIPAAgentManagementOntology.UNEXPECTEDPARAMETER;
public static final String UNEXPECTEDPARAMETER_OBJECT_NAME = "_0";
public static final String UNEXPECTEDPARAMETER_PARAMETER_NAME = "_1";
public static final String UNRECOGNISEDPARAMETERVALUE = jade.domain.FIPAAgentManagement.FIPAAgentManagementOntology.UNRECOGNISEDPARAMETERVALUE;
public static final String UNRECOGNISEDPARAMETERVALUE_OBJECT_NAME = "_0";
public static final String UNRECOGNISEDPARAMETERVALUE_PARAMETER_NAME = "_1";
// The singleton instance of this ontology
private static Ontology theInstance = new JADEManagementOntology();
/**
This method grants access to the unique instance of the
ontology.
@return An <code>Ontology</code> object, containing the concepts
of the ontology.
*/
public static Ontology getInstance() {
return theInstance;
}
/**
* Constructor
*/
private JADEManagementOntology() {
//__CLDC_UNSUPPORTED__BEGIN
super(NAME, BasicOntology.getInstance(), new BCReflectiveIntrospector());
//__CLDC_UNSUPPORTED__END
/*__J2ME_COMPATIBILITY__BEGIN
super(NAME, BasicOntology.getInstance(), null);
__J2ME_COMPATIBILITY__END*/
try {
//__CLDC_UNSUPPORTED__BEGIN
// Concepts definitions
add(new ConceptSchema(CONTAINERID), ContainerID.class);
// AgentActions definitions
add(new AgentActionSchema(KILLCONTAINER), KillContainer.class);
add(new AgentActionSchema(CREATEAGENT), CreateAgent.class);
add(new AgentActionSchema(KILLAGENT), KillAgent.class);
add(new AgentActionSchema(INSTALLMTP), InstallMTP.class);
add(new AgentActionSchema(UNINSTALLMTP), UninstallMTP.class);
add(new AgentActionSchema(SNIFFON), SniffOn.class);
add(new AgentActionSchema(SNIFFOFF), SniffOff.class);
add(new AgentActionSchema(DEBUGON), DebugOn.class);
add(new AgentActionSchema(DEBUGOFF), DebugOff.class);
add(new AgentActionSchema(SHOWGUI), ShowGui.class);
// Predicates definitions
add(new PredicateSchema(UNSUPPORTEDVALUE), UnsupportedValue.class);
add(new PredicateSchema(UNRECOGNISEDVALUE), UnrecognisedValue.class);
add(new PredicateSchema(UNSUPPORTEDFUNCTION), UnsupportedFunction.class);
add(new PredicateSchema(MISSINGPARAMETER), MissingParameter.class);
add(new PredicateSchema(UNEXPECTEDPARAMETER), UnexpectedParameter.class);
add(new PredicateSchema(UNRECOGNISEDPARAMETERVALUE), UnrecognisedParameterValue.class);
add(new PredicateSchema(NOTREGISTERED), NotRegistered.class);
add(new PredicateSchema(INTERNALERROR), jade.domain.FIPAAgentManagement.InternalError.class);
//__CLDC_UNSUPPORTED__END
/*__J2ME_COMPATIBILITY__BEGIN
// Concepts definitions
add(new ConceptSchema(CONTAINERID));
// AgentActions definitions
add(new AgentActionSchema(KILLCONTAINER));
add(new AgentActionSchema(CREATEAGENT));
add(new AgentActionSchema(KILLAGENT));
add(new AgentActionSchema(INSTALLMTP));
add(new AgentActionSchema(UNINSTALLMTP));
add(new AgentActionSchema(SNIFFON));
add(new AgentActionSchema(SNIFFOFF));
add(new AgentActionSchema(DEBUGON));
add(new AgentActionSchema(DEBUGOFF));
add(new AgentActionSchema(SHOWGUI));
// Predicates definitions
add(new PredicateSchema(UNSUPPORTEDVALUE));
add(new PredicateSchema(UNRECOGNISEDVALUE));
add(new PredicateSchema(UNSUPPORTEDFUNCTION));
add(new PredicateSchema(MISSINGPARAMETER));
add(new PredicateSchema(UNEXPECTEDPARAMETER));
add(new PredicateSchema(UNRECOGNISEDPARAMETERVALUE));
add(new PredicateSchema(NOTREGISTERED));
add(new PredicateSchema(INTERNALERROR));
__J2ME_COMPATIBILITY__END*/
// Slots definitions
ConceptSchema cs = (ConceptSchema) getSchema(CONTAINERID);
cs.add(CONTAINERID_NAME, (PrimitiveSchema) getSchema(BasicOntology.STRING));
cs.add(CONTAINERID_ADDRESS, (PrimitiveSchema) getSchema(BasicOntology.STRING), ObjectSchema.OPTIONAL);
AgentActionSchema as = (AgentActionSchema) getSchema(KILLCONTAINER);
as.add(KILLCONTAINER_CONTAINER, (ConceptSchema) getSchema(CONTAINERID));
as.add(KILLCONTAINER_PASSWORD, (PrimitiveSchema) getSchema(BasicOntology.STRING), ObjectSchema.OPTIONAL);
as = (AgentActionSchema) getSchema(CREATEAGENT);
as.add(CREATEAGENT_AGENT_NAME, (PrimitiveSchema) getSchema(BasicOntology.STRING));
as.add(CREATEAGENT_CLASS_NAME, (PrimitiveSchema) getSchema(BasicOntology.STRING));
as.add(CREATEAGENT_ARGUMENTS, (TermSchema) TermSchema.getBaseSchema(), 0, ObjectSchema.UNLIMITED);
as.add(CREATEAGENT_CONTAINER, (ConceptSchema) getSchema(CONTAINERID));
as.add(CREATEAGENT_DELEGATION, (PrimitiveSchema) getSchema(BasicOntology.STRING), ObjectSchema.OPTIONAL);
as.add(CREATEAGENT_PASSWORD, (PrimitiveSchema) getSchema(BasicOntology.STRING), ObjectSchema.OPTIONAL);
as = (AgentActionSchema) getSchema(KILLAGENT);
as.add(KILLAGENT_AGENT, (ConceptSchema) getSchema(BasicOntology.AID));
as.add(KILLAGENT_PASSWORD, (PrimitiveSchema) getSchema(BasicOntology.STRING), ObjectSchema.OPTIONAL);
as = (AgentActionSchema) getSchema(INSTALLMTP);
as.add(INSTALLMTP_ADDRESS, (PrimitiveSchema) getSchema(BasicOntology.STRING), ObjectSchema.OPTIONAL);
as.add(INSTALLMTP_CONTAINER, (ConceptSchema) getSchema(CONTAINERID));
as.add(INSTALLMTP_CLASS_NAME, (PrimitiveSchema) getSchema(BasicOntology.STRING));
as = (AgentActionSchema) getSchema(UNINSTALLMTP);
as.add(UNINSTALLMTP_ADDRESS, (PrimitiveSchema) getSchema(BasicOntology.STRING));
as.add(UNINSTALLMTP_CONTAINER, (ConceptSchema) getSchema(CONTAINERID));
as = (AgentActionSchema) getSchema(SNIFFON);
as.add(SNIFFON_SNIFFER, (ConceptSchema) getSchema(BasicOntology.AID));
as.add(SNIFFON_SNIFFED_AGENTS, (ConceptSchema) getSchema(BasicOntology.AID), 1, ObjectSchema.UNLIMITED);
as.add(SNIFFON_PASSWORD, (PrimitiveSchema) getSchema(BasicOntology.STRING), ObjectSchema.OPTIONAL);
as = (AgentActionSchema) getSchema(SNIFFOFF);
as.add(SNIFFOFF_SNIFFER, (ConceptSchema) getSchema(BasicOntology.AID));
as.add(SNIFFOFF_SNIFFED_AGENTS, (ConceptSchema) getSchema(BasicOntology.AID), 1, ObjectSchema.UNLIMITED);
as.add(SNIFFOFF_PASSWORD, (PrimitiveSchema) getSchema(BasicOntology.STRING), ObjectSchema.OPTIONAL);
as = (AgentActionSchema) getSchema(DEBUGON);
as.add(DEBUGON_DEBUGGER, (ConceptSchema) getSchema(BasicOntology.AID));
as.add(DEBUGON_DEBUGGED_AGENTS, (ConceptSchema) getSchema(BasicOntology.AID), 1, ObjectSchema.UNLIMITED);
as.add(DEBUGON_PASSWORD, (PrimitiveSchema) getSchema(BasicOntology.STRING), ObjectSchema.OPTIONAL);
as = (AgentActionSchema) getSchema(DEBUGOFF);
as.add(DEBUGOFF_DEBUGGER, (ConceptSchema) getSchema(BasicOntology.AID));
as.add(DEBUGOFF_DEBUGGED_AGENTS, (ConceptSchema) getSchema(BasicOntology.AID), 1, ObjectSchema.UNLIMITED);
as.add(DEBUGOFF_PASSWORD, (PrimitiveSchema) getSchema(BasicOntology.STRING), ObjectSchema.OPTIONAL);
PredicateSchema ps = (PredicateSchema) getSchema(UNSUPPORTEDVALUE);
ps.add(UNSUPPORTEDVALUE_VALUE, (PrimitiveSchema) getSchema(BasicOntology.STRING));
ps = (PredicateSchema) getSchema(UNRECOGNISEDVALUE);
ps.add(UNRECOGNISEDVALUE_VALUE, (PrimitiveSchema) getSchema(BasicOntology.STRING));
ps = (PredicateSchema) getSchema(UNSUPPORTEDFUNCTION);
ps.add(UNSUPPORTEDFUNCTION_FUNCTION, (PrimitiveSchema) getSchema(BasicOntology.STRING));
ps = (PredicateSchema) getSchema(MISSINGPARAMETER);
ps.add(MISSINGPARAMETER_OBJECT_NAME, (PrimitiveSchema) getSchema(BasicOntology.STRING));
ps.add(MISSINGPARAMETER_PARAMETER_NAME, (PrimitiveSchema) getSchema(BasicOntology.STRING));
ps = (PredicateSchema) getSchema(UNEXPECTEDPARAMETER);
ps.add(UNEXPECTEDPARAMETER_OBJECT_NAME, (PrimitiveSchema) getSchema(BasicOntology.STRING));
ps.add(UNEXPECTEDPARAMETER_PARAMETER_NAME, (PrimitiveSchema) getSchema(BasicOntology.STRING));
ps = (PredicateSchema) getSchema(UNRECOGNISEDPARAMETERVALUE);
ps.add(UNRECOGNISEDPARAMETERVALUE_OBJECT_NAME, (PrimitiveSchema) getSchema(BasicOntology.STRING));
ps.add(UNRECOGNISEDPARAMETERVALUE_PARAMETER_NAME, (PrimitiveSchema) getSchema(BasicOntology.STRING));
ps = (PredicateSchema) getSchema(INTERNALERROR);
ps.add(INTERNALERROR_MESSAGE, (PrimitiveSchema) getSchema(BasicOntology.STRING), ObjectSchema.OPTIONAL);
}
catch(OntologyException oe) {
oe.printStackTrace();
}
}
}
|
package org.intermine.web;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import org.intermine.objectstore.ObjectStore;
import org.intermine.web.bag.BagQueryConfig;
import org.intermine.web.bag.BagQueryResult;
import org.intermine.web.bag.BagQueryRunner;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.StringReader;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.upload.FormFile;
/**
* An action that makes a bag from text.
*
* @author Kim Rutherford
*/
public class BuildBagAction extends InterMineAction
{
/**
* Action for creating a bag of InterMineObjects or Strings from identifiers in text field.
*
* @param mapping The ActionMapping used to select this instance
* @param form The optional ActionForm bean for this request (if any)
* @param request The HTTP request we are processing
* @param response The HTTP response we are creating
* @return an ActionForward object defining where control goes next
* @exception Exception if the application business logic throws
* an exception
*/
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception {
HttpSession session = request.getSession();
BuildBagForm buildBagForm = (BuildBagForm) form;
ServletContext servletContext = session.getServletContext();
ObjectStore os = (ObjectStore) servletContext.getAttribute(Constants.OBJECTSTORE);
String newBagName = buildBagForm.getBagName();
String type = buildBagForm.getType();
if (StringUtils.isEmpty(type)) {
recordError(new ActionMessage("bagBuild.typeNotSet"), request);
return mapping.findForward("mymine");
}
Map classKeys = (Map) servletContext.getAttribute(Constants.CLASS_KEYS);
BagQueryConfig bagQueryConfig =
(BagQueryConfig) servletContext.getAttribute(Constants.BAG_QUERY_CONFIG);
BagQueryRunner bagRunner =
new BagQueryRunner(os, classKeys, bagQueryConfig, servletContext);
int maxBagSize = WebUtil.getIntSessionProperty(session, "max.bag.size", 100000);
Profile profile = (Profile) session.getAttribute(Constants.PROFILE);
if (profile == null || profile.getUsername() == null) {
int defaultMaxNotLoggedSize = 3;
maxBagSize = WebUtil.getIntSessionProperty(session, "max.bag.size.notloggedin",
defaultMaxNotLoggedSize);
}
BufferedReader reader = null;
if (request.getParameter("paste") != null) {
String trimmedText = buildBagForm.getText().trim();
if (trimmedText.length() == 0) {
recordError(new ActionMessage("bagBuild.noBagPaste"), request);
return mapping.findForward("mymine");
}
reader = new BufferedReader(new StringReader(trimmedText));
} else {
if (request.getParameter("file") != null) {
FormFile formFile = buildBagForm.getFormFile();
if (formFile == null || formFile.getFileName() == null
|| formFile.getFileName().length() == 0) {
recordError(new ActionMessage("bagBuild.noBagFile"), request);
return mapping.findForward("mymine");
}
reader = new BufferedReader(new InputStreamReader(formFile.getInputStream()));
} else {
throw new RuntimeException("unknown action type in BuildBagAction");
}
}
String thisLine;
List list = new ArrayList();
int elementCount = 0;
while ((thisLine = reader.readLine()) != null) {
StringTokenizer st = new StringTokenizer(thisLine, " \n\t,");
while (st.hasMoreTokens()) {
String token = st.nextToken();
list.add(token);
elementCount++;
if (elementCount > maxBagSize) {
ActionMessage actionMessage = null;
if (profile == null || profile.getUsername() == null) {
actionMessage = new ActionMessage("bag.bigNotLoggedIn",
new Integer(maxBagSize));
} else {
actionMessage = new ActionMessage("bag.tooBig", new Integer(maxBagSize));
}
recordError(actionMessage, request);
return mapping.findForward("mymine");
}
}
}
BagQueryResult bagQueryResult =
bagRunner.searchForBag(type, list, buildBagForm.getExtraFieldValue());
session.setAttribute("bagQueryResult", bagQueryResult);
request.setAttribute("bagName", newBagName);
request.setAttribute("bagType", type);
return mapping.findForward("bagUploadConfirm");
}
}
|
package jlibs.core.i18n;
import jlibs.core.io.IOUtil;
import jlibs.core.lang.ClassUtil;
import jlibs.core.net.URLUtil;
import jlibs.core.util.i18n.I18N;
import org.testng.Assert;
import org.testng.annotations.Test;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import static jlibs.core.i18n.Bundle1.BUNDLE1;
import static jlibs.core.i18n.Bundle2.BUNDLE2;
/**
* @author Santhosh Kumar T
*/
public class ResourceBundleTest{
private String compile(String... files){
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
ArrayList<String> args = new ArrayList<String>();
args.add("-d");
args.add(ClassUtil.getClassPath(getClass()));
args.add("-s");
args.add(ClassUtil.getClassPath(getClass()));
for(String file: files){
URL url = getClass().getResource(file);
args.add(URLUtil.toSystemID(url));
}
ByteArrayOutputStream err = new ByteArrayOutputStream();
if(compiler.run(null, null, err, args.toArray(new String[args.size()]))==0)
return null;
return err.toString();
}
private void assertErrors(String errors, String... searchFor){
if(searchFor.length==0)
Assert.assertNull(errors, "compilation failed with errors:\n"+errors);
else{
for(String error: searchFor){
error = error.replace('\\', '/');
if(errors.indexOf(error)==-1)
Assert.fail("[Expected Error] "+error+"\n[Actual Error] "+errors);
}
}
}
@Test(description="@ResourceBundle can't be applied on class")
public void classBundle(){
assertErrors(compile("/i18n/ClassBundle.java"),
"i18n/ClassBundle.java:12: jlibs.core.util.i18n.ResourceBundle annotation can be applied only for interface\n" +
"public abstract class ClassBundle{\n" +
" ^"
);
}
@Test(description="methods in interface must have @Message")
public void missingMessageAnnotation(){
assertErrors(compile("/i18n/MissingMessageAnnotationBundle.java"),
"i18n/MissingMessageAnnotationBundle.java:",
": jlibs.core.util.i18n.Message annotation is missing on this method\n" +
" public String lastSucussfullLogin(Date date);\n" +
" ^"
);
}
@Test(description="method with @Message must return String")
public void invalidMethodReturn(){
assertErrors(compile("/i18n/InvalidMethodReturnBundle.java"),
"i18n/InvalidMethodReturnBundle.java:14: method annotated with jlibs.core.util.i18n.Message must return java.lang.String\n" +
" public Date lastSucussfullLogin(Date date);\n" +
" ^"
);
}
@Test(description="invalid formats in message")
public void invalidMessageFormat(){
assertErrors(compile("/i18n/InvalidMessageFormatBundle.java"),
"Invalid Message Format: unknown format type at"
);
}
@Test(description="number of parameter in message and method should match")
public void argumentCountMismatch(){
assertErrors(compile("/i18n/ArgumentCountMismatchBundle.java"),
"no of args in message format doesn't match with the number of parameters this method accepts"
);
}
@Test(description="all method arguments must be used in message")
public void missingArgument(){
assertErrors(compile("/i18n/MissingArgumentBundle.java"),
"/i18n/MissingArgumentBundle.java:",
": {1} is missing in message\n" +
" @Message(\"SQL Execution completed in {0} seconds with {2} errors and {2} warnings\")\n" +
" ^"
);
}
@Test(description="two methods in a java file can't have same key")
public void duplicateKeyInSameFile(){
assertErrors(compile("/i18n/DuplicateKeyBundle.java"),
"key 'JLIBS015' is already used by \"public java.lang.String executionFinished(long, int, int)\" in i18n.DuplicateKeyBundle interface"
);
}
@Test(description="two methods in two interfaces can't have same key")
public void duplicateKeyAcrossFiles(){
assertErrors(compile("/i18n/DuplicateKey1Bundle.java", "/i18n/DuplicateKey2Bundle.java"),
"key 'JLIBS015' is already used by \"public java.lang.String executionFinished(long, int, int)\" in i18n.DuplicateKey1Bundle interface"
);
}
@Test(description="two methods in two interfaces can't have same signature")
public void methodSignatureClash(){
assertErrors(compile("/i18n/MethodSignatureClash1Bundle.java", "/i18n/MethodSignatureClash2Bundle.java"),
"i18n/MethodSignatureClash2Bundle.java:12: clashes with similar method in i18n.MethodSignatureClash1Bundle interface\n" +
" public String executing(String query);"
);
}
@Test(description="test generated interface implementation methods")
public void testImplementation(){
Assert.assertEquals(BUNDLE1.executing("myquery"), "executing myquery");
Assert.assertEquals(BUNDLE2.executed("myquery"), "executed myquery");
}
@Test(description="test whether custom key is used")
public void testCustomKey(){
Assert.assertEquals(BUNDLE1.executionTook(10), "execution took 10 seconds");
Assert.assertEquals(I18N.getValue(Bundle1.class, "timeTaken", 10), "execution took 10 seconds");
}
@Test(description="test that documentation is generated in properties file")
public void testDocumentation() throws IOException{
String props = IOUtil.pump(Bundle1.class.getResourceAsStream("Bundle.properties"), true).toString();
if(props.indexOf("# {0} query\nexecuted=executed {0}")==-1)
Assert.fail("documentation must be generated for method with no javadoc");
if(props.indexOf("# {0} time ==> time taken in seconds\ntimeTaken=execution took {0, number} seconds")==-1)
Assert.fail("documentation must be generated for method with javadoc");
if(props.indexOf("# {0} query\nexecuting=executing {0}")==-1)
Assert.fail("documentation must be generated for method with javadoc with no param description");
}
}
|
package fr.paris.lutece.portal.business.user;
import fr.paris.lutece.portal.business.rbac.AdminRole;
import fr.paris.lutece.portal.business.right.Right;
import fr.paris.lutece.portal.business.user.authentication.LuteceDefaultAdminUser;
import fr.paris.lutece.util.sql.DAOUtil;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* This class porvides Data Access methods for AdminUser objects
*/
public class AdminUserDAO implements IAdminUserDAO
{
// Constants
private static final String CONSTANT_AND_STATUS = " AND status = ?";
private static final String CONSTANT_AND_USER_LEVEL = " AND level_user = ?";
private static final String CONSTANT_ORDER_BY_LAST_NAME = " ORDER BY last_name ";
private static final String CONSTANT_PERCENT = "%";
private static final String SQL_QUERY_NEWPK = "SELECT max( id_user ) FROM core_admin_user ";
private static final String SQL_QUERY_INSERT = "INSERT INTO core_admin_user ( id_user , access_code, last_name , first_name, email, status, locale, level_user, accessibility_mode, password_max_valid_date, account_max_valid_date ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ) ";
private static final String SQL_QUERY_SELECTALL = "SELECT id_user , access_code, last_name , first_name, email, status, locale, level_user, accessibility_mode, reset_password, password_max_valid_date, account_max_valid_date, last_login, workgroup_key FROM core_admin_user ORDER BY last_name ";
private static final String SQL_QUERY_SELECT_USER_FROM_USER_ID = "SELECT id_user , access_code, last_name , first_name, email, status, password, locale, level_user, reset_password, accessibility_mode, password_max_valid_date, account_max_valid_date, workgroup_key FROM core_admin_user WHERE id_user = ? ";
private static final String SQL_QUERY_SELECT_USER_FROM_ACCESS_CODE = "SELECT id_user, access_code, last_name, first_name, email, status, locale, level_user, reset_password, accessibility_mode, password_max_valid_date, last_login FROM core_admin_user WHERE access_code = ? ";
private static final String SQL_QUERY_SELECT_USER_FROM_EMAIL = "SELECT access_code FROM core_admin_user WHERE email = ? ";
private static final String SQL_QUERY_SELECT_RIGHTS_FROM_USER_ID = " SELECT a.id_right , a.name, a.admin_url , a.description , a.plugin_name, a.id_feature_group, a.icon_url, a.level_right, a.documentation_url, a.id_order " +
" FROM core_admin_right a , core_user_right b " + " WHERE a.id_right = b.id_right " + " AND b.id_user = ? " +
" ORDER BY a.id_order ASC, a.id_right ASC ";
private static final String SQL_QUERY_UPDATE = "UPDATE core_admin_user SET access_code = ? , last_name = ? , first_name = ?, email = ?, status = ?, locale = ?, reset_password = ?, accessibility_mode = ?, password_max_valid_date = ? WHERE id_user = ? ";
private static final String SQL_QUERY_DELETE = "DELETE FROM core_admin_user WHERE id_user = ? ";
private static final String SQL_QUERY_INSERT_USER_RIGHT = "INSERT INTO core_user_right ( id_right, id_user ) VALUES ( ? , ? ) ";
private static final String SQL_QUERY_DELETE_ALL_USER_RIGHTS = "DELETE FROM core_user_right WHERE id_user = ? ";
private static final String SQL_QUERY_SELECT_ROLES_FROM_USER_ID = " SELECT a.role_key , a.role_description " +
" FROM core_admin_role a , core_user_role b WHERE a.role_key = b.role_key " +
" AND b.id_user = ? ORDER BY a.role_key ";
private static final String SQL_QUERY_INSERT_USER_ROLE = " INSERT INTO core_user_role ( role_key, id_user ) VALUES ( ? , ? ) ";
private static final String SQL_QUERY_DELETE_ALL_USER_ROLES = " DELETE FROM core_user_role WHERE id_user = ? ";
private static final String SQL_CHECK_ROLE_ATTRIBUTED = " SELECT id_user FROM core_user_role WHERE role_key = ?";
private static final String SQL_CHECK_ACCESS_CODE_IN_USE = " SELECT id_user FROM core_admin_user WHERE access_code = ?";
private static final String SQL_CHECK_EMAIL_IN_USE = " SELECT id_user FROM core_admin_user WHERE email = ?";
private static final String SQL_QUERY_INSERT_DEFAULT_USER = " INSERT INTO core_admin_user ( id_user, access_code, last_name, first_name, email, status, password, locale, level_user, accessibility_mode, reset_password, password_max_valid_date, account_max_valid_date, last_login, workgroup_key ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ) ";
private static final String SQL_QUERY_UPDATE_DEFAULT_USER = " UPDATE core_admin_user SET access_code = ?, last_name = ?, first_name = ?, email = ?, status = ?, password = ?, locale = ?, reset_password = ?, accessibility_mode = ?, password_max_valid_date = ?, workgroup_key = ? WHERE id_user = ? ";
private static final String SQL_QUERY_SELECT_USERS_ID_BY_ROLES = " SELECT a.id_user , a.access_code, a.last_name , a.first_name, a.email, a.status, a.locale, a.accessibility_mode, a.password_max_valid_date " +
" FROM core_admin_user a, core_user_role b WHERE a.id_user = b.id_user AND b.role_key = ? ";
private static final String SQL_QUERY_SELECT_USER_RIGHTS_OWN = " SELECT DISTINCT b.id_right FROM core_admin_right a , core_user_right b WHERE b.id_user = ? and a.id_right = b.id_right and a.level_right >= ?";
private static final String SQL_QUERY_SELECT_USER_RIGHTS_DELEGATED = " SELECT DISTINCT b.id_right FROM core_admin_right a , core_user_right b WHERE b.id_user = ? and a.id_right = b.id_right and a.level_right < ?";
private static final String SQL_QUERY_DELETE_USER_RIGHTS = " DELETE FROM core_user_right WHERE id_user = ? and id_right = ?";
private static final String SQL_QUERY_SELECT_USERS_BY_LEVEL = " SELECT a.id_user, a.access_code, a.last_name, a.first_name, a.email, a.status, a.locale, a.accessibility_mode " +
" FROM core_admin_user a WHERE a.level_user = ? ";
private static final String SQL_QUERY_UPDATE_USERS_ROLE = "UPDATE core_user_role SET role_key = ? WHERE role_key = ?";
private static final String SQL_QUERY_SELECT_USER_ROLE = " SELECT id_user FROM core_user_role WHERE id_user = ? AND role_key = ? ";
private static final String SQL_QUERY_DELETE_ROLE_FOR_USER = " DELETE FROM core_user_role WHERE id_user = ? AND role_key = ? ";
private static final String SQL_QUERY_SELECT_USER_FROM_SEARCH = " SELECT id_user, access_code, last_name, first_name, email, status, locale, level_user, accessibility_mode " +
" FROM core_admin_user WHERE access_code LIKE ? AND last_name LIKE ? AND email LIKE ? ";
private static final String SQL_QUERY_SELECT_USERS_BY_RIGHT = " SELECT u.id_user , u.access_code, u.last_name , u.first_name, u.email, u.status, u.locale, u.level_user, u.accessibility_mode " +
" FROM core_admin_user u INNER JOIN core_user_right r ON u.id_user = r.id_user WHERE r.id_right = ? ";
private static final String SQL_QUERY_SELECT_USER_RIGHT = " SELECT id_user FROM core_user_right WHERE id_user = ? AND id_right = ? ";
private static final String SQL_SELECT_USER_PASSWORD_HISTORY = "SELECT password FROM core_user_password_history WHERE id_user = ? ORDER BY date_password_change desc";
private static final String SQL_COUNT_USER_PASSWORD_HISTORY = "SELECT COUNT(*) FROM core_user_password_history WHERE id_user = ? AND date_password_change > ?";
private static final String SQL_INSERT_PASSWORD_HISTORY = "INSERT INTO core_user_password_history (id_user, password) VALUES ( ?, ? ) ";
private static final String SQL_DELETE_PASSWORD_HISTORY = "DELETE FROM core_user_password_history WHERE id_user = ?";
private static final String SQL_SELECT_ANONYMIZATION_STATUS_USER_FILED = "SELECT field_name, anonymize from core_admin_user_anonymize_field";
private static final String SQL_UPDATE_ANONYMIZATION_STATUS_USER_FILED = "UPDATE core_admin_user_anonymize_field SET anonymize = ? WHERE field_name = ? ";
private static final String SQL_QUERY_SELECT_EXPIRED_USER_ID = "SELECT id_user FROM core_admin_user WHERE status = ?";
private static final String SQL_QUERY_SELECT_EXPIRED_LIFE_TIME_USER_ID = "SELECT id_user FROM core_admin_user WHERE account_max_valid_date < ? and status < ? ";
private static final String SQL_QUERY_SELECT_USER_ID_FIRST_ALERT = "SELECT id_user FROM core_admin_user WHERE nb_alerts_sent = 0 and status < ? and account_max_valid_date < ? ";
private static final String SQL_QUERY_SELECT_USER_ID_OTHER_ALERT = "SELECT id_user FROM core_admin_user " +
"WHERE nb_alerts_sent > 0 and nb_alerts_sent <= ? and status < ? and (account_max_valid_date + nb_alerts_sent * ?) < ? ";
private static final String SQL_QUERY_SELECT_USER_ID_PASSWORD_EXPIRED = " SELECT id_user FROM core_admin_user WHERE password_max_valid_date < ? AND reset_password = 0 ";
private static final String SQL_QUERY_UPDATE_STATUS = " UPDATE core_admin_user SET status = ? WHERE id_user IN ( ";
private static final String SQL_QUERY_UPDATE_NB_ALERT = " UPDATE core_admin_user SET nb_alerts_sent = nb_alerts_sent + 1 WHERE id_user IN ( ";
private static final String SQL_QUERY_UPDATE_RESET_PASSWORD_LIST_ID = " UPDATE core_admin_user SET reset_password = 1 WHERE id_user IN ( ";
private static final String SQL_QUERY_UPDATE_REACTIVATE_ACCOUNT = " UPDATE core_admin_user SET nb_alerts_sent = 0, account_max_valid_date = ? WHERE id_user = ? ";
private static final String SQL_QUERY_UPDATE_DATE_LAST_LOGIN = " UPDATE core_admin_user SET last_login = ? WHERE id_user = ? ";
private static final String CONSTANT_CLOSE_PARENTHESIS = " ) ";
private static final String CONSTANT_COMMA = ", ";
/**
* {@inheritDoc}
*/
@Override
public AdminUser load( int nUserId )
{
AdminUser user = null;
DAOUtil daoUtil = new DAOUtil( SQL_QUERY_SELECT_USER_FROM_USER_ID );
daoUtil.setInt( 1, nUserId );
daoUtil.executeQuery( );
if ( daoUtil.next( ) )
{
user = new AdminUser( );
user.setUserId( daoUtil.getInt( 1 ) );
user.setAccessCode( daoUtil.getString( 2 ) );
user.setLastName( daoUtil.getString( 3 ) );
user.setFirstName( daoUtil.getString( 4 ) );
user.setEmail( daoUtil.getString( 5 ) );
user.setStatus( daoUtil.getInt( 6 ) );
user.setLocale( new Locale( daoUtil.getString( 8 ) ) );
user.setUserLevel( daoUtil.getInt( 9 ) );
user.setPasswordReset( daoUtil.getBoolean( 10 ) );
user.setAccessibilityMode( daoUtil.getBoolean( 11 ) );
user.setPasswordMaxValidDate( daoUtil.getTimestamp( 12 ) );
long accountTime = daoUtil.getLong( 13 );
if ( accountTime > 0 )
{
user.setAccountMaxValidDate( new Timestamp( accountTime ) );
}
}
daoUtil.free( );
return user;
}
/**
* {@inheritDoc}
*/
@Override
public AdminUser selectUserByAccessCode( String strUserAccessCode )
{
AdminUser user = null;
DAOUtil daoUtil = new DAOUtil( SQL_QUERY_SELECT_USER_FROM_ACCESS_CODE );
daoUtil.setString( 1, strUserAccessCode );
daoUtil.executeQuery( );
if ( daoUtil.next( ) )
{
user = new AdminUser( );
user.setUserId( daoUtil.getInt( 1 ) );
user.setAccessCode( daoUtil.getString( 2 ) );
user.setLastName( daoUtil.getString( 3 ) );
user.setFirstName( daoUtil.getString( 4 ) );
user.setEmail( daoUtil.getString( 5 ) );
user.setStatus( daoUtil.getInt( 6 ) );
user.setLocale( new Locale( daoUtil.getString( 7 ) ) );
user.setUserLevel( daoUtil.getInt( 8 ) );
user.setPasswordReset( daoUtil.getBoolean( 9 ) );
user.setAccessibilityMode( daoUtil.getBoolean( 10 ) );
user.setPasswordMaxValidDate( daoUtil.getTimestamp( 11 ) );
Timestamp dateLastLogin = daoUtil.getTimestamp( 12 );
if ( ( dateLastLogin != null ) && !dateLastLogin.equals( AdminUser.DEFAULT_DATE_LAST_LOGIN ) )
{
user.setDateLastLogin( dateLastLogin );
}
}
daoUtil.free( );
return user;
}
/**
* {@inheritDoc}
*/
@Override
public String selectUserByEmail( String strEmail )
{
DAOUtil daoUtil = new DAOUtil( SQL_QUERY_SELECT_USER_FROM_EMAIL );
daoUtil.setString( 1, strEmail );
daoUtil.executeQuery( );
String strAccessCode = null;
if ( daoUtil.next( ) )
{
strAccessCode = daoUtil.getString( 1 );
}
daoUtil.free( );
return strAccessCode;
}
/**
* {@inheritDoc}
*/
@Override
public Collection<AdminUser> selectUserList( )
{
Collection<AdminUser> userList = new ArrayList<AdminUser>( );
DAOUtil daoUtil = new DAOUtil( SQL_QUERY_SELECTALL );
daoUtil.executeQuery( );
while ( daoUtil.next( ) )
{
AdminUser user = new AdminUser( );
user.setUserId( daoUtil.getInt( 1 ) );
user.setAccessCode( daoUtil.getString( 2 ) );
user.setLastName( daoUtil.getString( 3 ) );
user.setFirstName( daoUtil.getString( 4 ) );
user.setEmail( daoUtil.getString( 5 ) );
user.setStatus( daoUtil.getInt( 6 ) );
user.setLocale( new Locale( daoUtil.getString( 7 ) ) );
user.setUserLevel( daoUtil.getInt( 8 ) );
user.setAccessibilityMode( daoUtil.getBoolean( 9 ) );
user.setPasswordReset( daoUtil.getBoolean( 10 ) );
user.setPasswordMaxValidDate( daoUtil.getTimestamp( 11 ) );
long accountTime = daoUtil.getLong( 12 );
if ( accountTime > 0 )
{
user.setAccountMaxValidDate( new Timestamp( accountTime ) );
}
Timestamp dateLastLogin = daoUtil.getTimestamp( 13 );
if ( ( dateLastLogin != null ) && !dateLastLogin.equals( AdminUser.DEFAULT_DATE_LAST_LOGIN ) )
{
user.setDateLastLogin( dateLastLogin );
}
user.setWorkgroupKey( daoUtil.getString( 14 ) );
userList.add( user );
}
daoUtil.free( );
return userList;
}
/**
* {@inheritDoc}
*/
@Override
public int newPrimaryKey( )
{
DAOUtil daoUtil = new DAOUtil( SQL_QUERY_NEWPK );
daoUtil.executeQuery( );
int nKey;
if ( !daoUtil.next( ) )
{
// if the table is empty
nKey = 1;
}
nKey = daoUtil.getInt( 1 ) + 1;
daoUtil.free( );
return nKey;
}
/**
* {@inheritDoc}
*/
@Override
public synchronized void insert( AdminUser user )
{
user.setUserId( newPrimaryKey( ) );
DAOUtil daoUtil = new DAOUtil( SQL_QUERY_INSERT );
daoUtil.setInt( 1, user.getUserId( ) );
daoUtil.setString( 2, user.getAccessCode( ) );
daoUtil.setString( 3, user.getLastName( ) );
daoUtil.setString( 4, user.getFirstName( ) );
daoUtil.setString( 5, user.getEmail( ) );
daoUtil.setInt( 6, user.getStatus( ) );
daoUtil.setString( 7, user.getLocale( ).toString( ) );
daoUtil.setInt( 8, user.getUserLevel( ) );
daoUtil.setBoolean( 9, user.getAccessibilityMode( ) );
daoUtil.setTimestamp( 10, user.getPasswordMaxValidDate( ) );
if ( user.getAccountMaxValidDate( ) == null )
{
daoUtil.setLongNull( 11 );
}
else
{
daoUtil.setLong( 11, user.getAccountMaxValidDate( ).getTime( ) );
}
daoUtil.executeUpdate( );
daoUtil.free( );
}
/**
* {@inheritDoc}
*/
@Override
public void store( AdminUser user )
{
DAOUtil daoUtil = new DAOUtil( SQL_QUERY_UPDATE );
daoUtil.setString( 1, user.getAccessCode( ) );
daoUtil.setString( 2, user.getLastName( ) );
daoUtil.setString( 3, user.getFirstName( ) );
daoUtil.setString( 4, user.getEmail( ) );
daoUtil.setInt( 5, user.getStatus( ) );
daoUtil.setString( 6, user.getLocale( ).toString( ) );
daoUtil.setBoolean( 7, user.isPasswordReset( ) );
daoUtil.setBoolean( 8, user.getAccessibilityMode( ) );
daoUtil.setTimestamp( 9, user.getPasswordMaxValidDate( ) );
daoUtil.setInt( 10, user.getUserId( ) );
daoUtil.executeUpdate( );
daoUtil.free( );
}
/**
* {@inheritDoc}
*/
@Override
public void delete( int nUserId )
{
DAOUtil daoUtil = new DAOUtil( SQL_QUERY_DELETE );
daoUtil.setInt( 1, nUserId );
daoUtil.executeUpdate( );
daoUtil.free( );
}
/**
* {@inheritDoc}
*/
@Override
public Map<String, Right> selectRightsListForUser( int nUserId )
{
Map<String, Right> rightsMap = new HashMap<String, Right>( );
DAOUtil daoUtil = new DAOUtil( SQL_QUERY_SELECT_RIGHTS_FROM_USER_ID );
daoUtil.setInt( 1, nUserId );
daoUtil.executeQuery( );
while ( daoUtil.next( ) )
{
Right right = new Right( );
right.setId( daoUtil.getString( 1 ) );
right.setNameKey( daoUtil.getString( 2 ) );
right.setUrl( daoUtil.getString( 3 ) );
right.setDescriptionKey( daoUtil.getString( 4 ) );
right.setPluginName( daoUtil.getString( 5 ) );
right.setFeatureGroup( daoUtil.getString( 6 ) );
right.setIconUrl( daoUtil.getString( 7 ) );
right.setLevel( daoUtil.getInt( 8 ) );
right.setDocumentationUrl( daoUtil.getString( 9 ) );
right.setOrder( daoUtil.getInt( 10 ) );
rightsMap.put( right.getId( ), right );
}
daoUtil.free( );
return rightsMap;
}
/**
* {@inheritDoc}
*/
@Override
public void insertRightsListForUser( int nUserId, String strRightId )
{
DAOUtil daoUtil = new DAOUtil( SQL_QUERY_INSERT_USER_RIGHT );
daoUtil.setString( 1, strRightId );
daoUtil.setInt( 2, nUserId );
daoUtil.executeUpdate( );
daoUtil.free( );
}
/**
* {@inheritDoc}
*/
@Override
public void deleteAllRightsForUser( int nUserId )
{
DAOUtil daoUtil = new DAOUtil( SQL_QUERY_DELETE_ALL_USER_RIGHTS );
daoUtil.setInt( 1, nUserId );
daoUtil.executeUpdate( );
daoUtil.free( );
}
/**
* {@inheritDoc}
*/
@Override
public Map<String, AdminRole> selectRolesListForUser( int nUserId )
{
Map<String, AdminRole> rolesMap = new HashMap<String, AdminRole>( );
DAOUtil daoUtil = new DAOUtil( SQL_QUERY_SELECT_ROLES_FROM_USER_ID );
daoUtil.setInt( 1, nUserId );
daoUtil.executeQuery( );
while ( daoUtil.next( ) )
{
AdminRole role = new AdminRole( );
role.setKey( daoUtil.getString( 1 ) );
role.setDescription( daoUtil.getString( 2 ) );
rolesMap.put( role.getKey( ), role );
}
daoUtil.free( );
return rolesMap;
}
/**
* {@inheritDoc}
*/
@Override
public void insertRolesListForUser( int nUserId, String strRoleKey )
{
DAOUtil daoUtil = new DAOUtil( SQL_QUERY_INSERT_USER_ROLE );
daoUtil.setString( 1, strRoleKey );
daoUtil.setInt( 2, nUserId );
daoUtil.executeUpdate( );
daoUtil.free( );
}
/**
* {@inheritDoc}
*/
@Override
public void deleteAllRolesForUser( int nUserId )
{
DAOUtil daoUtil = new DAOUtil( SQL_QUERY_DELETE_ALL_USER_ROLES );
daoUtil.setInt( 1, nUserId );
daoUtil.executeUpdate( );
daoUtil.free( );
}
/**
* {@inheritDoc}
*/
@Override
public boolean checkRoleAttributed( String strRoleKey )
{
boolean bInUse = false;
DAOUtil daoUtil = new DAOUtil( SQL_CHECK_ROLE_ATTRIBUTED );
daoUtil.setString( 1, strRoleKey );
daoUtil.executeQuery( );
if ( daoUtil.next( ) )
{
bInUse = true;
}
daoUtil.free( );
return bInUse;
}
/**
* {@inheritDoc}
*/
@Override
public int checkAccessCodeAlreadyInUse( String strAccessCode )
{
int nIdUser = -1;
DAOUtil daoUtil = new DAOUtil( SQL_CHECK_ACCESS_CODE_IN_USE );
daoUtil.setString( 1, strAccessCode );
daoUtil.executeQuery( );
if ( daoUtil.next( ) )
{
nIdUser = daoUtil.getInt( 1 );
}
daoUtil.free( );
return nIdUser;
}
/**
* {@inheritDoc}
*/
@Override
public int checkEmailAlreadyInUse( String strEmail )
{
int nIdUser = -1;
DAOUtil daoUtil = new DAOUtil( SQL_CHECK_EMAIL_IN_USE );
daoUtil.setString( 1, strEmail );
daoUtil.executeQuery( );
if ( daoUtil.next( ) )
{
nIdUser = daoUtil.getInt( 1 );
}
daoUtil.free( );
return nIdUser;
}
// for no-module mode
/**
* {@inheritDoc}
*/
@Override
public void insert( LuteceDefaultAdminUser user )
{
DAOUtil daoUtil = new DAOUtil( SQL_QUERY_INSERT_DEFAULT_USER );
user.setUserId( newPrimaryKey( ) );
daoUtil.setInt( 1, user.getUserId( ) );
daoUtil.setString( 2, user.getAccessCode( ) );
daoUtil.setString( 3, user.getLastName( ) );
daoUtil.setString( 4, user.getFirstName( ) );
daoUtil.setString( 5, user.getEmail( ) );
daoUtil.setInt( 6, user.getStatus( ) );
daoUtil.setString( 7, user.getPassword( ) );
daoUtil.setString( 8, user.getLocale( ).toString( ) );
daoUtil.setInt( 9, user.getUserLevel( ) );
daoUtil.setBoolean( 10, user.getAccessibilityMode( ) );
daoUtil.setBoolean( 11, user.isPasswordReset( ) );
daoUtil.setTimestamp( 12, user.getPasswordMaxValidDate( ) );
if ( user.getAccountMaxValidDate( ) == null )
{
daoUtil.setLongNull( 13 );
}
else
{
daoUtil.setLong( 13, user.getAccountMaxValidDate( ).getTime( ) );
}
daoUtil.setTimestamp( 14, user.getDateLastLogin( ) );
daoUtil.setString( 15, user.getWorkgroupKey( ) );
daoUtil.executeUpdate( );
daoUtil.free( );
}
/**
* {@inheritDoc}
*/
@Override
public void store( LuteceDefaultAdminUser user )
{
DAOUtil daoUtil = new DAOUtil( SQL_QUERY_UPDATE_DEFAULT_USER );
daoUtil.setString( 1, user.getAccessCode( ) );
daoUtil.setString( 2, user.getLastName( ) );
daoUtil.setString( 3, user.getFirstName( ) );
daoUtil.setString( 4, user.getEmail( ) );
daoUtil.setInt( 5, user.getStatus( ) );
daoUtil.setString( 6, user.getPassword( ) );
daoUtil.setString( 7, user.getLocale( ).toString( ) );
daoUtil.setBoolean( 8, user.isPasswordReset( ) );
daoUtil.setBoolean( 9, user.getAccessibilityMode( ) );
daoUtil.setTimestamp( 10, user.getPasswordMaxValidDate( ) );
daoUtil.setString( 11, user.getWorkgroupKey( ) );
daoUtil.setInt( 12, user.getUserId( ) );
daoUtil.executeUpdate( );
daoUtil.free( );
}
/**
* {@inheritDoc}
*/
@Override
public LuteceDefaultAdminUser loadDefaultAdminUser( int nUserId )
{
LuteceDefaultAdminUser user = new LuteceDefaultAdminUser( );
DAOUtil daoUtil = new DAOUtil( SQL_QUERY_SELECT_USER_FROM_USER_ID );
daoUtil.setInt( 1, nUserId );
daoUtil.executeQuery( );
if ( daoUtil.next( ) )
{
user.setUserId( daoUtil.getInt( 1 ) );
user.setAccessCode( daoUtil.getString( 2 ) );
user.setLastName( daoUtil.getString( 3 ) );
user.setFirstName( daoUtil.getString( 4 ) );
user.setEmail( daoUtil.getString( 5 ) );
user.setStatus( daoUtil.getInt( 6 ) );
user.setPassword( daoUtil.getString( 7 ) );
Locale locale = new Locale( daoUtil.getString( 8 ) );
user.setLocale( locale );
user.setUserLevel( daoUtil.getInt( 9 ) );
user.setPasswordReset( daoUtil.getBoolean( 10 ) );
user.setAccessibilityMode( daoUtil.getBoolean( 11 ) );
user.setWorkgroupKey( daoUtil.getString( 14 ) );
}
daoUtil.free( );
return user;
}
/**
* {@inheritDoc}
*/
@Override
public Collection<AdminUser> selectUsersByRole( String strRoleKey )
{
Collection<AdminUser> userList = new ArrayList<AdminUser>( );
DAOUtil daoUtil = new DAOUtil( SQL_QUERY_SELECT_USERS_ID_BY_ROLES );
daoUtil.setString( 1, strRoleKey );
daoUtil.executeQuery( );
while ( daoUtil.next( ) )
{
AdminUser user = new AdminUser( );
user.setUserId( daoUtil.getInt( 1 ) );
user.setAccessCode( daoUtil.getString( 2 ) );
user.setLastName( daoUtil.getString( 3 ) );
user.setFirstName( daoUtil.getString( 4 ) );
user.setEmail( daoUtil.getString( 5 ) );
user.setStatus( daoUtil.getInt( 6 ) );
user.setLocale( new Locale( daoUtil.getString( 7 ) ) );
user.setAccessibilityMode( daoUtil.getBoolean( 8 ) );
user.setPasswordMaxValidDate( daoUtil.getTimestamp( 9 ) );
userList.add( user );
}
daoUtil.free( );
return userList;
}
/**
* {@inheritDoc}
*/
@Override
public Collection<AdminUser> selectUsersByLevel( int nIdLevel )
{
Collection<AdminUser> userList = new ArrayList<AdminUser>( );
DAOUtil daoUtil = new DAOUtil( SQL_QUERY_SELECT_USERS_BY_LEVEL );
daoUtil.setInt( 1, nIdLevel );
daoUtil.executeQuery( );
while ( daoUtil.next( ) )
{
AdminUser user = new AdminUser( );
user.setUserId( daoUtil.getInt( 1 ) );
user.setAccessCode( daoUtil.getString( 2 ) );
user.setLastName( daoUtil.getString( 3 ) );
user.setFirstName( daoUtil.getString( 4 ) );
user.setEmail( daoUtil.getString( 5 ) );
user.setStatus( daoUtil.getInt( 6 ) );
user.setLocale( new Locale( daoUtil.getString( 7 ) ) );
user.setAccessibilityMode( daoUtil.getBoolean( 8 ) );
userList.add( user );
}
daoUtil.free( );
return userList;
}
/**
* Select rights by user, by user level and by type (Delegated or own)
*
* @param nUserId the id of the user
* @param nUserLevel the id of the user level
* @param bDelegated true if select concern delegated rights
* @return collection of id rights
*/
private Collection<String> selectIdRights( int nUserId, int nUserLevel, boolean bDelegated )
{
String strSqlQuery = bDelegated ? SQL_QUERY_SELECT_USER_RIGHTS_DELEGATED : SQL_QUERY_SELECT_USER_RIGHTS_OWN;
Collection<String> idRightList = new ArrayList<String>( );
DAOUtil daoUtil = new DAOUtil( strSqlQuery );
daoUtil.setInt( 1, nUserId );
daoUtil.setInt( 2, nUserLevel );
daoUtil.executeQuery( );
while ( daoUtil.next( ) )
{
idRightList.add( daoUtil.getString( 1 ) );
}
daoUtil.free( );
return idRightList;
}
/**
* Deletes rights by user and by id right
*
* @param nUserId the user id
* @param idRightList the list of rights to delete
*/
private void deleteRightsForUser( int nUserId, Collection<String> idRightList )
{
for ( String strIdRight : idRightList )
{
DAOUtil daoUtil = new DAOUtil( SQL_QUERY_DELETE_USER_RIGHTS );
daoUtil.setInt( 1, nUserId );
daoUtil.setString( 2, strIdRight );
daoUtil.executeUpdate( );
daoUtil.free( );
}
}
/**
* {@inheritDoc}
*/
@Override
public void deleteAllOwnRightsForUser( int nUserId, int nUserLevel )
{
Collection<String> idRightList = selectIdRights( nUserId, nUserLevel, false );
deleteRightsForUser( nUserId, idRightList );
}
/**
* {@inheritDoc}
*/
@Override
public void deleteAllDelegatedRightsForUser( int nUserId, int nUserLevel )
{
Collection<String> idRightList = selectIdRights( nUserId, nUserLevel, true );
deleteRightsForUser( nUserId, idRightList );
}
/**
* {@inheritDoc}
*/
@Override
public void storeUsersRole( String strOldRoleKey, AdminRole role )
{
DAOUtil daoUtil = new DAOUtil( SQL_QUERY_UPDATE_USERS_ROLE );
daoUtil.setString( 1, role.getKey( ) );
daoUtil.setString( 2, strOldRoleKey );
daoUtil.executeUpdate( );
daoUtil.free( );
}
/**
* {@inheritDoc}
*/
@Override
public boolean hasRole( int nUserId, String strRoleKey )
{
boolean bHasRole = false;
DAOUtil daoUtil = new DAOUtil( SQL_QUERY_SELECT_USER_ROLE );
daoUtil.setInt( 1, nUserId );
daoUtil.setString( 2, strRoleKey );
daoUtil.executeQuery( );
if ( daoUtil.next( ) )
{
bHasRole = true;
}
daoUtil.free( );
return bHasRole;
}
/**
* {@inheritDoc}
*/
@Override
public void deleteRoleForUser( int nUserId, String strRoleKey )
{
DAOUtil daoUtil = new DAOUtil( SQL_QUERY_DELETE_ROLE_FOR_USER );
daoUtil.setInt( 1, nUserId );
daoUtil.setString( 2, strRoleKey );
daoUtil.executeUpdate( );
daoUtil.free( );
}
/**
* {@inheritDoc}
*/
@Override
public Collection<AdminUser> selectUsersByFilter( AdminUserFilter auFilter )
{
Collection<AdminUser> userList = new ArrayList<AdminUser>( );
DAOUtil daoUtil;
String query = SQL_QUERY_SELECT_USER_FROM_SEARCH;
if ( auFilter.getStatus( ) != -1 )
{
query += CONSTANT_AND_STATUS;
}
if ( auFilter.getUserLevel( ) != -1 )
{
query += CONSTANT_AND_USER_LEVEL;
}
query += CONSTANT_ORDER_BY_LAST_NAME;
daoUtil = new DAOUtil( query );
daoUtil.setString( 1, CONSTANT_PERCENT + auFilter.getAccessCode( ) + CONSTANT_PERCENT );
daoUtil.setString( 2, CONSTANT_PERCENT + auFilter.getLastName( ) + CONSTANT_PERCENT );
daoUtil.setString( 3, CONSTANT_PERCENT + auFilter.getEmail( ) + CONSTANT_PERCENT );
if ( auFilter.getStatus( ) != -1 )
{
daoUtil.setInt( 4, auFilter.getStatus( ) );
if ( auFilter.getUserLevel( ) != -1 )
{
daoUtil.setInt( 6, auFilter.getUserLevel( ) );
}
}
else
{
if ( auFilter.getUserLevel( ) != -1 )
{
daoUtil.setInt( 5, auFilter.getUserLevel( ) );
}
}
daoUtil.executeQuery( );
while ( daoUtil.next( ) )
{
AdminUser user = new AdminUser( );
user.setUserId( daoUtil.getInt( 1 ) );
user.setAccessCode( daoUtil.getString( 2 ) );
user.setLastName( daoUtil.getString( 3 ) );
user.setFirstName( daoUtil.getString( 4 ) );
user.setEmail( daoUtil.getString( 5 ) );
user.setStatus( daoUtil.getInt( 6 ) );
user.setLocale( new Locale( daoUtil.getString( 7 ) ) );
user.setUserLevel( daoUtil.getInt( 8 ) );
user.setAccessibilityMode( daoUtil.getBoolean( 9 ) );
userList.add( user );
}
daoUtil.free( );
return userList;
}
/**
* {@inheritDoc}
*/
@Override
public Collection<AdminUser> selectUsersByRight( String strIdRight )
{
Collection<AdminUser> userList = new ArrayList<AdminUser>( );
DAOUtil daoUtil = new DAOUtil( SQL_QUERY_SELECT_USERS_BY_RIGHT );
daoUtil.setString( 1, strIdRight );
daoUtil.executeQuery( );
while ( daoUtil.next( ) )
{
AdminUser user = new AdminUser( );
user.setUserId( daoUtil.getInt( 1 ) );
user.setAccessCode( daoUtil.getString( 2 ) );
user.setLastName( daoUtil.getString( 3 ) );
user.setFirstName( daoUtil.getString( 4 ) );
user.setEmail( daoUtil.getString( 5 ) );
user.setStatus( daoUtil.getInt( 6 ) );
user.setLocale( new Locale( daoUtil.getString( 7 ) ) );
user.setUserLevel( daoUtil.getInt( 8 ) );
user.setAccessibilityMode( daoUtil.getBoolean( 9 ) );
userList.add( user );
}
daoUtil.free( );
return userList;
}
/**
* {@inheritDoc}
*/
@Override
public boolean hasRight( int nUserId, String strIdRight )
{
boolean bHasRight = false;
DAOUtil daoUtil = new DAOUtil( SQL_QUERY_SELECT_USER_RIGHT );
daoUtil.setInt( 1, nUserId );
daoUtil.setString( 2, strIdRight );
daoUtil.executeQuery( );
if ( daoUtil.next( ) )
{
bHasRight = true;
}
daoUtil.free( );
return bHasRight;
}
/**
* {@inheritDoc}
*/
@Override
public void deleteRightForUser( int nUserId, String strIdRight )
{
DAOUtil daoUtil = new DAOUtil( SQL_QUERY_DELETE_USER_RIGHTS );
daoUtil.setInt( 1, nUserId );
daoUtil.setString( 2, strIdRight );
daoUtil.executeUpdate( );
daoUtil.free( );
}
/**
* {@inheritDoc}
*/
@Override
public List<String> selectUserPasswordHistory( int nUserID )
{
List<String> listPasswordHistory = new ArrayList<String>( );
DAOUtil daoUtil = new DAOUtil( SQL_SELECT_USER_PASSWORD_HISTORY );
daoUtil.setInt( 1, nUserID );
daoUtil.executeQuery( );
while ( daoUtil.next( ) )
{
listPasswordHistory.add( daoUtil.getString( 1 ) );
}
daoUtil.free( );
return listPasswordHistory;
}
/**
* {@inheritDoc}
*/
@Override
public int countUserPasswordHistoryFromDate( Timestamp minDate, int nUserId )
{
int nNbRes = 0;
DAOUtil daoUtil = new DAOUtil( SQL_COUNT_USER_PASSWORD_HISTORY );
daoUtil.setInt( 1, nUserId );
daoUtil.setTimestamp( 2, minDate );
daoUtil.executeQuery( );
if ( daoUtil.next( ) )
{
nNbRes = daoUtil.getInt( 1 );
}
daoUtil.free( );
return nNbRes;
}
/**
* {@inheritDoc}
*/
@Override
public void insertNewPasswordInHistory( String strPassword, int nUserId )
{
DAOUtil daoUtil = new DAOUtil( SQL_INSERT_PASSWORD_HISTORY );
daoUtil.setInt( 1, nUserId );
daoUtil.setString( 2, strPassword );
daoUtil.executeUpdate( );
daoUtil.free( );
}
/**
* {@inheritDoc}
*/
@Override
public void removeAllPasswordHistoryForUser( int nUserId )
{
DAOUtil daoUtil = new DAOUtil( SQL_DELETE_PASSWORD_HISTORY );
daoUtil.setInt( 1, nUserId );
daoUtil.executeUpdate( );
daoUtil.free( );
}
/**
* {@inheritDoc}
*/
@Override
public Map<String, Boolean> selectAnonymizationStatusUserStaticField( )
{
DAOUtil daoUtil = new DAOUtil( SQL_SELECT_ANONYMIZATION_STATUS_USER_FILED );
daoUtil.executeQuery( );
Map<String, Boolean> resultMap = new HashMap<String, Boolean>( );
while ( daoUtil.next( ) )
{
resultMap.put( daoUtil.getString( 1 ), daoUtil.getBoolean( 2 ) );
}
daoUtil.free( );
return resultMap;
}
/**
* {@inheritDoc}
*/
@Override
public void updateAnonymizationStatusUserStaticField( String strFieldName, boolean bAnonymizeFiled )
{
DAOUtil daoUtil = new DAOUtil( SQL_UPDATE_ANONYMIZATION_STATUS_USER_FILED );
daoUtil.setBoolean( 1, bAnonymizeFiled );
daoUtil.setString( 2, strFieldName );
daoUtil.executeUpdate( );
daoUtil.free( );
}
/**
* {@inheritDoc}
*/
@Override
public List<Integer> findAllExpiredUserId( )
{
DAOUtil daoUtil = new DAOUtil( SQL_QUERY_SELECT_EXPIRED_USER_ID );
daoUtil.setInt( 1, AdminUser.EXPIRED_CODE );
List<Integer> listIdExpiredUser = new ArrayList<Integer>( );
daoUtil.executeQuery( );
while ( daoUtil.next( ) )
{
listIdExpiredUser.add( daoUtil.getInt( 1 ) );
}
daoUtil.free( );
return listIdExpiredUser;
}
/**
* {@inheritDoc}
*/
@Override
public List<Integer> getIdUsersWithExpiredLifeTimeList( Timestamp currentTimestamp )
{
DAOUtil daoUtil = new DAOUtil( SQL_QUERY_SELECT_EXPIRED_LIFE_TIME_USER_ID );
daoUtil.setLong( 1, currentTimestamp.getTime( ) );
daoUtil.setInt( 2, AdminUser.EXPIRED_CODE );
List<Integer> listIdExpiredUser = new ArrayList<Integer>( );
daoUtil.executeQuery( );
while ( daoUtil.next( ) )
{
listIdExpiredUser.add( daoUtil.getInt( 1 ) );
}
daoUtil.free( );
return listIdExpiredUser;
}
/**
* {@inheritDoc}
*/
@Override
public List<Integer> getIdUsersToSendFirstAlert( Timestamp alertMaxDate )
{
DAOUtil daoUtil = new DAOUtil( SQL_QUERY_SELECT_USER_ID_FIRST_ALERT );
daoUtil.setInt( 1, AdminUser.EXPIRED_CODE );
daoUtil.setLong( 2, alertMaxDate.getTime( ) );
List<Integer> listIdUserFirstAlert = new ArrayList<Integer>( );
daoUtil.executeQuery( );
while ( daoUtil.next( ) )
{
listIdUserFirstAlert.add( daoUtil.getInt( 1 ) );
}
daoUtil.free( );
return listIdUserFirstAlert;
}
/**
* {@inheritDoc}
*/
@Override
public List<Integer> getIdUsersToSendOtherAlert( Timestamp alertMaxDate, Timestamp timeBetweenAlerts,
int maxNumberAlerts )
{
DAOUtil daoUtil = new DAOUtil( SQL_QUERY_SELECT_USER_ID_OTHER_ALERT );
daoUtil.setInt( 1, maxNumberAlerts );
daoUtil.setInt( 2, AdminUser.EXPIRED_CODE );
daoUtil.setLong( 3, timeBetweenAlerts.getTime( ) );
daoUtil.setLong( 4, alertMaxDate.getTime( ) );
List<Integer> listIdUserFirstAlert = new ArrayList<Integer>( );
daoUtil.executeQuery( );
while ( daoUtil.next( ) )
{
listIdUserFirstAlert.add( daoUtil.getInt( 1 ) );
}
daoUtil.free( );
return listIdUserFirstAlert;
}
/**
* {@inheritDoc}
*/
@Override
public List<Integer> getIdUsersWithExpiredPasswordsList( Timestamp currentTimestamp )
{
DAOUtil daoUtil = new DAOUtil( SQL_QUERY_SELECT_USER_ID_PASSWORD_EXPIRED );
daoUtil.setTimestamp( 1, currentTimestamp );
List<Integer> idUserPasswordExpiredlist = new ArrayList<Integer>( );
daoUtil.executeQuery( );
while ( daoUtil.next( ) )
{
idUserPasswordExpiredlist.add( daoUtil.getInt( 1 ) );
}
daoUtil.free( );
return idUserPasswordExpiredlist;
}
/**
* {@inheritDoc}
*/
@Override
public void updateUserStatus( List<Integer> listIdUser, int nNewStatus )
{
if ( ( listIdUser != null ) && ( listIdUser.size( ) > 0 ) )
{
StringBuilder sbSQL = new StringBuilder( );
sbSQL.append( SQL_QUERY_UPDATE_STATUS );
for ( int i = 0; i < listIdUser.size( ); i++ )
{
if ( i > 0 )
{
sbSQL.append( CONSTANT_COMMA );
}
sbSQL.append( listIdUser.get( i ) );
}
sbSQL.append( CONSTANT_CLOSE_PARENTHESIS );
DAOUtil daoUtil = new DAOUtil( sbSQL.toString( ) );
daoUtil.setInt( 1, nNewStatus );
daoUtil.executeUpdate( );
daoUtil.free( );
}
}
/**
* {@inheritDoc}
*/
@Override
public void updateNbAlert( List<Integer> listIdUser )
{
if ( ( listIdUser != null ) && ( listIdUser.size( ) > 0 ) )
{
StringBuilder sbSQL = new StringBuilder( );
sbSQL.append( SQL_QUERY_UPDATE_NB_ALERT );
for ( int i = 0; i < listIdUser.size( ); i++ )
{
if ( i > 0 )
{
sbSQL.append( CONSTANT_COMMA );
}
sbSQL.append( listIdUser.get( i ) );
}
sbSQL.append( CONSTANT_CLOSE_PARENTHESIS );
DAOUtil daoUtil = new DAOUtil( sbSQL.toString( ) );
daoUtil.executeUpdate( );
daoUtil.free( );
}
}
/**
* {@inheritDoc}
*/
@Override
public void updateChangePassword( List<Integer> listIdUser )
{
if ( ( listIdUser != null ) && ( listIdUser.size( ) > 0 ) )
{
StringBuilder sbSQL = new StringBuilder( );
sbSQL.append( SQL_QUERY_UPDATE_RESET_PASSWORD_LIST_ID );
for ( int i = 0; i < listIdUser.size( ); i++ )
{
if ( i > 0 )
{
sbSQL.append( CONSTANT_COMMA );
}
sbSQL.append( listIdUser.get( i ) );
}
sbSQL.append( CONSTANT_CLOSE_PARENTHESIS );
DAOUtil daoUtil = new DAOUtil( sbSQL.toString( ) );
daoUtil.executeUpdate( );
daoUtil.free( );
}
}
/**
* {@inheritDoc}
*/
@Override
public void updateUserExpirationDate( int nIdUser, Timestamp newExpirationDate )
{
DAOUtil daoUtil = new DAOUtil( SQL_QUERY_UPDATE_REACTIVATE_ACCOUNT );
if ( newExpirationDate == null )
{
daoUtil.setLongNull( 1 );
}
else
{
daoUtil.setLong( 1, newExpirationDate.getTime( ) );
}
daoUtil.setInt( 2, nIdUser );
daoUtil.executeUpdate( );
daoUtil.free( );
}
/**
* {@inheritDoc}
*/
@Override
public void updateDateLastLogin( int nIdUser, Timestamp dateLastLogin )
{
DAOUtil daoUtil = new DAOUtil( SQL_QUERY_UPDATE_DATE_LAST_LOGIN );
daoUtil.setTimestamp( 1, dateLastLogin );
daoUtil.setInt( 2, nIdUser );
daoUtil.executeUpdate( );
daoUtil.free( );
}
}
|
package com.google.sps.utils;
// Imports the Google Cloud client library
import com.google.cloud.dialogflow.v2.QueryInput;
import com.google.cloud.dialogflow.v2.QueryResult;
import com.google.gson.Gson;
import com.google.protobuf.ByteString;
import com.google.protobuf.Struct;
import com.google.protobuf.Value;
import com.google.sps.utils.TextUtils;
import com.google.sps.utils.SpeechUtils;
import com.google.sps.data.Location;
import com.google.sps.data.Output;
import com.google.sps.agents.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
/**
* Identifies agent from Dialogflow API Query result and creates Output object
*/
public class AgentUtils {
public static Output getOutput(QueryResult queryResult, String languageCode) {
String fulfillment = null;
String display = null;
String redirect = null;
byte[] byteStringToByteArray = null;
Agent object = null;
String detectedIntent = queryResult.getIntent().getDisplayName();
String agentName = getAgentName(detectedIntent);
String intentName = getIntentName(detectedIntent);
// Retrieve detected input from DialogFlow result.
String inputDetected = queryResult.getQueryText();
inputDetected = inputDetected.equals("") ? " (null) " : inputDetected;
Map<String, Value> parameterMap = getParameterMap(queryResult);
object = getAgent(agentName, intentName, parameterMap);
if (object != null) {
fulfillment = object.getOutput();
fulfillment = fulfillment == null ? queryResult.getFulfillmentText() : fulfillment;
display = object.getDisplay();
redirect = object.getRedirect();
} else {
fulfillment = queryResult.getFulfillmentText();
fulfillment = fulfillment.equals("") ? "I didn't hear you. Can you repeat that?" : fulfillment;
}
fulfillment = fulfillment == null ? queryResult.getFulfillmentText() : fulfillment;
byteStringToByteArray = getByteStringToByteArray(fulfillment, languageCode);
Output output = new Output(inputDetected, fulfillment, byteStringToByteArray, display, redirect);
return output;
}
private static Agent getAgent(String agentName, String intentName, Map<String, Value> parameterMap) {
switch(agentName) {
case "calculator":
return new Tip(intentName, parameterMap);
case "currency":
return new Currency(intentName, parameterMap);
case "language":
return new Language(intentName, parameterMap);
case "name":
return new Name(intentName, parameterMap);
case "reminders":
return new Reminders(intentName, parameterMap);
case "time":
return new Time(intentName, parameterMap);
case "translate":
return new TranslateAgent(intentName, parameterMap);
case "units":
return new UnitConverter(intentName, parameterMap);
case "weather":
return new Weather(intentName, parameterMap);
case "web":
return new WebSearch(intentName, parameterMap);
default:
return null;
}
}
private static String getAgentName(String detectedIntent) {
String[] intentList = detectedIntent.split("\\.", 2);
return intentList[0];
}
private static String getIntentName(String detectedIntent) {
String[] intentList = detectedIntent.split("\\.", 2);
String intentName = detectedIntent;
if (intentList.length > 1) {
intentName = intentList[1];
}
return intentName;
}
public static Map<String, Value> getParameterMap(QueryResult queryResult) {
Struct paramStruct = queryResult.getParameters();
Map<String, Value> parameters = paramStruct.getFieldsMap();
return parameters;
}
public static byte[] getByteStringToByteArray(String fulfillment, String languageCode){
byte[] byteArray = null;
try {
ByteString audioResponse = SpeechUtils.synthesizeText(fulfillment, languageCode);
byteArray = audioResponse.toByteArray();
} catch (Exception e) {
e.printStackTrace();
}
return byteArray;
}
public static String getLanguageCode(String language) {
if (language == null) {
return "en-US";
}
switch(language) {
case "Chinese":
return "zh-CN";
case "English":
return "en-US";
case "French":
return "fr";
case "German":
return "de";
case "Hindi":
return "hi";
case "Italian":
return "it";
case "Japanese":
return "ja";
case "Korean":
return "ko";
case "Portuguese":
return "pt";
case "Russian":
return "ru";
case "Spanish":
return "es";
case "Swedish":
return "sv";
default:
return null;
}
}
}
|
package org.apache.commons.collections;
import java.io.IOException;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.Vector;
/**
* This class extends normal Java properties by adding the possibility
* to use the same key many times concatenating the value strings
* instead of overwriting them.
*
* <p>The Extended Properties syntax is explained here:
*
* <ul>
* <li>
* Each property has the syntax <code>key = value</code>
* </li>
* <li>
* The <i>key</i> may use any character but the equal sign '='.
* </li>
* <li>
* <i>value</i> may be separated on different lines if a backslash
* is placed at the end of the line that continues below.
* </li>
* <li>
* If <i>value</i> is a list of strings, each token is separated
* by a comma ','.
* </li>
* <li>
* Commas in each token are escaped placing a backslash right before
* the comma.
* </li>
* <li>
* If a <i>key</i> is used more than once, the values are appended
* like if they were on the same line separated with commas.
* </li>
* <li>
* Blank lines and lines starting with character '#' are skipped.
* </li>
* <li>
* If a property is named "include" (or whatever is defined by
* setInclude() and getInclude() and the value of that property is
* the full path to a file on disk, that file will be included into
* the ConfigurationsRepository. You can also pull in files relative
* to the parent configuration file. So if you have something
* like the following:
*
* include = additional.properties
*
* Then "additional.properties" is expected to be in the same
* directory as the parent configuration file.
*
* Duplicate name values will be replaced, so be careful.
*
* </li>
* </ul>
*
* <p>Here is an example of a valid extended properties file:
*
* <p><pre>
* # lines starting with # are comments
*
* # This is the simplest property
* key = value
*
* # A long property may be separated on multiple lines
* longvalue = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \
* aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
*
* # This is a property with many tokens
* tokens_on_a_line = first token, second token
*
* # This sequence generates exactly the same result
* tokens_on_multiple_lines = first token
* tokens_on_multiple_lines = second token
*
* # commas may be escaped in tokens
* commas.excaped = Hi\, what'up?
* </pre>
*
* <p><b>NOTE</b>: this class has <b>not</b> been written for
* performance nor low memory usage. In fact, it's way slower than it
* could be and generates too much memory garbage. But since
* performance is not an issue during intialization (and there is not
* much time to improve it), I wrote it this way. If you don't like
* it, go ahead and tune it up!
*
*
* @author <a href="mailto:stefano@apache.org">Stefano Mazzocchi</a>
* @author <a href="mailto:jon@latchkey.com">Jon S. Stevens</a>
* @author <a href="mailto:daveb@miceda-data">Dave Bryson</a>
* @author <a href="mailto:jvanzyl@periapt.com">Jason van Zyl</a>
* @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
* @author <a href="mailto:leon@opticode.co.za">Leon Messerschmidt</a>
* @author <a href="mailto:kjohnson@transparent.com>Kent Johnson</a>
* @author <a href="mailto:dlr@finemaltcoding.com>Daniel Rall</a>
* @author <a href="mailto:ipriha@surfeu.fi>Ilkka Priha</a>
* @version $Id: ExtendedProperties.java,v 1.2 2001/05/04 02:22:48 geirm Exp $
*/
public class ExtendedProperties extends Hashtable
{
/**
* Default configurations repository.
*/
private ExtendedProperties defaults;
/**
* The file connected to this repository (holding comments and
* such).
*
* @serial
*/
protected String file;
/**
* Base path of the configuration file used to create
* this ExtendedProperties object.
*/
protected String basePath;
/**
* File separator.
*/
protected String fileSeparator = System.getProperty("file.separator");
/**
* Has this configuration been intialized.
*/
protected boolean isInitialized = false;
/**
* This is the name of the property that can point to other
* properties file for including other properties files.
*/
protected static String include = "include";
/**
* These are the keys in the order they listed
* in the configuration file. This is useful when
* you wish to perform operations with configuration
* information in a particular order.
*/
protected ArrayList keysAsListed = new ArrayList();
/**
* This class is used to read properties lines. These lines do
* not terminate with new-line chars but rather when there is no
* backslash sign a the end of the line. This is used to
* concatenate multiple lines for readability.
*/
class PropertiesReader extends LineNumberReader
{
/**
* Constructor.
*
* @param reader A Reader.
*/
public PropertiesReader(Reader reader)
{
super(reader);
}
/**
* Read a property.
*
* @return A String.
* @exception IOException.
*/
public String readProperty() throws IOException
{
StringBuffer buffer = new StringBuffer();
try
{
while (true)
{
String line = readLine().trim();
if ((line.length() != 0) && (line.charAt(0) != '
{
if (line.endsWith("\\"))
{
line = line.substring(0, line.length() - 1);
buffer.append(line);
}
else
{
buffer.append(line);
break;
}
}
}
}
catch (NullPointerException e)
{
return null;
}
return buffer.toString();
}
}
/**
* This class divides into tokens a property value. Token
* separator is "," but commas into the property value are escaped
* using the backslash in front.
*/
class PropertiesTokenizer extends StringTokenizer
{
/**
* The property delimiter used while parsing (a comma).
*/
static final String DELIMITER = ",";
/**
* Constructor.
*
* @param string A String.
*/
public PropertiesTokenizer(String string)
{
super(string, DELIMITER);
}
/**
* Check whether the object has more tokens.
*
* @return True if the object has more tokens.
*/
public boolean hasMoreTokens()
{
return super.hasMoreTokens();
}
/**
* Get next token.
*
* @return A String.
*/
public String nextToken()
{
StringBuffer buffer = new StringBuffer();
while (hasMoreTokens())
{
String token = super.nextToken();
if (token.endsWith("\\"))
{
buffer.append(token.substring(0, token.length() - 1));
buffer.append(DELIMITER);
}
else
{
buffer.append(token);
break;
}
}
return buffer.toString().trim();
}
}
/**
* Creates an empty extended properties object.
*/
public ExtendedProperties()
{
super();
}
/**
* Creates and loads the extended properties from the specified
* file.
*
* @param file A String.
* @exception IOException.
*/
public ExtendedProperties(String file) throws IOException
{
this(file,null);
}
/**
* Creates and loads the extended properties from the specified
* file.
*
* @param file A String.
* @exception IOException.
*/
public ExtendedProperties(String file, String defaultFile)
throws IOException
{
this.file = file;
basePath = new File(file).getAbsolutePath();
basePath = basePath.substring(0, basePath.lastIndexOf(fileSeparator) + 1);
this.load(new FileInputStream(file));
if (defaultFile != null)
{
defaults = new ExtendedProperties(defaultFile);
}
}
/**
* Private initializer method that sets up the generic
* resources.
*
* @exception IOException, if there was an I/O problem.
*/
private void init( ExtendedProperties exp ) throws IOException
{
isInitialized = true;
}
/**
* Indicate to client code whether property
* resources have been initialized or not.
*/
public boolean isInitialized()
{
return isInitialized;
}
/**
* Gets the property value for including other properties files.
* By default it is "include".
*
* @return A String.
*/
public String getInclude()
{
return this.include;
}
/**
* Sets the property value for including other properties files.
* By default it is "include".
*
* @param inc A String.
*/
public void setInclude(String inc)
{
this.include = inc;
}
/**
* Load the properties from the given input stream.
*
* @param input An InputStream.
* @exception IOException.
*/
public void load( InputStream input )
throws IOException
{
load(input,null);
}
/**
* Load the properties from the given input stream
* and using the specified encoding.
*
* @param input An InputStream.
* @param enc An encoding.
* @exception IOException.
*/
public synchronized void load(InputStream input, String enc)
throws IOException
{
PropertiesReader reader = null;
if (enc != null)
{
try
{
reader =
new PropertiesReader(new InputStreamReader(input,enc));
}
catch (UnsupportedEncodingException e)
{
// Get one with the default encoding...
}
}
if (reader == null)
{
reader =
new PropertiesReader(new InputStreamReader(input));
}
try
{
while (true)
{
String line = reader.readProperty();
int equalSign = line.indexOf('=');
if (equalSign > 0)
{
String key = line.substring(0, equalSign).trim();
String value = line.substring(equalSign + 1).trim();
/*
* Configure produces lines like this ... just
* ignore them.
*/
if ("".equals(value))
continue;
if (getInclude() != null &&
key.equalsIgnoreCase(getInclude()))
{
/*
* Recursively load properties files.
*/
File file = null;
if (value.startsWith(fileSeparator))
{
/*
* We have an absolute path so we'll
* use this.
*/
file = new File(value);
}
else
{
/*
* We have a relative path, and we have
* two possible forms here. If we have the
* "./" form then just strip that off first
* before continuing.
*/
if (value.startsWith("." + fileSeparator))
{
value = value.substring(2);
}
file = new File(basePath + value);
}
if (file != null && file.exists() && file.canRead())
{
load ( new FileInputStream(file));
}
}
else
{
addProperty(key,value);
//setProperty(key,value);
}
}
}
}
catch (NullPointerException e)
{
/*
* Should happen only when EOF is reached.
*/
return;
}
}
/**
* Gets a property from the configuration.
*
* @param key property to retrieve
* @return value as object. Will return user value if exists,
* if not then default value if exists, otherwise null
*/
public Object getProperty( String key)
{
/*
* first, try to get from the 'user value' store
*/
Object o = this.get(key);
if ( o == null)
{
/*
* if there isn't a value there, get it from the
* defaults if we have them
*/
if (defaults != null)
{
o = defaults.get(key);
}
}
return o;
}
/**
* Add a property to the configuration. If it already
* exists then the value stated here will be added
* to the configuration entry. For example, if
*
* resource.loader = file
*
* is already present in the configuration and you
*
* addProperty("resource.loader", "classpath")
*
* Then you will end up with a Vector like the
* following:
*
* ["file", "classpath"]
*
* @param String key
* @param String value
*/
//public void setProperty(String key, Object token)
public void addProperty(String key, Object token)
{
Object o = this.get(key);
/*
* $$$ GMJ
* FIXME : post 1.0 release, we need to not assume
* that a scalar is a String - it can be an Object
* so we should make a little vector-like class
* say, Foo that wraps (not extends Vector),
* so we can do things like
* if ( !( o instanceof Foo) )
* so we know it's our 'vector' container
*
* This applies throughout
*/
if (o instanceof String)
{
Vector v = new Vector(2);
v.addElement(o);
v.addElement(token);
put(key, v);
}
else if (o instanceof Vector)
{
((Vector) o).addElement(token);
}
else
{
/*
* This is the first time that we have seen
* request to place an object in the
* configuration with the key 'key'. So
* we just want to place it directly into
* the configuration ... but we are going to
* make a special exception for String objects
* that contain "," characters. We will take
* CSV lists and turn the list into a vector of
* Strings before placing it in the configuration.
* This is a concession for Properties and the
* like that cannot parse multiple same key
* values.
*/
if (token instanceof String &&
((String)token).indexOf(PropertiesTokenizer.DELIMITER) > 0)
{
PropertiesTokenizer tokenizer =
new PropertiesTokenizer((String)token);
while (tokenizer.hasMoreTokens())
{
String value = tokenizer.nextToken();
/*
* we know this is a string, so make sure it
* just goes in rather than risking vectorization
* if it contains an escaped comma
*/
addStringProperty(key,value);
}
}
else
{
/*
* We want to keep track of the order the keys
* are parsed, or dynamically entered into
* the configuration. So when we see a key
* for the first time we will place it in
* an ArrayList so that if a client class needs
* to perform operations with configuration
* in a definite order it will be possible.
*/
/*
* safety check
*/
if( !containsKey( key ) )
{
keysAsListed.add(key);
}
/*
* and the value
*/
put(key, token);
}
}
}
/**
* Sets a string property w/o checking for commas - used
* internally when a property has been broken up into
* strings that could contain escaped commas to prevent
* the inadvertant vectorization.
*
* Thanks to Leon Messerschmidt for this one.
*
*/
private void addStringProperty(String key, String token)
{
Object o = this.get(key);
/*
* $$$ GMJ
* FIXME : post 1.0 release, we need to not assume
* that a scalar is a String - it can be an Object
* so we should make a little vector-like class
* say, Foo that wraps (not extends Vector),
* so we can do things like
* if ( !( o instanceof Foo) )
* so we know it's our 'vector' container
*
* This applies throughout
*/
/*
* do the usual thing - if we have a value and
* it's scalar, make a vector, otherwise add
* to the vector
*/
if (o instanceof String)
{
Vector v = new Vector(2);
v.addElement(o);
v.addElement(token);
put(key, v);
}
else if (o instanceof Vector)
{
((Vector) o).addElement(token);
}
else
{
if( !containsKey( key ) )
{
keysAsListed.add(key);
}
put( key, token);
}
}
/**
* Set a property, this will replace any previously
* set values. Set values is implicitly a call
* to clearProperty(key), addProperty(key,value).
*
* @param String key
* @param String value
*/
public void setProperty(String key, Object value)
{
clearProperty(key);
addProperty(key,value);
}
/**
* Save the properties to the given outputstream.
*
* @param output An OutputStream.
* @param header A String.
* @exception IOException.
*/
public synchronized void save(OutputStream output,
String Header)
throws IOException
{
if(output != null)
{
PrintWriter theWrtr = new PrintWriter(output);
if(Header != null)
{
theWrtr.println(Header);
}
Enumeration theKeys = keys();
while(theKeys.hasMoreElements())
{
String key = (String) theKeys.nextElement();
Object value = get((Object) key);
if(value != null)
{
if(value instanceof String)
{
StringBuffer currentOutput = new StringBuffer();
currentOutput.append(key);
currentOutput.append("=");
currentOutput.append((String) value);
theWrtr.println(currentOutput.toString());
}
else if(value instanceof Vector)
{
Vector values = (Vector) value;
Enumeration valuesEnum = values.elements();
while(valuesEnum.hasMoreElements())
{
String currentElement =
(String) valuesEnum.nextElement();
StringBuffer currentOutput = new StringBuffer();
currentOutput.append(key);
currentOutput.append("=");
currentOutput.append(currentElement);
theWrtr.println(currentOutput.toString());
}
}
}
theWrtr.println();
theWrtr.flush();
}
}
}
/**
* Combines an existing Hashtable with this Hashtable.
*
* Warning: It will overwrite previous entries without warning.
*
* @param ExtendedProperties
*/
public void combine( ExtendedProperties c )
{
for (Iterator i = c.getKeys() ; i.hasNext() ;)
{
String key = (String) i.next();
//clearProperty(key);
setProperty( key, c.get(key) );
}
}
/**
* Clear a property in the configuration.
*
* @param String key to remove along with corresponding value.
*/
public void clearProperty(String key)
{
if (containsKey(key))
{
/*
* we also need to rebuild the keysAsListed or else
* things get *very* confusing
*/
for(int i = 0; i < keysAsListed.size(); i++)
{
if ( ( (String) keysAsListed.get(i)).equals( key ) )
{
keysAsListed.remove(i);
break;
}
}
remove(key);
}
}
/**
* Get the list of the keys contained in the configuration
* repository.
*
* @return An Iterator.
*/
public Iterator getKeys()
{
return keysAsListed.iterator();
}
/**
* Get the list of the keys contained in the configuration
* repository that match the specified prefix.
*
* @param prefix The prefix to test against.
* @return An Iterator of keys that match the prefix.
*/
public Iterator getKeys(String prefix)
{
Iterator keys = getKeys();
ArrayList matchingKeys = new ArrayList();
while( keys.hasNext() )
{
Object key = keys.next();
if( key instanceof String && ((String) key).startsWith(prefix) )
{
matchingKeys.add(key);
}
}
return matchingKeys.iterator();
}
/**
* Create an ExtendedProperties object that is a subset
* of this one. Take into account duplicate keys
* by using the setProperty() in ExtendedProperties.
*
* @param String prefix
*/
public ExtendedProperties subset(String prefix)
{
ExtendedProperties c = new ExtendedProperties();
Iterator keys = getKeys();
boolean validSubset = false;
while( keys.hasNext() )
{
Object key = keys.next();
if( key instanceof String && ((String) key).startsWith(prefix) )
{
if (!validSubset)
{
validSubset = true;
}
String newKey = null;
/*
* Check to make sure that c.subset(prefix) doesn't
* blow up when there is only a single property
* with the key prefix. This is not a useful
* subset but it is a valid subset.
*/
if ( ((String)key).length() == prefix.length())
{
newKey = prefix;
}
else
{
newKey = ((String)key).substring(prefix.length() + 1);
}
/*
* Make sure to use the setProperty() method and not
* just put(). setProperty() takes care of catching
* all the keys in the order they appear in a
* properties files or the order they are set
* dynamically.
*/
c.setProperty(newKey, get(key));
}
}
if (validSubset)
{
return c;
}
else
{
return null;
}
}
/**
* Display the configuration for debugging
* purposes.
*/
public void display()
{
Iterator i = getKeys();
while (i.hasNext())
{
String key = (String) i.next();
Object value = get(key);
System.out.println(key + " => " + value);
}
}
/**
* Get a string associated with the given configuration key.
*
* @param key The configuration key.
* @return The associated string.
* @exception ClassCastException is thrown if the key maps to an
* object that is not a String.
*/
public String getString(String key)
{
return getString(key, null);
}
/**
* Get a string associated with the given configuration key.
*
* @param key The configuration key.
* @param defaultValue The default value.
* @return The associated string if key is found,
* default value otherwise.
* @exception ClassCastException is thrown if the key maps to an
* object that is not a String.
*/
public String getString(String key,
String defaultValue)
{
Object value = get(key);
if (value instanceof String)
{
return (String) value;
}
else if (value == null)
{
if (defaults != null)
{
return defaults.getString(key, defaultValue);
}
else
{
return defaultValue;
}
}
else if (value instanceof Vector)
{
return (String) ((Vector) value).get(0);
}
else
{
throw new ClassCastException(
'\'' + key + "' doesn't map to a String object");
}
}
public Properties getProperties(String key)
{
return getProperties(key, new Properties());
}
public Properties getProperties(String key,
Properties defaults)
{
/*
* Grab an array of the tokens for this key.
*/
String[] tokens = getStringArray(key);
/*
* Each token is of the form 'key=value'.
*/
Properties props = new Properties(defaults);
for (int i = 0; i < tokens.length; i++)
{
String token = tokens[i];
int equalSign = token.indexOf('=');
if (equalSign > 0)
{
String pkey = token.substring(0, equalSign).trim();
String pvalue = token.substring(equalSign + 1).trim();
props.put(pkey, pvalue);
}
else
{
throw new IllegalArgumentException('\'' + token +
"' does not contain " +
"an equals sign");
}
}
return props;
}
/**
* Get an array of strings associated with the given configuration
* key.
*
* @param key The configuration key.
* @return The associated string array if key is found.
* @exception ClassCastException is thrown if the key maps to an
* object that is not a String/Vector.
*/
public String[] getStringArray(String key)
{
Object value = get(key);
// What's your vector, Victor?
Vector vector;
if (value instanceof String)
{
vector = new Vector(1);
vector.addElement(value);
}
else if (value instanceof Vector)
{
vector = (Vector)value;
}
else if (value == null)
{
if (defaults != null)
{
return defaults.getStringArray(key);
}
else
{
return new String[0];
}
}
else
{
throw new ClassCastException(
'\'' + key + "' doesn't map to a String/Vector object");
}
String[] tokens = new String[vector.size()];
for (int i = 0; i < tokens.length; i++)
{
tokens[i] = (String)vector.elementAt(i);
}
return tokens;
}
/**
* Get a Vector of strings associated with the given configuration
* key.
*
* @param key The configuration key.
* @return The associated Vector.
* @exception ClassCastException is thrown if the key maps to an
* object that is not a Vector.
*/
public Vector getVector(String key)
{
return getVector(key, null);
}
/**
* Get a Vector of strings associated with the given configuration
* key.
*
* @param key The configuration key.
* @param defaultValue The default value.
* @return The associated Vector.
* @exception ClassCastException is thrown if the key maps to an
* object that is not a Vector.
*/
public Vector getVector(String key,
Vector defaultValue)
{
Object value = get(key);
if (value instanceof Vector)
{
return (Vector) value;
}
else if (value instanceof String)
{
Vector v = new Vector(1);
v.addElement((String) value);
put(key, v);
return v;
}
else if (value == null)
{
if (defaults != null)
{
return defaults.getVector(key, defaultValue);
}
else
{
return ((defaultValue == null) ?
new Vector() : defaultValue);
}
}
else
{
throw new ClassCastException(
'\'' + key + "' doesn't map to a Vector object");
}
}
/**
* Get a boolean associated with the given configuration key.
*
* @param key The configuration key.
* @return The associated boolean.
* @exception NoSuchElementException is thrown if the key doesn't
* map to an existing object.
* @exception ClassCastException is thrown if the key maps to an
* object that is not a Boolean.
*/
public boolean getBoolean(String key)
{
Boolean b = getBoolean(key, (Boolean) null);
if (b != null)
{
return b.booleanValue();
}
else
{
throw new NoSuchElementException(
'\'' + key + "' doesn't map to an existing object");
}
}
/**
* Get a boolean associated with the given configuration key.
*
* @param key The configuration key.
* @param defaultValue The default value.
* @return The associated boolean.
* @exception ClassCastException is thrown if the key maps to an
* object that is not a Boolean.
*/
public boolean getBoolean(String key, boolean defaultValue)
{
return getBoolean(key, new Boolean(defaultValue)).booleanValue();
}
/**
* Get a boolean associated with the given configuration key.
*
* @param key The configuration key.
* @param defaultValue The default value.
* @return The associated boolean if key is found and has valid
* format, default value otherwise.
* @exception ClassCastException is thrown if the key maps to an
* object that is not a Boolean.
*/
public Boolean getBoolean(String key, Boolean defaultValue)
{
Object value = get(key);
if (value instanceof Boolean)
{
return (Boolean) value;
}
else if (value instanceof String)
{
String s = testBoolean((String)value);
Boolean b = new Boolean(s);
put(key, b);
return b;
}
else if (value == null)
{
if (defaults != null)
{
return defaults.getBoolean(key, defaultValue);
}
else
{
return defaultValue;
}
}
else
{
throw new ClassCastException(
'\'' + key + "' doesn't map to a Boolean object");
}
}
/**
* Test whether the string represent by value maps to a boolean
* value or not. We will allow <code>true</code>, <code>on</code>,
* and <code>yes</code> for a <code>true</code> boolean value, and
* <code>false</code>, <code>off</code>, and <code>no</code> for
* <code>false</code> boolean values. Case of value to test for
* boolean status is ignored.
*
* @param String The value to test for boolean state.
* @return <code>true</code> or <code>false</code> if the supplied
* text maps to a boolean value, or <code>null</code> otherwise.
*/
public String testBoolean(String value)
{
String s = ((String)value).toLowerCase();
if (s.equals("true") || s.equals("on") || s.equals("yes"))
{
return "true";
}
else if (s.equals("false") || s.equals("off") || s.equals("no"))
{
return "false";
}
else
{
return null;
}
}
/**
* Get a byte associated with the given configuration key.
*
* @param key The configuration key.
* @return The associated byte.
* @exception NoSuchElementException is thrown if the key doesn't
* map to an existing object.
* @exception ClassCastException is thrown if the key maps to an
* object that is not a Byte.
* @exception NumberFormatException is thrown if the value mapped
* by the key has not a valid number format.
*/
public byte getByte(String key)
{
Byte b = getByte(key, null);
if (b != null)
{
return b.byteValue();
}
else
{
throw new NoSuchElementException(
'\'' + key + " doesn't map to an existing object");
}
}
/**
* Get a byte associated with the given configuration key.
*
* @param key The configuration key.
* @param defaultValue The default value.
* @return The associated byte.
* @exception ClassCastException is thrown if the key maps to an
* object that is not a Byte.
* @exception NumberFormatException is thrown if the value mapped
* by the key has not a valid number format.
*/
public byte getByte(String key,
byte defaultValue)
{
return getByte(key, new Byte(defaultValue)).byteValue();
}
/**
* Get a byte associated with the given configuration key.
*
* @param key The configuration key.
* @param defaultValue The default value.
* @return The associated byte if key is found and has valid
* format, default value otherwise.
* @exception ClassCastException is thrown if the key maps to an
* object that is not a Byte.
* @exception NumberFormatException is thrown if the value mapped
* by the key has not a valid number format.
*/
public Byte getByte(String key,
Byte defaultValue)
{
Object value = get(key);
if (value instanceof Byte)
{
return (Byte) value;
}
else if (value instanceof String)
{
Byte b = new Byte((String) value);
put(key, b);
return b;
}
else if (value == null)
{
if (defaults != null)
{
return defaults.getByte(key, defaultValue);
}
else
{
return defaultValue;
}
}
else
{
throw new ClassCastException(
'\'' + key + "' doesn't map to a Byte object");
}
}
/**
* Get a short associated with the given configuration key.
*
* @param key The configuration key.
* @return The associated short.
* @exception NoSuchElementException is thrown if the key doesn't
* map to an existing object.
* @exception ClassCastException is thrown if the key maps to an
* object that is not a Short.
* @exception NumberFormatException is thrown if the value mapped
* by the key has not a valid number format.
*/
public short getShort(String key)
{
Short s = getShort(key, null);
if (s != null)
{
return s.shortValue();
}
else
{
throw new NoSuchElementException(
'\'' + key + "' doesn't map to an existing object");
}
}
/**
* Get a short associated with the given configuration key.
*
* @param key The configuration key.
* @param defaultValue The default value.
* @return The associated short.
* @exception ClassCastException is thrown if the key maps to an
* object that is not a Short.
* @exception NumberFormatException is thrown if the value mapped
* by the key has not a valid number format.
*/
public short getShort(String key,
short defaultValue)
{
return getShort(key, new Short(defaultValue)).shortValue();
}
/**
* Get a short associated with the given configuration key.
*
* @param key The configuration key.
* @param defaultValue The default value.
* @return The associated short if key is found and has valid
* format, default value otherwise.
* @exception ClassCastException is thrown if the key maps to an
* object that is not a Short.
* @exception NumberFormatException is thrown if the value mapped
* by the key has not a valid number format.
*/
public Short getShort(String key,
Short defaultValue)
{
Object value = get(key);
if (value instanceof Short)
{
return (Short) value;
}
else if (value instanceof String)
{
Short s = new Short((String) value);
put(key, s);
return s;
}
else if (value == null)
{
if (defaults != null)
{
return defaults.getShort(key, defaultValue);
}
else
{
return defaultValue;
}
}
else
{
throw new ClassCastException(
'\'' + key + "' doesn't map to a Short object");
}
}
/**
* The purpose of this method is to get the configuration resource
* with the given name as an integer.
*
* @param name The resource name.
* @return The value of the resource as an integer.
*/
public int getInt(String name)
{
return getInteger(name);
}
/**
* The purpose of this method is to get the configuration resource
* with the given name as an integer, or a default value.
*
* @param name The resource name
* @param def The default value of the resource.
* @return The value of the resource as an integer.
*/
public int getInt(String name,
int def)
{
return getInteger(name, def);
}
/**
* Get a int associated with the given configuration key.
*
* @param key The configuration key.
* @return The associated int.
* @exception NoSuchElementException is thrown if the key doesn't
* map to an existing object.
* @exception ClassCastException is thrown if the key maps to an
* object that is not a Integer.
* @exception NumberFormatException is thrown if the value mapped
* by the key has not a valid number format.
*/
public int getInteger(String key)
{
Integer i = getInteger(key, null);
if (i != null)
{
return i.intValue();
}
else
{
throw new NoSuchElementException(
'\'' + key + "' doesn't map to an existing object");
}
}
/**
* Get a int associated with the given configuration key.
*
* @param key The configuration key.
* @param defaultValue The default value.
* @return The associated int.
* @exception ClassCastException is thrown if the key maps to an
* object that is not a Integer.
* @exception NumberFormatException is thrown if the value mapped
* by the key has not a valid number format.
*/
public int getInteger(String key,
int defaultValue)
{
Integer i = getInteger(key, null);
if (i == null)
{
return defaultValue;
}
return i.intValue();
}
/**
* Get a int associated with the given configuration key.
*
* @param key The configuration key.
* @param defaultValue The default value.
* @return The associated int if key is found and has valid
* format, default value otherwise.
* @exception ClassCastException is thrown if the key maps to an
* object that is not a Integer.
* @exception NumberFormatException is thrown if the value mapped
* by the key has not a valid number format.
*/
public Integer getInteger(String key,
Integer defaultValue)
{
Object value = get(key);
if (value instanceof Integer)
{
return (Integer) value;
}
else if (value instanceof String)
{
Integer i = new Integer((String) value);
put(key, i);
return i;
}
else if (value == null)
{
if (defaults != null)
{
return defaults.getInteger(key, defaultValue);
}
else
{
return defaultValue;
}
}
else
{
throw new ClassCastException(
'\'' + key + "' doesn't map to a Integer object");
}
}
/**
* Get a long associated with the given configuration key.
*
* @param key The configuration key.
* @return The associated long.
* @exception NoSuchElementException is thrown if the key doesn't
* map to an existing object.
* @exception ClassCastException is thrown if the key maps to an
* object that is not a Long.
* @exception NumberFormatException is thrown if the value mapped
* by the key has not a valid number format.
*/
public long getLong(String key)
{
Long l = getLong(key, null);
if (l != null)
{
return l.longValue();
}
else
{
throw new NoSuchElementException(
'\'' + key + "' doesn't map to an existing object");
}
}
/**
* Get a long associated with the given configuration key.
*
* @param key The configuration key.
* @param defaultValue The default value.
* @return The associated long.
* @exception ClassCastException is thrown if the key maps to an
* object that is not a Long.
* @exception NumberFormatException is thrown if the value mapped
* by the key has not a valid number format.
*/
public long getLong(String key,
long defaultValue)
{
return getLong(key, new Long(defaultValue)).longValue();
}
/**
* Get a long associated with the given configuration key.
*
* @param key The configuration key.
* @param defaultValue The default value.
* @return The associated long if key is found and has valid
* format, default value otherwise.
* @exception ClassCastException is thrown if the key maps to an
* object that is not a Long.
* @exception NumberFormatException is thrown if the value mapped
* by the key has not a valid number format.
*/
public Long getLong(String key,
Long defaultValue)
{
Object value = get(key);
if (value instanceof Long)
{
return (Long) value;
}
else if (value instanceof String)
{
Long l = new Long((String) value);
put(key, l);
return l;
}
else if (value == null)
{
if (defaults != null)
{
return defaults.getLong(key, defaultValue);
}
else
{
return defaultValue;
}
}
else
{
throw new ClassCastException(
'\'' + key + "' doesn't map to a Long object");
}
}
/**
* Get a float associated with the given configuration key.
*
* @param key The configuration key.
* @return The associated float.
* @exception NoSuchElementException is thrown if the key doesn't
* map to an existing object.
* @exception ClassCastException is thrown if the key maps to an
* object that is not a Float.
* @exception NumberFormatException is thrown if the value mapped
* by the key has not a valid number format.
*/
public float getFloat(String key)
{
Float f = getFloat(key, null);
if (f != null)
{
return f.floatValue();
}
else
{
throw new NoSuchElementException(
'\'' + key + "' doesn't map to an existing object");
}
}
/**
* Get a float associated with the given configuration key.
*
* @param key The configuration key.
* @param defaultValue The default value.
* @return The associated float.
* @exception ClassCastException is thrown if the key maps to an
* object that is not a Float.
* @exception NumberFormatException is thrown if the value mapped
* by the key has not a valid number format.
*/
public float getFloat(String key,
float defaultValue)
{
return getFloat(key, new Float(defaultValue)).floatValue();
}
/**
* Get a float associated with the given configuration key.
*
* @param key The configuration key.
* @param defaultValue The default value.
* @return The associated float if key is found and has valid
* format, default value otherwise.
* @exception ClassCastException is thrown if the key maps to an
* object that is not a Float.
* @exception NumberFormatException is thrown if the value mapped
* by the key has not a valid number format.
*/
public Float getFloat(String key,
Float defaultValue)
{
Object value = get(key);
if (value instanceof Float)
{
return (Float) value;
}
else if (value instanceof String)
{
Float f = new Float((String) value);
put(key, f);
return f;
}
else if (value == null)
{
if (defaults != null)
{
return defaults.getFloat(key, defaultValue);
}
else
{
return defaultValue;
}
}
else
{
throw new ClassCastException(
'\'' + key + "' doesn't map to a Float object");
}
}
/**
* Get a double associated with the given configuration key.
*
* @param key The configuration key.
* @return The associated double.
* @exception NoSuchElementException is thrown if the key doesn't
* map to an existing object.
* @exception ClassCastException is thrown if the key maps to an
* object that is not a Double.
* @exception NumberFormatException is thrown if the value mapped
* by the key has not a valid number format.
*/
public double getDouble(String key)
{
Double d = getDouble(key, null);
if (d != null)
{
return d.doubleValue();
}
else
{
throw new NoSuchElementException(
'\'' + key + "' doesn't map to an existing object");
}
}
/**
* Get a double associated with the given configuration key.
*
* @param key The configuration key.
* @param defaultValue The default value.
* @return The associated double.
* @exception ClassCastException is thrown if the key maps to an
* object that is not a Double.
* @exception NumberFormatException is thrown if the value mapped
* by the key has not a valid number format.
*/
public double getDouble(String key,
double defaultValue)
{
return getDouble(key, new Double(defaultValue)).doubleValue();
}
/**
* Get a double associated with the given configuration key.
*
* @param key The configuration key.
* @param defaultValue The default value.
* @return The associated double if key is found and has valid
* format, default value otherwise.
* @exception ClassCastException is thrown if the key maps to an
* object that is not a Double.
* @exception NumberFormatException is thrown if the value mapped
* by the key has not a valid number format.
*/
public Double getDouble(String key,
Double defaultValue)
{
Object value = get(key);
if (value instanceof Double)
{
return (Double) value;
}
else if (value instanceof String)
{
Double d = new Double((String) value);
put(key, d);
return d;
}
else if (value == null)
{
if (defaults != null)
{
return defaults.getDouble(key, defaultValue);
}
else
{
return defaultValue;
}
}
else
{
throw new ClassCastException(
'\'' + key + "' doesn't map to a Double object");
}
}
/**
* Convert a standard properties class into a configuration
* class.
*
* @param p properties object to convert into
* a ExtendedProperties object.
*
* @return ExtendedProperties configuration created from the
* properties object.
*/
public static ExtendedProperties convertProperties(Properties p)
{
ExtendedProperties c = new ExtendedProperties();
for (Enumeration e = p.keys(); e.hasMoreElements() ; )
{
String s = (String) e.nextElement();
c.setProperty(s, p.getProperty(s));
}
return c;
}
}
|
package net.ontopia.presto.jaxb;
import java.util.Collection;
import java.util.Collections;
import javax.xml.bind.annotation.XmlRootElement;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.map.annotate.JsonSerialize;
@XmlRootElement
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown=true)
public class Topic extends Document {
private String id;
private String name;
private String interfaceControl;
private Boolean readOnlyMode;
private Boolean errors;
private Origin origin;
private TopicType type;
private String view;
private Collection<Link> links;
private Collection<View> views = Collections.emptySet();
private Collection<FieldData> fields;
private String format = "topic";
@Override
public String getFormat() {
return format;
}
@Override
public void setFormat(String format) {
this.format = format;
}
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setReadOnlyMode(Boolean readOnlyMode) {
this.readOnlyMode = readOnlyMode;
}
public Boolean isReadOnlyMode() {
return readOnlyMode;
}
public void setType(TopicType type) {
this.type = type;
}
public TopicType getType() {
return type;
}
public void setView(String view) {
this.view = view;
}
public String getView() {
return view;
}
public void setFields(Collection<FieldData> fields) {
this.fields = fields;
}
public Collection<FieldData> getFields() {
return fields;
}
// builder methods
public static Topic topic(String id, String name) {
Topic result = new Topic();
result.setId(id);
result.setName(name);
return result;
}
public void setOrigin(Origin origin) {
this.origin = origin;
}
public Origin getOrigin() {
return origin;
}
public void setLinks(Collection<Link> links) {
if (links.isEmpty()) {
this.links = null;
} else {
this.links = links;
}
}
public Collection<Link> getLinks() {
return links;
}
public void setViews(Collection<View> views) {
this.views = views;
}
public Collection<View> getViews() {
if (views == null) {
return Collections.emptySet();
} else {
return views;
}
}
public Boolean getErrors() {
return errors;
}
public void setErrors(Boolean errors) {
this.errors = errors;
}
public String getInterfaceControl() {
return interfaceControl;
}
public void setInterfaceControl(String interfaceControl) {
this.interfaceControl = interfaceControl;
}
}
|
package org.jdesktop.swingx.action;
import java.awt.Insets;
import java.beans.PropertyChangeListener;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.swing.AbstractButton;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.ButtonGroup;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComponent;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JToggleButton;
import javax.swing.JToolBar;
/**
* Creates user interface elements based on action ids and lists of action ids.
* All action ids must represent actions managed by the ActionManager.
* <p>
* <h3>Action Lists</h3>
* Use the createXXX(List) methods to construct containers of actions like menu
* bars, menus, popups and toolbars from actions represented as action ids in a
* <i>java.util.List</i>. Each element in the action-list can be one of 3 types:
* <ul>
* <li>action id: corresponds to an action managed by the ActionManager
* <li>null: indicates a separator should be inserted.
* <li>java.util.List: represents a submenu. See the note below which describes
* the configuration of menus.
* </li>
* The order of elements in an action-list determines the arrangement of the ui
* components which are contructed from the action-list.
* <p>
* For a menu or submenu, the first element in the action-list represents a menu
* and subsequent elements represent menu items or separators (if null).
* <p>
* This class can be used as a general component factory which will construct
* components from Actions if the <code>create<comp>(Action,...)</code>
* methods are used.
*
* @see ActionManager
*/
public class ActionContainerFactory {
/**
* Standard margin for toolbar buttons to improve their look
*/
private static Insets TOOLBAR_BUTTON_MARGIN = new Insets(1, 1, 1, 1);
private ActionMap manager;
// Map between group id + component and the ButtonGroup
private Map<Integer, ButtonGroup> groupMap;
/**
* Constructs an container factory which uses the default
* ActionManager.
*
*/
public ActionContainerFactory() {
}
/**
* Constructs an container factory which uses managed actions.
*
* @param manager use the actions managed with this manager for
* constructing ui componenents.
*/
public ActionContainerFactory(ActionMap manager) {
setActionManager(manager);
}
/**
* Gets the ActionManager instance. If the ActionManager has not been explicitly
* set then the default ActionManager instance will be used.
*
* @return the ActionManager used by the ActionContainerFactory.
* @see #setActionManager
*/
public ActionMap getActionManager() {
if (manager == null) {
manager = ActionManager.getInstance();
}
return manager;
}
/**
* Sets the ActionManager instance that will be used by this
* ActionContainerFactory
*/
public void setActionManager(ActionMap manager) {
this.manager = manager;
}
/**
* Constructs a toolbar from an action-list id. By convention,
* the identifier of the main toolbar should be "main-toolbar"
*
* @param list a list of action ids used to construct the toolbar.
* @return the toolbar or null
*/
public JToolBar createToolBar(Object[] list) {
return createToolBar(Arrays.asList(list));
}
/**
* Constructs a toolbar from an action-list id. By convention,
* the identifier of the main toolbar should be "main-toolbar"
*
* @param list a list of action ids used to construct the toolbar.
* @return the toolbar or null
*/
public JToolBar createToolBar(List<Object> list) {
JToolBar toolbar = new JToolBar();
Iterator<Object> iter = list.iterator();
while(iter.hasNext()) {
Object element = iter.next();
if (element == null) {
toolbar.addSeparator();
} else {
AbstractButton button = createButton(element, toolbar);
// toolbar buttons shouldn't steal focus
button.setFocusable(false);
/*
* TODO
* The next two lines improve the default look of the buttons.
* This code should be changed to retrieve the default look
* from some UIDefaults object.
*/
button.setMargin(TOOLBAR_BUTTON_MARGIN);
button.setBorderPainted(false);
toolbar.add(button);
}
}
return toolbar;
}
/**
* Constructs a popup menu from an array of action ids.
*
* @param list an array of action ids used to construct the popup.
* @return the popup or null
*/
public JPopupMenu createPopup(Object[] list) {
return createPopup(Arrays.asList(list));
}
/**
* Constructs a popup menu from a list of action ids.
*
* @param list a list of action ids used to construct the popup.
* @return the popup or null
*/
public JPopupMenu createPopup(List<Object> list) {
JPopupMenu popup = new JPopupMenu();
Iterator<Object> iter = list.iterator();
while(iter.hasNext()) {
Object element = iter.next();
if (element == null) {
popup.addSeparator();
} else if (element instanceof List) {
JMenu newMenu= createMenu((List)element);
if (newMenu!= null) {
popup.add(newMenu);
}
} else {
popup.add(createMenuItem(element, popup));
}
}
return popup;
}
/**
* Constructs a menu tree from a list of actions or lists of lists or actions.
*
* TODO This method is broken. It <em>should</em> expect either that every
* entry is a List (thus, the sub menus off the main MenuBar), or it should
* handle normal actions properly. By submitting a List of all Actions, nothing
* is created....
* <p>
* For example, If my list is [action, action, action], then nothing is added
* to the menu bar. However, if my list is [list[action], action, action, action] then
* I get a menu and under it the tree actions. This should not be, because if I
* wanted those actions to be on the sub menu, then they should have been
* listed within the sub list!
*
* @param actionIds an array which represents the root item.
* @return a menu bar which represents the menu bar tree
*/
public JMenuBar createMenuBar(Object[] actionIds) {
return createMenuBar(Arrays.asList(actionIds));
}
/**
* Constructs a menu tree from a list of actions or lists of lists or actions.
* TODO This method is broken. It <em>should</em> expect either that every
* entry is a List (thus, the sub menus off the main MenuBar), or it should
* handle normal actions properly. By submitting a List of all Actions, nothing
* is created....
* <p>
* For example, If my list is [action, action, action], then nothing is added
* to the menu bar. However, if my list is [list[action], action, action, action] then
* I get a menu and under it the tree actions. This should not be, because if I
* wanted those actions to be on the sub menu, then they should have been
* listed within the sub list!
*
* @param list a list which represents the root item.
* @return a menu bar which represents the menu bar tree
*/
public JMenuBar createMenuBar(List<Object> list) {
JMenuBar menubar = new JMenuBar();
JMenu menu = null;
Iterator<Object> iter = list.iterator();
while(iter.hasNext()) {
Object element = iter.next();
if (element == null) {
if (menu != null) {
menu.addSeparator();
}
} else if (element instanceof List) {
menu = createMenu((List)element);
if (menu != null) {
menubar.add(menu);
}
} else {
if (menu != null) {
menu.add(createMenuItem(element, menu));
}
}
}
return menubar;
}
/**
* Creates and returns a menu from a List which represents actions, separators
* and sub-menus. The menu
* constructed will have the attributes from the first action in the List.
* Subsequent actions in the list represent menu items.
*
* @param actionIds an array of action ids used to construct the menu and menu items.
* the first element represents the action used for the menu,
* @return the constructed JMenu or null
*/
public JMenu createMenu(Object[] actionIds) {
return createMenu(Arrays.asList(actionIds));
}
/**
* Creates and returns a menu from a List which represents actions, separators
* and sub-menus. The menu
* constructed will have the attributes from the first action in the List.
* Subsequent actions in the list represent menu items.
*
* @param list a list of action ids used to construct the menu and menu items.
* the first element represents the action used for the menu,
* @return the constructed JMenu or null
*/
public JMenu createMenu(List<Object> list) {
// The first item will be the action for the JMenu
Action action = getAction(list.get(0));
if (action == null) {
return null;
}
JMenu menu = new JMenu(action);
// The rest of the items represent the menu items.
Iterator<Object> iter = list.listIterator(1);
while(iter.hasNext()) {
Object element = iter.next();
if (element == null) {
menu.addSeparator();
} else if (element instanceof List) {
JMenu newMenu = createMenu((List)element);
if (newMenu != null) {
menu.add(newMenu);
}
} else {
menu.add(createMenuItem(element, menu));
}
}
return menu;
}
/**
* Convenience method to get the action from an ActionManager.
*/
private Action getAction(Object id) {
Action action = getActionManager().get(id);
if (action == null) {
throw new RuntimeException("ERROR: No Action for " + id);
}
return action;
}
/**
* Returns the button group corresponding to the groupid
*
* @param groupid the value of the groupid attribute for the action element
* @param container a container which will further identify the ButtonGroup
*/
private ButtonGroup getGroup(String groupid, JComponent container) {
if (groupMap == null) {
groupMap = new HashMap<Integer, ButtonGroup>();
}
int intCode = groupid.hashCode();
if (container != null) {
intCode ^= container.hashCode();
}
Integer hashCode = new Integer(intCode);
ButtonGroup group = groupMap.get(hashCode);
if (group == null) {
group = new ButtonGroup();
groupMap.put(hashCode, group);
}
return group;
}
/**
* Creates a menu item based on the attributes of the action element.
* Will return a JMenuItem, JRadioButtonMenuItem or a JCheckBoxMenuItem
* depending on the context of the Action.
*
* @return a JMenuItem or subclass depending on type.
*/
private JMenuItem createMenuItem(Object id, JComponent container) {
return createMenuItem(getAction(id), container);
}
/**
* Creates a menu item based on the attributes of the action element.
* Will return a JMenuItem, JRadioButtonMenuItem or a JCheckBoxMenuItem
* depending on the context of the Action.
*
* @param action a mangaged Action
* @param container the parent container may be null for non-group actions.
* @return a JMenuItem or subclass depending on type.
*/
public JMenuItem createMenuItem(Action action, JComponent container) {
JMenuItem menuItem = null;
if (action instanceof AbstractActionExt) {
AbstractActionExt ta = (AbstractActionExt)action;
if (ta.isStateAction()) {
String groupid = (String)ta.getGroup();
if (groupid != null) {
// If this action has a groupid attribute then it's a
// GroupAction
menuItem = createRadioButtonMenuItem(getGroup(groupid, container),
(AbstractActionExt)action);
} else {
menuItem = createCheckBoxMenuItem((AbstractActionExt)action);
}
}
}
if (menuItem == null) {
menuItem= new JMenuItem(action);
configureMenuItemFromExtActionProperties(menuItem, action);
}
return menuItem;
}
/**
* Creates a menu item based on the attributes of the action.
* Will return a JMenuItem, JRadioButtonMenuItem or a JCheckBoxMenuItem
* depending on the context of the Action.
*
* @param action an action used to create the menu item
* @return a JMenuItem or subclass depending on type.
*/
public JMenuItem createMenuItem(Action action) {
return createMenuItem(action, null);
}
/**
* Creates, configures and returns an AbstractButton.
*
* The attributes of the action element
* registered with the ActionManger by the given id.
* Will return a JButton or a JToggleButton.
*
* @param id the identifer
* @param container the JComponent which parents the group, if any.
* @return an AbstractButton based on the
*/
public AbstractButton createButton(Object id, JComponent container) {
return createButton(getAction(id), container);
}
/**
* Creates a button based on the attributes of the action. If the container
* parameter is non-null then it will be used to uniquely identify
* the returned component within a ButtonGroup. If the action doesn't
* represent a grouped component then this value can be null.
*
* @param action an action used to create the button
* @param container the parent container to uniquely identify
* grouped components or null
* @return will return a JButton or a JToggleButton.
*/
public AbstractButton createButton(Action action, JComponent container) {
if (action == null) {
return null;
}
AbstractButton button = null;
if (action instanceof AbstractActionExt) {
// Check to see if we should create a toggle button
AbstractActionExt ta = (AbstractActionExt)action;
if (ta.isStateAction()) {
// If this action has a groupid attribute then it's a
// GroupAction
String groupid = (String)ta.getGroup();
if (groupid == null) {
button = createToggleButton(ta);
} else {
button = createToggleButton(ta, getGroup(groupid, container));
}
}
}
if (button == null) {
// Create a regular button
button = new JButton(action);
configureButtonFromExtActionProperties(button, action);
}
return button;
}
/**
* Creates a button based on the attributes of the action.
*
* @param action an action used to create the button
* @return will return a JButton or a JToggleButton.
*/
public AbstractButton createButton(Action action) {
return createButton(action, null);
}
/**
* Adds and configures a toggle button.
* @param a an abstraction of a toggle action.
*/
private JToggleButton createToggleButton(AbstractActionExt a) {
return createToggleButton(a, null);
}
/**
* Adds and configures a toggle button.
* @param a an abstraction of a toggle action.
* @param group the group to add the toggle button or null
*/
private JToggleButton createToggleButton(AbstractActionExt a, ButtonGroup group) {
JToggleButton button = new JToggleButton();
configureButton(button, a, group);
return button;
}
/**
*
* @param button
* @param a
* @param group
*/
public void configureButton(JToggleButton button, AbstractActionExt a, ButtonGroup group) {
configureSelectableButton(button, a, group);
configureButtonFromExtActionProperties(button, a);
}
public void configureSelectableButton(AbstractButton button, AbstractActionExt a, ButtonGroup group){
if ((a != null) && !a.isStateAction()) throw
new IllegalArgumentException("the Action must be a stateAction");
// we assume that all button configuration is done exclusively through this method!!
if (button.getAction() == a) return;
// unconfigure if the old Action is a state AbstractActionExt
// PENDING JW: automate unconfigure via a PCL that is listening to
// the button's action property? Think about memory leak implications!
Action oldAction = button.getAction();
if (oldAction instanceof AbstractActionExt) {
AbstractActionExt actionExt = (AbstractActionExt) oldAction;
// remove as itemListener
button.removeItemListener(actionExt);
// remove the button related PCL from the old actionExt
PropertyChangeListener[] l = actionExt.getPropertyChangeListeners();
for (int i = l.length - 1; i >= 0; i
if (l[i] instanceof ToggleActionPropertyChangeListener) {
ToggleActionPropertyChangeListener togglePCL = (ToggleActionPropertyChangeListener) l[i];
if (togglePCL.isToggling(button)) {
actionExt.removePropertyChangeListener(togglePCL);
}
}
}
}
button.setAction(a);
if (group != null) {
group.add(button);
}
if (a != null) {
button.addItemListener(a);
// JW: move the initial config into the PCL??
button.setSelected(a.isSelected());
new ToggleActionPropertyChangeListener(a, button);
// new ToggleActionPCL(button, a);
}
}
/**
* This method will be called after buttons created from an action. Override
* for custom configuration.
*
* @param button the button to be configured
* @param action the action used to construct the menu item.
*/
protected void configureButtonFromExtActionProperties(AbstractButton button, Action action) {
if (action.getValue(Action.SHORT_DESCRIPTION) == null) {
button.setToolTipText((String)action.getValue(Action.NAME));
}
// Use the large icon for toolbar buttons.
if (action.getValue(AbstractActionExt.LARGE_ICON) != null) {
button.setIcon((Icon)action.getValue(AbstractActionExt.LARGE_ICON));
}
// Don't show the text under the toolbar buttons if they have an icon
if (button.getIcon() != null) {
button.setText("");
}
}
/**
* This method will be called after menu items are created.
* Override for custom configuration.
*
* @param menuItem the menu item to be configured
* @param action the action used to construct the menu item.
*/
protected void configureMenuItemFromExtActionProperties(JMenuItem menuItem, Action action) {
}
/**
* Helper method to add a checkbox menu item.
*/
private JCheckBoxMenuItem createCheckBoxMenuItem(AbstractActionExt a) {
JCheckBoxMenuItem mi = new JCheckBoxMenuItem();
configureSelectableButton(mi, a, null);
configureMenuItemFromExtActionProperties(mi, a);
return mi;
}
/**
* Helper method to add a radio button menu item.
*/
private JRadioButtonMenuItem createRadioButtonMenuItem(ButtonGroup group,
AbstractActionExt a) {
JRadioButtonMenuItem mi = new JRadioButtonMenuItem();
configureSelectableButton(mi, a, group);
configureMenuItemFromExtActionProperties(mi, a);
return mi;
}
}
|
// Triple Play - utilities for use in PlayN-based games
package tripleplay.demo.ui;
import playn.core.Font;
import playn.core.PlayN;
import react.Function;
import tripleplay.ui.Background;
import tripleplay.ui.Behavior;
import tripleplay.ui.Constraints;
import tripleplay.ui.Group;
import tripleplay.ui.Icons;
import tripleplay.ui.Label;
import tripleplay.ui.Shim;
import tripleplay.ui.Slider;
import tripleplay.ui.Style;
import tripleplay.ui.ValueLabel;
import tripleplay.ui.layout.AxisLayout;
import tripleplay.demo.DemoScreen;
public class SliderDemo extends DemoScreen
{
@Override protected String name () {
return "Sliders";
}
@Override protected String title () {
return "UI: Sliders";
}
@Override protected Group createIface () {
Group iface = new Group(AxisLayout.vertical().gap(10)).add(
new Shim(15, 15),
new Label("Click and drag the slider to change the value:"),
sliderAndLabel(new Slider(0, -100, 100), "-000"),
new Shim(15, 15),
new Label("This one counts by 2s:"),
sliderAndLabel(new Slider(0, -50, 50).setIncrement(2).addStyles(
Behavior.Track.HOVER_LIMIT.is(35f)), "-00"),
new Shim(15, 15),
new Label("With a background, custom bar and thumb image:"),
sliderAndLabel(
new Slider(0, -50, 50).addStyles(
Style.BACKGROUND.is(Background.roundRect(0xFFFFFFFF, 16).inset(4)),
Slider.THUMB_IMAGE.is(Icons.loader(
PlayN.assets().getImage("images/smiley.png"), 24, 24)),
Slider.BAR_HEIGHT.is(18f),
Slider.BAR_BACKGROUND.is(Background.roundRect(0xFFFF0000, 9))), "-00"));
return iface;
}
protected Group sliderAndLabel (Slider slider, String minText) {
ValueLabel label = new ValueLabel(slider.value.map(FORMATTER)).
setStyles(Style.HALIGN.right, Style.FONT.is(FIXED)).
setConstraint(Constraints.minSize(minText));
return new Group(AxisLayout.horizontal()).add(slider, label);
}
protected Function<Float,String> FORMATTER = new Function<Float,String>() {
public String apply (Float value) {
return String.valueOf(value.intValue());
}
};
protected static Font FIXED = PlayN.graphics().createFont("Fixed", Font.Style.PLAIN, 16);
}
|
package models.nodes;
import play.libs.F.Function;
import play.libs.F.None;
import play.libs.F.Option;
import play.libs.F.Promise;
import play.libs.F.Some;
import constants.NodeType;
import managers.nodes.UserManager;
public class User extends LabeledNodeWithProperties {
public String username;
public String password;
private User() {
super(NodeType.USER);
}
public User(String username, String password) {
this();
this.username = username;
this.password = password;
this.jsonProperties.put("username", username);
}
public Promise<Option<User>> get() {
return this.exists().map(new GetFunction(this));
}
public Promise<Boolean> create() {
return this.exists().flatMap(new CreateFunction(this));
}
public Promise<Boolean> delete() {
return Promise.pure(false);
}
private class GetFunction implements Function<Boolean, Option<User>> {
private User user;
public GetFunction(User user) {
this.user = user;
}
public Option<User> apply(Boolean exists) {
if (exists) {
return new Some<User>(this.user);
}
return new None<User>();
}
}
private class CreateFunction
implements Function<Boolean, Promise<Boolean>> {
private User user;
public CreateFunction(User user) {
this.user = user;
}
public Promise<Boolean> apply(Boolean exists) {
if (exists) {
return Promise.pure(false);
}
return UserManager.create(this.user);
}
}
}
|
package me.shortify.sparkserver;
import static spark.Spark.before;
import static spark.Spark.get;
import static spark.Spark.options;
import static spark.Spark.post;
import me.shortify.dao.CassandraDAO;
import me.shortify.sparkserver.exception.BadCustomURLException;
import me.shortify.sparkserver.exception.BadURLException;
import me.shortify.sparkserver.exception.ShortURLNotFoundException;
import me.shortify.sparkserver.exception.URLExistsException;
public class Services {
private static final String API_CONTEXT = "/api/v1";
public static void setupEndpoints() {
ShortenerServices shortenerServices = new ShortenerServices(new CassandraDAO());
set404();
setConversione(shortenerServices);
setVisitaShortUrl(shortenerServices);
setIspezioneUrl(shortenerServices);
setOpzioni();
}
private static void setConversione(ShortenerServices ss) {
post(API_CONTEXT + API.CONVERT, (request, response) -> {
String shortUrl = null;
try {
shortUrl = ss.conversioneURL(request.body());
} catch(URLExistsException e) {
System.err.println(e.getMessage());
response.status(401);
} catch(BadCustomURLException e) {
System.err.println(e.getMessage());
response.status(401);
} catch(BadURLException e) {
System.err.println(e.getMessage());
response.status(401);
}
return shortUrl;
});
}
private static void set404() {
get("/404.html", (request, response) -> {
return null;
});
}
private static void setVisitaShortUrl(ShortenerServices ss) {
get("/:goto", (request, response) -> {
try {
String longUrl = ss.visitaURL(request.params(":goto"), request.ip());
response.redirect(longUrl);
} catch(ShortURLNotFoundException e) {
System.err.println(e.getMessage());
response.redirect("404.html");
}
return null;
});
}
private static void setIspezioneUrl(ShortenerServices ss) {
post(API_CONTEXT + API.STATS, (request, response) -> {
String statistiche = "";
try {
statistiche = ss.ispezionaURL(request.body());
} catch (ShortURLNotFoundException e) {
System.err.println(e.getMessage());
response.redirect("404.html");
}
return statistiche;
});
}
private static void setOpzioni() {
|
package org.jsmpp.util;
import static org.testng.Assert.*;
import org.jsmpp.PDUStringException;
import org.jsmpp.SMPPConstant;
import org.jsmpp.bean.BindResp;
import org.jsmpp.bean.BindType;
import org.testng.annotations.Test;
/**
* Test composing PDU, decompose and read.
* @author uudashr
*
*/
public class ComposerDecomposerReaderTest {
private static final boolean DEBUG = false;
@Test(groups="checkintest")
public void lowLevel() {
byte[] b = null;
String systemId = "smsc";
PDUByteBuffer buf = new PDUByteBuffer(BindType.BIND_TRX.responseCommandId(), 0, 1);
buf.append(systemId);
b = buf.toBytes();
assertEquals(b.length, 16 + systemId.length() + 1);
printLog("Length of bytes : " + b.length);
SequentialBytesReader reader = new SequentialBytesReader(b);
assertEquals(b.length, reader.remainBytesLength());
int commandLength = reader.readInt();
assertEquals(commandLength, b.length);
assertEquals(4, reader.cursor);
assertEquals(b.length - 4, reader.remainBytesLength());
int commandId = reader.readInt();
assertEquals(commandId, BindType.BIND_TRX.responseCommandId());
assertEquals(8, reader.cursor);
assertEquals(b.length - 8, reader.remainBytesLength());
int commandStatus = reader.readInt();
assertEquals(commandStatus, SMPPConstant.STAT_ESME_ROK);
assertEquals(12, reader.cursor);
assertEquals(b.length - 12, reader.remainBytesLength());
int sequenceNumber = reader.readInt();
assertEquals(sequenceNumber, 1);
assertEquals(16, reader.cursor);
assertEquals(b.length - 16, reader.remainBytesLength());
String readedSystemId = reader.readCString();
assertEquals(readedSystemId, systemId);
}
@Test(groups="checkintest")
public void highLevel() {
PDUComposer composer = new DefaultComposer();
PDUDecomposer decomposer = new DefaultDecomposer();
byte[] b = null;
String systemId = "smsc";
BindType bindType = BindType.BIND_TRX;
try {
b = composer.bindResp(bindType.responseCommandId(), 1, systemId);
assertEquals(b.length, 16 + systemId.length() + 1);
printLog("Length of bytes : " + b.length);
} catch (PDUStringException e) {
fail("Failed composing bind response", e);
}
try {
BindResp resp = decomposer.bindResp(b);
assertEquals(resp.getCommandLength(), b.length);
assertEquals(resp.getCommandId(), bindType.responseCommandId());
assertEquals(resp.getCommandStatus(), SMPPConstant.STAT_ESME_ROK);
assertEquals(resp.getSequenceNumber(), 1);
assertEquals(resp.getSystemId(), systemId);
} catch (PDUStringException e) {
fail("Failed decomposing bind response", e);
}
}
private static void printLog(String message) {
if (DEBUG) {
System.out.println(message);
}
}
}
|
package org.helioviewer.gl3d.gui;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import org.helioviewer.gl3d.camera.GL3DCamera;
import org.helioviewer.jhv.display.Displayer;
import org.helioviewer.jhv.gui.IconBank;
import org.helioviewer.jhv.gui.IconBank.JHVIcon;
/**
* Action that resets the view transformation of the current {@link GL3DCamera}
* to its default settings.
*
* @author Simon Spoerri (simon.spoerri@fhnw.ch)
*
*/
public class GL3DResetCameraAction extends AbstractAction {
private static final long serialVersionUID = 1L;
public GL3DResetCameraAction() {
super("Reset Camera", IconBank.getIcon(JHVIcon.RESET));
putValue(SHORT_DESCRIPTION, "Reset Camera Position to Default");
// putValue(MNEMONIC_KEY, KeyEvent.VK_R);
// putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_COMMA,
// KeyEvent.ALT_MASK));
}
@Override
public void actionPerformed(ActionEvent e) {
GL3DCameraSelectorModel.getInstance().getCurrentCamera().reset();
Displayer.getSingletonInstance().display();
}
}
|
package org.helioviewer.jhv.gui.dialogs;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.KeyEvent;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.ListCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.helioviewer.jhv.JHVDirectory;
import org.helioviewer.jhv.base.logging.Log;
import org.helioviewer.jhv.base.time.TimeUtils;
import org.helioviewer.jhv.gui.ImageViewerGui;
import org.helioviewer.jhv.gui.UIGlobals;
import org.helioviewer.jhv.gui.interfaces.ShowableDialog;
import org.helioviewer.jhv.viewmodel.metadata.HelioviewerMetaData;
import org.helioviewer.jhv.viewmodel.metadata.MetaData;
import org.helioviewer.jhv.viewmodel.view.View;
import org.helioviewer.jhv.viewmodel.view.fitsview.FITSView;
import org.helioviewer.jhv.viewmodel.view.jp2view.JP2View;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* Dialog that is used to display meta data for an image.
*/
@SuppressWarnings("serial")
public class MetaDataDialog extends JDialog implements ActionListener, ShowableDialog {
private static class LocalTableModel extends DefaultTableModel {
public LocalTableModel(Object[][] object, Object[] objects) {
super(object, objects);
}
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
}
private final JButton closeButton = new JButton("Close");
private final JButton exportFitsButton = new JButton("Export FITS Header as XML");
private final DefaultTableModel fitsModel = new LocalTableModel(null, new Object[] { "FITS Key", "value" });
private final DefaultListModel jhList = new DefaultListModel();
private final JList jhBox = new JList(jhList);
private final DefaultListModel basicList = new DefaultListModel();
private final JList basicBox = new JList(basicList);
private Document xmlDoc = null;
private boolean metaDataOK;
private String outFileName;
public MetaDataDialog(View view) {
super(ImageViewerGui.getMainFrame(), "Image Information");
setLayout(new BorderLayout());
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
bottomPanel.add(exportFitsButton);
bottomPanel.add(closeButton);
basicBox.setCellRenderer(new WrappedTextCellRenderer());
jhBox.setCellRenderer(new WrappedTextCellRenderer());
ComponentListener cl = new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
// force cache invalidation by temporarily setting fixed height
((JList) e.getComponent()).setFixedCellHeight(10);
((JList) e.getComponent()).setFixedCellHeight(-1);
}
};
jhBox.addComponentListener(cl);
JTable fTable = new JTable(fitsModel);
TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(fitsModel);
fTable.setRowSorter(sorter);
JPanel sp = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.weightx = 1;
c.weighty = 0;
c.gridx = 0;
c.gridy = 0;
c.anchor = GridBagConstraints.CENTER;
c.fill = GridBagConstraints.BOTH;
c.gridwidth = 1;
sp.add((basicBox), c);
c.weighty = 3;
c.gridy = 1;
sp.add(new JScrollPane(fTable), c);
c.weighty = 1.25;
c.gridy = 2;
sp.add(new JScrollPane(jhBox), c);
add(sp, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.PAGE_END);
closeButton.addActionListener(this);
exportFitsButton.addActionListener(this);
setMetaData(view);
getRootPane().registerKeyboardAction(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
closePressed();
}
}, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_IN_FOCUSED_WINDOW);
}
private static class WrappedTextCellRenderer extends JTextArea implements ListCellRenderer {
public WrappedTextCellRenderer() {
setLineWrap(true);
setWrapStyleWord(true);
setFont(UIGlobals.UIFontMono);
}
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
setText("" + value.toString().trim());
int width = list.getWidth();
if (width > 0)
setSize(width, Short.MAX_VALUE);
return this;
}
}
private void resetData() {
if (!metaDataOK) {
exportFitsButton.setEnabled(false);
} else {
exportFitsButton.setEnabled(true);
}
}
private void addDataItem(String key, DefaultListModel model) {
model.addElement(key);
}
private void addDataItem(String nodeName, String nodeValue, boolean isFits) {
if (isFits)
fitsModel.addRow(new Object[] { nodeName, nodeValue });
else
jhList.addElement(nodeName + ": " + nodeValue);
}
@Override
public void showDialog() {
if (!metaDataOK)
setSize(450, 200);
else
setSize(450, 600);
setLocationRelativeTo(ImageViewerGui.getMainFrame());
pack();
getRootPane().setDefaultButton(closeButton);
setVisible(true);
}
private void closePressed() {
xmlDoc = null;
resetData();
dispose();
}
@Override
public void actionPerformed(ActionEvent _a) {
if (_a.getSource() == closeButton) {
closePressed();
} else if (_a.getSource() == exportFitsButton) {
DOMSource source = new DOMSource(xmlDoc.getDocumentElement().getElementsByTagName("fits").item(0));
boolean saveSuccessful = saveXMLDocument(source, outFileName);
if (saveSuccessful)
JOptionPane.showMessageDialog(this, "Fits data saved to " + outFileName);
}
}
private void setMetaData(View v) {
MetaData metaData = v.getImageLayer().getMetaData();
if (!(metaData instanceof HelioviewerMetaData)) {
metaDataOK = false;
resetData();
addDataItem("Error: No metadata is available.", basicList);
} else {
HelioviewerMetaData m = (HelioviewerMetaData) metaData;
metaDataOK = true;
resetData();
addDataItem("
addDataItem(" Basic Information ", basicList);
addDataItem("
addDataItem("Observatory: " + m.getObservatory(), basicList);
addDataItem("Instrument: " + m.getInstrument(), basicList);
addDataItem("Detector: " + m.getDetector(), basicList);
addDataItem("Measurement: " + m.getMeasurement(), basicList);
addDataItem("Observation Date: " + m.getViewpoint().time, basicList);
String xmlText = null;
if (v instanceof JP2View) {
xmlText = ((JP2View) v).getXMLMetaData();
} else if (v instanceof FITSView) {
xmlText = ((FITSView) v).getHeaderAsXML();
}
if (xmlText != null) {
try {
InputStream in = new ByteArrayInputStream(xmlText.trim().replace("&", "&").getBytes("UTF-8"));
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(in);
// Send xml data to meta data dialog box
Node root = doc.getDocumentElement().getElementsByTagName("fits").item(0);
writeXMLData(root, 0);
root = doc.getDocumentElement().getElementsByTagName("helioviewer").item(0);
if (root != null) {
writeXMLData(root, 0);
}
// set the xml data for the MetaDataDialog
xmlDoc = doc;
// export file name
outFileName = JHVDirectory.EXPORTS.getPath() + m.getFullName() + "__" + TimeUtils.filenameDateFormat.format(m.getViewpoint().time.getDate()) + ".fits.xml";
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
/**
* A method that writes the xml box specified by its root node to the list
* box in image info dialog box.
*
* @param node
* Node to write
* @param indent
* Number of tabstops to insert
*/
private String lastNodeSeen = null;
private void writeXMLData(Node node, int indent) {
// get element name and value
String nodeName = node.getNodeName();
String nodeValue = getElementValue(node);
if (nodeName.equals("fits")) {
lastNodeSeen = nodeName;
} else if (nodeName.equals("helioviewer")) {
lastNodeSeen = nodeName;
addDataItem("
addDataItem(" Helioviewer Header", jhList);
addDataItem("
} else {
addDataItem(nodeName, nodeValue, lastNodeSeen.equals("fits"));
}
// write the child nodes recursively
NodeList children = node.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE) {
writeXMLData(child, indent + 1);
}
}
}
/**
* A method that gets the value of a node element.
*
* If the node itself has children and no text value, an empty string is
* returned. This is maybe an overkill for our purposes now, but takes into
* account the possibility of nested tags.
*
* @param elem
* Node to read
* @return value of the node
*/
private final String getElementValue(Node elem) {
if (elem != null && elem.hasChildNodes()) {
for (Node child = elem.getFirstChild(); child != null; child = child.getNextSibling()) {
if (child.getNodeType() == Node.TEXT_NODE) {
return child.getNodeValue();
}
}
}
return "";
}
/**
* This routine saves the fits data into an XML file.
*
* @param source
* XML document to save
* @param filename
* XML file name
*/
private boolean saveXMLDocument(DOMSource source, String filename) {
// open the output stream where XML Document will be saved
File xmlOutFile = new File(filename);
FileOutputStream fos;
try {
fos = new FileOutputStream(xmlOutFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
}
// Use a Transformer for the purpose of output
Transformer transformer;
TransformerFactory transformerFactory = TransformerFactory.newInstance();
try {
transformer = transformerFactory.newTransformer();
} catch (TransformerConfigurationException e) {
e.printStackTrace();
try {
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return false;
}
// The source is the fits header
// The destination for output
StreamResult result = new StreamResult(fos);
// transform source into result will do a file save
try {
transformer.transform(source, result);
} catch (TransformerException e) {
e.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
Log.error("Fail at closing file." + e);
}
return true;
}
@Override
public void init() {
}
}
|
package org.judal.jdbc.test;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.HashMap;
import java.util.Map;
import javax.jdo.JDOException;
import org.judal.jdbc.JDBCEngine;
import org.judal.jdbc.metadata.SQLFunctions;
import org.judal.metadata.TableDef;
import org.judal.storage.java.ArrayRecord;
import org.judal.storage.java.MapRecord;
import org.judal.storage.query.AbstractQuery;
import org.judal.storage.query.Connective;
import org.judal.storage.query.Expression;
import org.judal.storage.query.Operator;
import org.judal.storage.relational.RelationalDataSource;
import org.judal.storage.relational.RelationalTable;
import org.judal.storage.table.ColumnGroup;
import org.judal.storage.table.IndexableTable;
import org.judal.storage.table.Record;
import org.judal.storage.table.RecordSet;
import org.judal.storage.table.impl.SingleIntColumnRecord;
import org.judal.storage.table.impl.SingleLongColumnRecord;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class TestSQLFunctions extends TestJDBC {
private static Map<String,String> properties;
private static RelationalDataSource dts;
@BeforeClass
public static void init() throws ClassNotFoundException, JDOException, IOException {
properties = new TestJDBC().getTestProperties();
JDBCEngine jdbc = new JDBCEngine();
dts = jdbc.getDataSource(properties);
}
@AfterClass
public static void destroy() {
dts.close();
}
@Test
public void test01() throws JDOException, UnsupportedOperationException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
HashMap<String,Object> tableProperties = new HashMap<>();
TableDef tdef = dts.createTableDef("test_sql_funcs", tableProperties);
tdef.addPrimaryKeyColumn("", "pk", Types.INTEGER);
tdef.addColumnMetadata("", "dt", Types.TIMESTAMP, 8, true);
tdef.addColumnMetadata("", "name", Types.VARCHAR, 100, true);
tdef.addColumnMetadata("", "desc", Types.VARCHAR, 2000, true);
dts.createTable(tdef, tableProperties);
MapRecord rec = new MapRecord(tdef);
SQLFunctions fn = new SQLFunctions(dts.getRdbmsId());
try (IndexableTable tbl = dts.openIndexedTable(rec)) {
rec.put("pk", 1);
rec.put("dt", new Timestamp(System.currentTimeMillis()));
rec.put("name", "Name of
rec.put("desc", "Description of
tbl.store(rec);
rec.clear();
rec.put("pk", 2);
rec.put("dt", new Timestamp(System.currentTimeMillis()));
rec.put("name", "The Name of
rec.put("desc", "Description of
tbl.store(rec);
rec.clear();
rec.put("pk", 3);
rec.put("dt", new Timestamp(System.currentTimeMillis()));
rec.put("name", "The Name of
tbl.store(rec);
rec.clear();
rec.put("pk", 4);
rec.put("dt", new Timestamp(System.currentTimeMillis()));
rec.put("name", "The Name of
tbl.store(rec);
rec.clear();
RecordSet<MapRecord> rst = tbl.fetch(new ColumnGroup(fn.LENGTH+"(name) AS NameLength"), "pk", new Integer(1));
assertEquals(1, rst.size());
assertEquals(10, rst.get(0).getInt("NameLength"));
}
SingleLongColumnRecord sir = new SingleLongColumnRecord("test_sql_funcs", "RecCount");
try (RelationalTable tbl = dts.openRelationalTable(sir)) {
AbstractQuery qry = tbl.newQuery();
qry.setResult("COUNT(*) AS RecCount");
qry.setResultClass(SingleLongColumnRecord.class);
qry.setFilter(qry.newPredicate(Connective.AND).add("desc", Operator.ISNULL));
RecordSet<SingleLongColumnRecord> ast = tbl.fetch(qry);
assertEquals(2, ast.get(0).getValue().intValue());
qry.setFilter(qry.newPredicate(Connective.AND).add(fn.ISNULL+"(desc,'Description of #1')", Operator.EQ, "Description of #1"));
ast = tbl.fetch(qry);
assertEquals(3, ast.get(0).getValue().intValue());
}
dts.dropTable("test_sql_funcs", false);
}
}
|
package jodd.upload;
/**
* {@link FileUpload} factory for handling uploaded files. Implementations may
* handle uploaded files differently: to store them to memory, directly to disk
* or something else.
*/
public interface FileUploadFactory {
/**
* Creates new instance of {@link FileUpload uploaded file}.
*/
FileUpload create(MultipartRequestInputStream input);
}
|
// -*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
// @homepage@
package example;
import java.awt.*;
import java.awt.event.HierarchyEvent;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
public final class MainPanel extends JPanel {
private final String[] columnNames = {"No.", "Name", "Progress", ""};
private final DefaultTableModel model = new DefaultTableModel(null, columnNames);
private final JTable table = new JTable(model) {
@Override public void updateUI() {
super.updateUI();
removeColumn(getColumnModel().getColumn(3));
JProgressBar progress = new JProgressBar();
TableCellRenderer renderer = new DefaultTableCellRenderer();
TableColumn tc = getColumnModel().getColumn(2);
tc.setCellRenderer((tbl, value, isSelected, hasFocus, row, column) -> {
Integer i = (Integer) value;
String text = "Done";
if (i < 0) {
text = "Canceled";
} else if (i < progress.getMaximum()) { // < 100
progress.setValue(i);
progress.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
return progress;
}
return renderer.getTableCellRendererComponent(tbl, text, isSelected, hasFocus, row, column);
});
}
};
// TEST: public final ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
// TEST: public final Executor executor = Executors.newFixedThreadPool(2);
private final Set<Integer> deletedRowSet = new TreeSet<>();
// private final Map<Integer, SwingWorker<Integer, Integer>> workerMap = new ConcurrentHashMap<>();
private int number;
private MainPanel() {
super(new BorderLayout());
table.setRowSorter(new TableRowSorter<>(model));
addProgressValue("Name 1", 100, null);
ExecutorService executor = Executors.newSingleThreadExecutor();
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.getViewport().setBackground(Color.WHITE);
table.setComponentPopupMenu(new TablePopupMenu(executor));
table.setFillsViewportHeight(true);
table.setIntercellSpacing(new Dimension());
table.setShowGrid(false);
table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
TableColumn column = table.getColumnModel().getColumn(0);
column.setMaxWidth(60);
column.setMinWidth(60);
column.setResizable(false);
addHierarchyListener(e -> {
if ((e.getChangeFlags() & HierarchyEvent.DISPLAYABILITY_CHANGED) != 0 && !e.getComponent().isDisplayable()) {
executor.shutdownNow();
}
});
JButton button = new JButton("add");
button.addActionListener(e -> addActionPerformed(executor));
add(button, BorderLayout.SOUTH);
add(scrollPane);
setPreferredSize(new Dimension(320, 240));
}
public void addProgressValue(String name, Integer iv, SwingWorker<?, ?> worker) {
Object[] obj = {number, name, iv, worker};
model.addRow(obj);
number++;
}
public void addActionPerformed(ExecutorService executor) {
int key = model.getRowCount();
SwingWorker<Integer, Integer> worker = new BackgroundTask() {
@Override protected void process(List<Integer> c) {
if (isCancelled()) {
return;
}
if (!isDisplayable()) {
System.out.println("process: DISPOSE_ON_CLOSE");
cancel(true);
executor.shutdown();
return;
}
c.forEach(v -> model.setValueAt(v, key, 2));
}
@Override protected void done() {
if (!isDisplayable()) {
System.out.println("done: DISPOSE_ON_CLOSE");
cancel(true);
executor.shutdown();
return;
}
String text;
int i = -1;
if (isCancelled()) {
text = "Cancelled";
} else {
try {
i = get();
text = i >= 0 ? "Done" : "Disposed";
} catch (InterruptedException | ExecutionException ex) {
text = ex.getMessage();
Thread.currentThread().interrupt();
}
}
System.out.format("%s:%s(%dms)%n", key, text, i);
// executor.remove(this);
}
};
addProgressValue("example", 0, worker);
executor.execute(worker);
}
private class TablePopupMenu extends JPopupMenu {
private final JMenuItem cancelMenuItem;
private final JMenuItem deleteMenuItem;
protected TablePopupMenu(ExecutorService executor) {
super();
add("add").addActionListener(e -> addActionPerformed(executor));
addSeparator();
cancelMenuItem = add("cancel");
cancelMenuItem.addActionListener(e -> cancelActionPerformed());
deleteMenuItem = add("delete");
deleteMenuItem.addActionListener(e -> deleteActionPerformed());
}
@Override public void show(Component c, int x, int y) {
if (c instanceof JTable) {
boolean flag = ((JTable) c).getSelectedRowCount() > 0;
cancelMenuItem.setEnabled(flag);
deleteMenuItem.setEnabled(flag);
super.show(c, x, y);
}
}
private SwingWorker<?, ?> getSwingWorker(int identifier) {
// Integer key = (Integer) model.getValueAt(identifier, 0);
// return workerMap.get(key);
return (SwingWorker<?, ?>) model.getValueAt(identifier, 3);
}
private void deleteActionPerformed() {
int[] selection = table.getSelectedRows();
if (selection.length == 0) {
return;
}
for (int i: selection) {
int mi = table.convertRowIndexToModel(i);
deletedRowSet.add(mi);
SwingWorker<?, ?> worker = getSwingWorker(mi);
if (Objects.nonNull(worker) && !worker.isDone()) {
worker.cancel(true);
// executor.remove(worker);
}
// worker = null;
}
RowSorter<? extends TableModel> sorter = table.getRowSorter();
((TableRowSorter<? extends TableModel>) sorter).setRowFilter(new RowFilter<TableModel, Integer>() {
@Override public boolean include(Entry<? extends TableModel, ? extends Integer> entry) {
return !deletedRowSet.contains(entry.getIdentifier());
}
});
table.clearSelection();
table.repaint();
}
private void cancelActionPerformed() {
int[] selection = table.getSelectedRows();
for (int i: selection) {
int mi = table.convertRowIndexToModel(i);
SwingWorker<?, ?> worker = getSwingWorker(mi);
if (Objects.nonNull(worker) && !worker.isDone()) {
worker.cancel(true);
}
// worker = null;
}
table.repaint();
}
}
public static void main(String[] args) {
EventQueue.invokeLater(MainPanel::createAndShowGui);
}
private static void createAndShowGui() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
Toolkit.getDefaultToolkit().beep();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
// frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class BackgroundTask extends SwingWorker<Integer, Integer> {
private final int sleepDummy = new Random().nextInt(50) + 1;
@Override protected Integer doInBackground() throws InterruptedException {
int lengthOfTask = 120;
int current = 0;
while (current <= lengthOfTask && !isCancelled()) {
publish(100 * current / lengthOfTask);
Thread.sleep(sleepDummy);
current++;
}
return sleepDummy * lengthOfTask;
}
}
|
package org.batfish.main;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.nio.file.DirectoryStream;
import java.nio.file.FileVisitOption;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiFunction;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.SystemUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.batfish.bdp.BdpDataPlanePlugin;
import org.batfish.bgp.JsonExternalBgpAdvertisementPlugin;
import org.batfish.common.Answerer;
import org.batfish.common.BatfishException;
import org.batfish.common.BatfishLogger;
import org.batfish.common.BfConsts;
import org.batfish.common.CleanBatfishException;
import org.batfish.common.Directory;
import org.batfish.common.Pair;
import org.batfish.common.Version;
import org.batfish.common.Warning;
import org.batfish.common.Warnings;
import org.batfish.common.plugin.BgpTablePlugin;
import org.batfish.common.plugin.DataPlanePlugin;
import org.batfish.common.plugin.ExternalBgpAdvertisementPlugin;
import org.batfish.common.plugin.IBatfish;
import org.batfish.common.plugin.PluginClientType;
import org.batfish.common.plugin.PluginConsumer;
import org.batfish.common.util.BatfishObjectMapper;
import org.batfish.common.util.CommonUtil;
import org.batfish.config.Settings;
import org.batfish.config.Settings.EnvironmentSettings;
import org.batfish.config.Settings.TestrigSettings;
import org.batfish.datamodel.AbstractRoute;
import org.batfish.datamodel.BgpAdvertisement;
import org.batfish.datamodel.BgpAdvertisement.BgpAdvertisementType;
import org.batfish.datamodel.BgpNeighbor;
import org.batfish.datamodel.BgpProcess;
import org.batfish.datamodel.Configuration;
import org.batfish.datamodel.ConfigurationFormat;
import org.batfish.datamodel.DataPlane;
import org.batfish.datamodel.Edge;
import org.batfish.datamodel.Flow;
import org.batfish.datamodel.FlowHistory;
import org.batfish.datamodel.FlowTrace;
import org.batfish.datamodel.ForwardingAction;
import org.batfish.datamodel.GenericConfigObject;
import org.batfish.datamodel.HeaderSpace;
import org.batfish.datamodel.Interface;
import org.batfish.datamodel.InterfaceType;
import org.batfish.datamodel.Ip;
import org.batfish.datamodel.IpAccessList;
import org.batfish.datamodel.IpAccessListLine;
import org.batfish.datamodel.IpsecVpn;
import org.batfish.datamodel.OspfArea;
import org.batfish.datamodel.OspfNeighbor;
import org.batfish.datamodel.OspfProcess;
import org.batfish.datamodel.Prefix;
import org.batfish.datamodel.Route;
import org.batfish.datamodel.SubRange;
import org.batfish.datamodel.Topology;
import org.batfish.datamodel.Vrf;
import org.batfish.datamodel.VrrpGroup;
import org.batfish.datamodel.answers.AclLinesAnswerElement;
import org.batfish.datamodel.answers.AclLinesAnswerElement.AclReachabilityEntry;
import org.batfish.datamodel.answers.Answer;
import org.batfish.datamodel.answers.AnswerElement;
import org.batfish.datamodel.answers.AnswerStatus;
import org.batfish.datamodel.answers.ConvertConfigurationAnswerElement;
import org.batfish.datamodel.answers.DataPlaneAnswerElement;
import org.batfish.datamodel.answers.EnvironmentCreationAnswerElement;
import org.batfish.datamodel.answers.FlattenVendorConfigurationAnswerElement;
import org.batfish.datamodel.answers.InitInfoAnswerElement;
import org.batfish.datamodel.answers.NodAnswerElement;
import org.batfish.datamodel.answers.NodFirstUnsatAnswerElement;
import org.batfish.datamodel.answers.NodSatAnswerElement;
import org.batfish.datamodel.answers.ParseEnvironmentBgpTablesAnswerElement;
import org.batfish.datamodel.answers.ParseEnvironmentRoutingTablesAnswerElement;
import org.batfish.datamodel.answers.ParseStatus;
import org.batfish.datamodel.answers.ParseVendorConfigurationAnswerElement;
import org.batfish.datamodel.answers.ReportAnswerElement;
import org.batfish.datamodel.answers.RunAnalysisAnswerElement;
import org.batfish.datamodel.answers.StringAnswerElement;
import org.batfish.datamodel.assertion.AssertionAst;
import org.batfish.datamodel.collections.AdvertisementSet;
import org.batfish.datamodel.collections.BgpAdvertisementsByVrf;
import org.batfish.datamodel.collections.EdgeSet;
import org.batfish.datamodel.collections.InterfaceSet;
import org.batfish.datamodel.collections.MultiSet;
import org.batfish.datamodel.collections.NamedStructureEquivalenceSet;
import org.batfish.datamodel.collections.NamedStructureEquivalenceSets;
import org.batfish.datamodel.collections.NodeInterfacePair;
import org.batfish.datamodel.collections.NodeRoleMap;
import org.batfish.datamodel.collections.NodeSet;
import org.batfish.datamodel.collections.NodeVrfSet;
import org.batfish.datamodel.collections.RoleSet;
import org.batfish.datamodel.collections.RoutesByVrf;
import org.batfish.datamodel.collections.TreeMultiSet;
import org.batfish.datamodel.questions.Question;
import org.batfish.datamodel.questions.Question.InstanceData;
import org.batfish.datamodel.questions.Question.InstanceData.Variable;
import org.batfish.grammar.BatfishCombinedParser;
import org.batfish.grammar.BgpTableFormat;
import org.batfish.grammar.GrammarSettings;
import org.batfish.grammar.ParseTreePrettyPrinter;
import org.batfish.grammar.assertion.AssertionCombinedParser;
import org.batfish.grammar.assertion.AssertionExtractor;
import org.batfish.grammar.assertion.AssertionParser.AssertionContext;
import org.batfish.grammar.juniper.JuniperCombinedParser;
import org.batfish.grammar.juniper.JuniperFlattener;
import org.batfish.grammar.topology.BatfishTopologyCombinedParser;
import org.batfish.grammar.topology.BatfishTopologyExtractor;
import org.batfish.grammar.topology.GNS3TopologyCombinedParser;
import org.batfish.grammar.topology.GNS3TopologyExtractor;
import org.batfish.grammar.topology.RoleCombinedParser;
import org.batfish.grammar.topology.RoleExtractor;
import org.batfish.grammar.topology.TopologyExtractor;
import org.batfish.grammar.vyos.VyosCombinedParser;
import org.batfish.grammar.vyos.VyosFlattener;
import org.batfish.job.BatfishJobExecutor;
import org.batfish.job.ConvertConfigurationJob;
import org.batfish.job.ConvertConfigurationResult;
import org.batfish.job.FlattenVendorConfigurationJob;
import org.batfish.job.FlattenVendorConfigurationResult;
import org.batfish.job.ParseEnvironmentBgpTableJob;
import org.batfish.job.ParseEnvironmentBgpTableResult;
import org.batfish.job.ParseEnvironmentRoutingTableJob;
import org.batfish.job.ParseEnvironmentRoutingTableResult;
import org.batfish.job.ParseVendorConfigurationJob;
import org.batfish.job.ParseVendorConfigurationResult;
import org.batfish.representation.aws_vpcs.AwsVpcConfiguration;
import org.batfish.representation.host.HostConfiguration;
import org.batfish.representation.iptables.IptablesVendorConfiguration;
import org.batfish.vendor.VendorConfiguration;
import org.batfish.z3.AclLine;
import org.batfish.z3.AclReachabilityQuerySynthesizer;
import org.batfish.z3.BlacklistDstIpQuerySynthesizer;
import org.batfish.z3.CompositeNodJob;
import org.batfish.z3.EarliestMoreGeneralReachableLineQuerySynthesizer;
import org.batfish.z3.MultipathInconsistencyQuerySynthesizer;
import org.batfish.z3.NodFirstUnsatJob;
import org.batfish.z3.NodFirstUnsatResult;
import org.batfish.z3.NodJob;
import org.batfish.z3.NodJobResult;
import org.batfish.z3.NodSatJob;
import org.batfish.z3.NodSatResult;
import org.batfish.z3.QuerySynthesizer;
import org.batfish.z3.ReachEdgeQuerySynthesizer;
import org.batfish.z3.ReachabilityQuerySynthesizer;
import org.batfish.z3.Synthesizer;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
/**
* This class encapsulates the main control logic for Batfish.
*/
public class Batfish extends PluginConsumer implements AutoCloseable, IBatfish {
private static final String BASE_TESTRIG_TAG = "BASE";
private static final String DELTA_TESTRIG_TAG = "DELTA";
private static final String DIFFERENTIAL_FLOW_TAG = "DIFFERENTIAL";
private static final String GEN_OSPF_STARTING_IP = "10.0.0.0";
/**
* The name of the [optional] topology file within a test-rig
*/
private static final String TOPOLOGY_FILENAME = "topology.net";
public static void applyBaseDir(
TestrigSettings settings, Path containerDir,
String testrig, String envName) {
Path testrigDir = containerDir.resolve(testrig);
settings.setName(testrig);
settings.setBasePath(testrigDir);
EnvironmentSettings envSettings = settings.getEnvironmentSettings();
settings.setSerializeIndependentPath(testrigDir
.resolve(BfConsts.RELPATH_VENDOR_INDEPENDENT_CONFIG_DIR));
settings.setSerializeVendorPath(
testrigDir.resolve(BfConsts.RELPATH_VENDOR_SPECIFIC_CONFIG_DIR));
settings.setTestRigPath(
testrigDir.resolve(BfConsts.RELPATH_TEST_RIG_DIR));
settings.setParseAnswerPath(
testrigDir.resolve(BfConsts.RELPATH_PARSE_ANSWER_PATH));
settings.setConvertAnswerPath(
testrigDir.resolve(BfConsts.RELPATH_CONVERT_ANSWER_PATH));
if (envName != null) {
envSettings.setName(envName);
Path envPath = testrigDir.resolve(BfConsts.RELPATH_ENVIRONMENTS_DIR)
.resolve(envName);
envSettings.setEnvironmentBasePath(envPath);
envSettings.setDataPlanePath(
envPath.resolve(BfConsts.RELPATH_DATA_PLANE));
envSettings.setDataPlaneAnswerPath(
envPath.resolve(BfConsts.RELPATH_DATA_PLANE_ANSWER_PATH));
envSettings.setParseEnvironmentBgpTablesAnswerPath(envPath
.resolve(BfConsts.RELPATH_ENVIRONMENT_BGP_TABLES_ANSWER));
envSettings.setParseEnvironmentRoutingTablesAnswerPath(envPath
.resolve(BfConsts.RELPATH_ENVIRONMENT_ROUTING_TABLES_ANSWER));
envSettings.setSerializeEnvironmentBgpTablesPath(envPath
.resolve(BfConsts.RELPATH_SERIALIZED_ENVIRONMENT_BGP_TABLES));
envSettings
.setSerializeEnvironmentRoutingTablesPath(envPath.resolve(
BfConsts.RELPATH_SERIALIZED_ENVIRONMENT_ROUTING_TABLES));
Path envDirPath = envPath.resolve(BfConsts.RELPATH_ENV_DIR);
envSettings.setEnvPath(envDirPath);
envSettings.setNodeBlacklistPath(
envDirPath.resolve(BfConsts.RELPATH_NODE_BLACKLIST_FILE));
envSettings.setInterfaceBlacklistPath(envDirPath
.resolve(BfConsts.RELPATH_INTERFACE_BLACKLIST_FILE));
envSettings.setEdgeBlacklistPath(
envDirPath.resolve(BfConsts.RELPATH_EDGE_BLACKLIST_FILE));
envSettings.setSerializedTopologyPath(
envDirPath.resolve(BfConsts.RELPATH_TOPOLOGY_FILE));
envSettings.setDeltaConfigurationsDir(
envDirPath.resolve(BfConsts.RELPATH_CONFIGURATIONS_DIR));
envSettings.setExternalBgpAnnouncementsPath(envDirPath
.resolve(BfConsts.RELPATH_EXTERNAL_BGP_ANNOUNCEMENTS));
envSettings.setEnvironmentBgpTablesPath(
envDirPath.resolve(BfConsts.RELPATH_ENVIRONMENT_BGP_TABLES));
envSettings.setEnvironmentRoutingTablesPath(envDirPath
.resolve(BfConsts.RELPATH_ENVIRONMENT_ROUTING_TABLES));
envSettings.setPrecomputedRoutesPath(
envPath.resolve(BfConsts.RELPATH_PRECOMPUTED_ROUTES));
envSettings.setDeltaCompiledConfigurationsDir(envPath
.resolve(BfConsts.RELPATH_VENDOR_INDEPENDENT_CONFIG_DIR));
envSettings.setDeltaVendorConfigurationsDir(
envPath.resolve(BfConsts.RELPATH_VENDOR_SPECIFIC_CONFIG_DIR));
}
}
public static String flatten(
String input, BatfishLogger logger,
Settings settings, ConfigurationFormat format, String header) {
switch (format) {
case JUNIPER: {
JuniperCombinedParser parser = new JuniperCombinedParser(
input,
settings);
ParserRuleContext tree = parse(parser, logger, settings);
JuniperFlattener flattener = new JuniperFlattener(header);
ParseTreeWalker walker = new ParseTreeWalker();
walker.walk(flattener, tree);
return flattener.getFlattenedConfigurationText();
}
case VYOS: {
VyosCombinedParser parser = new VyosCombinedParser(input, settings);
ParserRuleContext tree = parse(parser, logger, settings);
VyosFlattener flattener = new VyosFlattener(header);
ParseTreeWalker walker = new ParseTreeWalker();
walker.walk(flattener, tree);
return flattener.getFlattenedConfigurationText();
}
// $CASES-OMITTED$
default:
throw new BatfishException("Invalid format for flattening");
}
}
public static void initQuestionSettings(Settings settings) {
String questionName = settings.getQuestionName();
Path testrigDir = settings.getActiveTestrigSettings().getBasePath();
if (questionName != null) {
Path questionPath = testrigDir.resolve(BfConsts.RELPATH_QUESTIONS_DIR)
.resolve(questionName);
settings.setQuestionPath(
questionPath.resolve(BfConsts.RELPATH_QUESTION_FILE));
}
}
public static void initTestrigSettings(Settings settings) {
String testrig = settings.getTestrig();
String envName = settings.getEnvironmentName();
String questionName = settings.getQuestionName();
Path containerDir = settings.getContainerDir();
if (testrig != null) {
applyBaseDir(settings.getBaseTestrigSettings(), containerDir, testrig,
envName);
String deltaTestrig = settings.getDeltaTestrig();
String deltaEnvName = settings.getDeltaEnvironmentName();
TestrigSettings deltaTestrigSettings = settings
.getDeltaTestrigSettings();
if (deltaTestrig != null && deltaEnvName == null) {
deltaEnvName = envName;
settings.setDeltaEnvironmentName(envName);
}
else if (deltaTestrig == null && deltaEnvName != null) {
deltaTestrig = testrig;
settings.setDeltaTestrig(testrig);
}
if (deltaTestrig != null) {
applyBaseDir(deltaTestrigSettings, containerDir, deltaTestrig,
deltaEnvName);
}
if (settings.getDiffActive()) {
settings
.setActiveTestrigSettings(settings.getDeltaTestrigSettings());
}
else {
settings
.setActiveTestrigSettings(settings.getBaseTestrigSettings());
}
initQuestionSettings(settings);
}
else if (containerDir != null) {
throw new CleanBatfishException(
"Must supply argument to -" + BfConsts.ARG_TESTRIG);
}
}
/**
* Returns a sorted list of {@link Path paths} contains all files under the
* directory indicated by {@code configsPath}. Directories under
* {@code configsPath} are recursively expanded but not included in the
* returned list.
*
* <p>
* Temporary files(files start with {@code .} are omitted from the returned
* list.
* </p>
*
* <p>
* This method follows all symbolic links.
* </p>
*/
static List<Path> listAllFiles(Path configsPath) {
List<Path> configFilePaths;
try (Stream<Path> allFiles = Files.walk(configsPath, FileVisitOption.FOLLOW_LINKS)) {
configFilePaths = allFiles
.filter(path -> !path.getFileName().toString().startsWith(".")
&& Files.isRegularFile(path))
.sorted().collect(Collectors.toList());
}
catch (IOException e) {
throw new BatfishException("Failed to walk path: " + configsPath, e);
}
return configFilePaths;
}
public static void logWarnings(BatfishLogger logger, Warnings warnings) {
for (Warning warning : warnings.getRedFlagWarnings()) {
logger.redflag(logWarningsHelper(warning));
}
for (Warning warning : warnings.getUnimplementedWarnings()) {
logger.unimplemented(logWarningsHelper(warning));
}
for (Warning warning : warnings.getPedanticWarnings()) {
logger.pedantic(logWarningsHelper(warning));
}
}
private static String logWarningsHelper(Warning warning) {
return " " + warning.getTag() + ": " + warning.getText() + "\n";
}
public static ParserRuleContext parse(
BatfishCombinedParser<?, ?> parser,
BatfishLogger logger, Settings settings) {
ParserRuleContext tree;
try {
tree = parser.parse();
}
catch (BatfishException e) {
throw new ParserBatfishException("Parser error", e);
}
List<String> errors = parser.getErrors();
int numErrors = errors.size();
if (numErrors > 0) {
logger.error(numErrors + " ERROR(S)\n");
for (int i = 0; i < numErrors; i++) {
String prefix = "ERROR " + (i + 1) + ": ";
String msg = errors.get(i);
String prefixedMsg = CommonUtil.applyPrefix(prefix, msg);
logger.error(prefixedMsg + "\n");
}
throw new ParserBatfishException("Parser error(s)");
}
else if (!settings.printParseTree()) {
logger.info("OK\n");
}
else {
logger.info("OK, PRINTING PARSE TREE:\n");
logger.info(ParseTreePrettyPrinter.print(tree, parser) + "\n\n");
}
return tree;
}
private final Map<String, BiFunction<Question, IBatfish, Answerer>> _answererCreators;
private TestrigSettings _baseTestrigSettings;
private SortedMap<BgpTableFormat, BgpTablePlugin> _bgpTablePlugins;
private final Map<TestrigSettings, SortedMap<String, Configuration>> _cachedConfigurations;
private final Map<TestrigSettings, DataPlane> _cachedDataPlanes;
private final Map<EnvironmentSettings, SortedMap<String, BgpAdvertisementsByVrf>>
_cachedEnvironmentBgpTables;
private final Map<EnvironmentSettings, SortedMap<String, RoutesByVrf>>
_cachedEnvironmentRoutingTables;
private DataPlanePlugin _dataPlanePlugin;
private TestrigSettings _deltaTestrigSettings;
private Set<ExternalBgpAdvertisementPlugin> _externalBgpAdvertisementPlugins;
private BatfishLogger _logger;
private Settings _settings;
// this variable is used communicate with parent thread on how the job
// finished
private boolean _terminatedWithException;
private TestrigSettings _testrigSettings;
private final List<TestrigSettings> _testrigSettingsStack;
private long _timerCount;
public Batfish(
Settings settings,
Map<TestrigSettings, SortedMap<String, Configuration>> cachedConfigurations,
Map<TestrigSettings, DataPlane> cachedDataPlanes,
Map<EnvironmentSettings, SortedMap<String, BgpAdvertisementsByVrf>> cachedEnvironmentBgpTables,
Map<EnvironmentSettings, SortedMap<String, RoutesByVrf>> cachedEnvironmentRoutingTables) {
super(settings.getSerializeToText(), settings.getPluginDirs());
_settings = settings;
_bgpTablePlugins = new TreeMap<>();
_cachedConfigurations = cachedConfigurations;
_cachedEnvironmentBgpTables = cachedEnvironmentBgpTables;
_cachedEnvironmentRoutingTables = cachedEnvironmentRoutingTables;
_cachedDataPlanes = cachedDataPlanes;
_externalBgpAdvertisementPlugins = new TreeSet<>();
_testrigSettings = settings.getActiveTestrigSettings();
_baseTestrigSettings = settings.getBaseTestrigSettings();
_deltaTestrigSettings = settings.getDeltaTestrigSettings();
_logger = _settings.getLogger();
_terminatedWithException = false;
_answererCreators = new HashMap<>();
_testrigSettingsStack = new ArrayList<>();
}
private Answer analyze() {
Answer answer = new Answer();
String analysisName = _settings.getAnalysisName();
Path analysisQuestionsDir = _settings.getContainerDir()
.resolve(Paths.get(BfConsts.RELPATH_ANALYSES_DIR, analysisName,
BfConsts.RELPATH_QUESTIONS_DIR).toString());
if (!Files.exists(analysisQuestionsDir)) {
throw new BatfishException("Analysis questions dir does not exist: '"
+ analysisQuestionsDir.toString() + "'");
}
RunAnalysisAnswerElement ae = new RunAnalysisAnswerElement();
try (Stream<Path> questions = CommonUtil.list(analysisQuestionsDir)) {
questions.forEach(analysisQuestionDir -> {
String questionName = analysisQuestionDir.getFileName().toString();
Path analysisQuestionPath = analysisQuestionDir
.resolve(BfConsts.RELPATH_QUESTION_FILE);
_settings.setQuestionPath(analysisQuestionPath);
Answer currentAnswer = answer();
initAnalysisQuestionPath(analysisName, questionName);
outputAnswer(currentAnswer);
ae.getAnswers().put(questionName, currentAnswer);
});
}
answer.addAnswerElement(ae);
return answer;
}
private void anonymizeConfigurations() {
// TODO Auto-generated method stub
}
private Answer answer() {
Question question = parseQuestion();
if (_settings.getDifferential()) {
question.setDifferential(true);
}
boolean dp = question.getDataPlane();
boolean diff = question.getDifferential();
boolean diffActive = _settings.getDiffActive() && !diff;
_settings.setDiffActive(diffActive);
_settings.setDiffQuestion(diff);
initQuestionEnvironments(question, diff, diffActive, dp);
AnswerElement answerElement = null;
BatfishException exception = null;
try {
if (question.getDifferential() == true) {
answerElement = Answerer.create(question, this).answerDiff();
}
else {
answerElement = Answerer.create(question, this).answer();
}
}
catch (Exception e) {
exception = new BatfishException("Failed to answer question", e);
}
Answer answer = new Answer();
answer.setQuestion(question);
if (exception == null) {
// success
answer.setStatus(AnswerStatus.SUCCESS);
answer.addAnswerElement(answerElement);
}
else {
// failure
answer.setStatus(AnswerStatus.FAILURE);
answer.addAnswerElement(exception.getBatfishStackTrace());
}
return answer;
}
@Override
public AnswerElement answerAclReachability(
String aclNameRegexStr,
NamedStructureEquivalenceSets<?> aclEqSets) {
if (SystemUtils.IS_OS_MAC_OSX) {
// TODO: remove when z3 parallelism bug on OSX is fixed
_settings.setSequential(true);
}
AclLinesAnswerElement answerElement = new AclLinesAnswerElement();
Pattern aclNameRegex;
try {
aclNameRegex = Pattern.compile(aclNameRegexStr);
}
catch (PatternSyntaxException e) {
throw new BatfishException(
"Supplied regex for nodes is not a valid java regex: \""
+ aclNameRegexStr + "\"",
e);
}
checkConfigurations();
Map<String, Configuration> configurations = loadConfigurations();
List<NodSatJob<AclLine>> jobs = new ArrayList<>();
for (Entry<String, ?> e : aclEqSets.getSameNamedStructures().entrySet()) {
String aclName = e.getKey();
if (!aclNameRegex.matcher(aclName).matches()) {
continue;
}
// skip juniper srx inbound filters, as they can't really contain
// operator error
if (aclName.contains("~ZONE_INTERFACE_FILTER~")
|| aclName.contains("~INBOUND_ZONE_FILTER~")) {
continue;
}
SortedSet<?> s = (SortedSet<?>) e.getValue();
for (Object o : s) {
NamedStructureEquivalenceSet<?> aclEqSet = (NamedStructureEquivalenceSet<?>) o;
String hostname = aclEqSet.getRepresentativeElement();
SortedSet<String> eqClassNodes = aclEqSet.getNodes();
answerElement.addEquivalenceClass(aclName, hostname, eqClassNodes);
Configuration c = configurations.get(hostname);
IpAccessList acl = c.getIpAccessLists().get(aclName);
int numLines = acl.getLines().size();
if (numLines == 0) {
_logger.redflag("RED_FLAG: Acl \"" + hostname + ":" + aclName
+ "\" contains no lines\n");
continue;
}
AclReachabilityQuerySynthesizer query = new AclReachabilityQuerySynthesizer(
hostname, aclName, numLines);
Synthesizer aclSynthesizer = synthesizeAcls(
Collections.singletonMap(hostname, c));
NodSatJob<AclLine> job = new NodSatJob<>(_settings, aclSynthesizer,
query);
jobs.add(job);
}
}
Map<AclLine, Boolean> output = new TreeMap<>();
computeNodSatOutput(jobs, output);
// rearrange output for next step
Map<String, Map<String, List<AclLine>>> arrangedAclLines = new TreeMap<>();
for (Entry<AclLine, Boolean> e : output.entrySet()) {
AclLine line = e.getKey();
String hostname = line.getHostname();
Map<String, List<AclLine>> byAclName =
arrangedAclLines.computeIfAbsent(hostname, k -> new TreeMap<>());
String aclName = line.getAclName();
List<AclLine> aclLines = byAclName.computeIfAbsent(aclName, k -> new ArrayList<>());
aclLines.add(line);
}
// now get earliest more general lines
List<NodFirstUnsatJob<AclLine, Integer>> step2Jobs = new ArrayList<>();
for (Entry<String, Map<String, List<AclLine>>> e : arrangedAclLines
.entrySet()) {
String hostname = e.getKey();
Configuration c = configurations.get(hostname);
Synthesizer aclSynthesizer = synthesizeAcls(
Collections.singletonMap(hostname, c));
Map<String, List<AclLine>> byAclName = e.getValue();
for (Entry<String, List<AclLine>> e2 : byAclName.entrySet()) {
String aclName = e2.getKey();
IpAccessList ipAccessList = c.getIpAccessLists().get(aclName);
List<AclLine> lines = e2.getValue();
for (int i = 0; i < lines.size(); i++) {
AclLine line = lines.get(i);
boolean reachable = output.get(line);
if (!reachable) {
List<AclLine> toCheck = new ArrayList<>();
for (int j = 0; j < i; j++) {
AclLine earlierLine = lines.get(j);
boolean earlierIsReachable = output.get(earlierLine);
if (earlierIsReachable) {
toCheck.add(earlierLine);
}
}
EarliestMoreGeneralReachableLineQuerySynthesizer query =
new EarliestMoreGeneralReachableLineQuerySynthesizer(
line, toCheck, ipAccessList);
NodFirstUnsatJob<AclLine, Integer> job = new NodFirstUnsatJob<>(
_settings, aclSynthesizer, query);
step2Jobs.add(job);
}
}
}
}
Map<AclLine, Integer> step2Output = new TreeMap<>();
computeNodFirstUnsatOutput(step2Jobs, step2Output);
for (AclLine line : output.keySet()) {
Integer earliestMoreGeneralReachableLine = step2Output.get(line);
line.setEarliestMoreGeneralReachableLine(
earliestMoreGeneralReachableLine);
}
Set<Pair<String, String>> aclsWithUnreachableLines = new TreeSet<>();
Set<Pair<String, String>> allAcls = new TreeSet<>();
int numUnreachableLines = 0;
int numLines = output.entrySet().size();
for (Entry<AclLine, Boolean> e : output.entrySet()) {
AclLine aclLine = e.getKey();
boolean sat = e.getValue();
String hostname = aclLine.getHostname();
String aclName = aclLine.getAclName();
Pair<String, String> qualifiedAclName = new Pair<>(hostname, aclName);
allAcls.add(qualifiedAclName);
if (!sat) {
numUnreachableLines++;
aclsWithUnreachableLines.add(qualifiedAclName);
}
}
for (Entry<AclLine, Boolean> e : output.entrySet()) {
AclLine aclLine = e.getKey();
int index = aclLine.getLine();
boolean sat = e.getValue();
String hostname = aclLine.getHostname();
String aclName = aclLine.getAclName();
Pair<String, String> qualifiedAclName = new Pair<>(hostname, aclName);
IpAccessList ipAccessList = configurations.get(hostname)
.getIpAccessLists().get(aclName);
IpAccessListLine ipAccessListLine = ipAccessList.getLines().get(index);
AclReachabilityEntry line = new AclReachabilityEntry(
index,
ipAccessListLine.getName());
if (aclsWithUnreachableLines.contains(qualifiedAclName)) {
if (sat) {
_logger.debugf("%s:%s:%d:'%s' is REACHABLE\n", hostname, aclName,
line.getIndex(), line.getName());
answerElement.addReachableLine(hostname, ipAccessList, line);
}
else {
_logger.debugf("%s:%s:%d:'%s' is UNREACHABLE\n\t%s\n", hostname,
aclName, line.getIndex(), line.getName(),
ipAccessListLine.toString());
Integer earliestMoreGeneralLineIndex = aclLine
.getEarliestMoreGeneralReachableLine();
if (earliestMoreGeneralLineIndex != null) {
IpAccessListLine earliestMoreGeneralLine = ipAccessList
.getLines().get(earliestMoreGeneralLineIndex);
line.setEarliestMoreGeneralLineIndex(
earliestMoreGeneralLineIndex);
line.setEarliestMoreGeneralLineName(
earliestMoreGeneralLine.getName());
if (!earliestMoreGeneralLine.getAction()
.equals(ipAccessListLine.getAction())) {
line.setDifferentAction(true);
}
}
answerElement.addUnreachableLine(hostname, ipAccessList, line);
aclsWithUnreachableLines.add(qualifiedAclName);
}
}
else {
answerElement.addReachableLine(hostname, ipAccessList, line);
}
}
for (Pair<String, String> qualfiedAcl : aclsWithUnreachableLines) {
String hostname = qualfiedAcl.getFirst();
String aclName = qualfiedAcl.getSecond();
_logger.debugf("%s:%s has at least 1 unreachable line\n", hostname,
aclName);
}
int numAclsWithUnreachableLines = aclsWithUnreachableLines.size();
int numAcls = allAcls.size();
double percentUnreachableAcls = 100d * numAclsWithUnreachableLines
/ numAcls;
double percentUnreachableLines = 100d * numUnreachableLines / numLines;
_logger.debugf("SUMMARY:\n");
_logger.debugf("\t%d/%d (%.1f%%) acls have unreachable lines\n",
numAclsWithUnreachableLines, numAcls, percentUnreachableAcls);
_logger.debugf("\t%d/%d (%.1f%%) acl lines are unreachable\n",
numUnreachableLines, numLines, percentUnreachableLines);
return answerElement;
}
private void checkBaseDirExists() {
Path baseDir = _testrigSettings.getBasePath();
if (baseDir == null) {
throw new BatfishException("Test rig directory not set");
}
if (!Files.exists(baseDir)) {
throw new CleanBatfishException("Test rig does not exist: \""
+ baseDir.getFileName().toString() + "\"");
}
}
@Override
public void checkConfigurations() {
checkConfigurations(_testrigSettings);
}
public void checkConfigurations(TestrigSettings testrigSettings) {
Path path = testrigSettings.getSerializeIndependentPath();
if (!Files.exists(path)) {
throw new CleanBatfishException(
"Missing compiled vendor-independent configurations for this test-rig\n");
}
else {
try (Stream<Path> paths = CommonUtil.list(path)) {
if (!paths.iterator().hasNext()) {
throw new CleanBatfishException(
"Nothing to do: Set of vendor-independent configurations for this test-rig is empty\n");
}
}
}
}
@Override
public void checkDataPlane() {
checkDataPlane(_testrigSettings);
}
public void checkDataPlane(TestrigSettings testrigSettings) {
EnvironmentSettings envSettings = testrigSettings
.getEnvironmentSettings();
if (!Files.exists(envSettings.getDataPlanePath())) {
throw new CleanBatfishException(
"Missing data plane for testrig: \"" + testrigSettings.getName()
+ "\", environment: \"" + envSettings.getName() + "\"\n");
}
}
public void checkDiffEnvironmentExists() {
checkDiffEnvironmentSpecified();
checkEnvironmentExists(_deltaTestrigSettings);
}
private void checkDiffEnvironmentSpecified() {
if (_settings.getDeltaEnvironmentName() == null) {
throw new CleanBatfishException(
"No differential environment specified for differential question");
}
}
public void checkDifferentialDataPlaneQuestionDependencies() {
checkDiffEnvironmentSpecified();
checkConfigurations();
checkDataPlane(_baseTestrigSettings);
checkDataPlane(_deltaTestrigSettings);
}
@Override
public void checkEnvironmentExists() {
checkEnvironmentExists(_testrigSettings);
}
public void checkEnvironmentExists(TestrigSettings testrigSettings) {
if (!environmentExists(testrigSettings)) {
throw new CleanBatfishException("Environment not initialized: \""
+ testrigSettings.getEnvironmentSettings().getName() + "\"");
}
}
private void checkQuestionsDirExists() {
checkBaseDirExists();
Path questionsDir = _testrigSettings.getBasePath()
.resolve(BfConsts.RELPATH_QUESTIONS_DIR);
if (!Files.exists(questionsDir)) {
throw new CleanBatfishException("questions dir does not exist: \""
+ questionsDir.getFileName().toString() + "\"");
}
}
@Override
public void close() throws Exception {
}
private Answer compileEnvironmentConfigurations(
TestrigSettings testrigSettings) {
Answer answer = new Answer();
EnvironmentSettings envSettings = testrigSettings
.getEnvironmentSettings();
Path deltaConfigurationsDir = envSettings.getDeltaConfigurationsDir();
Path vendorConfigsDir = envSettings.getDeltaVendorConfigurationsDir();
Path indepConfigsDir = envSettings.getDeltaCompiledConfigurationsDir();
if (deltaConfigurationsDir != null) {
if (Files.exists(deltaConfigurationsDir)) {
answer.append(serializeVendorConfigs(
envSettings.getEnvPath(),
vendorConfigsDir));
answer.append(serializeIndependentConfigs(
vendorConfigsDir,
indepConfigsDir));
}
return answer;
}
else {
throw new BatfishException(
"Delta configurations directory cannot be null");
}
}
public Set<Flow> computeCompositeNodOutput(
List<CompositeNodJob> jobs,
NodAnswerElement answerElement) {
_logger.info("\n*** EXECUTING COMPOSITE NOD JOBS ***\n");
resetTimer();
Set<Flow> flows = new TreeSet<>();
BatfishJobExecutor<CompositeNodJob, NodAnswerElement, NodJobResult, Set<Flow>> executor =
new BatfishJobExecutor<>(
_settings, _logger, true, "Composite NOD");
executor.executeJobs(jobs, flows, answerElement);
printElapsedTime();
return flows;
}
private Answer computeDataPlane(boolean differentialContext) {
checkEnvironmentExists();
return _dataPlanePlugin.computeDataPlane(differentialContext);
}
private void computeEnvironmentBgpTables() {
EnvironmentSettings envSettings = _testrigSettings
.getEnvironmentSettings();
Path outputPath = envSettings.getSerializeEnvironmentBgpTablesPath();
Path inputPath = envSettings.getEnvironmentBgpTablesPath();
serializeEnvironmentBgpTables(inputPath, outputPath);
}
private void computeEnvironmentRoutingTables() {
EnvironmentSettings envSettings = _testrigSettings
.getEnvironmentSettings();
Path outputPath = envSettings.getSerializeEnvironmentRoutingTablesPath();
Path inputPath = envSettings.getEnvironmentRoutingTablesPath();
serializeEnvironmentRoutingTables(inputPath, outputPath);
}
@Override
public InterfaceSet computeFlowSinks(
Map<String, Configuration> configurations, boolean differentialContext,
Topology topology) {
InterfaceSet flowSinks = null;
if (differentialContext) {
pushBaseEnvironment();
flowSinks = loadDataPlane().getFlowSinks();
popEnvironment();
}
NodeSet blacklistNodes = getNodeBlacklist();
if (blacklistNodes != null) {
if (differentialContext) {
flowSinks.removeNodes(blacklistNodes);
}
}
Set<NodeInterfacePair> blacklistInterfaces = getInterfaceBlacklist();
if (blacklistInterfaces != null) {
for (NodeInterfacePair blacklistInterface : blacklistInterfaces) {
if (differentialContext) {
flowSinks.remove(blacklistInterface);
}
}
}
if (!differentialContext) {
flowSinks = computeFlowSinks(configurations, topology);
}
return flowSinks;
}
private InterfaceSet computeFlowSinks(
Map<String, Configuration> configurations, Topology topology) {
// TODO: confirm VRFs are handled correctly
InterfaceSet flowSinks = new InterfaceSet();
InterfaceSet topologyInterfaces = new InterfaceSet();
for (Edge edge : topology.getEdges()) {
topologyInterfaces.add(edge.getInterface1());
topologyInterfaces.add(edge.getInterface2());
}
for (Configuration node : configurations.values()) {
String hostname = node.getHostname();
for (Interface iface : node.getInterfaces().values()) {
String ifaceName = iface.getName();
NodeInterfacePair p = new NodeInterfacePair(hostname, ifaceName);
if (iface.getActive()
&& !iface.isLoopback(node.getConfigurationFormat())
&& !topologyInterfaces.contains(p)) {
flowSinks.add(p);
}
}
}
return flowSinks;
}
@Override
public Map<Ip, Set<String>> computeIpOwners(
Map<String, Configuration> configurations, boolean excludeInactive) {
// TODO: confirm VRFs are handled correctly
Map<Ip, Set<String>> ipOwners = new HashMap<>();
Map<Pair<Prefix, Integer>, Set<Interface>> vrrpGroups = new HashMap<>();
configurations.forEach((hostname, c) -> {
for (Interface i : c.getInterfaces().values()) {
if (i.getActive() || (!excludeInactive && i.getBlacklisted())) {
// collect vrrp info
i.getVrrpGroups().forEach((groupNum, vrrpGroup) -> {
Prefix prefix = vrrpGroup.getVirtualAddress();
Pair<Prefix, Integer> key = new Pair<>(prefix, groupNum);
Set<Interface> candidates =
vrrpGroups.computeIfAbsent(
key, k -> Collections.newSetFromMap(new IdentityHashMap<>()));
candidates.add(i);
});
// collect prefixes
i.getAllPrefixes().stream().map(p -> p.getAddress())
.forEach(ip -> {
Set<String> owners = ipOwners.computeIfAbsent(ip, k -> new HashSet<>());
owners.add(hostname);
});
}
}
});
vrrpGroups.forEach((p, candidates) -> {
int groupNum = p.getSecond();
Prefix prefix = p.getFirst();
Ip ip = prefix.getAddress();
int lowestPriority = Integer.MAX_VALUE;
String bestCandidate = null;
Set<String> bestCandidates = new HashSet<>();
for (Interface candidate : candidates) {
VrrpGroup group = candidate.getVrrpGroups().get(groupNum);
int currentPriority = group.getPriority();
if (currentPriority < lowestPriority) {
lowestPriority = currentPriority;
bestCandidates.clear();
bestCandidate = candidate.getOwner().getHostname();
}
if (currentPriority == lowestPriority) {
bestCandidates.add(candidate.getOwner().getHostname());
}
}
if (bestCandidates.size() != 1) {
throw new BatfishException(
"multiple best vrrp candidates:" + bestCandidates);
}
Set<String> owners = ipOwners.computeIfAbsent(ip, k -> new HashSet<>());
owners.add(bestCandidate);
});
return ipOwners;
}
@Override
public Map<Ip, String> computeIpOwnersSimple(Map<Ip, Set<String>> ipOwners) {
Map<Ip, String> ipOwnersSimple = new HashMap<>();
ipOwners.forEach((ip, owners) -> {
String hostname = owners.size() == 1 ? owners.iterator().next()
: Route.AMBIGUOUS_NEXT_HOP;
ipOwnersSimple.put(ip, hostname);
});
return ipOwnersSimple;
}
public <Key, Result> void computeNodFirstUnsatOutput(
List<NodFirstUnsatJob<Key, Result>> jobs, Map<Key, Result> output) {
_logger.info("\n*** EXECUTING NOD UNSAT JOBS ***\n");
resetTimer();
BatfishJobExecutor<NodFirstUnsatJob<Key, Result>, NodFirstUnsatAnswerElement, NodFirstUnsatResult<Key, Result>, Map<Key, Result>>
executor = new BatfishJobExecutor<>(
_settings, _logger, true, "NOD First-UNSAT");
executor.executeJobs(jobs, output, new NodFirstUnsatAnswerElement());
printElapsedTime();
}
public Set<Flow> computeNodOutput(List<NodJob> jobs) {
_logger.info("\n*** EXECUTING NOD JOBS ***\n");
resetTimer();
Set<Flow> flows = new TreeSet<>();
BatfishJobExecutor<NodJob, NodAnswerElement, NodJobResult, Set<Flow>> executor =
new BatfishJobExecutor<>(
_settings, _logger, true, "NOD");
// todo: do something with nod answer element
executor.executeJobs(jobs, flows, new NodAnswerElement());
printElapsedTime();
return flows;
}
public <Key> void computeNodSatOutput(
List<NodSatJob<Key>> jobs,
Map<Key, Boolean> output) {
_logger.info("\n*** EXECUTING NOD SAT JOBS ***\n");
resetTimer();
BatfishJobExecutor<NodSatJob<Key>, NodSatAnswerElement, NodSatResult<Key>, Map<Key, Boolean>>
executor = new BatfishJobExecutor<>(
_settings, _logger, true, "NOD SAT");
executor.executeJobs(jobs, output, new NodSatAnswerElement());
printElapsedTime();
}
@Override
public Topology computeTopology(Map<String, Configuration> configurations) {
resetTimer();
Topology topology = computeTopology(
_testrigSettings.getTestRigPath(),
configurations);
EdgeSet blacklistEdges = getEdgeBlacklist();
if (blacklistEdges != null) {
EdgeSet edges = topology.getEdges();
edges.removeAll(blacklistEdges);
if (blacklistEdges.size() > 0) {
}
}
NodeSet blacklistNodes = getNodeBlacklist();
if (blacklistNodes != null) {
for (String blacklistNode : blacklistNodes) {
topology.removeNode(blacklistNode);
}
}
Set<NodeInterfacePair> blacklistInterfaces = getInterfaceBlacklist();
if (blacklistInterfaces != null) {
for (NodeInterfacePair blacklistInterface : blacklistInterfaces) {
topology.removeInterface(blacklistInterface);
}
}
Topology prunedTopology = new Topology(topology.getEdges());
printElapsedTime();
return prunedTopology;
}
private Topology computeTopology(
Path testRigPath,
Map<String, Configuration> configurations) {
Path topologyFilePath = testRigPath.resolve(TOPOLOGY_FILENAME);
Topology topology;
// Get generated facts from topology file
if (Files.exists(topologyFilePath)) {
topology = processTopologyFile(topologyFilePath);
}
else {
// guess adjacencies based on interface subnetworks
_logger.info(
"*** (GUESSING TOPOLOGY IN ABSENCE OF EXPLICIT FILE) ***\n");
topology = synthesizeTopology(configurations);
}
return topology;
}
private Map<String, Configuration> convertConfigurations(
Map<String, GenericConfigObject> vendorConfigurations,
ConvertConfigurationAnswerElement answerElement) {
_logger.info(
"\n*** CONVERTING VENDOR CONFIGURATIONS TO INDEPENDENT FORMAT ***\n");
resetTimer();
Map<String, Configuration> configurations = new TreeMap<>();
List<ConvertConfigurationJob> jobs = new ArrayList<>();
for (String hostname : vendorConfigurations.keySet()) {
Warnings warnings = new Warnings(
_settings.getPedanticAsError(),
_settings.getPedanticRecord()
&& _logger.isActive(BatfishLogger.LEVEL_PEDANTIC),
_settings.getRedFlagAsError(),
_settings.getRedFlagRecord()
&& _logger.isActive(BatfishLogger.LEVEL_REDFLAG),
_settings.getUnimplementedAsError(),
_settings.getUnimplementedRecord()
&& _logger.isActive(BatfishLogger.LEVEL_UNIMPLEMENTED),
_settings.printParseTree());
GenericConfigObject vc = vendorConfigurations.get(hostname);
ConvertConfigurationJob job = new ConvertConfigurationJob(_settings,
vc, hostname, warnings);
jobs.add(job);
}
BatfishJobExecutor<ConvertConfigurationJob, ConvertConfigurationAnswerElement, ConvertConfigurationResult, Map<String, Configuration>>
executor = new BatfishJobExecutor<>(
_settings, _logger, _settings.getHaltOnConvertError(),
"Convert configurations to vendor-independent format");
executor.executeJobs(jobs, configurations, answerElement);
printElapsedTime();
return configurations;
}
@Override
public EnvironmentCreationAnswerElement createEnvironment(
String newEnvName,
SortedSet<String> nodeBlacklist,
SortedSet<NodeInterfacePair> interfaceBlacklist,
SortedSet<Edge> edgeBlacklist, boolean dp) {
EnvironmentCreationAnswerElement answerElement = new EnvironmentCreationAnswerElement();
EnvironmentSettings envSettings = _testrigSettings
.getEnvironmentSettings();
String oldEnvName = envSettings.getName();
if (oldEnvName.equals(newEnvName)) {
throw new BatfishException(
"Cannot create new environment: name of environment is same as that of old");
}
answerElement.setNewEnvironmentName(newEnvName);
answerElement.setOldEnvironmentName(oldEnvName);
Path oldEnvPath = envSettings.getEnvPath();
applyBaseDir(_testrigSettings, _settings.getContainerDir(),
_testrigSettings.getName(), newEnvName
);
EnvironmentSettings newEnvSettings = _testrigSettings
.getEnvironmentSettings();
Path newEnvPath = newEnvSettings.getEnvPath();
if (Files.exists(newEnvPath)) {
throw new BatfishException("Cannot create new environment '"
+ newEnvName + "': environment with same name already exists");
}
newEnvPath.toFile().mkdirs();
try {
FileUtils.copyDirectory(oldEnvPath.toFile(), newEnvPath.toFile());
}
catch (IOException e) {
throw new BatfishException(
"Failed to intialize new environment from old environment", e);
}
// write node blacklist from question
String nodeBlacklistStr;
if (nodeBlacklist != null && !nodeBlacklist.isEmpty()) {
try {
nodeBlacklistStr = new BatfishObjectMapper()
.writeValueAsString(nodeBlacklist);
}
catch (JsonProcessingException e) {
throw new BatfishException("Could not serialize node blacklist", e);
}
CommonUtil.writeFile(
newEnvSettings.getNodeBlacklistPath(),
nodeBlacklistStr);
}
// write interface blacklist from question
if (interfaceBlacklist != null && !interfaceBlacklist.isEmpty()) {
String interfaceBlacklistStr;
try {
interfaceBlacklistStr = new BatfishObjectMapper()
.writeValueAsString(interfaceBlacklist);
}
catch (JsonProcessingException e) {
throw new BatfishException(
"Could not serialize interface blacklist", e);
}
CommonUtil.writeFile(
newEnvSettings.getInterfaceBlacklistPath(),
interfaceBlacklistStr);
}
// write edge blacklist from question
if (edgeBlacklist != null) {
String edgeBlacklistStr;
try {
edgeBlacklistStr = new BatfishObjectMapper()
.writeValueAsString(edgeBlacklist);
}
catch (JsonProcessingException e) {
throw new BatfishException("Could not serialize edge blacklist", e);
}
CommonUtil.writeFile(
newEnvSettings.getEdgeBlacklistPath(),
edgeBlacklistStr);
}
if (dp && !dataPlaneDependenciesExist(_testrigSettings)) {
computeDataPlane(true);
}
return answerElement;
}
private boolean dataPlaneDependenciesExist(TestrigSettings testrigSettings) {
checkConfigurations();
Path dpPath = testrigSettings.getEnvironmentSettings()
.getDataPlaneAnswerPath();
return Files.exists(dpPath);
}
public SortedMap<String, Configuration> deserializeConfigurations(
Path serializedConfigPath) {
_logger.info(
"\n*** DESERIALIZING VENDOR-INDEPENDENT CONFIGURATION STRUCTURES ***\n");
resetTimer();
if (!Files.exists(serializedConfigPath)) {
throw new BatfishException(
"Missing vendor-independent configs directory: '"
+ serializedConfigPath.toString() + "'");
}
Map<Path, String> namesByPath = new TreeMap<>();
try (DirectoryStream<Path> stream = Files
.newDirectoryStream(serializedConfigPath)) {
for (Path serializedConfig : stream) {
String name = serializedConfig.getFileName().toString();
namesByPath.put(serializedConfig, name);
}
}
catch (IOException e) {
throw new BatfishException(
"Error reading vendor-independent configs directory: '"
+ serializedConfigPath.toString() + "'",
e);
}
SortedMap<String, Configuration> configurations = deserializeObjects(
namesByPath, Configuration.class);
printElapsedTime();
return configurations;
}
private SortedMap<String, BgpAdvertisementsByVrf> deserializeEnvironmentBgpTables(
Path serializeEnvironmentBgpTablesPath) {
_logger.info("\n*** DESERIALIZING ENVIRONMENT BGP TABLES ***\n");
resetTimer();
Map<Path, String> namesByPath = new TreeMap<>();
try (DirectoryStream<Path> serializedBgpTables = Files
.newDirectoryStream(serializeEnvironmentBgpTablesPath)) {
for (Path serializedBgpTable : serializedBgpTables) {
String name = serializedBgpTable.getFileName().toString();
namesByPath.put(serializedBgpTable, name);
}
}
catch (IOException e) {
throw new BatfishException(
"Error reading serialized BGP tables directory", e);
}
SortedMap<String, BgpAdvertisementsByVrf> bgpTables = deserializeObjects(
namesByPath, BgpAdvertisementsByVrf.class);
printElapsedTime();
return bgpTables;
}
private SortedMap<String, RoutesByVrf> deserializeEnvironmentRoutingTables(
Path serializeEnvironmentRoutingTablesPath) {
_logger.info("\n*** DESERIALIZING ENVIRONMENT ROUTING TABLES ***\n");
resetTimer();
Map<Path, String> namesByPath = new TreeMap<>();
try (DirectoryStream<Path> serializedRoutingTables = Files
.newDirectoryStream(serializeEnvironmentRoutingTablesPath)) {
for (Path serializedRoutingTable : serializedRoutingTables) {
String name = serializedRoutingTable.getFileName().toString();
namesByPath.put(serializedRoutingTable, name);
}
}
catch (IOException e) {
throw new BatfishException(
"Error reading serialized routing tables directory", e);
}
SortedMap<String, RoutesByVrf> routingTables = deserializeObjects(
namesByPath, RoutesByVrf.class);
printElapsedTime();
return routingTables;
}
public <S extends Serializable> SortedMap<String, S> deserializeObjects(
Map<Path, String> namesByPath, Class<S> outputClass) {
String outputClassName = outputClass.getName();
BatfishLogger logger = getLogger();
Map<String, byte[]> dataByName = new TreeMap<>();
AtomicInteger readCompleted = newBatch(
"Reading and unpacking files containg '" + outputClassName
+ "' instances",
namesByPath.size());
namesByPath.forEach((inputPath, name) -> {
logger.debug("Reading and gunzipping: " + outputClassName + " '" + name
+ "' from '" + inputPath.toString() + "'");
byte[] data = fromGzipFile(inputPath);
logger.debug(" ...OK\n");
dataByName.put(name, data);
readCompleted.incrementAndGet();
});
Map<String, S> unsortedOutput = new ConcurrentHashMap<>();
AtomicInteger deserializeCompleted = newBatch(
"Deserializing '" + outputClassName + "' instances",
dataByName.size());
dataByName.keySet().parallelStream().forEach(name -> {
byte[] data = dataByName.get(name);
S object = deserializeObject(data, outputClass);
unsortedOutput.put(name, object);
deserializeCompleted.incrementAndGet();
});
SortedMap<String, S> output = new TreeMap<>(unsortedOutput);
return output;
}
public Map<String, GenericConfigObject> deserializeVendorConfigurations(
Path serializedVendorConfigPath) {
_logger.info("\n*** DESERIALIZING VENDOR CONFIGURATION STRUCTURES ***\n");
resetTimer();
Map<Path, String> namesByPath = new TreeMap<>();
try (DirectoryStream<Path> serializedConfigs = Files
.newDirectoryStream(serializedVendorConfigPath)) {
for (Path serializedConfig : serializedConfigs) {
String name = serializedConfig.getFileName().toString();
namesByPath.put(serializedConfig, name);
}
}
catch (IOException e) {
throw new BatfishException(
"Error reading vendor configs directory",
e);
}
Map<String, GenericConfigObject> vendorConfigurations = deserializeObjects(
namesByPath, GenericConfigObject.class);
printElapsedTime();
return vendorConfigurations;
}
private void disableUnusableVlanInterfaces(
Map<String, Configuration> configurations) {
for (Configuration c : configurations.values()) {
Map<Integer, Interface> vlanInterfaces = new HashMap<>();
Map<Integer, Integer> vlanMemberCounts = new HashMap<>();
Set<Interface> nonVlanInterfaces = new HashSet<>();
Integer vlanNumber = null;
// Populate vlanInterface and nonVlanInterfaces, and initialize
// vlanMemberCounts:
for (Interface iface : c.getInterfaces().values()) {
if ((iface.getInterfaceType() == InterfaceType.VLAN)
&& ((vlanNumber = CommonUtil
.getInterfaceVlanNumber(iface.getName())) != null)) {
vlanInterfaces.put(vlanNumber, iface);
vlanMemberCounts.put(vlanNumber, 0);
}
else {
nonVlanInterfaces.add(iface);
}
}
// Update vlanMemberCounts:
for (Interface iface : nonVlanInterfaces) {
List<SubRange> vlans = new ArrayList<>();
vlanNumber = iface.getAccessVlan();
if (vlanNumber == 0) { // vlan trunked interface
vlans.addAll(iface.getAllowedVlans());
vlanNumber = iface.getNativeVlan();
}
vlans.add(new SubRange(vlanNumber, vlanNumber));
for (SubRange sr : vlans) {
for (int vlanId = sr.getStart(); vlanId <= sr
.getEnd(); ++vlanId) {
vlanMemberCounts.compute(
vlanId,
(k, v) -> (v == null) ? 1 : (v + 1));
}
}
}
// Disable all "normal" vlan interfaces with zero member counts:
String hostname = c.getHostname();
SubRange normalVlanRange = c.getNormalVlanRange();
for (Map.Entry<Integer, Integer> entry : vlanMemberCounts.entrySet()) {
if (entry.getValue() == 0) {
vlanNumber = entry.getKey();
if ((vlanNumber >= normalVlanRange.getStart())
&& (vlanNumber <= normalVlanRange.getEnd())) {
Interface iface = vlanInterfaces.get(vlanNumber);
if ((iface != null) && iface.getAutoState()) {
_logger.warnf(
"WARNING: Disabling unusable vlan interface because no switch port is assigned to it: \"%s:%d\"\n",
hostname, vlanNumber);
iface.setActive(false);
iface.setBlacklisted(true);
}
}
}
}
}
}
private void disableUnusableVpnInterfaces(
Map<String, Configuration> configurations) {
initRemoteIpsecVpns(configurations);
for (Configuration c : configurations.values()) {
for (IpsecVpn vpn : c.getIpsecVpns().values()) {
if (vpn.getRemoteIpsecVpn() == null) {
String hostname = c.getHostname();
Interface bindInterface = vpn.getBindInterface();
if (bindInterface != null) {
bindInterface.setActive(false);
bindInterface.setBlacklisted(true);
String bindInterfaceName = bindInterface.getName();
_logger.warnf(
"WARNING: Disabling unusable vpn interface because we cannot determine remote endpoint: \"%s:%s\"\n",
hostname, bindInterfaceName);
}
}
}
}
}
private boolean environmentBgpTablesExist(EnvironmentSettings envSettings) {
checkConfigurations();
Path answerPath = envSettings.getParseEnvironmentBgpTablesAnswerPath();
return Files.exists(answerPath);
}
private boolean environmentExists(TestrigSettings testrigSettings) {
checkBaseDirExists();
Path envPath = testrigSettings.getEnvironmentSettings().getEnvPath();
if (envPath == null) {
throw new CleanBatfishException(
"No environment specified for testrig: "
+ testrigSettings.getName());
}
return Files.exists(envPath);
}
private boolean environmentRoutingTablesExist(
EnvironmentSettings envSettings) {
checkConfigurations();
Path answerPath = envSettings
.getParseEnvironmentRoutingTablesAnswerPath();
return Files.exists(answerPath);
}
private void flatten(Path inputPath, Path outputPath) {
Map<Path, String> configurationData = readConfigurationFiles(
inputPath,
BfConsts.RELPATH_CONFIGURATIONS_DIR);
Map<Path, String> outputConfigurationData = new TreeMap<>();
Path outputConfigDir = outputPath
.resolve(BfConsts.RELPATH_CONFIGURATIONS_DIR);
CommonUtil.createDirectories(outputConfigDir);
_logger.info("\n*** FLATTENING TEST RIG ***\n");
resetTimer();
List<FlattenVendorConfigurationJob> jobs = new ArrayList<>();
for (Path inputFile : configurationData.keySet()) {
Warnings warnings = new Warnings(
_settings.getPedanticAsError(),
_settings.getPedanticRecord()
&& _logger.isActive(BatfishLogger.LEVEL_PEDANTIC),
_settings.getRedFlagAsError(),
_settings.getRedFlagRecord()
&& _logger.isActive(BatfishLogger.LEVEL_REDFLAG),
_settings.getUnimplementedAsError(),
_settings.getUnimplementedRecord()
&& _logger.isActive(BatfishLogger.LEVEL_UNIMPLEMENTED),
_settings.printParseTree());
String fileText = configurationData.get(inputFile);
String name = inputFile.getFileName().toString();
Path outputFile = outputConfigDir.resolve(name);
FlattenVendorConfigurationJob job = new FlattenVendorConfigurationJob(
_settings, fileText, inputFile, outputFile, warnings);
jobs.add(job);
}
BatfishJobExecutor<FlattenVendorConfigurationJob, FlattenVendorConfigurationAnswerElement, FlattenVendorConfigurationResult, Map<Path, String>>
executor = new BatfishJobExecutor<>(
_settings, _logger,
_settings.getFlatten() || _settings.getHaltOnParseError(),
"Flatten configurations");
// todo: do something with answer element
executor.executeJobs(jobs, outputConfigurationData,
new FlattenVendorConfigurationAnswerElement());
printElapsedTime();
for (Entry<Path, String> e : outputConfigurationData.entrySet()) {
Path outputFile = e.getKey();
String flatConfigText = e.getValue();
String outputFileAsString = outputFile.toString();
_logger.debug("Writing config to \"" + outputFileAsString + "\"...");
CommonUtil.writeFile(outputFile, flatConfigText);
_logger.debug("OK\n");
}
Path inputTopologyPath = inputPath.resolve(TOPOLOGY_FILENAME);
Path outputTopologyPath = outputPath.resolve(TOPOLOGY_FILENAME);
if (Files.isRegularFile(inputTopologyPath)) {
String topologyFileText = CommonUtil.readFile(inputTopologyPath);
CommonUtil.writeFile(outputTopologyPath, topologyFileText);
}
}
private void generateOspfConfigs(Path topologyPath, Path outputPath) {
Topology topology = parseTopology(topologyPath);
Map<String, Configuration> configs = new TreeMap<>();
NodeSet allNodes = new NodeSet();
Map<NodeInterfacePair, Set<NodeInterfacePair>> interfaceMap = new HashMap<>();
// first we collect set of all mentioned nodes, and build mapping from
// each interface to the set of interfaces that connect to each other
for (Edge edge : topology.getEdges()) {
allNodes.add(edge.getNode1());
allNodes.add(edge.getNode2());
NodeInterfacePair interface1 = new NodeInterfacePair(
edge.getNode1(),
edge.getInt1());
NodeInterfacePair interface2 = new NodeInterfacePair(
edge.getNode2(),
edge.getInt2());
Set<NodeInterfacePair> interfaceSet = interfaceMap.get(interface1);
if (interfaceSet == null) {
interfaceSet = new HashSet<>();
}
interfaceMap.put(interface1, interfaceSet);
interfaceMap.put(interface2, interfaceSet);
interfaceSet.add(interface1);
interfaceSet.add(interface2);
}
// then we create configs for every mentioned node
for (String hostname : allNodes) {
Configuration config = new Configuration(hostname);
configs.put(hostname, config);
}
// Now we create interfaces for each edge and record the number of
// neighbors so we know how large to make the subnet
long currentStartingIpAsLong = new Ip(GEN_OSPF_STARTING_IP).asLong();
Set<Set<NodeInterfacePair>> interfaceSets = new HashSet<>();
interfaceSets.addAll(interfaceMap.values());
for (Set<NodeInterfacePair> interfaceSet : interfaceSets) {
int numInterfaces = interfaceSet.size();
if (numInterfaces < 2) {
throw new BatfishException(
"The following interface set contains less than two interfaces: "
+ interfaceSet.toString());
}
int numHostBits = 0;
for (int shiftedValue = numInterfaces
- 1; shiftedValue != 0; shiftedValue >>= 1, numHostBits++) {
}
int subnetBits = 32 - numHostBits;
int offset = 0;
for (NodeInterfacePair currentPair : interfaceSet) {
Ip ip = new Ip(currentStartingIpAsLong + offset);
Prefix prefix = new Prefix(ip, subnetBits);
String ifaceName = currentPair.getInterface();
Interface iface = new Interface(
ifaceName,
configs.get(currentPair.getHostname()));
iface.setPrefix(prefix);
// dirty hack for setting bandwidth for now
double ciscoBandwidth = org.batfish.representation.cisco.Interface
.getDefaultBandwidth(ifaceName);
double juniperBandwidth = org.batfish.representation.juniper.Interface
.getDefaultBandwidthByName(ifaceName);
double bandwidth = Math.min(ciscoBandwidth, juniperBandwidth);
iface.setBandwidth(bandwidth);
String hostname = currentPair.getHostname();
Configuration config = configs.get(hostname);
config.getInterfaces().put(ifaceName, iface);
offset++;
}
currentStartingIpAsLong += (1 << numHostBits);
}
for (Configuration config : configs.values()) {
// use cisco arbitrarily
config.setConfigurationFormat(ConfigurationFormat.CISCO_IOS);
OspfProcess proc = new OspfProcess();
config.getDefaultVrf().setOspfProcess(proc);
proc.setReferenceBandwidth(
org.batfish.representation.cisco.OspfProcess.DEFAULT_REFERENCE_BANDWIDTH);
long backboneArea = 0;
OspfArea area = new OspfArea(backboneArea);
proc.getAreas().put(backboneArea, area);
area.getInterfaces()
.addAll(config.getDefaultVrf().getInterfaces().values());
}
serializeIndependentConfigs(configs, outputPath);
}
private void generateStubs(
String inputRole, int stubAs,
String interfaceDescriptionRegex) {
// Map<String, Configuration> configs = loadConfigurations();
// Pattern pattern = Pattern.compile(interfaceDescriptionRegex);
// Map<String, Configuration> stubConfigurations = new TreeMap<>();
// resetTimer();
// // load old node-roles to be updated at end
// RoleSet stubRoles = new RoleSet();
// stubRoles.add(STUB_ROLE);
// Path nodeRolesPath = _settings.getNodeRolesPath();
// _logger.info("Deserializing old node-roles mappings: \"" +
// nodeRolesPath
// NodeRoleMap nodeRoles = deserializeObject(nodeRolesPath,
// NodeRoleMap.class);
// _logger.info("OK\n");
// // create origination policy common to all stubs
// String stubOriginationPolicyName = "~STUB_ORIGINATION_POLICY~";
// PolicyMap stubOriginationPolicy = new PolicyMap(
// stubOriginationPolicyName);
// PolicyMapClause clause = new PolicyMapClause();
// stubOriginationPolicy.getClauses().add(clause);
// String stubOriginationRouteFilterListName =
// "~STUB_ORIGINATION_ROUTE_FILTER~";
// RouteFilterList rf = new RouteFilterList(
// stubOriginationRouteFilterListName);
// RouteFilterLine rfl = new RouteFilterLine(LineAction.ACCEPT,
// Prefix.ZERO,
// new SubRange(0, 0));
// rf.addLine(rfl);
// PolicyMapMatchRouteFilterListLine matchLine = new
// PolicyMapMatchRouteFilterListLine(
// Collections.singleton(rf));
// clause.getMatchLines().add(matchLine);
// clause.setAction(PolicyMapAction.PERMIT);
// Set<String> skipWarningNodes = new HashSet<>();
// for (Configuration config : configs.values()) {
// if (!config.getRoles().contains(inputRole)) {
// continue;
// for (BgpNeighbor neighbor : config.getBgpProcess().getNeighbors()
// .values()) {
// if (!neighbor.getRemoteAs().equals(stubAs)) {
// continue;
// Prefix neighborPrefix = neighbor.getPrefix();
// if (neighborPrefix.getPrefixLength() != 32) {
// throw new BatfishException(
// "do not currently handle generating stubs based on dynamic bgp
// sessions");
// Ip neighborAddress = neighborPrefix.getAddress();
// int edgeAs = neighbor.getLocalAs();
// /*
// * Now that we have the ip address of the stub, we want to find the
// * interface that connects to it. We will extract the hostname for
// * the stub from the description of this interface using the
// * supplied regex.
// */
// boolean found = false;
// for (Interface iface : config.getInterfaces().values()) {
// Prefix prefix = iface.getPrefix();
// if (prefix == null || !prefix.contains(neighborAddress)) {
// continue;
// // the neighbor address falls within the network assigned to this
// // interface, so now we check the description
// String description = iface.getDescription();
// Matcher matcher = pattern.matcher(description);
// if (matcher.find()) {
// String hostname = matcher.group(1);
// if (configs.containsKey(hostname)) {
// Configuration duplicateConfig = configs.get(hostname);
// if (!duplicateConfig.getRoles().contains(STUB_ROLE)
// || duplicateConfig.getRoles().size() != 1) {
// throw new BatfishException(
// "A non-generated node with hostname: \""
// + hostname
// + "\" already exists in network under analysis");
// else {
// if (!skipWarningNodes.contains(hostname)) {
// _logger
// .warn("WARNING: Overwriting previously generated node: \""
// + hostname + "\"\n");
// skipWarningNodes.add(hostname);
// found = true;
// Configuration stub = stubConfigurations.get(hostname);
// // create stub if it doesn't exist yet
// if (stub == null) {
// stub = new Configuration(hostname);
// stubConfigurations.put(hostname, stub);
// // create flow sink interface for stub with common deatils
// String flowSinkName = "TenGibabitEthernet100/100";
// Interface flowSink = new Interface(flowSinkName, stub);
// flowSink.setPrefix(Prefix.ZERO);
// flowSink.setActive(true);
// flowSink.setBandwidth(10E9d);
// stub.getInterfaces().put(flowSinkName, flowSink);
// stub.setBgpProcess(new BgpProcess());
// stub.getPolicyMaps().put(stubOriginationPolicyName,
// stubOriginationPolicy);
// stub.getRouteFilterLists()
// .put(stubOriginationRouteFilterListName, rf);
// stub.setConfigurationFormat(ConfigurationFormat.CISCO);
// stub.setRoles(stubRoles);
// nodeRoles.put(hostname, stubRoles);
// // create interface that will on which peering will occur
// Map<String, Interface> stubInterfaces = stub.getInterfaces();
// String stubInterfaceName = "TenGigabitEthernet0/"
// + (stubInterfaces.size() - 1);
// Interface stubInterface = new Interface(stubInterfaceName,
// stub);
// stubInterfaces.put(stubInterfaceName, stubInterface);
// stubInterface.setPrefix(
// new Prefix(neighborAddress, prefix.getPrefixLength()));
// stubInterface.setActive(true);
// stubInterface.setBandwidth(10E9d);
// // create neighbor within bgp process
// BgpNeighbor edgeNeighbor = new BgpNeighbor(prefix, stub);
// edgeNeighbor.getOriginationPolicies()
// .add(stubOriginationPolicy);
// edgeNeighbor.setRemoteAs(edgeAs);
// edgeNeighbor.setLocalAs(stubAs);
// edgeNeighbor.setSendCommunity(true);
// edgeNeighbor.setDefaultMetric(0);
// stub.getBgpProcess().getNeighbors()
// .put(edgeNeighbor.getPrefix(), edgeNeighbor);
// break;
// else {
// throw new BatfishException(
// "Unable to derive stub hostname from interface description: \""
// + description + "\" using regex: \""
// + interfaceDescriptionRegex + "\"");
// if (!found) {
// throw new BatfishException(
// "Could not determine stub hostname corresponding to ip: \""
// + neighborAddress.toString()
// + "\" listed as neighbor on router: \""
// + config.getHostname() + "\"");
// // write updated node-roles mappings to disk
// _logger.info("Serializing updated node-roles mappings: \"" +
// nodeRolesPath
// serializeObject(nodeRoles, nodeRolesPath);
// _logger.info("OK\n");
// printElapsedTime();
// // write stubs to disk
// serializeIndependentConfigs(stubConfigurations,
// _testrigSettings.getSerializeIndependentPath());
}
@Override
public Map<String, BiFunction<Question, IBatfish, Answerer>> getAnswererCreators() {
return _answererCreators;
}
public TestrigSettings getBaseTestrigSettings() {
return _baseTestrigSettings;
}
public Map<String, Configuration> getConfigurations(
Path serializedVendorConfigPath,
ConvertConfigurationAnswerElement answerElement) {
Map<String, GenericConfigObject> vendorConfigurations = deserializeVendorConfigurations(
serializedVendorConfigPath);
Map<String, Configuration> configurations = convertConfigurations(
vendorConfigurations, answerElement);
postProcessConfigurations(configurations.values());
return configurations;
}
public DataPlanePlugin getDataPlanePlugin() {
return _dataPlanePlugin;
}
private Map<String, Configuration> getDeltaConfigurations() {
EnvironmentSettings envSettings = _testrigSettings
.getEnvironmentSettings();
Path deltaDir = envSettings.getDeltaConfigurationsDir();
if (deltaDir != null && Files.exists(deltaDir)) {
if (Files.exists(envSettings.getDeltaCompiledConfigurationsDir())) {
return deserializeConfigurations(
envSettings.getDeltaCompiledConfigurationsDir());
}
else {
throw new BatfishException("Missing compiled delta configurations");
}
}
else {
return Collections.emptyMap();
}
}
public TestrigSettings getDeltaTestrigSettings() {
return _deltaTestrigSettings;
}
@Override
public String getDifferentialFlowTag() {
// return _settings.getQuestionName() + ":" +
// _baseTestrigSettings.getName()
// + ":" + _baseTestrigSettings.getEnvironmentSettings().getName()
// + ":" + _deltaTestrigSettings.getName() + ":"
// + _deltaTestrigSettings.getEnvironmentSettings().getName();
return DIFFERENTIAL_FLOW_TAG;
}
public EdgeSet getEdgeBlacklist() {
EdgeSet blacklistEdges = null;
Path edgeBlacklistPath = _testrigSettings.getEnvironmentSettings()
.getEdgeBlacklistPath();
if (edgeBlacklistPath != null) {
if (Files.exists(edgeBlacklistPath)) {
blacklistEdges = parseEdgeBlacklist(edgeBlacklistPath);
}
}
return blacklistEdges;
}
private double getElapsedTime(long beforeTime) {
long difference = System.currentTimeMillis() - beforeTime;
double seconds = difference / 1000d;
return seconds;
}
private SortedMap<String, BgpAdvertisementsByVrf> getEnvironmentBgpTables(
Path inputPath, ParseEnvironmentBgpTablesAnswerElement answerElement) {
if (Files.exists(inputPath.getParent()) && !Files.exists(inputPath)) {
return new TreeMap<>();
}
SortedMap<Path, String> inputData = readFiles(
inputPath,
"Environment BGP Tables");
SortedMap<String, BgpAdvertisementsByVrf> bgpTables = parseEnvironmentBgpTables(
inputData, answerElement);
return bgpTables;
}
public String getEnvironmentName() {
return _testrigSettings.getEnvironmentSettings().getName();
}
private SortedMap<String, RoutesByVrf> getEnvironmentRoutingTables(
Path inputPath,
ParseEnvironmentRoutingTablesAnswerElement answerElement) {
if (Files.exists(inputPath.getParent()) && !Files.exists(inputPath)) {
return new TreeMap<>();
}
SortedMap<Path, String> inputData = readFiles(
inputPath,
"Environment Routing Tables");
SortedMap<String, RoutesByVrf> routingTables = parseEnvironmentRoutingTables(
inputData, answerElement);
return routingTables;
}
@Override
public String getFlowTag() {
return getFlowTag(_testrigSettings);
}
public String getFlowTag(TestrigSettings testrigSettings) {
// return _settings.getQuestionName() + ":" + testrigSettings.getName() +
// + testrigSettings.getEnvironmentSettings().getName();
if (testrigSettings == _deltaTestrigSettings) {
return DELTA_TESTRIG_TAG;
}
else if (testrigSettings == _baseTestrigSettings) {
return BASE_TESTRIG_TAG;
}
else {
throw new BatfishException("Could not determine flow tag");
}
}
@Override
public GrammarSettings getGrammarSettings() {
return _settings;
}
@Override
public FlowHistory getHistory() {
FlowHistory flowHistory = new FlowHistory();
if (_settings.getDiffQuestion()) {
String tag = getDifferentialFlowTag();
// String baseName = _baseTestrigSettings.getName() + ":"
// + _baseTestrigSettings.getEnvironmentSettings().getName();
String baseName = getFlowTag(_baseTestrigSettings);
// String deltaName = _deltaTestrigSettings.getName() + ":"
// + _deltaTestrigSettings.getEnvironmentSettings().getName();
String deltaName = getFlowTag(_deltaTestrigSettings);
pushBaseEnvironment();
populateFlowHistory(flowHistory, baseName, tag);
popEnvironment();
pushDeltaEnvironment();
populateFlowHistory(flowHistory, deltaName, tag);
popEnvironment();
}
else {
String tag = getFlowTag();
// String name = testrigSettings.getName() + ":"
// + testrigSettings.getEnvironmentSettings().getName();
String envName = tag;
populateFlowHistory(flowHistory, envName, tag);
}
_logger.debug(flowHistory.toString());
return flowHistory;
}
public Set<NodeInterfacePair> getInterfaceBlacklist() {
Set<NodeInterfacePair> blacklistInterfaces = null;
Path interfaceBlacklistPath = _testrigSettings.getEnvironmentSettings()
.getInterfaceBlacklistPath();
if (interfaceBlacklistPath != null) {
if (Files.exists(interfaceBlacklistPath)) {
blacklistInterfaces = parseInterfaceBlacklist(
interfaceBlacklistPath);
}
}
return blacklistInterfaces;
}
@Override
public BatfishLogger getLogger() {
return _logger;
}
public NodeSet getNodeBlacklist() {
NodeSet blacklistNodes = null;
Path nodeBlacklistPath = _testrigSettings.getEnvironmentSettings()
.getNodeBlacklistPath();
if (nodeBlacklistPath != null) {
if (Files.exists(nodeBlacklistPath)) {
blacklistNodes = parseNodeBlacklist(nodeBlacklistPath);
}
}
return blacklistNodes;
}
@Override
public SortedMap<String, SortedMap<String, SortedSet<AbstractRoute>>> getRoutes() {
return _dataPlanePlugin.getRoutes();
}
public Settings getSettings() {
return _settings;
}
private Set<Edge> getSymmetricEdgePairs(EdgeSet edges) {
LinkedHashSet<Edge> consumedEdges = new LinkedHashSet<>();
for (Edge edge : edges) {
if (consumedEdges.contains(edge)) {
continue;
}
Edge reverseEdge = new Edge(
edge.getInterface2(),
edge.getInterface1());
consumedEdges.add(edge);
consumedEdges.add(reverseEdge);
}
return consumedEdges;
}
public boolean getTerminatedWithException() {
return _terminatedWithException;
}
@Override
public Directory getTestrigFileTree() {
Path trPath = _testrigSettings.getTestRigPath();
Directory dir = new Directory(trPath);
return dir;
}
public String getTestrigName() {
return _testrigSettings.getName();
}
public TestrigSettings getTestrigSettings() {
return _testrigSettings;
}
@Override
public PluginClientType getType() {
return PluginClientType.BATFISH;
}
private void histogram(Path testRigPath) {
Map<Path, String> configurationData = readConfigurationFiles(
testRigPath,
BfConsts.RELPATH_CONFIGURATIONS_DIR);
// todo: either remove histogram function or do something userful with
// answer
Map<String, VendorConfiguration> vendorConfigurations = parseVendorConfigurations(
configurationData, new ParseVendorConfigurationAnswerElement(),
ConfigurationFormat.UNKNOWN);
_logger.info("Building feature histogram...");
MultiSet<String> histogram = new TreeMultiSet<>();
for (VendorConfiguration vc : vendorConfigurations.values()) {
Set<String> unimplementedFeatures = vc.getUnimplementedFeatures();
histogram.add(unimplementedFeatures);
}
_logger.info("OK\n");
for (String feature : histogram.elements()) {
int count = histogram.count(feature);
_logger.output(feature + ": " + count + "\n");
}
}
private void initAnalysisQuestionPath(
String analysisName,
String questionName) {
Path questionDir = _testrigSettings.getBasePath()
.resolve(Paths
.get(BfConsts.RELPATH_ANALYSES_DIR, analysisName,
BfConsts.RELPATH_QUESTIONS_DIR, questionName)
.toString());
questionDir.toFile().mkdirs();
Path questionPath = questionDir.resolve(BfConsts.RELPATH_QUESTION_FILE);
_settings.setQuestionPath(questionPath);
}
@Override
public void initBgpAdvertisements(
Map<String, Configuration> configurations) {
AdvertisementSet globalBgpAdvertisements = _dataPlanePlugin
.getAdvertisements();
for (Configuration node : configurations.values()) {
node.initBgpAdvertisements();
for (Vrf vrf : node.getVrfs().values()) {
vrf.initBgpAdvertisements();
}
}
for (BgpAdvertisement bgpAdvertisement : globalBgpAdvertisements) {
BgpAdvertisementType type = bgpAdvertisement.getType();
String srcVrf = bgpAdvertisement.getSrcVrf();
String dstVrf = bgpAdvertisement.getDstVrf();
switch (type) {
case EBGP_ORIGINATED: {
String originationNodeName = bgpAdvertisement.getSrcNode();
Configuration originationNode = configurations
.get(originationNodeName);
if (originationNode != null) {
originationNode.getBgpAdvertisements().add(bgpAdvertisement);
originationNode.getOriginatedAdvertisements()
.add(bgpAdvertisement);
originationNode.getOriginatedEbgpAdvertisements()
.add(bgpAdvertisement);
Vrf originationVrf = originationNode.getVrfs().get(srcVrf);
originationVrf.getBgpAdvertisements().add(bgpAdvertisement);
originationVrf.getOriginatedAdvertisements()
.add(bgpAdvertisement);
originationVrf.getOriginatedEbgpAdvertisements()
.add(bgpAdvertisement);
}
else {
throw new BatfishException(
"Originated bgp advertisement refers to missing node: \""
+ originationNodeName + "\"");
}
break;
}
case IBGP_ORIGINATED: {
String originationNodeName = bgpAdvertisement.getSrcNode();
Configuration originationNode = configurations
.get(originationNodeName);
if (originationNode != null) {
originationNode.getBgpAdvertisements().add(bgpAdvertisement);
originationNode.getOriginatedAdvertisements()
.add(bgpAdvertisement);
originationNode.getOriginatedEbgpAdvertisements()
.add(bgpAdvertisement);
Vrf originationVrf = originationNode.getVrfs().get(srcVrf);
originationVrf.getBgpAdvertisements().add(bgpAdvertisement);
originationVrf.getOriginatedAdvertisements()
.add(bgpAdvertisement);
originationVrf.getOriginatedIbgpAdvertisements()
.add(bgpAdvertisement);
}
else {
throw new BatfishException(
"Originated bgp advertisement refers to missing node: \""
+ originationNodeName + "\"");
}
break;
}
case EBGP_RECEIVED: {
String recevingNodeName = bgpAdvertisement.getDstNode();
Configuration receivingNode = configurations.get(recevingNodeName);
if (receivingNode != null) {
receivingNode.getBgpAdvertisements().add(bgpAdvertisement);
receivingNode.getReceivedAdvertisements().add(bgpAdvertisement);
receivingNode.getReceivedEbgpAdvertisements()
.add(bgpAdvertisement);
Vrf receivingVrf = receivingNode.getVrfs().get(dstVrf);
receivingVrf.getBgpAdvertisements().add(bgpAdvertisement);
receivingVrf.getReceivedAdvertisements().add(bgpAdvertisement);
receivingVrf.getReceivedEbgpAdvertisements()
.add(bgpAdvertisement);
}
break;
}
case IBGP_RECEIVED: {
String recevingNodeName = bgpAdvertisement.getDstNode();
Configuration receivingNode = configurations.get(recevingNodeName);
if (receivingNode != null) {
receivingNode.getBgpAdvertisements().add(bgpAdvertisement);
receivingNode.getReceivedAdvertisements().add(bgpAdvertisement);
receivingNode.getReceivedEbgpAdvertisements()
.add(bgpAdvertisement);
Vrf receivingVrf = receivingNode.getVrfs().get(dstVrf);
receivingVrf.getBgpAdvertisements().add(bgpAdvertisement);
receivingVrf.getReceivedAdvertisements().add(bgpAdvertisement);
receivingVrf.getReceivedIbgpAdvertisements()
.add(bgpAdvertisement);
}
break;
}
case EBGP_SENT: {
String sendingNodeName = bgpAdvertisement.getSrcNode();
Configuration sendingNode = configurations.get(sendingNodeName);
if (sendingNode != null) {
sendingNode.getBgpAdvertisements().add(bgpAdvertisement);
sendingNode.getSentAdvertisements().add(bgpAdvertisement);
sendingNode.getSentEbgpAdvertisements().add(bgpAdvertisement);
Vrf sendingVrf = sendingNode.getVrfs().get(srcVrf);
sendingVrf.getBgpAdvertisements().add(bgpAdvertisement);
sendingVrf.getSentAdvertisements().add(bgpAdvertisement);
sendingVrf.getSentEbgpAdvertisements().add(bgpAdvertisement);
}
break;
}
case IBGP_SENT: {
String sendingNodeName = bgpAdvertisement.getSrcNode();
Configuration sendingNode = configurations.get(sendingNodeName);
if (sendingNode != null) {
sendingNode.getBgpAdvertisements().add(bgpAdvertisement);
sendingNode.getSentAdvertisements().add(bgpAdvertisement);
sendingNode.getSentEbgpAdvertisements().add(bgpAdvertisement);
Vrf sendingVrf = sendingNode.getVrfs().get(srcVrf);
sendingVrf.getBgpAdvertisements().add(bgpAdvertisement);
sendingVrf.getSentAdvertisements().add(bgpAdvertisement);
sendingVrf.getSentIbgpAdvertisements().add(bgpAdvertisement);
}
break;
}
default:
throw new BatfishException("Invalid bgp advertisement type");
}
}
}
@Override
public void initBgpOriginationSpaceExplicit(
Map<String, Configuration> configurations) {
// ProtocolDependencyAnalysis protocolDependencyAnalysis = new
// ProtocolDependencyAnalysis(
// configurations);
// DependencyDatabase database = protocolDependencyAnalysis
// .getDependencyDatabase();
// for (Entry<String, Configuration> e : configurations.entrySet()) {
// PrefixSpace ebgpExportSpace = new PrefixSpace();
// String name = e.getKey();
// Configuration node = e.getValue();
// BgpProcess proc = node.getBgpProcess();
// if (proc != null) {
// Set<PotentialExport> bgpExports = database.getPotentialExports(name,
// RoutingProtocol.BGP);
// for (PotentialExport export : bgpExports) {
// DependentRoute exportSourceRoute = export.getDependency();
// if (!exportSourceRoute.dependsOn(RoutingProtocol.BGP)
// && !exportSourceRoute.dependsOn(RoutingProtocol.IBGP)) {
// Prefix prefix = export.getPrefix();
// ebgpExportSpace.addPrefix(prefix);
// proc.setOriginationSpace(ebgpExportSpace);
}
@Override
public InitInfoAnswerElement initInfo(
boolean summary,
boolean environmentRoutes) {
checkConfigurations();
InitInfoAnswerElement answerElement = new InitInfoAnswerElement();
if (environmentRoutes) {
ParseEnvironmentRoutingTablesAnswerElement parseAnswer =
loadParseEnvironmentRoutingTablesAnswerElement();
if (!summary) {
SortedMap<String, org.batfish.common.Warnings> warnings = answerElement
.getWarnings();
warnings.putAll(parseAnswer.getWarnings());
}
answerElement.setParseStatus(parseAnswer.getParseStatus());
}
else {
ParseVendorConfigurationAnswerElement parseAnswer =
loadParseVendorConfigurationAnswerElement();
ConvertConfigurationAnswerElement convertAnswer = loadConvertConfigurationAnswerElement();
if (!summary) {
SortedMap<String, org.batfish.common.Warnings> warnings = answerElement
.getWarnings();
warnings.putAll(parseAnswer.getWarnings());
convertAnswer.getWarnings().forEach((hostname, convertWarnings) -> {
org.batfish.common.Warnings combined = warnings.get(hostname);
if (combined == null) {
warnings.put(hostname, convertWarnings);
}
else {
combined.getPedanticWarnings()
.addAll(convertWarnings.getPedanticWarnings());
combined.getRedFlagWarnings()
.addAll(convertWarnings.getRedFlagWarnings());
combined.getUnimplementedWarnings()
.addAll(convertWarnings.getUnimplementedWarnings());
}
});
}
answerElement.setParseStatus(parseAnswer.getParseStatus());
for (String failed : convertAnswer.getFailed()) {
answerElement.getParseStatus().put(failed, ParseStatus.FAILED);
}
}
_logger.info(answerElement.prettyPrint());
return answerElement;
}
private void initQuestionEnvironment(
Question question, boolean dp,
boolean differentialContext) {
EnvironmentSettings envSettings = _testrigSettings
.getEnvironmentSettings();
if (!environmentExists(_testrigSettings)) {
Path envPath = envSettings.getEnvPath();
// create environment required folders
CommonUtil.createDirectories(envPath);
}
if (!environmentBgpTablesExist(envSettings)) {
computeEnvironmentBgpTables();
}
if (!environmentRoutingTablesExist(envSettings)) {
computeEnvironmentRoutingTables();
}
if (dp && !dataPlaneDependenciesExist(_testrigSettings)) {
computeDataPlane(differentialContext);
}
}
private void initQuestionEnvironments(
Question question, boolean diff,
boolean diffActive, boolean dp) {
if (diff || !diffActive) {
pushBaseEnvironment();
initQuestionEnvironment(question, dp, false);
popEnvironment();
}
if (diff || diffActive) {
pushDeltaEnvironment();
initQuestionEnvironment(question, dp, true);
popEnvironment();
}
}
@Override
public void initRemoteBgpNeighbors(
Map<String, Configuration> configurations,
Map<Ip, Set<String>> ipOwners) {
// TODO: handle duplicate ips on different vrfs
Map<BgpNeighbor, Ip> remoteAddresses = new IdentityHashMap<>();
Map<Ip, Set<BgpNeighbor>> localAddresses = new HashMap<>();
for (Configuration node : configurations.values()) {
String hostname = node.getHostname();
for (Vrf vrf : node.getVrfs().values()) {
BgpProcess proc = vrf.getBgpProcess();
if (proc != null) {
for (BgpNeighbor bgpNeighbor : proc.getNeighbors().values()) {
bgpNeighbor.initCandidateRemoteBgpNeighbors();
if (bgpNeighbor.getPrefix().getPrefixLength() < 32) {
throw new BatfishException(hostname
+ ": Do not support dynamic bgp sessions at this time: "
+ bgpNeighbor.getPrefix());
}
Ip remoteAddress = bgpNeighbor.getAddress();
if (remoteAddress == null) {
throw new BatfishException(hostname
+ ": Could not determine remote address of bgp neighbor: "
+ bgpNeighbor);
}
Ip localAddress = bgpNeighbor.getLocalIp();
if (localAddress == null
|| !ipOwners.containsKey(localAddress)
|| !ipOwners.get(localAddress).contains(hostname)) {
continue;
}
remoteAddresses.put(bgpNeighbor, remoteAddress);
Set<BgpNeighbor> localAddressOwners =
localAddresses.computeIfAbsent(
localAddress,
k -> Collections.newSetFromMap(new IdentityHashMap<>()));
localAddressOwners.add(bgpNeighbor);
}
}
}
}
for (Entry<BgpNeighbor, Ip> e : remoteAddresses.entrySet()) {
BgpNeighbor bgpNeighbor = e.getKey();
Ip remoteAddress = e.getValue();
Ip localAddress = bgpNeighbor.getLocalIp();
Set<BgpNeighbor> remoteBgpNeighborCandidates = localAddresses
.get(remoteAddress);
if (remoteBgpNeighborCandidates != null) {
for (BgpNeighbor remoteBgpNeighborCandidate : remoteBgpNeighborCandidates) {
Ip reciprocalRemoteIp = remoteBgpNeighborCandidate.getAddress();
if (localAddress.equals(reciprocalRemoteIp)) {
bgpNeighbor.getCandidateRemoteBgpNeighbors()
.add(remoteBgpNeighborCandidate);
bgpNeighbor.setRemoteBgpNeighbor(remoteBgpNeighborCandidate);
}
}
}
}
}
@Override
public void initRemoteIpsecVpns(Map<String, Configuration> configurations) {
Map<IpsecVpn, Ip> remoteAddresses = new HashMap<>();
Map<Ip, Set<IpsecVpn>> externalAddresses = new HashMap<>();
for (Configuration c : configurations.values()) {
for (IpsecVpn ipsecVpn : c.getIpsecVpns().values()) {
Ip remoteAddress = ipsecVpn.getIkeGateway().getAddress();
remoteAddresses.put(ipsecVpn, remoteAddress);
Set<Prefix> externalPrefixes = ipsecVpn.getIkeGateway()
.getExternalInterface().getAllPrefixes();
for (Prefix externalPrefix : externalPrefixes) {
Ip externalAddress = externalPrefix.getAddress();
Set<IpsecVpn> vpnsUsingExternalAddress =
externalAddresses.computeIfAbsent(externalAddress, k -> new HashSet<>());
vpnsUsingExternalAddress.add(ipsecVpn);
}
}
}
for (Entry<IpsecVpn, Ip> e : remoteAddresses.entrySet()) {
IpsecVpn ipsecVpn = e.getKey();
Ip remoteAddress = e.getValue();
ipsecVpn.initCandidateRemoteVpns();
Set<IpsecVpn> remoteIpsecVpnCandidates = externalAddresses
.get(remoteAddress);
if (remoteIpsecVpnCandidates != null) {
for (IpsecVpn remoteIpsecVpnCandidate : remoteIpsecVpnCandidates) {
Ip remoteIpsecVpnLocalAddress = remoteIpsecVpnCandidate
.getIkeGateway().getLocalAddress();
if (remoteIpsecVpnLocalAddress != null
&& !remoteIpsecVpnLocalAddress.equals(remoteAddress)) {
continue;
}
Ip reciprocalRemoteAddress = remoteAddresses
.get(remoteIpsecVpnCandidate);
Set<IpsecVpn> reciprocalVpns = externalAddresses
.get(reciprocalRemoteAddress);
if (reciprocalVpns != null
&& reciprocalVpns.contains(ipsecVpn)) {
ipsecVpn.setRemoteIpsecVpn(remoteIpsecVpnCandidate);
ipsecVpn.getCandidateRemoteIpsecVpns()
.add(remoteIpsecVpnCandidate);
}
}
}
}
}
@Override
public void initRemoteOspfNeighbors(
Map<String, Configuration> configurations,
Map<Ip, Set<String>> ipOwners, Topology topology) {
for (Entry<String, Configuration> e : configurations.entrySet()) {
String hostname = e.getKey();
Configuration c = e.getValue();
for (Entry<String, Vrf> e2 : c.getVrfs().entrySet()) {
Vrf vrf = e2.getValue();
OspfProcess proc = vrf.getOspfProcess();
if (proc != null) {
proc.setOspfNeighbors(new TreeMap<>());
if (proc != null) {
String vrfName = e2.getKey();
for (Entry<Long, OspfArea> e3 : proc.getAreas().entrySet()) {
long areaNum = e3.getKey();
OspfArea area = e3.getValue();
for (Interface iface : area.getInterfaces()) {
String ifaceName = iface.getName();
EdgeSet ifaceEdges = topology.getInterfaceEdges()
.get(new NodeInterfacePair(hostname, ifaceName));
boolean hasNeighbor = false;
Ip localIp = iface.getPrefix().getAddress();
if (ifaceEdges != null) {
for (Edge edge : ifaceEdges) {
if (edge.getNode1().equals(hostname)) {
String remoteHostname = edge.getNode2();
String remoteIfaceName = edge.getInt2();
Configuration remoteNode = configurations
.get(remoteHostname);
Interface remoteIface = remoteNode
.getInterfaces().get(remoteIfaceName);
Vrf remoteVrf = remoteIface.getVrf();
String remoteVrfName = remoteVrf.getName();
OspfProcess remoteProc = remoteVrf
.getOspfProcess();
if (remoteProc.getOspfNeighbors() == null) {
remoteProc
.setOspfNeighbors(new TreeMap<>());
}
if (remoteProc != null) {
OspfArea remoteArea = remoteProc.getAreas()
.get(areaNum);
if (remoteArea != null
&& remoteArea.getInterfaceNames()
.contains(remoteIfaceName)) {
Ip remoteIp = remoteIface.getPrefix()
.getAddress();
Pair<Ip, Ip> localKey = new Pair<>(
localIp, remoteIp);
OspfNeighbor neighbor = proc
.getOspfNeighbors().get(localKey);
if (neighbor == null) {
hasNeighbor = true;
// initialize local neighbor
neighbor = new OspfNeighbor(localKey);
neighbor.setArea(areaNum);
neighbor.setVrf(vrfName);
neighbor.setOwner(c);
neighbor.setInterface(iface);
proc.getOspfNeighbors().put(
localKey,
neighbor);
// initialize remote neighbor
Pair<Ip, Ip> remoteKey = new Pair<>(
remoteIp, localIp);
OspfNeighbor remoteNeighbor = new OspfNeighbor(
remoteKey);
remoteNeighbor.setArea(areaNum);
remoteNeighbor.setVrf(remoteVrfName);
remoteNeighbor.setOwner(remoteNode);
remoteNeighbor
.setInterface(remoteIface);
remoteProc.getOspfNeighbors()
.put(remoteKey, remoteNeighbor);
// link neighbors
neighbor.setRemoteOspfNeighbor(
remoteNeighbor);
remoteNeighbor.setRemoteOspfNeighbor(
neighbor);
}
}
}
}
}
}
if (!hasNeighbor) {
Pair<Ip, Ip> key = new Pair<>(localIp, Ip.ZERO);
OspfNeighbor neighbor = new OspfNeighbor(key);
neighbor.setArea(areaNum);
neighbor.setVrf(vrfName);
neighbor.setOwner(c);
neighbor.setInterface(iface);
proc.getOspfNeighbors().put(key, neighbor);
}
}
}
}
}
}
}
}
@Override
public SortedMap<String, Configuration> loadConfigurations() {
SortedMap<String, Configuration> configurations = _cachedConfigurations
.get(_testrigSettings);
if (configurations == null) {
ConvertConfigurationAnswerElement ccae = loadConvertConfigurationAnswerElement();
if (!Version.isCompatibleVersion("Service",
"Old processed configurations", ccae.getVersion())) {
repairConfigurations();
}
configurations = deserializeConfigurations(
_testrigSettings.getSerializeIndependentPath());
_cachedConfigurations.put(_testrigSettings, configurations);
}
processNodeBlacklist(configurations);
processInterfaceBlacklist(configurations);
processDeltaConfigurations(configurations);
disableUnusableVlanInterfaces(configurations);
disableUnusableVpnInterfaces(configurations);
return configurations;
}
@Override
public ConvertConfigurationAnswerElement loadConvertConfigurationAnswerElement() {
return loadConvertConfigurationAnswerElement(true);
}
private ConvertConfigurationAnswerElement loadConvertConfigurationAnswerElement(
boolean firstAttempt) {
ConvertConfigurationAnswerElement ccae = deserializeObject(
_testrigSettings.getConvertAnswerPath(),
ConvertConfigurationAnswerElement.class);
if (!Version.isCompatibleVersion("Service",
"Old processed configurations", ccae.getVersion())) {
if (firstAttempt) {
repairConfigurations();
return loadConvertConfigurationAnswerElement(false);
}
else {
throw new BatfishException(
"Version error repairing configurations for convert configuration answer element");
}
}
else {
return ccae;
}
}
@Override
public DataPlane loadDataPlane() {
DataPlane dp = _cachedDataPlanes.get(_testrigSettings);
if (dp == null) {
/*
* Data plane should exist after loading answer element, as it triggers
* repair if necessary. However, it might not be cached if it was not
* repaired, so we still might need to load it from disk.
*/
loadDataPlaneAnswerElement();
dp = _cachedDataPlanes.get(_testrigSettings);
if (dp == null) {
newBatch("Loading data plane from disk", 0);
dp = deserializeObject(
_testrigSettings.getEnvironmentSettings().getDataPlanePath(),
DataPlane.class);
_cachedDataPlanes.put(_testrigSettings, dp);
}
}
return dp;
}
private DataPlaneAnswerElement loadDataPlaneAnswerElement() {
return loadDataPlaneAnswerElement(true);
}
private DataPlaneAnswerElement loadDataPlaneAnswerElement(
boolean firstAttempt) {
DataPlaneAnswerElement bae = deserializeObject(
_testrigSettings.getEnvironmentSettings().getDataPlaneAnswerPath(),
DataPlaneAnswerElement.class);
if (!Version.isCompatibleVersion("Service", "Old data plane",
bae.getVersion())) {
if (firstAttempt) {
repairDataPlane();
return loadDataPlaneAnswerElement(false);
}
else {
throw new BatfishException(
"Version error repairing data plane for data plane answer element");
}
}
else {
return bae;
}
}
@Override
public SortedMap<String, BgpAdvertisementsByVrf> loadEnvironmentBgpTables() {
EnvironmentSettings envSettings = _testrigSettings
.getEnvironmentSettings();
SortedMap<String, BgpAdvertisementsByVrf> environmentBgpTables = _cachedEnvironmentBgpTables
.get(envSettings);
if (environmentBgpTables == null) {
ParseEnvironmentBgpTablesAnswerElement ae = loadParseEnvironmentBgpTablesAnswerElement();
if (!Version.isCompatibleVersion("Service",
"Old processed environment BGP tables", ae.getVersion())) {
repairEnvironmentBgpTables();
}
environmentBgpTables = deserializeEnvironmentBgpTables(
envSettings.getSerializeEnvironmentBgpTablesPath());
_cachedEnvironmentBgpTables.put(envSettings, environmentBgpTables);
}
return environmentBgpTables;
}
@Override
public SortedMap<String, RoutesByVrf> loadEnvironmentRoutingTables() {
EnvironmentSettings envSettings = _testrigSettings
.getEnvironmentSettings();
SortedMap<String, RoutesByVrf> environmentRoutingTables = _cachedEnvironmentRoutingTables
.get(envSettings);
if (environmentRoutingTables == null) {
ParseEnvironmentRoutingTablesAnswerElement pertae =
loadParseEnvironmentRoutingTablesAnswerElement();
if (!Version.isCompatibleVersion(
"Service",
"Old processed environment routing tables",
pertae.getVersion())) {
repairEnvironmentRoutingTables();
}
environmentRoutingTables = deserializeEnvironmentRoutingTables(
envSettings.getSerializeEnvironmentRoutingTablesPath());
_cachedEnvironmentRoutingTables.put(
envSettings,
environmentRoutingTables);
}
return environmentRoutingTables;
}
@Override
public ParseEnvironmentBgpTablesAnswerElement loadParseEnvironmentBgpTablesAnswerElement() {
return loadParseEnvironmentBgpTablesAnswerElement(true);
}
private ParseEnvironmentBgpTablesAnswerElement loadParseEnvironmentBgpTablesAnswerElement(
boolean firstAttempt) {
Path answerPath = _testrigSettings.getEnvironmentSettings()
.getParseEnvironmentBgpTablesAnswerPath();
if (!Files.exists(answerPath)) {
repairEnvironmentBgpTables();
}
ParseEnvironmentBgpTablesAnswerElement ae = deserializeObject(
answerPath,
ParseEnvironmentBgpTablesAnswerElement.class);
if (!Version.isCompatibleVersion("Service",
"Old processed environment BGP tables", ae.getVersion())) {
if (firstAttempt) {
repairEnvironmentRoutingTables();
return loadParseEnvironmentBgpTablesAnswerElement(false);
}
else {
throw new BatfishException(
"Version error repairing environment BGP tables for parse environment BGP tables answer element");
}
}
else {
return ae;
}
}
@Override
public ParseEnvironmentRoutingTablesAnswerElement loadParseEnvironmentRoutingTablesAnswerElement() {
return loadParseEnvironmentRoutingTablesAnswerElement(true);
}
private ParseEnvironmentRoutingTablesAnswerElement loadParseEnvironmentRoutingTablesAnswerElement(
boolean firstAttempt) {
Path answerPath = _testrigSettings.getEnvironmentSettings()
.getParseEnvironmentRoutingTablesAnswerPath();
if (!Files.exists(answerPath)) {
repairEnvironmentRoutingTables();
}
ParseEnvironmentRoutingTablesAnswerElement pertae = deserializeObject(
answerPath, ParseEnvironmentRoutingTablesAnswerElement.class);
if (!Version.isCompatibleVersion("Service",
"Old processed environment routing tables", pertae.getVersion())) {
if (firstAttempt) {
repairEnvironmentRoutingTables();
return loadParseEnvironmentRoutingTablesAnswerElement(false);
}
else {
throw new BatfishException(
"Version error repairing environment routing tables for parse environment routing tables answer element");
}
}
else {
return pertae;
}
}
@Override
public ParseVendorConfigurationAnswerElement loadParseVendorConfigurationAnswerElement() {
return loadParseVendorConfigurationAnswerElement(true);
}
private ParseVendorConfigurationAnswerElement loadParseVendorConfigurationAnswerElement(
boolean firstAttempt) {
ParseVendorConfigurationAnswerElement pvcae = deserializeObject(
_testrigSettings.getParseAnswerPath(),
ParseVendorConfigurationAnswerElement.class);
if (!Version.isCompatibleVersion("Service",
"Old processed configurations", pvcae.getVersion())) {
if (firstAttempt) {
repairVendorConfigurations();
return loadParseVendorConfigurationAnswerElement(false);
}
else {
throw new BatfishException(
"Version error repairing vendor configurations for parse configuration answer element");
}
}
else {
return pvcae;
}
}
public Topology loadTopology() {
Path topologyPath = _testrigSettings.getEnvironmentSettings()
.getSerializedTopologyPath();
_logger.info("Deserializing topology...");
Topology topology = deserializeObject(topologyPath, Topology.class);
_logger.info("OK\n");
return topology;
}
@Override
public AnswerElement multipath(HeaderSpace headerSpace) {
if (SystemUtils.IS_OS_MAC_OSX) {
// TODO: remove when z3 parallelism bug on OSX is fixed
_settings.setSequential(true);
}
Settings settings = getSettings();
String tag = getFlowTag(_testrigSettings);
Map<String, Configuration> configurations = loadConfigurations();
Set<Flow> flows = null;
Synthesizer dataPlaneSynthesizer = synthesizeDataPlane();
List<NodJob> jobs = new ArrayList<>();
configurations.forEach((node, configuration) -> {
for (String vrf : configuration.getVrfs().keySet()) {
MultipathInconsistencyQuerySynthesizer query =
new MultipathInconsistencyQuerySynthesizer(
node, vrf, headerSpace);
NodeVrfSet nodes = new NodeVrfSet();
nodes.add(new Pair<>(node, vrf));
NodJob job = new NodJob(settings, dataPlaneSynthesizer, query,
nodes, tag);
jobs.add(job);
}
});
flows = computeNodOutput(jobs);
getDataPlanePlugin().processFlows(flows);
AnswerElement answerElement = getHistory();
return answerElement;
}
@Override
public AtomicInteger newBatch(String description, int jobs) {
return Driver.newBatch(_settings, description, jobs);
}
void outputAnswer(Answer answer) {
ObjectMapper mapper = new BatfishObjectMapper();
try {
Answer structuredAnswer = answer;
Answer prettyAnswer = structuredAnswer.prettyPrintAnswer();
StringBuilder structuredAnswerSb = new StringBuilder();
String structuredAnswerRawString = mapper
.writeValueAsString(structuredAnswer);
structuredAnswerSb.append(structuredAnswerRawString);
structuredAnswerSb.append("\n");
String structuredAnswerString = structuredAnswerSb.toString();
StringBuilder prettyAnswerSb = new StringBuilder();
String prettyAnswerRawString = mapper.writeValueAsString(prettyAnswer);
prettyAnswerSb.append(prettyAnswerRawString);
prettyAnswerSb.append("\n");
String answerString;
String prettyAnswerString = prettyAnswerSb.toString();
if (_settings.prettyPrintAnswer()) {
answerString = prettyAnswerString;
}
else {
answerString = structuredAnswerString;
}
_logger.debug(answerString);
writeJsonAnswer(structuredAnswerString, prettyAnswerString);
}
catch (Exception e) {
BatfishException be = new BatfishException(
"Error in sending answer",
e);
try {
Answer failureAnswer = Answer.failureAnswer(
e.toString(),
answer.getQuestion());
failureAnswer.addAnswerElement(be.getBatfishStackTrace());
Answer structuredAnswer = failureAnswer;
Answer prettyAnswer = structuredAnswer.prettyPrintAnswer();
StringBuilder structuredAnswerSb = new StringBuilder();
String structuredAnswerRawString = mapper
.writeValueAsString(structuredAnswer);
structuredAnswerSb.append(structuredAnswerRawString);
structuredAnswerSb.append("\n");
String structuredAnswerString = structuredAnswerSb.toString();
StringBuilder prettyAnswerSb = new StringBuilder();
String prettyAnswerRawString = mapper
.writeValueAsString(prettyAnswer);
prettyAnswerSb.append(prettyAnswerRawString);
prettyAnswerSb.append("\n");
String answerString;
String prettyAnswerString = prettyAnswerSb.toString();
if (_settings.prettyPrintAnswer()) {
answerString = prettyAnswerString;
}
else {
answerString = structuredAnswerString;
}
_logger.error(answerString);
writeJsonAnswer(structuredAnswerString, prettyAnswerString);
}
catch (Exception e1) {
String errorMessage = String.format(
"Could not serialize failure answer.",
ExceptionUtils.getStackTrace(e1));
_logger.error(errorMessage);
}
throw be;
}
}
void outputAnswerWithLog(Answer answer) {
ObjectMapper mapper = new BatfishObjectMapper();
try {
Answer structuredAnswer = answer;
Answer prettyAnswer = structuredAnswer.prettyPrintAnswer();
StringBuilder structuredAnswerSb = new StringBuilder();
String structuredAnswerRawString = mapper
.writeValueAsString(structuredAnswer);
structuredAnswerSb.append(structuredAnswerRawString);
structuredAnswerSb.append("\n");
String structuredAnswerString = structuredAnswerSb.toString();
StringBuilder prettyAnswerSb = new StringBuilder();
String prettyAnswerRawString = mapper.writeValueAsString(prettyAnswer);
prettyAnswerSb.append(prettyAnswerRawString);
prettyAnswerSb.append("\n");
String answerString;
String prettyAnswerString = prettyAnswerSb.toString();
if (_settings.prettyPrintAnswer()) {
answerString = prettyAnswerString;
}
else {
answerString = structuredAnswerString;
}
_logger.debug(answerString);
writeJsonAnswerWithLog(answerString, structuredAnswerString,
prettyAnswerString);
}
catch (Exception e) {
BatfishException be = new BatfishException(
"Error in sending answer",
e);
try {
Answer failureAnswer = Answer.failureAnswer(
e.toString(),
answer.getQuestion());
failureAnswer.addAnswerElement(be.getBatfishStackTrace());
Answer structuredAnswer = failureAnswer;
Answer prettyAnswer = structuredAnswer.prettyPrintAnswer();
StringBuilder structuredAnswerSb = new StringBuilder();
String structuredAnswerRawString = mapper
.writeValueAsString(structuredAnswer);
structuredAnswerSb.append(structuredAnswerRawString);
structuredAnswerSb.append("\n");
String structuredAnswerString = structuredAnswerSb.toString();
StringBuilder prettyAnswerSb = new StringBuilder();
String prettyAnswerRawString = mapper
.writeValueAsString(prettyAnswer);
prettyAnswerSb.append(prettyAnswerRawString);
prettyAnswerSb.append("\n");
String answerString;
String prettyAnswerString = prettyAnswerSb.toString();
if (_settings.prettyPrintAnswer()) {
answerString = prettyAnswerString;
}
else {
answerString = structuredAnswerString;
}
_logger.error(answerString);
writeJsonAnswerWithLog(answerString, structuredAnswerString,
prettyAnswerString);
}
catch (Exception e1) {
String errorMessage = String.format(
"Could not serialize failure answer.",
ExceptionUtils.getStackTrace(e1));
_logger.error(errorMessage);
}
throw be;
}
}
private ParserRuleContext parse(BatfishCombinedParser<?, ?> parser) {
return parse(parser, _logger, _settings);
}
public ParserRuleContext parse(
BatfishCombinedParser<?, ?> parser,
String filename) {
_logger.info("Parsing: \"" + filename + "\"...");
return parse(parser);
}
@Override
public AssertionAst parseAssertion(String text) {
AssertionCombinedParser parser = new AssertionCombinedParser(
text,
_settings);
AssertionContext tree = (AssertionContext) parse(parser);
ParseTreeWalker walker = new ParseTreeWalker();
AssertionExtractor extractor = new AssertionExtractor(
text,
parser.getParser());
walker.walk(extractor, tree);
AssertionAst ast = extractor.getAst();
return ast;
}
private AwsVpcConfiguration parseAwsVpcConfigurations(
Map<Path, String> configurationData) {
AwsVpcConfiguration config = new AwsVpcConfiguration();
for (Path file : configurationData.keySet()) {
// we stop classic link processing here because it interferes with VPC
// processing
if (file.toString().contains("classic-link")) {
_logger.errorf(
"%s has classic link configuration\n",
file.toString());
continue;
}
JSONObject jsonObj = null;
try {
jsonObj = new JSONObject(configurationData.get(file));
}
catch (JSONException e) {
_logger.errorf("%s does not have valid json\n", file.toString());
}
if (jsonObj != null) {
try {
config.addConfigElement(jsonObj, _logger);
}
catch (JSONException e) {
throw new BatfishException(
"Problems parsing JSON in " + file.toString(), e);
}
}
}
return config;
}
private EdgeSet parseEdgeBlacklist(Path edgeBlacklistPath) {
String edgeBlacklistText = CommonUtil.readFile(edgeBlacklistPath);
SortedSet<Edge> edges;
try {
edges = new BatfishObjectMapper().<SortedSet<Edge>>readValue(
edgeBlacklistText, new TypeReference<SortedSet<Edge>>() {
});
}
catch (IOException e) {
throw new BatfishException("Failed to parse edge blacklist", e);
}
return new EdgeSet(edges);
}
private SortedMap<String, BgpAdvertisementsByVrf> parseEnvironmentBgpTables(
SortedMap<Path, String> inputData,
ParseEnvironmentBgpTablesAnswerElement answerElement) {
_logger.info("\n*** PARSING ENVIRONMENT BGP TABLES ***\n");
resetTimer();
SortedMap<String, BgpAdvertisementsByVrf> bgpTables = new TreeMap<>();
List<ParseEnvironmentBgpTableJob> jobs = new ArrayList<>();
SortedMap<String, Configuration> configurations = loadConfigurations();
for (Path currentFile : inputData.keySet()) {
String hostname = currentFile.getFileName().toString();
String optionalSuffix = ".bgp";
if (hostname.endsWith(optionalSuffix)) {
hostname = hostname.substring(
0,
hostname.length() - optionalSuffix.length());
}
if (!configurations.containsKey(hostname)) {
continue;
}
Warnings warnings = new Warnings(
_settings.getPedanticAsError(),
_settings.getPedanticRecord()
&& _logger.isActive(BatfishLogger.LEVEL_PEDANTIC),
_settings.getRedFlagAsError(),
_settings.getRedFlagRecord()
&& _logger.isActive(BatfishLogger.LEVEL_REDFLAG),
_settings.getUnimplementedAsError(),
_settings.getUnimplementedRecord()
&& _logger.isActive(BatfishLogger.LEVEL_UNIMPLEMENTED),
_settings.printParseTree());
String fileText = inputData.get(currentFile);
ParseEnvironmentBgpTableJob job = new ParseEnvironmentBgpTableJob(
_settings, fileText, hostname, currentFile, warnings,
_bgpTablePlugins);
jobs.add(job);
}
BatfishJobExecutor<ParseEnvironmentBgpTableJob, ParseEnvironmentBgpTablesAnswerElement, ParseEnvironmentBgpTableResult, SortedMap<String, BgpAdvertisementsByVrf>>
executor = new BatfishJobExecutor<>(
_settings, _logger, _settings.getHaltOnParseError(),
"Parse environment BGP tables");
executor.executeJobs(jobs, bgpTables, answerElement);
printElapsedTime();
return bgpTables;
}
private SortedMap<String, RoutesByVrf> parseEnvironmentRoutingTables(
SortedMap<Path, String> inputData,
ParseEnvironmentRoutingTablesAnswerElement answerElement) {
_logger.info("\n*** PARSING ENVIRONMENT ROUTING TABLES ***\n");
resetTimer();
SortedMap<String, RoutesByVrf> routingTables = new TreeMap<>();
List<ParseEnvironmentRoutingTableJob> jobs = new ArrayList<>();
SortedMap<String, Configuration> configurations = loadConfigurations();
for (Path currentFile : inputData.keySet()) {
String hostname = currentFile.getFileName().toString();
if (!configurations.containsKey(hostname)) {
continue;
}
Warnings warnings = new Warnings(
_settings.getPedanticAsError(),
_settings.getPedanticRecord()
&& _logger.isActive(BatfishLogger.LEVEL_PEDANTIC),
_settings.getRedFlagAsError(),
_settings.getRedFlagRecord()
&& _logger.isActive(BatfishLogger.LEVEL_REDFLAG),
_settings.getUnimplementedAsError(),
_settings.getUnimplementedRecord()
&& _logger.isActive(BatfishLogger.LEVEL_UNIMPLEMENTED),
_settings.printParseTree());
String fileText = inputData.get(currentFile);
ParseEnvironmentRoutingTableJob job = new ParseEnvironmentRoutingTableJob(
_settings, fileText, currentFile, warnings, this);
jobs.add(job);
}
BatfishJobExecutor<ParseEnvironmentRoutingTableJob, ParseEnvironmentRoutingTablesAnswerElement, ParseEnvironmentRoutingTableResult, SortedMap<String, RoutesByVrf>>
executor = new BatfishJobExecutor<>(
_settings, _logger, _settings.getHaltOnParseError(),
"Parse environment routing tables");
executor.executeJobs(jobs, routingTables, answerElement);
printElapsedTime();
return routingTables;
}
private Set<NodeInterfacePair> parseInterfaceBlacklist(
Path interfaceBlacklistPath) {
String interfaceBlacklistText = CommonUtil
.readFile(interfaceBlacklistPath);
SortedSet<NodeInterfacePair> ifaces;
try {
ifaces = new BatfishObjectMapper()
.<SortedSet<NodeInterfacePair>>readValue(
interfaceBlacklistText,
new TypeReference<SortedSet<NodeInterfacePair>>() {
});
}
catch (IOException e) {
throw new BatfishException("Failed to parse interface blacklist", e);
}
return ifaces;
}
private NodeSet parseNodeBlacklist(Path nodeBlacklistPath) {
String nodeBlacklistText = CommonUtil.readFile(nodeBlacklistPath);
SortedSet<String> nodes;
try {
nodes = new BatfishObjectMapper().<SortedSet<String>>readValue(
nodeBlacklistText, new TypeReference<SortedSet<String>>() {
});
}
catch (IOException e) {
throw new BatfishException("Failed to parse node blacklist", e);
}
return new NodeSet(nodes);
}
private NodeRoleMap parseNodeRoles(Path testRigPath) {
Path rolePath = testRigPath.resolve("node_roles");
String roleFileText = CommonUtil.readFile(rolePath);
_logger.info("Parsing: \"" + rolePath.toAbsolutePath().toString() + "\"");
BatfishCombinedParser<?, ?> parser = new RoleCombinedParser(
roleFileText,
_settings);
RoleExtractor extractor = new RoleExtractor();
ParserRuleContext tree = parse(parser);
ParseTreeWalker walker = new ParseTreeWalker();
walker.walk(extractor, tree);
NodeRoleMap nodeRoles = extractor.getRoleMap();
return nodeRoles;
}
private Question parseQuestion() {
Path questionPath = _settings.getQuestionPath();
_logger.info("Reading question file: \"" + questionPath + "\"...");
String rawQuestionText = CommonUtil.readFile(questionPath);
_logger.info("OK\n");
String questionText = preprocessQuestion(rawQuestionText);
try {
ObjectMapper mapper = new BatfishObjectMapper(getCurrentClassLoader());
Question question = mapper.readValue(questionText, Question.class);
return question;
}
catch (IOException e) {
throw new BatfishException("Could not parse JSON question", e);
}
}
private Topology parseTopology(Path topologyFilePath) {
_logger.info("*** PARSING TOPOLOGY ***\n");
resetTimer();
String topologyFileText = CommonUtil.readFile(topologyFilePath);
BatfishCombinedParser<?, ?> parser = null;
TopologyExtractor extractor = null;
_logger.info("Parsing: \"" + topologyFilePath.toAbsolutePath().toString()
+ "\" ...");
if (topologyFileText.startsWith("autostart")) {
parser = new GNS3TopologyCombinedParser(topologyFileText, _settings);
extractor = new GNS3TopologyExtractor();
}
else if (topologyFileText
.startsWith(BatfishTopologyCombinedParser.HEADER)) {
parser = new BatfishTopologyCombinedParser(
topologyFileText,
_settings);
extractor = new BatfishTopologyExtractor();
}
else if (topologyFileText.equals("")) {
throw new BatfishException("ERROR: empty topology\n");
}
else {
_logger.fatal("...ERROR\n");
throw new BatfishException("Topology format error");
}
ParserRuleContext tree = parse(parser);
ParseTreeWalker walker = new ParseTreeWalker();
walker.walk(extractor, tree);
Topology topology = extractor.getTopology();
printElapsedTime();
return topology;
}
private Map<String, VendorConfiguration> parseVendorConfigurations(
Map<Path, String> configurationData,
ParseVendorConfigurationAnswerElement answerElement,
ConfigurationFormat configurationFormat) {
_logger.info("\n*** PARSING VENDOR CONFIGURATION FILES ***\n");
resetTimer();
Map<String, VendorConfiguration> vendorConfigurations = new TreeMap<>();
List<ParseVendorConfigurationJob> jobs = new ArrayList<>();
for (Path currentFile : configurationData.keySet()) {
Warnings warnings = new Warnings(
_settings.getPedanticAsError(),
_settings.getPedanticRecord()
&& _logger.isActive(BatfishLogger.LEVEL_PEDANTIC),
_settings.getRedFlagAsError(),
_settings.getRedFlagRecord()
&& _logger.isActive(BatfishLogger.LEVEL_REDFLAG),
_settings.getUnimplementedAsError(),
_settings.getUnimplementedRecord()
&& _logger.isActive(BatfishLogger.LEVEL_UNIMPLEMENTED),
_settings.printParseTree());
String fileText = configurationData.get(currentFile);
ParseVendorConfigurationJob job = new ParseVendorConfigurationJob(
_settings, fileText, currentFile, warnings, configurationFormat);
jobs.add(job);
}
BatfishJobExecutor<ParseVendorConfigurationJob, ParseVendorConfigurationAnswerElement, ParseVendorConfigurationResult, Map<String, VendorConfiguration>>
executor = new BatfishJobExecutor<>(
_settings, _logger, _settings.getHaltOnParseError(),
"Parse configurations");
executor.executeJobs(jobs, vendorConfigurations, answerElement);
printElapsedTime();
return vendorConfigurations;
}
@Override
public AnswerElement pathDiff(HeaderSpace headerSpace) {
if (SystemUtils.IS_OS_MAC_OSX) {
// TODO: remove when z3 parallelism bug on OSX is fixed
_settings.setSequential(true);
}
Settings settings = getSettings();
checkDifferentialDataPlaneQuestionDependencies();
String tag = getDifferentialFlowTag();
// load base configurations and generate base data plane
pushBaseEnvironment();
Map<String, Configuration> baseConfigurations = loadConfigurations();
Synthesizer baseDataPlaneSynthesizer = synthesizeDataPlane();
popEnvironment();
// load diff configurations and generate diff data plane
pushDeltaEnvironment();
Map<String, Configuration> diffConfigurations = loadConfigurations();
Synthesizer diffDataPlaneSynthesizer = synthesizeDataPlane();
popEnvironment();
Set<String> commonNodes = new TreeSet<>();
commonNodes.addAll(baseConfigurations.keySet());
commonNodes.retainAll(diffConfigurations.keySet());
pushDeltaEnvironment();
NodeSet blacklistNodes = getNodeBlacklist();
Set<NodeInterfacePair> blacklistInterfaces = getInterfaceBlacklist();
EdgeSet blacklistEdges = getEdgeBlacklist();
popEnvironment();
BlacklistDstIpQuerySynthesizer blacklistQuery = new BlacklistDstIpQuerySynthesizer(
null, blacklistNodes, blacklistInterfaces, blacklistEdges,
baseConfigurations);
// compute composite program and flows
List<Synthesizer> commonEdgeSynthesizers = new ArrayList<>();
commonEdgeSynthesizers.add(baseDataPlaneSynthesizer);
commonEdgeSynthesizers.add(diffDataPlaneSynthesizer);
commonEdgeSynthesizers.add(baseDataPlaneSynthesizer);
List<CompositeNodJob> jobs = new ArrayList<>();
// generate local edge reachability and black hole queries
pushDeltaEnvironment();
Topology diffTopology = loadTopology();
popEnvironment();
EdgeSet diffEdges = diffTopology.getEdges();
for (Edge edge : diffEdges) {
String ingressNode = edge.getNode1();
String outInterface = edge.getInt1();
String vrf = diffConfigurations.get(ingressNode).getInterfaces()
.get(outInterface).getVrf().getName();
ReachEdgeQuerySynthesizer reachQuery = new ReachEdgeQuerySynthesizer(
ingressNode, vrf, edge, true, headerSpace);
ReachEdgeQuerySynthesizer noReachQuery = new ReachEdgeQuerySynthesizer(
ingressNode, vrf, edge, true, new HeaderSpace());
noReachQuery.setNegate(true);
List<QuerySynthesizer> queries = new ArrayList<>();
queries.add(reachQuery);
queries.add(noReachQuery);
queries.add(blacklistQuery);
NodeVrfSet nodes = new NodeVrfSet();
nodes.add(new Pair<>(ingressNode, vrf));
CompositeNodJob job = new CompositeNodJob(settings,
commonEdgeSynthesizers, queries, nodes, tag);
jobs.add(job);
}
// we also need queries for nodes next to edges that are now missing,
// in the case that those nodes still exist
List<Synthesizer> missingEdgeSynthesizers = new ArrayList<>();
missingEdgeSynthesizers.add(baseDataPlaneSynthesizer);
missingEdgeSynthesizers.add(baseDataPlaneSynthesizer);
pushBaseEnvironment();
Topology baseTopology = loadTopology();
popEnvironment();
EdgeSet baseEdges = baseTopology.getEdges();
EdgeSet missingEdges = new EdgeSet();
missingEdges.addAll(baseEdges);
missingEdges.removeAll(diffEdges);
for (Edge missingEdge : missingEdges) {
String ingressNode = missingEdge.getNode1();
String outInterface = missingEdge.getInt1();
String vrf = diffConfigurations.get(ingressNode).getInterfaces()
.get(outInterface).getVrf().getName();
if (diffConfigurations.containsKey(ingressNode)) {
ReachEdgeQuerySynthesizer reachQuery = new ReachEdgeQuerySynthesizer(
ingressNode, vrf, missingEdge, true, headerSpace);
List<QuerySynthesizer> queries = new ArrayList<>();
queries.add(reachQuery);
queries.add(blacklistQuery);
NodeVrfSet nodes = new NodeVrfSet();
nodes.add(new Pair<>(ingressNode, vrf));
CompositeNodJob job = new CompositeNodJob(settings,
missingEdgeSynthesizers, queries, nodes, tag);
jobs.add(job);
}
}
// TODO: maybe do something with nod answer element
Set<Flow> flows = computeCompositeNodOutput(jobs, new NodAnswerElement());
pushBaseEnvironment();
getDataPlanePlugin().processFlows(flows);
popEnvironment();
pushDeltaEnvironment();
getDataPlanePlugin().processFlows(flows);
popEnvironment();
AnswerElement answerElement = getHistory();
return answerElement;
}
@Override
public void popEnvironment() {
int lastIndex = _testrigSettingsStack.size() - 1;
_testrigSettings = _testrigSettingsStack.get(lastIndex);
_testrigSettingsStack.remove(lastIndex);
}
private void populateFlowHistory(
FlowHistory flowHistory,
String environmentName, String tag) {
List<Flow> flows = _dataPlanePlugin.getHistoryFlows();
List<FlowTrace> flowTraces = _dataPlanePlugin.getHistoryFlowTraces();
int numEntries = flows.size();
for (int i = 0; i < numEntries; i++) {
Flow flow = flows.get(i);
if (flow.getTag().equals(tag)) {
FlowTrace flowTrace = flowTraces.get(i);
flowHistory.addFlowTrace(flow, environmentName, flowTrace);
}
}
}
private void postProcessConfigurations(
Collection<Configuration> configurations) {
// ComputeOSPF interface costs where they are missing
for (Configuration c : configurations) {
for (Vrf vrf : c.getVrfs().values()) {
OspfProcess proc = vrf.getOspfProcess();
if (proc != null) {
proc.initInterfaceCosts();
}
}
}
}
private String preprocessQuestion(String rawQuestionText) {
try {
JSONObject jobj = new JSONObject(rawQuestionText);
if (jobj.has(Question.INSTANCE_VAR)
&& !jobj.isNull(Question.INSTANCE_VAR)) {
String instanceDataStr = jobj.getString(Question.INSTANCE_VAR);
BatfishObjectMapper mapper = new BatfishObjectMapper();
InstanceData instanceData = mapper.<InstanceData>readValue(
instanceDataStr, new TypeReference<InstanceData>() {
});
for (Entry<String, Variable> e : instanceData.getVariables()
.entrySet()) {
String varName = e.getKey();
Variable variable = e.getValue();
JsonNode value = variable.getValue();
if (value == null) {
if (variable.getOptional()) {
/*
* For now we assume optional values are top-level
* variables and single-line. Otherwise it's not really
* clear what to do.
*/
jobj.remove(varName);
}
else {
// What to do here? For now, do nothing and assume that
// later validation will handle it.
}
continue;
}
if (variable.getType() == Variable.Type.QUESTION) {
if (variable.getMinElements() != null) {
if (!value.isArray()) {
throw new IllegalArgumentException(
"Expecting JSON array for array type");
}
JSONArray arr = new JSONArray();
for (int i = 0; i < value.size(); i++) {
String valueJsonString = new ObjectMapper()
.writeValueAsString(value.get(i));
arr.put(i, new JSONObject(
preprocessQuestion(valueJsonString)));
}
jobj.put(varName, arr);
}
else {
String valueJsonString = new ObjectMapper()
.writeValueAsString(value);
jobj.put(
varName,
new JSONObject(preprocessQuestion(valueJsonString)));
}
}
}
String questionText = jobj.toString();
for (Entry<String, Variable> e : instanceData.getVariables()
.entrySet()) {
String varName = e.getKey();
Variable variable = e.getValue();
JsonNode value = variable.getValue();
String valueJsonString = new ObjectMapper()
.writeValueAsString(value);
boolean stringType = variable.getType().getStringType();
boolean setType = variable.getMinElements() != null;
if (value != null) {
String topLevelVarNameRegex = Pattern
.quote("\"${" + varName + "}\"");
String inlineVarNameRegex = Pattern
.quote("${" + varName + "}");
String topLevelReplacement = valueJsonString;
String inlineReplacement;
if (stringType && !setType) {
inlineReplacement = valueJsonString.substring(
1,
valueJsonString.length() - 1);
}
else {
String quotedValueJsonString = JSONObject
.quote(valueJsonString);
inlineReplacement = quotedValueJsonString.substring(
1,
quotedValueJsonString.length() - 1);
}
String inlineReplacementRegex = Matcher
.quoteReplacement(inlineReplacement);
String topLevelReplacementRegex = Matcher
.quoteReplacement(topLevelReplacement);
questionText = questionText.replaceAll(
topLevelVarNameRegex,
topLevelReplacementRegex);
questionText = questionText.replaceAll(
inlineVarNameRegex,
inlineReplacementRegex);
}
}
return questionText;
}
return rawQuestionText;
}
catch (JSONException | IOException e) {
throw new BatfishException(
String.format(
"Could not convert raw question text [%s] to JSON",
rawQuestionText),
e);
}
}
@Override
public void printElapsedTime() {
double seconds = getElapsedTime(_timerCount);
_logger.info("Time taken for this task: " + seconds + " seconds\n");
}
private void printSymmetricEdgePairs() {
Map<String, Configuration> configs = loadConfigurations();
EdgeSet edges = synthesizeTopology(configs).getEdges();
Set<Edge> symmetricEdgePairs = getSymmetricEdgePairs(edges);
List<Edge> edgeList = new ArrayList<>();
edgeList.addAll(symmetricEdgePairs);
for (int i = 0; i < edgeList.size() / 2; i++) {
Edge edge1 = edgeList.get(2 * i);
Edge edge2 = edgeList.get(2 * i + 1);
_logger.output(edge1.getNode1() + ":" + edge1.getInt1() + ","
+ edge1.getNode2() + ":" + edge1.getInt2() + " "
+ edge2.getNode1() + ":" + edge2.getInt1() + ","
+ edge2.getNode2() + ":" + edge2.getInt2() + "\n");
}
printElapsedTime();
}
private void processDeltaConfigurations(
Map<String, Configuration> configurations) {
Map<String, Configuration> deltaConfigurations = getDeltaConfigurations();
configurations.putAll(deltaConfigurations);
// TODO: deal with topological changes
}
@Override
public AdvertisementSet processExternalBgpAnnouncements(
Map<String, Configuration> configurations) {
AdvertisementSet advertSet = new AdvertisementSet();
for (ExternalBgpAdvertisementPlugin plugin : _externalBgpAdvertisementPlugins) {
AdvertisementSet currentAdvertisements = plugin
.loadExternalBgpAdvertisements();
advertSet.addAll(currentAdvertisements);
}
return advertSet;
}
/**
* Reads the external bgp announcement specified in the environment, and
* populates the vendor-independent configurations with data about those
* announcements
*
* @param configurations
* The vendor-independent configurations to be modified
* @param allCommunities
*/
public AdvertisementSet processExternalBgpAnnouncements(
Map<String, Configuration> configurations,
SortedSet<Long> allCommunities) {
AdvertisementSet advertSet = new AdvertisementSet();
Path externalBgpAnnouncementsPath = _testrigSettings
.getEnvironmentSettings().getExternalBgpAnnouncementsPath();
if (Files.exists(externalBgpAnnouncementsPath)) {
String externalBgpAnnouncementsFileContents = CommonUtil
.readFile(externalBgpAnnouncementsPath);
// Populate advertSet with BgpAdvertisements that
// gets passed to populatePrecomputedBgpAdvertisements.
// See populatePrecomputedBgpAdvertisements for the things that get
// extracted from these advertisements.
try {
JSONObject jsonObj = new JSONObject(
externalBgpAnnouncementsFileContents);
JSONArray announcements = jsonObj
.getJSONArray(BfConsts.KEY_BGP_ANNOUNCEMENTS);
ObjectMapper mapper = new ObjectMapper();
for (int index = 0; index < announcements.length(); index++) {
JSONObject announcement = new JSONObject();
announcement.put("@id", index);
JSONObject announcementSrc = announcements.getJSONObject(index);
for (Iterator<?> i = announcementSrc.keys(); i.hasNext(); ) {
String key = (String) i.next();
if (!key.equals("@id")) {
announcement.put(key, announcementSrc.get(key));
}
}
BgpAdvertisement bgpAdvertisement = mapper.readValue(
announcement.toString(), BgpAdvertisement.class);
allCommunities.addAll(bgpAdvertisement.getCommunities());
advertSet.add(bgpAdvertisement);
}
}
catch (JSONException | IOException e) {
throw new BatfishException("Problems parsing JSON in "
+ externalBgpAnnouncementsPath.toString(), e);
}
}
return advertSet;
}
@Override
public void processFlows(Set<Flow> flows) {
_dataPlanePlugin.processFlows(flows);
}
private void processInterfaceBlacklist(
Map<String, Configuration> configurations) {
Set<NodeInterfacePair> blacklistInterfaces = getInterfaceBlacklist();
if (blacklistInterfaces != null) {
for (NodeInterfacePair p : blacklistInterfaces) {
String hostname = p.getHostname();
String ifaceName = p.getInterface();
Configuration node = configurations.get(hostname);
Interface iface = node.getInterfaces().get(ifaceName);
if (iface == null) {
throw new BatfishException(
"Cannot disable non-existent interface '" + ifaceName
+ "' on node '" + hostname + "'\n");
}
else {
iface.setActive(false);
iface.setBlacklisted(true);
}
}
}
}
private void processNodeBlacklist(
Map<String, Configuration> configurations) {
NodeSet blacklistNodes = getNodeBlacklist();
if (blacklistNodes != null) {
for (String hostname : blacklistNodes) {
Configuration node = configurations.get(hostname);
if (node != null) {
for (Interface iface : node.getInterfaces().values()) {
iface.setActive(false);
iface.setBlacklisted(true);
}
}
}
}
}
private Topology processTopologyFile(Path topologyFilePath) {
Topology topology = parseTopology(topologyFilePath);
return topology;
}
@Override
public void pushBaseEnvironment() {
_testrigSettingsStack.add(_testrigSettings);
_testrigSettings = _baseTestrigSettings;
}
@Override
public void pushDeltaEnvironment() {
_testrigSettingsStack.add(_testrigSettings);
_testrigSettings = _deltaTestrigSettings;
}
private Map<Path, String> readConfigurationFiles(
Path testRigPath,
String configsType) {
_logger.infof("\n*** READING %s FILES ***\n", configsType);
resetTimer();
Map<Path, String> configurationData = new TreeMap<>();
Path configsPath = testRigPath.resolve(configsType);
List<Path> configFilePaths = listAllFiles(configsPath);
AtomicInteger completed = newBatch(
"Reading network configuration files",
configFilePaths.size());
for (Path file : configFilePaths) {
_logger.debug("Reading: \"" + file.toString() + "\"\n");
String fileTextRaw = CommonUtil.readFile(file.toAbsolutePath());
String fileText = fileTextRaw
+ ((fileTextRaw.length() != 0) ? "\n" : "");
configurationData.put(file, fileText);
completed.incrementAndGet();
}
printElapsedTime();
return configurationData;
}
@Override
public String readExternalBgpAnnouncementsFile() {
Path externalBgpAnnouncementsPath = _testrigSettings
.getEnvironmentSettings().getExternalBgpAnnouncementsPath();
if (Files.exists(externalBgpAnnouncementsPath)) {
String externalBgpAnnouncementsFileContents = CommonUtil
.readFile(externalBgpAnnouncementsPath);
return externalBgpAnnouncementsFileContents;
}
else {
return null;
}
}
private SortedMap<Path, String> readFiles(
Path directory,
String description) {
_logger.infof("\n*** READING FILES: %s ***\n", description);
resetTimer();
SortedMap<Path, String> fileData = new TreeMap<>();
List<Path> filePaths;
try (Stream<Path> paths = CommonUtil.list(directory)) {
filePaths = paths
.filter(path -> !path.getFileName().toString().startsWith("."))
.sorted()
.collect(Collectors.toList());
}
AtomicInteger completed = newBatch(
"Reading files: " + description,
filePaths.size());
for (Path file : filePaths) {
_logger.debug("Reading: \"" + file.toString() + "\"\n");
String fileTextRaw = CommonUtil.readFile(file.toAbsolutePath());
String fileText = fileTextRaw
+ ((fileTextRaw.length() != 0) ? "\n" : "");
fileData.put(file, fileText);
completed.incrementAndGet();
}
printElapsedTime();
return fileData;
}
@Override
public AnswerElement reducedReachability(HeaderSpace headerSpace) {
if (SystemUtils.IS_OS_MAC_OSX) {
// TODO: remove when z3 parallelism bug on OSX is fixed
_settings.setSequential(true);
}
Settings settings = getSettings();
checkDifferentialDataPlaneQuestionDependencies();
String tag = getDifferentialFlowTag();
// load base configurations and generate base data plane
pushBaseEnvironment();
Map<String, Configuration> baseConfigurations = loadConfigurations();
Synthesizer baseDataPlaneSynthesizer = synthesizeDataPlane();
popEnvironment();
// load diff configurations and generate diff data plane
pushDeltaEnvironment();
Map<String, Configuration> diffConfigurations = loadConfigurations();
Synthesizer diffDataPlaneSynthesizer = synthesizeDataPlane();
popEnvironment();
Set<String> commonNodes = new TreeSet<>();
commonNodes.addAll(baseConfigurations.keySet());
commonNodes.retainAll(diffConfigurations.keySet());
pushDeltaEnvironment();
NodeSet blacklistNodes = getNodeBlacklist();
Set<NodeInterfacePair> blacklistInterfaces = getInterfaceBlacklist();
EdgeSet blacklistEdges = getEdgeBlacklist();
popEnvironment();
BlacklistDstIpQuerySynthesizer blacklistQuery = new BlacklistDstIpQuerySynthesizer(
null, blacklistNodes, blacklistInterfaces, blacklistEdges,
baseConfigurations);
// compute composite program and flows
List<Synthesizer> synthesizers = new ArrayList<>();
synthesizers.add(baseDataPlaneSynthesizer);
synthesizers.add(diffDataPlaneSynthesizer);
synthesizers.add(baseDataPlaneSynthesizer);
List<CompositeNodJob> jobs = new ArrayList<>();
// generate base reachability and diff blackhole and blacklist queries
for (String node : commonNodes) {
for (String vrf : baseConfigurations.get(node).getVrfs().keySet()) {
Map<String, Set<String>> nodeVrfs = new TreeMap<>();
nodeVrfs.put(node, Collections.singleton(vrf));
ReachabilityQuerySynthesizer acceptQuery = new ReachabilityQuerySynthesizer(
Collections.singleton(ForwardingAction.ACCEPT), headerSpace,
Collections.<String>emptySet(), nodeVrfs);
ReachabilityQuerySynthesizer notAcceptQuery = new ReachabilityQuerySynthesizer(
Collections.singleton(ForwardingAction.ACCEPT),
new HeaderSpace(), Collections.<String>emptySet(), nodeVrfs);
notAcceptQuery.setNegate(true);
NodeVrfSet nodes = new NodeVrfSet();
nodes.add(new Pair<>(node, vrf));
List<QuerySynthesizer> queries = new ArrayList<>();
queries.add(acceptQuery);
queries.add(notAcceptQuery);
queries.add(blacklistQuery);
CompositeNodJob job = new CompositeNodJob(settings, synthesizers,
queries, nodes, tag);
jobs.add(job);
}
}
// TODO: maybe do something with nod answer element
Set<Flow> flows = computeCompositeNodOutput(jobs, new NodAnswerElement());
pushBaseEnvironment();
getDataPlanePlugin().processFlows(flows);
popEnvironment();
pushDeltaEnvironment();
getDataPlanePlugin().processFlows(flows);
popEnvironment();
AnswerElement answerElement = getHistory();
return answerElement;
}
@Override
public void registerAnswerer(
String questionName, String questionClassName,
BiFunction<Question, IBatfish, Answerer> answererCreator) {
_answererCreators.put(questionName, answererCreator);
}
@Override
public void registerBgpTablePlugin(
BgpTableFormat format,
BgpTablePlugin bgpTablePlugin) {
_bgpTablePlugins.put(format, bgpTablePlugin);
}
@Override
public void registerExternalBgpAdvertisementPlugin(
ExternalBgpAdvertisementPlugin externalBgpAdvertisementPlugin) {
_externalBgpAdvertisementPlugins.add(externalBgpAdvertisementPlugin);
}
private void repairConfigurations() {
Path outputPath = _testrigSettings.getSerializeIndependentPath();
CommonUtil.deleteDirectory(outputPath);
ParseVendorConfigurationAnswerElement pvcae = loadParseVendorConfigurationAnswerElement();
if (!Version.isCompatibleVersion("Service", "Old parsed configurations",
pvcae.getVersion())) {
repairVendorConfigurations();
}
Path inputPath = _testrigSettings.getSerializeVendorPath();
serializeIndependentConfigs(inputPath, outputPath);
}
private void repairDataPlane() {
Path dataPlanePath = _testrigSettings.getEnvironmentSettings()
.getDataPlanePath();
Path dataPlaneAnswerPath = _testrigSettings.getEnvironmentSettings()
.getDataPlaneAnswerPath();
CommonUtil.deleteIfExists(dataPlanePath);
CommonUtil.deleteIfExists(dataPlaneAnswerPath);
computeDataPlane(false);
}
private void repairEnvironmentBgpTables() {
EnvironmentSettings envSettings = _testrigSettings
.getEnvironmentSettings();
Path answerPath = envSettings.getParseEnvironmentBgpTablesAnswerPath();
Path bgpTablesOutputPath = envSettings
.getSerializeEnvironmentBgpTablesPath();
CommonUtil.deleteIfExists(answerPath);
CommonUtil.deleteDirectory(bgpTablesOutputPath);
computeEnvironmentBgpTables();
}
private void repairEnvironmentRoutingTables() {
EnvironmentSettings envSettings = _testrigSettings
.getEnvironmentSettings();
Path answerPath = envSettings
.getParseEnvironmentRoutingTablesAnswerPath();
Path rtOutputPath = envSettings
.getSerializeEnvironmentRoutingTablesPath();
CommonUtil.deleteIfExists(answerPath);
CommonUtil.deleteDirectory(rtOutputPath);
computeEnvironmentRoutingTables();
}
private void repairVendorConfigurations() {
Path outputPath = _testrigSettings.getSerializeVendorPath();
CommonUtil.deleteDirectory(outputPath);
Path testRigPath = _testrigSettings.getTestRigPath();
serializeVendorConfigs(testRigPath, outputPath);
}
private AnswerElement report() {
ReportAnswerElement answerElement = new ReportAnswerElement();
checkQuestionsDirExists();
Path questionsDir = _settings.getActiveTestrigSettings().getBasePath()
.resolve(BfConsts.RELPATH_QUESTIONS_DIR);
ConcurrentMap<Path, String> answers = new ConcurrentHashMap<>();
try (DirectoryStream<Path> questions = Files.newDirectoryStream(questionsDir)) {
questions
.forEach(questionDirPath -> answers.put(
questionDirPath.resolve(BfConsts.RELPATH_ANSWER_JSON),
!questionDirPath.getFileName().startsWith(".")
&& Files.exists(questionDirPath
.resolve(BfConsts.RELPATH_ANSWER_JSON))
? CommonUtil
.readFile(questionDirPath.resolve(
BfConsts.RELPATH_ANSWER_JSON))
: ""));
}
catch (IOException e1) {
throw new BatfishException("Could not create directory stream for '"
+ questionsDir.toString() + "'", e1);
}
ObjectMapper mapper = new BatfishObjectMapper();
for (Entry<Path, String> entry : answers.entrySet()) {
Path answerPath = entry.getKey();
String answerText = entry.getValue();
if (!answerText.equals("")) {
try {
answerElement.getJsonAnswers().add(mapper.readTree(answerText));
}
catch (IOException e) {
throw new BatfishException("Error mapping JSON content of '"
+ answerPath.toString() + "' to object", e);
}
}
}
return answerElement;
}
@Override
public void resetTimer() {
_timerCount = System.currentTimeMillis();
}
public Answer run() {
newBatch("Begin job", 0);
loadPlugins();
if (_dataPlanePlugin == null) {
_dataPlanePlugin = new BdpDataPlanePlugin();
_dataPlanePlugin.initialize(this);
}
JsonExternalBgpAdvertisementPlugin jsonExternalBgpAdvertisementsPlugin =
new JsonExternalBgpAdvertisementPlugin();
jsonExternalBgpAdvertisementsPlugin.initialize(this);
_externalBgpAdvertisementPlugins.add(jsonExternalBgpAdvertisementsPlugin);
boolean action = false;
Answer answer = new Answer();
if (_settings.getPrintSymmetricEdgePairs()) {
printSymmetricEdgePairs();
return answer;
}
if (_settings.getReport()) {
answer.addAnswerElement(report());
return answer;
}
if (_settings.getSynthesizeTopology()) {
writeSynthesizedTopology();
return answer;
}
if (_settings.getSynthesizeJsonTopology()) {
writeJsonTopology();
return answer;
}
if (_settings.getHistogram()) {
histogram(_testrigSettings.getTestRigPath());
return answer;
}
if (_settings.getGenerateOspfTopologyPath() != null) {
generateOspfConfigs(
_settings.getGenerateOspfTopologyPath(),
_testrigSettings.getSerializeIndependentPath());
return answer;
}
if (_settings.getFlatten()) {
Path flattenSource = _testrigSettings.getTestRigPath();
Path flattenDestination = _settings.getFlattenDestination();
flatten(flattenSource, flattenDestination);
return answer;
}
if (_settings.getGenerateStubs()) {
String inputRole = _settings.getGenerateStubsInputRole();
String interfaceDescriptionRegex = _settings
.getGenerateStubsInterfaceDescriptionRegex();
int stubAs = _settings.getGenerateStubsRemoteAs();
generateStubs(inputRole, stubAs, interfaceDescriptionRegex);
return answer;
}
// if (_settings.getZ3()) {
// Map<String, Configuration> configurations = loadConfigurations();
// String dataPlanePath = _envSettings.getDataPlanePath();
// if (dataPlanePath == null) {
// throw new BatfishException("Missing path to data plane");
// File dataPlanePathAsFile = new File(dataPlanePath);
// genZ3(configurations, dataPlanePathAsFile);
// return answer;
if (_settings.getAnonymize()) {
anonymizeConfigurations();
return answer;
}
// if (_settings.getRoleTransitQuery()) {
// genRoleTransitQueries();
// return answer;
if (_settings.getSerializeVendor()) {
Path testRigPath = _testrigSettings.getTestRigPath();
Path outputPath = _testrigSettings.getSerializeVendorPath();
answer.append(serializeVendorConfigs(testRigPath, outputPath));
action = true;
}
if (_settings.getSerializeIndependent()) {
Path inputPath = _testrigSettings.getSerializeVendorPath();
Path outputPath = _testrigSettings.getSerializeIndependentPath();
answer.append(serializeIndependentConfigs(inputPath, outputPath));
action = true;
}
if (_settings.getInitInfo()) {
answer.addAnswerElement(initInfo(true, false));
action = true;
}
if (_settings.getCompileEnvironment()) {
answer.append(compileEnvironmentConfigurations(_testrigSettings));
action = true;
}
if (_settings.getAnswer()) {
answer.append(answer());
action = true;
}
if (_settings.getAnalyze()) {
answer.append(analyze());
action = true;
}
if (_settings.getDataPlane()) {
answer.append(computeDataPlane(_settings.getDiffActive()));
action = true;
}
if (!action) {
throw new CleanBatfishException(
"No task performed! Run with -help flag to see usage\n");
}
return answer;
}
private Answer serializeAwsVpcConfigs(Path testRigPath, Path outputPath) {
Answer answer = new Answer();
Map<Path, String> configurationData = readConfigurationFiles(
testRigPath,
BfConsts.RELPATH_AWS_VPC_CONFIGS_DIR);
AwsVpcConfiguration config = parseAwsVpcConfigurations(configurationData);
_logger.info("\n*** SERIALIZING AWS CONFIGURATION STRUCTURES ***\n");
resetTimer();
outputPath.toFile().mkdirs();
Path currentOutputPath = outputPath
.resolve(BfConsts.RELPATH_AWS_VPC_CONFIGS_FILE);
_logger.debug("Serializing AWS VPCs to " + currentOutputPath.toString()
+ "\"...");
serializeObject(config, currentOutputPath);
_logger.debug("OK\n");
printElapsedTime();
return answer;
}
private Answer serializeEnvironmentBgpTables(
Path inputPath,
Path outputPath) {
Answer answer = new Answer();
ParseEnvironmentBgpTablesAnswerElement answerElement =
new ParseEnvironmentBgpTablesAnswerElement();
answerElement.setVersion(Version.getVersion());
answer.addAnswerElement(answerElement);
SortedMap<String, BgpAdvertisementsByVrf> bgpTables = getEnvironmentBgpTables(
inputPath, answerElement);
serializeEnvironmentBgpTables(bgpTables, outputPath);
serializeObject(answerElement, _testrigSettings.getEnvironmentSettings()
.getParseEnvironmentBgpTablesAnswerPath());
return answer;
}
private void serializeEnvironmentBgpTables(
SortedMap<String, BgpAdvertisementsByVrf> bgpTables, Path outputPath) {
if (bgpTables == null) {
throw new BatfishException("Exiting due to parsing error(s)");
}
_logger.info("\n*** SERIALIZING ENVIRONMENT BGP TABLES ***\n");
resetTimer();
outputPath.toFile().mkdirs();
SortedMap<Path, BgpAdvertisementsByVrf> output = new TreeMap<>();
bgpTables.forEach((name, rt) -> {
Path currentOutputPath = outputPath.resolve(name);
output.put(currentOutputPath, rt);
});
serializeObjects(output);
printElapsedTime();
}
private Answer serializeEnvironmentRoutingTables(
Path inputPath,
Path outputPath) {
Answer answer = new Answer();
ParseEnvironmentRoutingTablesAnswerElement answerElement =
new ParseEnvironmentRoutingTablesAnswerElement();
answerElement.setVersion(Version.getVersion());
answer.addAnswerElement(answerElement);
SortedMap<String, RoutesByVrf> routingTables = getEnvironmentRoutingTables(
inputPath, answerElement);
serializeEnvironmentRoutingTables(routingTables, outputPath);
serializeObject(answerElement, _testrigSettings.getEnvironmentSettings()
.getParseEnvironmentRoutingTablesAnswerPath());
return answer;
}
private void serializeEnvironmentRoutingTables(
SortedMap<String, RoutesByVrf> routingTables, Path outputPath) {
if (routingTables == null) {
throw new BatfishException("Exiting due to parsing error(s)");
}
_logger.info("\n*** SERIALIZING ENVIRONMENT ROUTING TABLES ***\n");
resetTimer();
outputPath.toFile().mkdirs();
SortedMap<Path, RoutesByVrf> output = new TreeMap<>();
routingTables.forEach((name, rt) -> {
Path currentOutputPath = outputPath.resolve(name);
output.put(currentOutputPath, rt);
});
serializeObjects(output);
printElapsedTime();
}
private void serializeHostConfigs(
Path testRigPath, Path outputPath,
ParseVendorConfigurationAnswerElement answerElement) {
Map<Path, String> configurationData = readConfigurationFiles(
testRigPath,
BfConsts.RELPATH_HOST_CONFIGS_DIR);
// read the host files
Map<String, VendorConfiguration> hostConfigurations = parseVendorConfigurations(
configurationData, answerElement, ConfigurationFormat.HOST);
if (hostConfigurations == null) {
throw new BatfishException("Exiting due to parser errors");
}
// assign roles if that file exists
Path nodeRolesPath = _settings.getNodeRolesPath();
if (nodeRolesPath != null) {
NodeRoleMap nodeRoles = parseNodeRoles(testRigPath);
for (Entry<String, RoleSet> nodeRolesEntry : nodeRoles.entrySet()) {
String hostname = nodeRolesEntry.getKey();
VendorConfiguration config = hostConfigurations.get(hostname);
if (config == null) {
throw new BatfishException(
"role set assigned to non-existent node: \"" + hostname
+ "\"");
}
RoleSet roles = nodeRolesEntry.getValue();
config.setRoles(roles);
}
_logger.info(
"Serializing node-roles mappings: \"" + nodeRolesPath + "\"...");
serializeObject(nodeRoles, nodeRolesPath);
_logger.info("OK\n");
}
// read and associate iptables files for specified hosts
Map<Path, String> iptablesData = new TreeMap<>();
for (VendorConfiguration vc : hostConfigurations.values()) {
HostConfiguration hostConfig = (HostConfiguration) vc;
if (hostConfig.getIptablesFile() != null) {
Path path = Paths.get(
testRigPath.toString(),
hostConfig.getIptablesFile());
// ensure that the iptables file is not taking us outside of the
// testrig
try {
if (testRigPath.toFile().getCanonicalPath()
.contains(path.toFile().getCanonicalPath())) {
throw new BatfishException(
"Iptables file " + hostConfig.getIptablesFile()
+ " for host " + hostConfig.getHostname()
+ "is not contained within the testrig");
}
}
catch (IOException e) {
throw new BatfishException("Could not get canonical path", e);
}
String fileText = CommonUtil.readFile(path);
iptablesData.put(path, fileText);
}
}
Map<String, VendorConfiguration> iptablesConfigurations = parseVendorConfigurations(
iptablesData, answerElement, ConfigurationFormat.IPTABLES);
for (VendorConfiguration vc : hostConfigurations.values()) {
HostConfiguration hostConfig = (HostConfiguration) vc;
if (hostConfig.getIptablesFile() != null) {
Path path = Paths.get(
testRigPath.toString(),
hostConfig.getIptablesFile());
String relativePathStr = _testrigSettings.getBasePath()
.relativize(path).toString();
if (!iptablesConfigurations.containsKey(relativePathStr)) {
for (String key : iptablesConfigurations.keySet()) {
_logger.errorf("key : %s\n", key);
}
throw new BatfishException(
"Key not found for iptables: " + relativePathStr);
}
hostConfig.setIptablesConfig(
(IptablesVendorConfiguration) iptablesConfigurations
.get(relativePathStr));
}
}
// now, serialize
_logger.info("\n*** SERIALIZING VENDOR CONFIGURATION STRUCTURES ***\n");
resetTimer();
CommonUtil.createDirectories(outputPath);
Map<Path, VendorConfiguration> output = new TreeMap<>();
hostConfigurations.forEach((name, vc) -> {
Path currentOutputPath = outputPath.resolve(name);
output.put(currentOutputPath, vc);
});
serializeObjects(output);
// serialize warnings
serializeObject(answerElement, _testrigSettings.getParseAnswerPath());
printElapsedTime();
}
private void serializeIndependentConfigs(
Map<String, Configuration> configurations, Path outputPath) {
if (configurations == null) {
throw new BatfishException("Exiting due to conversion error(s)");
}
_logger.info(
"\n*** SERIALIZING VENDOR-INDEPENDENT CONFIGURATION STRUCTURES ***\n");
resetTimer();
outputPath.toFile().mkdirs();
Map<Path, Configuration> output = new TreeMap<>();
configurations.forEach((name, c) -> {
Path currentOutputPath = outputPath.resolve(name);
output.put(currentOutputPath, c);
});
serializeObjects(output);
printElapsedTime();
}
private Answer serializeIndependentConfigs(
Path vendorConfigPath,
Path outputPath) {
Answer answer = new Answer();
ConvertConfigurationAnswerElement answerElement = new ConvertConfigurationAnswerElement();
answerElement.setVersion(Version.getVersion());
if (_settings.getVerboseParse()) {
answer.addAnswerElement(answerElement);
}
Map<String, Configuration> configurations = getConfigurations(
vendorConfigPath, answerElement);
serializeIndependentConfigs(configurations, outputPath);
serializeObject(answerElement, _testrigSettings.getConvertAnswerPath());
return answer;
}
private void serializeNetworkConfigs(
Path testRigPath, Path outputPath,
ParseVendorConfigurationAnswerElement answerElement) {
Map<Path, String> configurationData = readConfigurationFiles(
testRigPath,
BfConsts.RELPATH_CONFIGURATIONS_DIR);
Map<String, VendorConfiguration> vendorConfigurations = parseVendorConfigurations(
configurationData, answerElement, ConfigurationFormat.UNKNOWN);
if (vendorConfigurations == null) {
throw new BatfishException("Exiting due to parser errors");
}
Path nodeRolesPath = _settings.getNodeRolesPath();
if (nodeRolesPath != null) {
NodeRoleMap nodeRoles = parseNodeRoles(testRigPath);
for (Entry<String, RoleSet> nodeRolesEntry : nodeRoles.entrySet()) {
String hostname = nodeRolesEntry.getKey();
VendorConfiguration config = vendorConfigurations.get(hostname);
if (config == null) {
throw new BatfishException(
"role set assigned to non-existent node: \"" + hostname
+ "\"");
}
RoleSet roles = nodeRolesEntry.getValue();
config.setRoles(roles);
}
_logger.info(
"Serializing node-roles mappings: \"" + nodeRolesPath + "\"...");
serializeObject(nodeRoles, nodeRolesPath);
_logger.info("OK\n");
}
_logger.info("\n*** SERIALIZING VENDOR CONFIGURATION STRUCTURES ***\n");
resetTimer();
CommonUtil.createDirectories(outputPath);
Map<Path, VendorConfiguration> output = new TreeMap<>();
vendorConfigurations.forEach((name, vc) -> {
if (name.contains(File.separator)) {
// iptables will get a hostname like configs/iptables-save if they
// are not set up correctly using host files
_logger.errorf(
"Cannot serialize configuration with hostname %s\n",
name);
answerElement
.addRedFlagWarning(
name,
new Warning(
"Cannot serialize network config. Bad hostname "
+ name.replace("\\", "/"),
"MISCELLANEOUS"));
}
else {
Path currentOutputPath = outputPath.resolve(name);
output.put(currentOutputPath, vc);
}
});
serializeObjects(output);
printElapsedTime();
}
public <S extends Serializable> void serializeObjects(
Map<Path, S> objectsByPath) {
if (objectsByPath.isEmpty()) {
return;
}
BatfishLogger logger = getLogger();
Map<Path, byte[]> dataByPath = new ConcurrentHashMap<>();
int size = objectsByPath.size();
String className = objectsByPath.values().iterator().next().getClass()
.getName();
AtomicInteger serializeCompleted = newBatch(
"Serializing '" + className + "' instances", size);
objectsByPath.keySet().parallelStream().forEach(outputPath -> {
S object = objectsByPath.get(outputPath);
byte[] gzipData = toGzipData(object);
dataByPath.put(outputPath, gzipData);
serializeCompleted.incrementAndGet();
});
AtomicInteger writeCompleted = newBatch(
"Packing and writing '" + className + "' instances to disk", size);
dataByPath.forEach((outputPath, data) -> {
logger.debug("Writing: \"" + outputPath.toString() + "\"...");
try {
Files.write(outputPath, data);
}
catch (IOException e) {
throw new BatfishException(
"Failed to write: '" + outputPath.toString() + "'");
}
logger.debug("OK\n");
writeCompleted.incrementAndGet();
});
}
private Answer serializeVendorConfigs(Path testRigPath, Path outputPath) {
Answer answer = new Answer();
boolean configsFound = false;
// look for network configs
Path networkConfigsPath = testRigPath
.resolve(BfConsts.RELPATH_CONFIGURATIONS_DIR);
ParseVendorConfigurationAnswerElement answerElement =
new ParseVendorConfigurationAnswerElement();
answerElement.setVersion(Version.getVersion());
if (_settings.getVerboseParse()) {
answer.addAnswerElement(answerElement);
}
if (Files.exists(networkConfigsPath)) {
serializeNetworkConfigs(testRigPath, outputPath, answerElement);
configsFound = true;
}
// look for AWS VPC configs
Path awsVpcConfigsPath = testRigPath
.resolve(BfConsts.RELPATH_AWS_VPC_CONFIGS_DIR);
if (Files.exists(awsVpcConfigsPath)) {
answer.append(serializeAwsVpcConfigs(testRigPath, outputPath));
configsFound = true;
}
// look for host configs
Path hostConfigsPath = testRigPath
.resolve(BfConsts.RELPATH_HOST_CONFIGS_DIR);
if (Files.exists(hostConfigsPath)) {
serializeHostConfigs(testRigPath, outputPath, answerElement);
configsFound = true;
}
if (!configsFound) {
throw new BatfishException("No valid configurations found");
}
// serialize warnings
serializeObject(answerElement, _testrigSettings.getParseAnswerPath());
return answer;
}
@Override
public void setDataPlanePlugin(DataPlanePlugin dataPlanePlugin) {
_dataPlanePlugin = dataPlanePlugin;
}
public void setTerminatedWithException(boolean terminatedWithException) {
_terminatedWithException = terminatedWithException;
}
@Override
public AnswerElement standard(
HeaderSpace headerSpace,
Set<ForwardingAction> actions, String ingressNodeRegexStr,
String notIngressNodeRegexStr, String finalNodeRegexStr,
String notFinalNodeRegexStr) {
if (SystemUtils.IS_OS_MAC_OSX) {
// TODO: remove when z3 parallelism bug on OSX is fixed
_settings.setSequential(true);
}
Settings settings = getSettings();
String tag = getFlowTag(_testrigSettings);
Map<String, Configuration> configurations = loadConfigurations();
Set<Flow> flows = null;
Synthesizer dataPlaneSynthesizer = synthesizeDataPlane();
// collect ingress nodes
Pattern ingressNodeRegex = Pattern.compile(ingressNodeRegexStr);
Pattern notIngressNodeRegex = Pattern.compile(notIngressNodeRegexStr);
Set<String> activeIngressNodes = new TreeSet<>();
for (String node : configurations.keySet()) {
Matcher ingressNodeMatcher = ingressNodeRegex.matcher(node);
Matcher notIngressNodeMatcher = notIngressNodeRegex.matcher(node);
if (ingressNodeMatcher.matches() && !notIngressNodeMatcher.matches()) {
activeIngressNodes.add(node);
}
}
if (activeIngressNodes.isEmpty()) {
return new StringAnswerElement(
"NOTHING TO DO: No nodes both match ingressNodeRegex: '"
+ ingressNodeRegexStr
+ "' and fail to match notIngressNodeRegex: '"
+ notIngressNodeRegexStr + "'");
}
// collect final nodes
Pattern finalNodeRegex = Pattern.compile(finalNodeRegexStr);
Pattern notFinalNodeRegex = Pattern.compile(notFinalNodeRegexStr);
Set<String> activeFinalNodes = new TreeSet<>();
for (String node : configurations.keySet()) {
Matcher finalNodeMatcher = finalNodeRegex.matcher(node);
Matcher notFinalNodeMatcher = notFinalNodeRegex.matcher(node);
if (finalNodeMatcher.matches() && !notFinalNodeMatcher.matches()) {
activeFinalNodes.add(node);
}
}
if (activeFinalNodes.isEmpty()) {
return new StringAnswerElement(
"NOTHING TO DO: No nodes both match finalNodeRegex: '"
+ finalNodeRegexStr
+ "' and fail to match notFinalNodeRegex: '"
+ notFinalNodeRegexStr + "'");
}
// build query jobs
List<NodJob> jobs = new ArrayList<>();
for (String ingressNode : activeIngressNodes) {
for (String ingressVrf : configurations.get(ingressNode).getVrfs()
.keySet()) {
Map<String, Set<String>> nodeVrfs = new TreeMap<>();
nodeVrfs.put(ingressNode, Collections.singleton(ingressVrf));
ReachabilityQuerySynthesizer query = new ReachabilityQuerySynthesizer(
actions, headerSpace, activeFinalNodes, nodeVrfs);
NodeVrfSet nodes = new NodeVrfSet();
nodes.add(new Pair<>(ingressNode, ingressVrf));
NodJob job = new NodJob(settings, dataPlaneSynthesizer, query,
nodes, tag);
jobs.add(job);
}
}
// run jobs and get resulting flows
flows = computeNodOutput(jobs);
getDataPlanePlugin().processFlows(flows);
AnswerElement answerElement = getHistory();
return answerElement;
}
private Synthesizer synthesizeAcls(
Map<String, Configuration> configurations) {
_logger.info("\n*** GENERATING Z3 LOGIC ***\n");
resetTimer();
_logger.info("Synthesizing Z3 ACL logic...");
Synthesizer s = new Synthesizer(configurations, _settings.getSimplify());
List<String> warnings = s.getWarnings();
int numWarnings = warnings.size();
if (numWarnings == 0) {
_logger.info("OK\n");
}
else {
for (String warning : warnings) {
_logger.warn(warning);
}
}
printElapsedTime();
return s;
}
public Synthesizer synthesizeDataPlane() {
_logger.info("\n*** GENERATING Z3 LOGIC ***\n");
resetTimer();
DataPlane dataPlane = loadDataPlane();
_logger.info("Synthesizing Z3 logic...");
Map<String, Configuration> configurations = loadConfigurations();
Synthesizer s = new Synthesizer(configurations, dataPlane,
_settings.getSimplify());
List<String> warnings = s.getWarnings();
int numWarnings = warnings.size();
if (numWarnings == 0) {
_logger.info("OK\n");
}
else {
for (String warning : warnings) {
_logger.warn(warning);
}
}
printElapsedTime();
return s;
}
private Topology synthesizeTopology(
Map<String, Configuration> configurations) {
_logger.info(
"\n*** SYNTHESIZING TOPOLOGY FROM INTERFACE SUBNET INFORMATION ***\n");
resetTimer();
EdgeSet edges = new EdgeSet();
Map<Prefix, Set<NodeInterfacePair>> prefixInterfaces = new HashMap<>();
configurations.forEach((nodeName, node) -> {
for (Entry<String, Interface> e : node.getInterfaces().entrySet()) {
String ifaceName = e.getKey();
Interface iface = e.getValue();
if (!iface.isLoopback(node.getConfigurationFormat())
&& iface.getActive()) {
for (Prefix prefix : iface.getAllPrefixes()) {
if (prefix.getPrefixLength() < 32) {
Prefix network = new Prefix(
prefix.getNetworkAddress(),
prefix.getPrefixLength());
NodeInterfacePair pair = new NodeInterfacePair(
nodeName,
ifaceName);
Set<NodeInterfacePair> interfaceBucket =
prefixInterfaces.computeIfAbsent(network, k -> new HashSet<>());
interfaceBucket.add(pair);
}
}
}
}
});
for (Set<NodeInterfacePair> bucket : prefixInterfaces.values()) {
for (NodeInterfacePair p1 : bucket) {
for (NodeInterfacePair p2 : bucket) {
if (!p1.equals(p2)) {
Edge edge = new Edge(p1, p2);
edges.add(edge);
}
}
}
}
return new Topology(edges);
}
@Override
public void writeDataPlane(DataPlane dp, DataPlaneAnswerElement ae) {
_cachedDataPlanes.put(_testrigSettings, dp);
serializeObject(
dp,
_testrigSettings.getEnvironmentSettings().getDataPlanePath());
serializeObject(
ae,
_testrigSettings.getEnvironmentSettings().getDataPlaneAnswerPath());
}
private void writeJsonAnswer(
String structuredAnswerString,
String prettyAnswerString) {
Path questionPath = _settings.getQuestionPath();
if (questionPath != null) {
Path questionDir = questionPath.getParent();
if (!Files.exists(questionDir)) {
throw new BatfishException(
"Could not write JSON answer to question dir '"
+ questionDir.toString()
+ "' because it does not exist");
}
boolean diff = _settings.getDiffQuestion();
String baseEnvName = _testrigSettings.getEnvironmentSettings()
.getName();
Path answerDir = questionDir.resolve(Paths
.get(BfConsts.RELPATH_ENVIRONMENTS_DIR, baseEnvName).toString());
if (diff) {
String deltaTestrigName = _deltaTestrigSettings.getName();
String deltaEnvName = _deltaTestrigSettings.getEnvironmentSettings()
.getName();
answerDir = answerDir.resolve(Paths
.get(BfConsts.RELPATH_DELTA, deltaTestrigName, deltaEnvName)
.toString());
}
Path structuredAnswerPath = answerDir
.resolve(BfConsts.RELPATH_ANSWER_JSON);
Path prettyAnswerPath = answerDir
.resolve(BfConsts.RELPATH_ANSWER_PRETTY_JSON);
answerDir.toFile().mkdirs();
CommonUtil.writeFile(structuredAnswerPath, structuredAnswerString);
CommonUtil.writeFile(prettyAnswerPath, prettyAnswerString);
}
}
private void writeJsonAnswerWithLog(
String answerString,
String structuredAnswerString, String prettyAnswerString) {
Path jsonPath = _settings.getAnswerJsonPath();
if (jsonPath != null) {
CommonUtil.writeFile(jsonPath, answerString);
}
Path questionPath = _settings.getQuestionPath();
if (questionPath != null) {
Path questionDir = questionPath.getParent();
if (!Files.exists(questionDir)) {
throw new BatfishException(
"Could not write JSON answer to question dir '"
+ questionDir.toString()
+ "' because it does not exist");
}
boolean diff = _settings.getDiffQuestion();
String baseEnvName = _testrigSettings.getEnvironmentSettings()
.getName();
Path answerDir = questionDir.resolve(Paths
.get(BfConsts.RELPATH_ENVIRONMENTS_DIR, baseEnvName).toString());
if (diff) {
String deltaTestrigName = _deltaTestrigSettings.getName();
String deltaEnvName = _deltaTestrigSettings.getEnvironmentSettings()
.getName();
answerDir = answerDir.resolve(Paths
.get(BfConsts.RELPATH_DELTA, deltaTestrigName, deltaEnvName)
.toString());
}
Path structuredAnswerPath = answerDir
.resolve(BfConsts.RELPATH_ANSWER_JSON);
Path prettyAnswerPath = answerDir
.resolve(BfConsts.RELPATH_ANSWER_PRETTY_JSON);
answerDir.toFile().mkdirs();
CommonUtil.writeFile(structuredAnswerPath, structuredAnswerString);
CommonUtil.writeFile(prettyAnswerPath, prettyAnswerString);
}
}
private void writeJsonTopology() {
try {
Map<String, Configuration> configs = loadConfigurations();
EdgeSet textEdges = synthesizeTopology(configs).getEdges();
JSONArray jEdges = new JSONArray();
for (Edge textEdge : textEdges) {
Configuration node1 = configs.get(textEdge.getNode1());
Configuration node2 = configs.get(textEdge.getNode2());
Interface interface1 = node1.getInterfaces()
.get(textEdge.getInt1());
Interface interface2 = node2.getInterfaces()
.get(textEdge.getInt2());
JSONObject jEdge = new JSONObject();
jEdge.put("interface1", interface1.toJSONObject());
jEdge.put("interface2", interface2.toJSONObject());
jEdges.put(jEdge);
}
JSONObject master = new JSONObject();
JSONObject topology = new JSONObject();
topology.put("edges", jEdges);
master.put("topology", topology);
String text = master.toString(3);
_logger.output(text);
}
catch (JSONException e) {
throw new BatfishException("Failed to synthesize JSON topology", e);
}
}
private void writeSynthesizedTopology() {
Map<String, Configuration> configs = loadConfigurations();
EdgeSet edges = synthesizeTopology(configs).getEdges();
_logger.output(BatfishTopologyCombinedParser.HEADER + "\n");
for (Edge edge : edges) {
_logger.output(edge.getNode1() + ":" + edge.getInt1() + ","
+ edge.getNode2() + ":" + edge.getInt2() + "\n");
}
printElapsedTime();
}
}
|
package de.stonebone.cars.server.servlet;
import java.nio.channels.DatagramChannel;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import javax.servlet.AsyncContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebListener;
import de.stonebone.cars.ControllerState;
import de.stonebone.cars.server.Server;
@WebListener
public class Main implements ServletContextListener, Runnable {
private final Set<AsyncContext> browsers = Collections.synchronizedSet(new HashSet<>());
private Thread thread;
private Server server;
public void addAsyncContext(AsyncContext asyncContext) {
asyncContext.setTimeout(0);
synchronized (browsers) {
browsers.add(asyncContext);
}
}
public void contextDestroyed(ServletContextEvent event) {
thread.interrupt();
server.close();
synchronized (browsers) {
for (AsyncContext asyncContext : browsers) {
asyncContext.complete();
}
}
try {
thread.join(1000);
} catch (InterruptedException e) {
// ignore
}
}
public void contextInitialized(ServletContextEvent event) {
event.getServletContext().setAttribute("main", this);
thread = new Thread(this, "asyncer");
thread.setDaemon(true);
thread.start();
server = new Server();
}
private String createDataString(StringBuilder builder, int id) {
builder.setLength(0);
builder.append("id:").append(id).append('\n');
builder.append("data:");
ControllerState[] cons = server.getServerState().getControllers();
for (int i = 0; i < cons.length; i++) {
cons[i].toCSV(builder);
if (i == cons.length -1)
break;
builder.append(',');
}
builder.append('\n');
builder.append("\n");
return builder.toString();
}
@Override
public void run() {
long nanos = System.nanoTime();
long delta = TimeUnit.MILLISECONDS.toNanos(300);
long next = nanos + delta;
int id = 0;
StringBuilder builder = new StringBuilder();
while (true) {
try (DatagramChannel channel = server.open()) {
Thread.yield();
nanos = System.nanoTime();
// receive and handle inbound packets...
server.handleChannel(channel);
server.releaseTokens(nanos);
if (nanos < next)
continue;
next = nanos + delta;
// broadcast to connected browsers...
synchronized (browsers) {
if (browsers.isEmpty())
continue;
String event = createDataString(builder, ++id);
Iterator<AsyncContext> iterator = browsers.iterator();
while (iterator.hasNext()) {
AsyncContext asyncContext = iterator.next();
try {
ServletResponse response = asyncContext.getResponse();
ServletOutputStream stream = response.getOutputStream();
stream.print(event);
stream.flush();
} catch (Exception e) {
iterator.remove();
}
}
}
} catch (Exception e) {
throw new RuntimeException("Exception in run()!", e);
}
}
}
}
|
package nl.mpi.kinnate.data;
import java.net.URI;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import javax.swing.ImageIcon;
import nl.mpi.arbil.data.ArbilDataNode;
import nl.mpi.arbil.data.ArbilDataNodeLoader;
import nl.mpi.arbil.data.ArbilNode;
import nl.mpi.arbil.data.ContainerNode;
import nl.mpi.arbil.util.MessageDialogHandler;
import nl.mpi.flap.model.FieldGroup;
import nl.mpi.kinnate.entityindexer.EntityCollection;
import nl.mpi.kinnate.entityindexer.IndexerParameters;
import nl.mpi.kinnate.kindata.DataTypes;
import nl.mpi.kinnate.kindata.EntityData;
import nl.mpi.kinnate.kindata.EntityRelation;
import nl.mpi.kinnate.svg.DataStoreSvg;
import nl.mpi.kinnate.svg.SymbolGraphic;
import nl.mpi.kinnate.uniqueidentifiers.UniqueIdentifier;
public class KinTreeNode extends ArbilNode implements Comparable {
private UniqueIdentifier uniqueIdentifier;
protected EntityData entityData = null;
protected IndexerParameters indexerParameters;
protected ArbilNode[] childNodes = null;
static private SymbolGraphic symbolGraphic = null;
protected EntityCollection entityCollection;
protected MessageDialogHandler dialogHandler;
protected ArbilDataNodeLoader dataNodeLoader;
private String derivedLabelString = null;
final protected DataStoreSvg dataStoreSvg;
public KinTreeNode(UniqueIdentifier uniqueIdentifier, EntityData entityData, DataStoreSvg dataStoreSvg, IndexerParameters indexerParameters, MessageDialogHandler dialogHandler, EntityCollection entityCollection, ArbilDataNodeLoader dataNodeLoader) {
// todo: create new constructor that takes a unique identifer and loads from the database.
super();
this.uniqueIdentifier = uniqueIdentifier;
this.dataStoreSvg = dataStoreSvg;
this.indexerParameters = indexerParameters;
this.entityData = entityData;
this.entityCollection = entityCollection;
this.dialogHandler = dialogHandler;
this.dataNodeLoader = dataNodeLoader;
if (symbolGraphic == null) {
symbolGraphic = new SymbolGraphic(dialogHandler);
}
}
// public void setEntityData(EntityData entityData) {
// // todo: this does not cause the tree to update so it is redundent
// this.entityData = entityData;
// derivedLabelString = null;
// symbolGraphic = null;
// // todo: clear or set the child entity data
// //childNodes
public EntityData getEntityData() {
return entityData;
}
public UniqueIdentifier getUniqueIdentifier() {
return uniqueIdentifier;
}
@Override
public String toString() {
if (derivedLabelString == null) {
if (entityData == null) {
return "<entity not loaded>";
} else {
StringBuilder labelBuilder = new StringBuilder();
final String[] labelArray = entityData.getLabel();
if (labelArray != null && labelArray.length > 0) {
for (String labelString : labelArray) {
labelBuilder.append(labelString);
labelBuilder.append(" ");
}
}
derivedLabelString = labelBuilder.toString();
if (derivedLabelString.replaceAll("\\s", "").isEmpty()) {
derivedLabelString = "<unlabeled entity>";
}
}
}
return derivedLabelString;
}
@Override
public ArbilDataNode[] getAllChildren() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void getAllChildren(Vector<ArbilDataNode> allChildren) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public ArbilNode[] getChildArray() {
if (childNodes == null) {
// add the related entities grouped into metanodes by relation type and within each group the subsequent nodes are filtered by the type of relation.
HashMap<DataTypes.RelationType, HashSet<KinTreeFilteredNode>> metaNodeMap = new HashMap<DataTypes.RelationType, HashSet<KinTreeFilteredNode>>();
for (EntityRelation entityRelation : entityData.getAllRelations()) {
if (!metaNodeMap.containsKey(entityRelation.getRelationType())) {
metaNodeMap.put(entityRelation.getRelationType(), new HashSet<KinTreeFilteredNode>());
}
metaNodeMap.get(entityRelation.getRelationType()).add(new KinTreeFilteredNode(entityRelation, dataStoreSvg, indexerParameters, dialogHandler, entityCollection, dataNodeLoader));
}
HashSet<ArbilNode> kinTreeMetaNodes = new HashSet<ArbilNode>();
for (Map.Entry<DataTypes.RelationType, HashSet<KinTreeFilteredNode>> filteredNodeEntry : metaNodeMap.entrySet()) {//values().toArray(new KinTreeFilteredNode[]{})
kinTreeMetaNodes.add(new FilteredNodeContainer(filteredNodeEntry.getKey().name(), null, filteredNodeEntry.getValue().toArray(new KinTreeFilteredNode[]{})));
}
getLinksMetaNode(kinTreeMetaNodes);
childNodes = kinTreeMetaNodes.toArray(new ArbilNode[]{});
}
return childNodes;
}
protected void getLinksMetaNode(HashSet<ArbilNode> kinTreeMetaNodes) {
if (entityData.archiveLinkArray != null) {
HashSet<ArbilDataNode> relationList = new HashSet<ArbilDataNode>();
for (URI archiveLink : entityData.archiveLinkArray) {
ArbilDataNode linkedArbilDataNode = dataNodeLoader.getArbilDataNode(null, archiveLink);
relationList.add(linkedArbilDataNode);
}
kinTreeMetaNodes.add(new ContainerNode(null, "External Links", null, relationList.toArray(new ArbilDataNode[]{})));
}
}
@Override
public int getChildCount() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public ImageIcon getIcon() {
if (entityData != null) {
return symbolGraphic.getSymbolGraphic(entityData.getSymbolNames(dataStoreSvg.defaultSymbol), entityData.isEgo);
}
return null;
}
@Override
public String getID() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public List<FieldGroup> getFieldGroups() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean hasCatalogue() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean hasHistory() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean hasLocalResource() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean hasResource() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean isArchivableFile() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean isCatalogue() {
return false;
}
@Override
public boolean isChildNode() {
return false;
}
@Override
public boolean isCmdiMetaDataNode() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean isCorpus() {
return false;
}
@Override
public boolean isDataLoaded() {
return true;
}
@Override
public boolean isDirectory() {
return false;
}
@Override
public boolean isEditable() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean isEmptyMetaNode() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean isFavorite() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean isLoading() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean isDataPartiallyLoaded() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean isLocal() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean isMetaDataNode() {
return false;
}
@Override
public boolean isResourceSet() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void setID(String id) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void setLabel(String label) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getLabel() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void setFieldGroups(List<FieldGroup> fieldGroups) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void setChildIds(List<String> idString) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public List<String> getChildIds() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean isSession() {
return false;
}
public int compareTo(Object o) {
if (o instanceof KinTreeNode) {
int compResult = this.toString().compareTo(o.toString());
if (compResult == 0) {
// todo: compare by age if the labels match
// compResult = entityData
}
return compResult;
} else {
// put kin nodes in front of other nodes
return 1;
}
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final KinTreeNode other = (KinTreeNode) obj;
// we compare the entity data instance because this is the only way to update the arbil tree
// todo: this does not break the graph selection process but check for other places where equals might be used
return this.entityData == other.entityData;
//// return this.hashCode() == other.hashCode();
// if (entityData == null || other.entityData == null) {
// // todo: it would be good for this to never be null, or at least to aways have the UniqueIdentifier to compare
// return false;
// if (this.getUniqueIdentifier() != other.getUniqueIdentifier() && (this.getUniqueIdentifier() == null || !this.getUniqueIdentifier().equals(other.getUniqueIdentifier()))) {
// return false;
// return true;
}
@Override
public int hashCode() {
int hash = 0;
hash = 37 * hash + (this.uniqueIdentifier != null ? this.uniqueIdentifier.hashCode() : 0);
return hash;
}
}
|
package nl.mpi.kinnate.ui;
import java.awt.BorderLayout;
import java.awt.Component;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import nl.mpi.arbil.data.ArbilDataNode;
import nl.mpi.arbil.data.ArbilDataNodeLoader;
import nl.mpi.arbil.ui.ArbilTable;
import nl.mpi.arbil.ui.ArbilTableModel;
import nl.mpi.arbil.ui.ArbilTree;
import nl.mpi.arbil.util.BugCatcherManager;
import nl.mpi.kinnate.kindata.EntityData;
import nl.mpi.kinnate.svg.GraphPanel;
public class MetadataPanel extends JPanel {
private ArbilTree arbilTree;
// JScrollPane tableScrollPane;
private ArbilTableModel kinTableModel;
private ArbilTableModel archiveTableModel;
private JScrollPane kinTableScrollPane;
private HidePane editorHidePane;
private ArrayList<ArbilDataNode> metadataNodes = new ArrayList<ArbilDataNode>();
private ArrayList<ArbilDataNode> archiveTreeNodes = new ArrayList<ArbilDataNode>();
private ArrayList<ArbilDataNode> archiveRootNodes = new ArrayList<ArbilDataNode>();
private ArrayList<SvgElementEditor> elementEditors = new ArrayList<SvgElementEditor>();
//private DateEditorPanel dateEditorPanel;
private ArbilDataNodeLoader dataNodeLoader;
public MetadataPanel(GraphPanel graphPanel, HidePane editorHidePane, TableCellDragHandler tableCellDragHandler, ArbilDataNodeLoader dataNodeLoader) {
this.arbilTree = new ArbilTree();
this.kinTableModel = new ArbilTableModel();
this.archiveTableModel = new ArbilTableModel();
this.dataNodeLoader = dataNodeLoader;
//dateEditorPanel = new DateEditorPanel();
ArbilTable kinTable = new ArbilTable(kinTableModel, "Selected Nodes");
ArbilTable archiveTable = new ArbilTable(archiveTableModel, "Selected Nodes");
this.arbilTree.setCustomPreviewTable(archiveTable);
kinTable.setTransferHandler(tableCellDragHandler);
kinTable.setDragEnabled(true);
this.editorHidePane = editorHidePane;
this.setLayout(new BorderLayout());
kinTableScrollPane = new JScrollPane(kinTable);
JScrollPane archiveTableScrollPane = new JScrollPane(archiveTable);
this.add(archiveTableScrollPane, BorderLayout.CENTER);
this.add(arbilTree, BorderLayout.LINE_START);
}
public void removeAllEditors() {
while (!elementEditors.isEmpty()) {
editorHidePane.removeTab(elementEditors.remove(0));
}
}
public void removeAllArbilDataNodeRows() {
kinTableModel.removeAllArbilDataNodeRows();
archiveTableModel.removeAllArbilDataNodeRows();
for (ArbilDataNode arbilDataNode : metadataNodes) {
if (arbilDataNode.getParentDomNode().getNeedsSaveToDisk(false)) {
// reloading will first check if a save is required then save and reload
dataNodeLoader.requestReload((ArbilDataNode) arbilDataNode.getParentDomNode());
}
}
metadataNodes.clear();
}
public void addArbilDataNode(ArbilDataNode arbilDataNode) {
archiveTableModel.addSingleArbilDataNode(arbilDataNode);
archiveRootNodes.clear(); // do not show the tree for archive tree selections
metadataNodes.add(arbilDataNode);
}
public void addEntityDataNode(KinDiagramPanel kinDiagramPanel, EntityData entityData) {
String entityPath = entityData.getEntityPath();
if (entityPath != null && entityPath.length() > 0) {
try {
ArbilDataNode arbilDataNode = dataNodeLoader.getArbilDataNode(null, new URI(entityPath));
// register this node with the graph panel
kinDiagramPanel.registerArbilNode(entityData.getUniqueIdentifier(), arbilDataNode);
kinTableModel.addSingleArbilDataNode(arbilDataNode);
metadataNodes.add(arbilDataNode);
// add the corpus links to the other table
if (entityData.archiveLinkArray != null) {
for (URI archiveLink : entityData.archiveLinkArray) {
ArbilDataNode archiveLinkNode = dataNodeLoader.getArbilDataNode(null, archiveLink);
// todo: we do not register this node with the graph panel because it is not rendered on the graph, but if the name of the node changes then it should be updated in the tree which is not yet handled
archiveTableModel.addSingleArbilDataNode(archiveLinkNode);
archiveTreeNodes.add(archiveLinkNode);
archiveRootNodes.add(archiveLinkNode.getParentDomNode());
metadataNodes.add(archiveLinkNode);
}
}
} catch (URISyntaxException urise) {
BugCatcherManager.getBugCatcher().logError(urise);
}
}
}
// public void setDateEditorEntities(ArrayList<EntityData> selectedEntities) {
// if (selectedEntities.isEmpty()) {
// editorHidePane.removeTab(dateEditorPanel);
// } else {
// dateEditorPanel.setEntities(selectedEntities);
// editorHidePane.addTab("Date Editor", dateEditorPanel);
public void addTab(String labelString, SvgElementEditor elementEditor) {
editorHidePane.addTab(labelString, elementEditor);
elementEditors.add(elementEditor);
}
public void removeTab(Component elementEditor) {
editorHidePane.removeTab(elementEditor);
}
public void updateEditorPane() {
// todo: add only imdi nodes to the tree and the root node of them
// todo: maybe have a table for entities and one for achive metdata
if (archiveTableModel.getArbilDataNodeCount() > 0) {
editorHidePane.addTab("External Links", this);
} else {
removeTab(this);
}
if (kinTableModel.getArbilDataNodeCount() > 0) {
editorHidePane.addTab("Kinship Data", kinTableScrollPane);
editorHidePane.setSelectedComponent(kinTableScrollPane);
} else {
removeTab(kinTableScrollPane);
}
if (!archiveRootNodes.isEmpty()) {
arbilTree.rootNodeChildren = archiveRootNodes.toArray(new ArbilDataNode[]{});
// todo: highlight or select the sub nodes that are actually linked
arbilTree.requestResort();
}
arbilTree.setVisible(!archiveRootNodes.isEmpty());
editorHidePane.setHiddeState();
}
}
|
package nl.mpi.kinnate.ui.menu;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;
import javax.xml.transform.TransformerException;
import nl.mpi.arbil.ui.ArbilWindowManager;
import nl.mpi.arbil.userstorage.SessionStorage;
import nl.mpi.arbil.util.ApplicationVersion;
import nl.mpi.arbil.util.ApplicationVersionManager;
import nl.mpi.arbil.util.ArbilBugCatcher;
import nl.mpi.arbil.util.BugCatcher;
import nl.mpi.kinnate.kindocument.CmdiTransformer;
import nl.mpi.kinnate.ui.window.AbstractDiagramManager;
public class HelpMenu extends JMenu {
public HelpMenu(AbstractDiagramManager diagramWindowManager, final BugCatcher bugCatcher, final ArbilWindowManager dialogHandler, final SessionStorage sessionStorage, final ApplicationVersionManager versionManager) {
this.setText("Help");
JMenuItem aboutMenuItem = new JMenuItem("About");
aboutMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
// todo:
// aboutMenuItemActionPerformed(evt);
} catch (Exception ex) {
bugCatcher.logError(ex);
}
}
});
this.add(aboutMenuItem);
JMenuItem helpMenuItem = new JMenuItem("Help");
helpMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F1, 0));
helpMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
// todo:
// helpMenuItemActionPerformed(evt);
} catch (Exception ex) {
bugCatcher.logError(ex);
}
}
});
this.add(helpMenuItem);
JMenuItem arbilForumMenuItem = new JMenuItem("KinOath Forum (Website)");
arbilForumMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
dialogHandler.openFileInExternalApplication(new URI("http:
} catch (Exception ex) {
bugCatcher.logError(ex);
}
}
});
this.add(arbilForumMenuItem);
final JMenuItem viewErrorLogMenuItem = new JMenuItem("View Error Log");
viewErrorLogMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
dialogHandler.openFileInExternalApplication(ArbilBugCatcher.getLogFile(sessionStorage, versionManager.getApplicationVersion()).toURI());
} catch (Exception ex) {
bugCatcher.logError(ex);
}
}
});
this.add(viewErrorLogMenuItem);
JMenuItem checkForUpdatesMenuItem = new JMenuItem("Check for Updates");
checkForUpdatesMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
if (!versionManager.forceUpdateCheck()) {
ApplicationVersion appVersion = versionManager.getApplicationVersion();
String versionString = appVersion.currentMajor + "." + appVersion.currentMinor + "." + appVersion.currentRevision;
dialogHandler.addMessageDialogToQueue("No updates found, current version is " + versionString, "Check for Updates");
}
} catch (Exception ex) {
bugCatcher.logError(ex);
}
}
});
// JMenuItem updateKmdiProfileMenuItem = new JMenuItem("Check Component Registry Updates (this will be moved to a panel)");
// updateKmdiProfileMenuItem.addActionListener(new java.awt.event.ActionListener() {
// // todo: move this to a panel with more options.
// public void actionPerformed(java.awt.event.ActionEvent evt) {
// try {
// String profileId = "clarin.eu:cr1:p_1320657629627";
// File xsdFile = new File(sessionStorage.getCacheDirectory(), "individual" + "-" + profileId + ".xsd");
// new CmdiTransformer(sessionStorage, bugCatcher).transformProfileXmlToXsd(xsdFile, profileId);
// } catch (IOException exception) {
// System.out.println("exception: " + exception.getMessage());
// } catch (TransformerException exception) {
// System.out.println("exception: " + exception.getMessage());
// this.add(updateKmdiProfileMenuItem);
this.addMenuListener(new MenuListener() {
public void menuCanceled(MenuEvent evt) {
}
public void menuDeselected(MenuEvent evt) {
}
public void menuSelected(MenuEvent evt) {
viewErrorLogMenuItem.setEnabled(ArbilBugCatcher.getLogFile(sessionStorage, versionManager.getApplicationVersion()).exists());
}
});
}
}
|
package com.benny.openlauncher.activity;
import android.app.Activity;
import android.app.ActivityOptions;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProviderInfo;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.res.Resources;
import android.graphics.Point;
import android.net.Uri;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.DrawerLayout.DrawerListener;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.TextView;
import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.benny.openlauncher.BuildConfig;
import com.benny.openlauncher.R;
import com.benny.openlauncher.activity.homeparts.HpAppDrawer;
import com.benny.openlauncher.activity.homeparts.HpDesktopPickAction;
import com.benny.openlauncher.activity.homeparts.HpDragNDrop;
import com.benny.openlauncher.activity.homeparts.HpInitSetup;
import com.benny.openlauncher.activity.homeparts.HpSearchBar;
import com.benny.openlauncher.interfaces.AppDeleteListener;
import com.benny.openlauncher.manager.Setup;
import com.benny.openlauncher.manager.Setup.DataManager;
import com.benny.openlauncher.model.Item;
import com.benny.openlauncher.model.Item.Type;
import com.benny.openlauncher.model.App;
import com.benny.openlauncher.util.AppManager;
import com.benny.openlauncher.util.AppSettings;
import com.benny.openlauncher.util.AppUpdateReceiver;
import com.benny.openlauncher.util.Definitions;
import com.benny.openlauncher.util.Definitions.ItemPosition;
import com.benny.openlauncher.util.LauncherAction;
import com.benny.openlauncher.util.LauncherAction.Action;
import com.benny.openlauncher.util.ShortcutReceiver;
import com.benny.openlauncher.util.Tool;
import com.benny.openlauncher.viewutil.DialogHelper;
import com.benny.openlauncher.viewutil.MinibarAdapter;
import com.benny.openlauncher.viewutil.WidgetHost;
import com.benny.openlauncher.widget.AppDrawerController;
import com.benny.openlauncher.widget.AppItemView;
import com.benny.openlauncher.widget.CalendarDropDownView;
import com.benny.openlauncher.widget.CellContainer;
import com.benny.openlauncher.widget.Desktop;
import com.benny.openlauncher.widget.Desktop.OnDesktopEditListener;
import com.benny.openlauncher.widget.DesktopOptionView;
import com.benny.openlauncher.widget.DesktopOptionView.DesktopOptionViewListener;
import com.benny.openlauncher.widget.Dock;
import com.benny.openlauncher.widget.DragNDropLayout;
import com.benny.openlauncher.widget.DragOptionView;
import com.benny.openlauncher.widget.GroupPopupView;
import com.benny.openlauncher.widget.PagerIndicator;
import com.benny.openlauncher.widget.SearchBar;
import com.benny.openlauncher.widget.SmoothViewPager;
import com.benny.openlauncher.widget.SwipeListView;
import net.gsantner.opoc.util.ContextUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public final class HomeActivity extends Activity implements OnDesktopEditListener, DesktopOptionViewListener, DrawerListener {
public static final Companion Companion = new Companion();
public static final int REQUEST_CREATE_APPWIDGET = 0x6475;
public static final int REQUEST_PERMISSION_STORAGE = 0x3648;
public static final int REQUEST_PICK_APPWIDGET = 0x2678;
@Nullable
private static Resources _resources;
private static final IntentFilter _appUpdateIntentFilter = new IntentFilter();
@Nullable
private static WidgetHost _appWidgetHost;
@NonNull
public static AppWidgetManager _appWidgetManager;
private static boolean _consumeNextResume;
@NonNull
public static DataManager _db;
public static float _itemTouchX;
public static float _itemTouchY;
@Nullable
public static HomeActivity _launcher;
private static final IntentFilter _shortcutIntentFilter = new IntentFilter();
private static final IntentFilter _timeChangesIntentFilter = new IntentFilter();
private HashMap deleteMefindViewCache;
private final AppUpdateReceiver _appUpdateReceiver = new AppUpdateReceiver();
private int cx;
private int cy;
private int rad;
private final ShortcutReceiver _shortcutReceiver = new ShortcutReceiver();
private BroadcastReceiver _timeChangedReceiver;
public static final class Companion {
private Companion() {
}
@Nullable
public final HomeActivity getLauncher() {
return _launcher;
}
public final void setLauncher(@Nullable HomeActivity v) {
_launcher = v;
}
@Nullable
public final Resources get_resources() {
return _resources;
}
public final void set_resources(@Nullable Resources v) {
_resources = v;
}
@NonNull
public final DataManager getDb() {
return _db;
}
public final void setDb(@NonNull DataManager v) {
_db = v;
}
@Nullable
public final WidgetHost getAppWidgetHost() {
return _appWidgetHost;
}
public final void setAppWidgetHost(@Nullable WidgetHost v) {
_appWidgetHost = v;
}
@NonNull
public final AppWidgetManager getAppWidgetManager() {
return _appWidgetManager;
}
public final void setAppWidgetManager(@NonNull AppWidgetManager v) {
_appWidgetManager = v;
}
public final float getItemTouchX() {
return _itemTouchX;
}
public final void setItemTouchX(float v) {
_itemTouchX = v;
}
public final float getItemTouchY() {
return _itemTouchY;
}
public final void setItemTouchY(float v) {
_itemTouchY = v;
}
public final boolean getConsumeNextResume() {
return _consumeNextResume;
}
public final void setConsumeNextResume(boolean v) {
_consumeNextResume = v;
}
private final IntentFilter getTimeChangesIntentFilter() {
return _timeChangesIntentFilter;
}
private final IntentFilter getAppUpdateIntentFilter() {
return _appUpdateIntentFilter;
}
private final IntentFilter getShortcutIntentFilter() {
return _shortcutIntentFilter;
}
}
public final void openAppDrawer() {
openAppDrawer$default(this, null, 0, 0, 7, null);
}
public final void openAppDrawer(@Nullable View view) {
openAppDrawer$default(this, view, 0, 0, 6, null);
}
public final void updateDock(boolean z) {
updateDock$default(this, z, 0, 2, null);
}
static {
Companion.getTimeChangesIntentFilter().addAction("android.intent.action.TIME_TICK");
Companion.getTimeChangesIntentFilter().addAction("android.intent.action.TIMEZONE_CHANGED");
Companion.getTimeChangesIntentFilter().addAction("android.intent.action.TIME_SET");
Companion.getAppUpdateIntentFilter().addAction("android.intent.action.PACKAGE_ADDED");
Companion.getAppUpdateIntentFilter().addAction("android.intent.action.PACKAGE_REMOVED");
Companion.getAppUpdateIntentFilter().addAction("android.intent.action.PACKAGE_CHANGED");
Companion.getAppUpdateIntentFilter().addDataScheme("package");
Companion.getShortcutIntentFilter().addAction("com.android.launcher.action.INSTALL_SHORTCUT");
}
@NonNull
public final DrawerLayout getDrawerLayout() {
return findViewById(R.id.drawer_layout);
}
protected void onCreate(@Nullable Bundle savedInstanceState) {
Companion.setLauncher(this);
Companion.set_resources(getResources());
ContextUtils contextUtils = new ContextUtils(getApplicationContext());
AppSettings appSettings = AppSettings.get();
contextUtils.setAppLanguage(appSettings.getLanguage());
super.onCreate(savedInstanceState);
if (!Setup.wasInitialised()) {
Setup.init(new HpInitSetup(this));
}
AppSettings appSettings2 = Setup.appSettings();
if (appSettings2.isSearchBarTimeEnabled()) {
_timeChangedReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
updateSearchClock();
}
}
};
}
Companion.setLauncher(this);
Companion companion = Companion;
DataManager dataManager = Setup.dataManager();
companion.setDb(dataManager);
setContentView(getLayoutInflater().inflate(R.layout.activity_home, null));
if (VERSION.SDK_INT >= 21) {
Window window = getWindow();
View decorView = window.getDecorView();
decorView.setSystemUiVisibility(1536);
}
init();
}
public final void onStartApp(@NonNull Context context, @NonNull Intent intent, @Nullable View view) {
ComponentName component = intent.getComponent();
if (BuildConfig.APPLICATION_ID.equals(component.getPackageName())) {
LauncherAction.RunAction(Action.LauncherSettings, context);
Companion.setConsumeNextResume(true);
} else {
try {
context.startActivity(intent, getActivityAnimationOpts(view));
Companion.setConsumeNextResume(true);
} catch (Exception e) {
Tool.toast(context, (int) R.string.toast_app_uninstalled);
}
}
}
public final void onStartApp(@NonNull Context context, @NonNull App app, @Nullable View view) {
if (BuildConfig.APPLICATION_ID.equals(app._packageName)) {
LauncherAction.RunAction(Action.LauncherSettings, context);
Companion.setConsumeNextResume(true);
} else {
try {
Intent intent = new Intent("android.intent.action.MAIN");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setClassName(app._packageName, app._className);
context.startActivity(intent, getActivityAnimationOpts(view));
Companion.setConsumeNextResume(true);
} catch (Exception e) {
Tool.toast(context, (int) R.string.toast_app_uninstalled);
}
}
}
protected void initAppManager() {
Setup.appLoader().addUpdateListener(new AppManager.AppUpdatedListener() {
@Override
public boolean onAppUpdated(List<App> it) {
if (getDesktop() == null) {
return false;
}
AppSettings appSettings = Setup.appSettings();
if (appSettings.getDesktopStyle() == 0) {
getDesktop().initDesktopNormal(HomeActivity.this);
if (appSettings.isAppFirstLaunch()) {
appSettings.setAppFirstLaunch(false);
Item appDrawerBtnItem = Item.newActionItem(8);
appDrawerBtnItem._x = 2;
Companion.getDb().saveItem(appDrawerBtnItem, 0, ItemPosition.Dock);
}
} else {
getDesktop().initDesktopShowAll(HomeActivity.this, HomeActivity.this);
}
getDock().initDockItem(HomeActivity.this);
return true;
}
});
Setup.appLoader().addDeleteListener(new AppDeleteListener() {
@Override
public boolean onAppDeleted(List<App> apps) {
AppSettings appSettings = Setup.appSettings();
if (appSettings.getDesktopStyle() == 0) {
getDesktop().initDesktopNormal(HomeActivity.this);
} else {
getDesktop().initDesktopShowAll(HomeActivity.this, HomeActivity.this);
}
getDock().initDockItem(HomeActivity.this);
setToHomePage();
return false;
}
});
AppManager.getInstance(this).init();
}
protected void initViews() {
new HpSearchBar(this, (SearchBar) findViewById(R.id.searchBar), (CalendarDropDownView) findViewById(R.id.calendarDropDownView)).initSearchBar();
initDock();
((AppDrawerController) findViewById(R.id.appDrawerController)).init();
((AppDrawerController) findViewById(R.id.appDrawerController)).setHome(this);
((DragOptionView) findViewById(R.id.dragOptionPanel)).setHome(this);
((Desktop) findViewById(R.id.desktop)).init();
Desktop desktop = (Desktop) findViewById(R.id.desktop);
desktop.setDesktopEditListener(this);
((DesktopOptionView) findViewById(R.id.desktopEditOptionPanel)).setDesktopOptionViewListener(this);
DesktopOptionView desktopOptionView = (DesktopOptionView) findViewById(R.id.desktopEditOptionPanel);
AppSettings appSettings = Setup.appSettings();
desktopOptionView.updateLockIcon(appSettings.isDesktopLock());
((Desktop) findViewById(R.id.desktop)).addOnPageChangeListener(new SmoothViewPager.OnPageChangeListener() {
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
public void onPageSelected(int position) {
DesktopOptionView desktopOptionView = (DesktopOptionView) findViewById(R.id.desktopEditOptionPanel);
AppSettings appSettings = Setup.appSettings();
desktopOptionView.updateHomeIcon(appSettings.getDesktopPageCurrent() == position);
}
public void onPageScrollStateChanged(int state) {
}
});
desktop = (Desktop) findViewById(R.id.desktop);
desktop.setPageIndicator((PagerIndicator) findViewById(R.id.desktopIndicator));
((DragOptionView) findViewById(R.id.dragOptionPanel)).setAutoHideView((SearchBar) findViewById(R.id.searchBar));
new HpAppDrawer(this, (PagerIndicator) findViewById(R.id.appDrawerIndicator), (DragOptionView) findViewById(R.id.dragOptionPanel)).initAppDrawer((AppDrawerController) findViewById(R.id.appDrawerController));
initMinibar();
}
public final void initSettings() {
updateHomeLayout();
AppSettings appSettings = Setup.appSettings();
if (appSettings.isDesktopFullscreen()) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
} else {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN, WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
}
Desktop desktop = findViewById(R.id.desktop);
AppSettings appSettings2 = Setup.appSettings();
desktop.setBackgroundColor(appSettings2.getDesktopBackgroundColor());
Dock dock = findViewById(R.id.dock);
appSettings2 = Setup.appSettings();
dock.setBackgroundColor(appSettings2.getDockColor());
getDrawerLayout().setDrawerLockMode(AppSettings.get().getMinibarEnable() ? DrawerLayout.LOCK_MODE_UNLOCKED : DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
}
public void onRemovePage() {
if (getDesktop().isCurrentPageEmpty()) {
getDesktop().removeCurrentPage();
return;
}
DialogHelper.alertDialog(this, getString(R.string.remove), "This page is not empty. Those item will also be removed.", new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
getDesktop().removeCurrentPage();
}
});
}
public final void initMinibar() {
final ArrayList<LauncherAction.ActionDisplayItem> items = new ArrayList<>();
final ArrayList<String> labels = new ArrayList<>();
final ArrayList<Integer> icons = new ArrayList<>();
for (String act : AppSettings.get().getMinibarArrangement()) {
if (act.length() > 1) {
LauncherAction.ActionDisplayItem item = LauncherAction.getActionItemFromString(act);
if (item != null) {
items.add(item);
labels.add(item._label);
icons.add(item._icon);
}
}
}
SwipeListView minibar = findViewById(R.id.minibar);
minibar.setAdapter(new MinibarAdapter(this, labels, icons));
minibar.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
LauncherAction.Action action = items.get(i)._action;
if (action == LauncherAction.Action.DeviceSettings || action == LauncherAction.Action.LauncherSettings || action == LauncherAction.Action.EditMinibar) {
_consumeNextResume = true;
}
LauncherAction.RunAction(action, HomeActivity.this);
if (action != LauncherAction.Action.DeviceSettings && action != LauncherAction.Action.LauncherSettings && action != LauncherAction.Action.EditMinibar) {
getDrawerLayout().closeDrawers();
}
}
});
// frame layout spans the entire side while the minibar container has gaps at the top and bottom
((FrameLayout) minibar.getParent()).setBackgroundColor(AppSettings.get().getMinibarBackgroundColor());
}
public void onBackPressed() {
handleLauncherPause(false);
((DrawerLayout) findViewById(R.id.drawer_layout)).closeDrawers();
}
public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
}
public void onDrawerOpened(@NonNull View drawerView) {
}
public void onDrawerClosed(@NonNull View drawerView) {
}
public void onDrawerStateChanged(int newState) {
}
protected void onResume() {
super.onResume();
AppSettings appSettings = Setup.appSettings();
boolean rotate = false;
if (appSettings.getAppRestartRequired()) {
appSettings = Setup.appSettings();
appSettings.setAppRestartRequired(false);
PendingIntent restartIntentP = PendingIntent.getActivity(this, 123556, new Intent(this, HomeActivity.class), PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + ((long) 100), restartIntentP);
System.exit(0);
return;
}
Companion.setLauncher(this);
WidgetHost appWidgetHost = Companion.getAppWidgetHost();
if (appWidgetHost != null) {
appWidgetHost.startListening();
}
Intent intent = getIntent();
handleLauncherPause(Intent.ACTION_MAIN.equals(intent.getAction()));
boolean user = AppSettings.get().getBool(R.string.pref_key__desktop_rotate, false);
boolean system = false;
try {
system = Settings.System.getInt(getContentResolver(), Settings.System.ACCELEROMETER_ROTATION) == 1;
} catch (SettingNotFoundException e) {
Log.d(HomeActivity.class.getSimpleName(), "Unable to read settings", e);
}
boolean rotate2 = false;
if (getResources().getBoolean(R.bool.isTablet)) {
rotate = system;
} else if (user && system) {
rotate = true;
}
if (rotate) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
@NonNull
public final Desktop getDesktop() {
Desktop desktop = (Desktop) findViewById(R.id.desktop);
return desktop;
}
@NonNull
public final Dock getDock() {
Dock dock = (Dock) findViewById(R.id.dock);
return dock;
}
@NonNull
public final AppDrawerController getAppDrawerController() {
AppDrawerController appDrawerController = (AppDrawerController) findViewById(R.id.appDrawerController);
return appDrawerController;
}
@NonNull
public final GroupPopupView getGroupPopup() {
GroupPopupView groupPopupView = (GroupPopupView) findViewById(R.id.groupPopup);
return groupPopupView;
}
@NonNull
public final SearchBar getSearchBar() {
SearchBar searchBar = (SearchBar) findViewById(R.id.searchBar);
return searchBar;
}
@NonNull
public final View getBackground() {
View findViewById = findViewById(R.id.background);
return findViewById;
}
@NonNull
public final PagerIndicator getDesktopIndicator() {
PagerIndicator pagerIndicator = (PagerIndicator) findViewById(R.id.desktopIndicator);
return pagerIndicator;
}
@NonNull
public final DragNDropLayout getDragNDropView() {
DragNDropLayout dragNDropLayout = (DragNDropLayout) findViewById(R.id.dragNDropView);
return dragNDropLayout;
}
private final void init() {
Companion.setAppWidgetHost(new WidgetHost(getApplicationContext(), R.id.app_widget_host));
Companion companion = Companion;
AppWidgetManager instance = AppWidgetManager.getInstance(this);
companion.setAppWidgetManager(instance);
WidgetHost appWidgetHost = Companion.getAppWidgetHost();
appWidgetHost.startListening();
initViews();
HpDragNDrop hpDragNDrop = new HpDragNDrop();
View findViewById = findViewById(R.id.leftDragHandle);
View findViewById2 = findViewById(R.id.rightDragHandle);
DragNDropLayout dragNDropLayout = findViewById(R.id.dragNDropView);
hpDragNDrop.initDragNDrop(this, findViewById, findViewById2, dragNDropLayout);
registerBroadcastReceiver();
initAppManager();
initSettings();
System.runFinalization();
System.gc();
}
public final void onUninstallItem(@NonNull Item item) {
Companion.setConsumeNextResume(true);
Setup.eventHandler().showDeletePackageDialog(this, item);
}
public final void onRemoveItem(@NonNull Item item) {
Desktop desktop = getDesktop();
View coordinateToChildView;
switch (item._locationInLauncher) {
case 0:
coordinateToChildView = desktop.getCurrentPage().coordinateToChildView(new Point(item._x, item._y));
desktop.removeItem(coordinateToChildView, true);
break;
case 1:
Dock dock = getDock();
coordinateToChildView = dock.coordinateToChildView(new Point(item._x, item._y));
dock.removeItem(coordinateToChildView, true);
break;
default:
break;
}
Companion.getDb().deleteItem(item, true);
}
public final void onInfoItem(@NonNull Item item) {
if (item._type == Type.APP) {
try {
String str = "android.settings.APPLICATION_DETAILS_SETTINGS";
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("package:");
Intent intent = item._intent;
ComponentName component = intent.getComponent();
stringBuilder.append(component.getPackageName());
startActivity(new Intent(str, Uri.parse(stringBuilder.toString())));
} catch (Exception e) {
Tool.toast((Context) this, (int) R.string.toast_app_uninstalled);
}
}
}
private final Bundle getActivityAnimationOpts(View view) {
Bundle bundle = null;
if (view == null) {
return null;
}
ActivityOptions opts = null;
if (VERSION.SDK_INT >= 23) {
int left = 0;
int top = 0;
int width = view.getMeasuredWidth();
int height = view.getMeasuredHeight();
if (view instanceof AppItemView) {
width = (int) ((AppItemView) view).getIconSize();
left = (int) ((AppItemView) view).getDrawIconLeft();
top = (int) ((AppItemView) view).getDrawIconTop();
}
opts = ActivityOptions.makeClipRevealAnimation(view, left, top, width, height);
} else if (VERSION.SDK_INT < 21) {
opts = ActivityOptions.makeScaleUpAnimation(view, 0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
}
if (opts != null) {
bundle = opts.toBundle();
}
return bundle;
}
public void onDesktopEdit() {
Tool.visibleViews(100, 20, (DesktopOptionView) findViewById(R.id.desktopEditOptionPanel));
hideDesktopIndicator();
updateDock$default(this, false, 0, 2, null);
updateSearchBar(false);
}
public void onFinishDesktopEdit() {
Tool.invisibleViews(100, 20, (DesktopOptionView) findViewById(R.id.desktopEditOptionPanel));
((PagerIndicator) findViewById(R.id.desktopIndicator)).hideDelay();
showDesktopIndicator();
updateDock$default(this, true, 0, 2, null);
updateSearchBar(true);
}
public void onSetPageAsHome() {
AppSettings appSettings = Setup.appSettings();
Desktop desktop = findViewById(R.id.desktop);
appSettings.setDesktopPageCurrent(desktop.getCurrentItem());
}
public void onLaunchSettings() {
Companion.setConsumeNextResume(true);
Setup.eventHandler().showLauncherSettings(this);
}
public void onPickDesktopAction() {
new HpDesktopPickAction(this).onPickDesktopAction();
}
public void onPickWidget() {
pickWidget();
}
private final void initDock() {
int iconSize = Setup.appSettings().getDockIconSize();
Dock dock = findViewById(R.id.dock);
dock.setHome(this);
dock.init();
AppSettings appSettings = Setup.appSettings();
if (appSettings.isDockShowLabel()) {
dock.getLayoutParams().height = Tool.dp2px(((16 + iconSize) + 14) + 10, this) + dock.getBottomInset();
} else {
dock.getLayoutParams().height = Tool.dp2px((16 + iconSize) + 10, this) + dock.getBottomInset();
}
}
public final void dimBackground() {
Tool.visibleViews(findViewById(R.id.background));
}
public final void unDimBackground() {
Tool.invisibleViews(findViewById(R.id.background));
}
public final void clearRoomForPopUp() {
Tool.invisibleViews((Desktop) findViewById(R.id.desktop));
hideDesktopIndicator();
updateDock$default(this, false, 0, 2, null);
}
public final void unClearRoomForPopUp() {
Tool.visibleViews((Desktop) findViewById(R.id.desktop));
showDesktopIndicator();
updateDock$default(this, true, 0, 2, null);
}
public static /* bridge */ /* synthetic */ void updateDock$default(HomeActivity homeActivity, boolean z, long j, int i, Object obj) {
if ((i & 2) != 0) {
j = 0;
}
homeActivity.updateDock(z, j);
}
public final void updateDock(boolean show, long delay) {
AppSettings appSettings = Setup.appSettings();
Desktop desktop;
LayoutParams layoutParams;
PagerIndicator pagerIndicator;
if (appSettings.getDockEnable() && show) {
Tool.visibleViews(100, delay, (Dock) findViewById(R.id.dock));
desktop = findViewById(R.id.desktop);
layoutParams = desktop.getLayoutParams();
((MarginLayoutParams) layoutParams).bottomMargin = Tool.dp2px(4, this);
pagerIndicator = findViewById(R.id.desktopIndicator);
layoutParams = pagerIndicator.getLayoutParams();
((MarginLayoutParams) layoutParams).bottomMargin = Tool.dp2px(4, this);
} else {
appSettings = Setup.appSettings();
if (appSettings.getDockEnable()) {
Tool.invisibleViews(100, (Dock) findViewById(R.id.dock));
} else {
Tool.goneViews(100, (Dock) findViewById(R.id.dock));
pagerIndicator = findViewById(R.id.desktopIndicator);
layoutParams = pagerIndicator.getLayoutParams();
((MarginLayoutParams) layoutParams).bottomMargin = Desktop._bottomInset + Tool.dp2px(4, (Context) this);
desktop = (Desktop) findViewById(R.id.desktop);
layoutParams = desktop.getLayoutParams();
((MarginLayoutParams) layoutParams).bottomMargin = Tool.dp2px(4, (Context) this);
}
}
}
public final void updateSearchBar(boolean show) {
AppSettings appSettings = Setup.appSettings();
if (appSettings.getSearchBarEnable() && show) {
Tool.visibleViews(100, (SearchBar) findViewById(R.id.searchBar));
} else {
appSettings = Setup.appSettings();
if (appSettings.getSearchBarEnable()) {
Tool.invisibleViews(100, (SearchBar) findViewById(R.id.searchBar));
} else {
Tool.goneViews((SearchBar) findViewById(R.id.searchBar));
}
}
}
public final void updateDesktopIndicatorVisibility() {
AppSettings appSettings = Setup.appSettings();
if (appSettings.isDesktopShowIndicator()) {
Tool.visibleViews(100, (PagerIndicator) findViewById(R.id.desktopIndicator));
return;
}
Tool.goneViews(100, (PagerIndicator) findViewById(R.id.desktopIndicator));
}
public final void hideDesktopIndicator() {
AppSettings appSettings = Setup.appSettings();
if (appSettings.isDesktopShowIndicator()) {
Tool.invisibleViews(100, (PagerIndicator) findViewById(R.id.desktopIndicator));
}
}
public final void showDesktopIndicator() {
AppSettings appSettings = Setup.appSettings();
if (appSettings.isDesktopShowIndicator()) {
Tool.visibleViews(100, (PagerIndicator) findViewById(R.id.desktopIndicator));
}
}
public final void updateSearchClock() {
SearchBar searchBar = (SearchBar) findViewById(R.id.searchBar);
TextView textView = searchBar._searchClock;
if (textView.getText() != null) {
try {
searchBar = (SearchBar) findViewById(R.id.searchBar);
searchBar.updateClock();
} catch (Exception e) {
((SearchBar) findViewById(R.id.searchBar))._searchClock.setText(R.string.bad_format);
}
}
}
public final void updateHomeLayout() {
updateSearchBar(true);
updateDock$default(this, true, 0, 2, null);
updateDesktopIndicatorVisibility();
AppSettings appSettings = Setup.appSettings();
if (!appSettings.getSearchBarEnable()) {
View findViewById = findViewById(R.id.leftDragHandle);
LayoutParams layoutParams = findViewById.getLayoutParams();
((MarginLayoutParams) layoutParams).topMargin = Desktop._topInset;
findViewById = findViewById(R.id.rightDragHandle);
layoutParams = findViewById.getLayoutParams();
Desktop desktop;
((MarginLayoutParams) layoutParams).topMargin = Desktop._topInset;
desktop = (Desktop) findViewById(R.id.desktop);
desktop.setPadding(0, Desktop._topInset, 0, 0);
}
appSettings = Setup.appSettings();
if (!appSettings.getDockEnable()) {
getDesktop().setPadding(0, 0, 0, Desktop._bottomInset);
}
}
private final void registerBroadcastReceiver() {
registerReceiver(_appUpdateReceiver, Companion.getAppUpdateIntentFilter());
if (_timeChangedReceiver != null) {
registerReceiver(_timeChangedReceiver, Companion.getTimeChangesIntentFilter());
}
registerReceiver(_shortcutReceiver, Companion.getShortcutIntentFilter());
}
private final void pickWidget() {
Companion.setConsumeNextResume(true);
int appWidgetId = Companion.getAppWidgetHost().allocateAppWidgetId();
Intent pickIntent = new Intent("android.appwidget.action.APPWIDGET_PICK");
pickIntent.putExtra("appWidgetId", appWidgetId);
startActivityForResult(pickIntent, REQUEST_PICK_APPWIDGET);
}
private final void configureWidget(Intent data) {
Bundle extras = data.getExtras();
int appWidgetId = extras.getInt("appWidgetId", -1);
AppWidgetProviderInfo appWidgetInfo = Companion.getAppWidgetManager().getAppWidgetInfo(appWidgetId);
if (appWidgetInfo.configure != null) {
Intent intent = new Intent("android.appwidget.action.APPWIDGET_CONFIGURE");
intent.setComponent(appWidgetInfo.configure);
intent.putExtra("appWidgetId", appWidgetId);
startActivityForResult(intent, REQUEST_CREATE_APPWIDGET);
} else {
createWidget(data);
}
}
private final void createWidget(Intent data) {
Bundle extras = data.getExtras();
int appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
AppWidgetProviderInfo appWidgetInfo = Companion.getAppWidgetManager().getAppWidgetInfo(appWidgetId);
Item item = Item.newWidgetItem(appWidgetId);
Desktop desktop = getDesktop();
List<CellContainer> pages = desktop.getPages();
item._spanX = (appWidgetInfo.minWidth - 1) / pages.get(desktop.getCurrentItem()).getCellWidth() + 1;
item._spanY = (appWidgetInfo.minHeight - 1) / pages.get(desktop.getCurrentItem()).getCellHeight() + 1;
Point point = desktop.getCurrentPage().findFreeSpace(item._spanX, item._spanY);
if (point != null) {
item._x = point.x;
item._y = point.y;
// add item to database
_db.saveItem(item, desktop.getCurrentItem(), Definitions.ItemPosition.Desktop);
desktop.addItemToPage(item, desktop.getCurrentItem());
} else {
Tool.toast(this, R.string.toast_not_enough_space);
}
}
protected void onDestroy() {
WidgetHost appWidgetHost = Companion.getAppWidgetHost();
if (appWidgetHost != null) {
appWidgetHost.stopListening();
}
Companion.setAppWidgetHost((WidgetHost) null);
unregisterReceiver(_appUpdateReceiver);
if (_timeChangedReceiver != null) {
unregisterReceiver(_timeChangedReceiver);
}
unregisterReceiver(_shortcutReceiver);
Companion.setLauncher((HomeActivity) null);
super.onDestroy();
}
public void onLowMemory() {
System.runFinalization();
System.gc();
super.onLowMemory();
}
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if (resultCode == -1) {
if (requestCode == REQUEST_PICK_APPWIDGET) {
configureWidget(data);
} else if (requestCode == REQUEST_CREATE_APPWIDGET) {
createWidget(data);
}
} else if (resultCode == 0 && data != null) {
int appWidgetId = data.getIntExtra("appWidgetId", -1);
if (appWidgetId != -1) {
WidgetHost appWidgetHost = Companion.getAppWidgetHost();
if (appWidgetHost != null) {
appWidgetHost.deleteAppWidgetId(appWidgetId);
}
}
}
}
protected void onStart() {
Companion.setLauncher(this);
WidgetHost appWidgetHost = Companion.getAppWidgetHost();
if (appWidgetHost != null) {
appWidgetHost.startListening();
}
super.onStart();
}
private final void handleLauncherPause(boolean wasHomePressed) {
if (!Companion.getConsumeNextResume() || wasHomePressed) {
onHandleLauncherPause();
} else {
Companion.setConsumeNextResume(false);
}
}
protected void onHandleLauncherPause() {
((GroupPopupView) findViewById(R.id.groupPopup)).dismissPopup();
((CalendarDropDownView) findViewById(R.id.calendarDropDownView)).animateHide();
((DragNDropLayout) findViewById(R.id.dragNDropView)).hidePopupMenu();
if (!((SearchBar) findViewById(R.id.searchBar)).collapse()) {
if (((Desktop) findViewById(R.id.desktop)) != null) {
Desktop desktop = (Desktop) findViewById(R.id.desktop);
if (desktop.getInEditMode()) {
desktop = (Desktop) findViewById(R.id.desktop);
List pages = desktop.getPages();
Desktop desktop2 = (Desktop) findViewById(R.id.desktop);
((CellContainer) pages.get(desktop2.getCurrentItem())).performClick();
} else {
AppDrawerController appDrawerController = (AppDrawerController) findViewById(R.id.appDrawerController);
View drawer = appDrawerController.getDrawer();
if (drawer.getVisibility() == View.VISIBLE) {
closeAppDrawer();
} else {
setToHomePage();
}
}
}
}
}
private final void setToHomePage() {
Desktop desktop = (Desktop) findViewById(R.id.desktop);
AppSettings appSettings = Setup.appSettings();
desktop.setCurrentItem(appSettings.getDesktopPageCurrent());
}
public static /* bridge */ /* synthetic */ void openAppDrawer$default(HomeActivity homeActivity, View view, int i, int i2, int i3, Object obj) {
if ((i3 & 1) != 0) {
view = (Desktop) homeActivity.findViewById(R.id.desktop);
}
if ((i3 & 2) != 0) {
i = -1;
}
if ((i3 & 4) != 0) {
i2 = -1;
}
homeActivity.openAppDrawer(view, i, i2);
}
public final void openAppDrawer(@Nullable View view, int x, int y) {
if (!(x > 0 && y > 0)) {
int[] pos = new int[2];
view.getLocationInWindow(pos);
cx = pos[0];
cy = pos[1];
cx += view.getWidth() / 2f;
cy += view.getHeight() / 2f;
if (view instanceof AppItemView) {
AppItemView appItemView = (AppItemView) view;
if (appItemView != null && appItemView.getShowLabel()) {
cy -= Tool.dp2px(14, this) / 2f;
}
rad = (int) (appItemView.getIconSize() / 2f - Tool.toPx(4));
}
cx -= ((MarginLayoutParams) getAppDrawerController().getDrawer().getLayoutParams()).getMarginStart();
cy -= ((MarginLayoutParams) getAppDrawerController().getDrawer().getLayoutParams()).topMargin;
cy -= getAppDrawerController().getPaddingTop();
} else {
cx = x;
cy = y;
rad = 0;
}
int finalRadius = Math.max(getAppDrawerController().getDrawer().getWidth(), getAppDrawerController().getDrawer().getHeight());
getAppDrawerController().open(cx, cy, rad, finalRadius);
}
public final void closeAppDrawer() {
int finalRadius = Math.max(getAppDrawerController().getDrawer().getWidth(), getAppDrawerController().getDrawer().getHeight());
getAppDrawerController().close(cx, cy, rad, finalRadius);
}
}
|
package com.buggycoder.tickmenot.model;
import android.provider.BaseColumns;
import com.activeandroid.Model;
import com.activeandroid.annotation.Column;
import com.activeandroid.annotation.Table;
import com.activeandroid.query.Select;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.List;
@Table(name = "notif", id = BaseColumns._ID)
public class WhatsappNotif extends Model {
private static final DateFormat df = new SimpleDateFormat("EEE, d MMM, h:mm a");
@Column(name = "event")
public String event;
@Column(name = "sender", index = true)
public String sender;
@Column(name = "message")
public String message;
@Column(name = "postTime", index = true)
public long postTime;
@Column(name = "hashCode", index = true)
public int hashCode;
public WhatsappNotif() {
super();
}
public WhatsappNotif(String event, String sender, String message, long postTime) {
this();
this.event = event;
this.sender = sender;
this.message = message;
this.postTime = postTime;
// may come in handy for dup checks
this.hashCode = hashCode();
}
public String getFormattedPostTime() {
return (postTime > 0) ? df.format(postTime) : "";
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
WhatsappNotif that = (WhatsappNotif) o;
return postTime == that.postTime &&
event.equals(that.event) &&
message.equals(that.message) &&
sender.equals(that.sender);
}
@Override
public int hashCode() {
if (hashCode != 0) {
// assuming nothing has altered the public fields :P
return hashCode;
}
int result = super.hashCode();
result = 31 * result + event.hashCode();
result = 31 * result + sender.hashCode();
result = 31 * result + message.hashCode();
result = 31 * result + (int) (postTime ^ (postTime >>> 32));
return result;
}
public static boolean isDup(WhatsappNotif notif) {
WhatsappNotif lastNotif = new Select()
.from(WhatsappNotif.class)
.where("sender = ?", notif.sender)
.orderBy("_id DESC")
.executeSingle();
return (lastNotif != null && lastNotif.equals(notif));
}
public static List<WhatsappNotif> list() {
List<WhatsappNotif> queryResult = new Select()
.from(WhatsappNotif.class)
.orderBy("_id DESC")
.limit(50)
.execute();
Collections.reverse(queryResult);
return queryResult;
}
}
|
package com.cbsanjaya.onepiece.sync;
import android.accounts.Account;
import android.content.AbstractThreadedSyncAdapter;
import android.content.ContentProviderClient;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.Context;
import android.content.OperationApplicationException;
import android.content.SyncResult;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.RemoteException;
import android.util.JsonReader;
import android.util.Log;
import com.cbsanjaya.onepiece.provider.TitleContract;
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 java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class SyncTitleAdapter extends AbstractThreadedSyncAdapter {
private static final String TAG = "SyncTitleAdapter";
/**
* URL to fetch content from during a sync.
*
* <p>This points to the Android Developers Blog. (Side note: We highly recommend reading the
* Android Developer Blog to stay up to date on the latest Android platform developments!)
*/
private static final String DOMAIN_URL = "https:
private static final String TITLE_URL = DOMAIN_URL + "onepiece/all.json";
private static final String TITLE_LAST5_URL = DOMAIN_URL + "onepiece/last5.json";
/**
* Network connection timeout, in milliseconds.
*/
private static final int NET_CONNECT_TIMEOUT_MILLIS = 15000; // 15 seconds
/**
* Network read timeout, in milliseconds.
*/
private static final int NET_READ_TIMEOUT_MILLIS = 10000; // 10 seconds
/**
* Content resolver, for performing database operations.
*/
private final ContentResolver mContentResolver;
/**
* Project used when querying content provider. Returns all known fields.
*/
private static final String[] PROJECTION = new String[] {
TitleContract.Title._ID,
TitleContract.Title.COLUMN_NAME_CHAPTER,
TitleContract.Title.COLUMN_NAME_TITLE};
// Constants representing column positions from PROJECTION.
private static final int COLUMN_ID = 0;
private static final int COLUMN_CHAPTER = 1;
private static final int COLUMN_TITLE = 2;
/**
* Constructor. Obtains handle to content resolver for later use.
*/
SyncTitleAdapter(Context context, boolean autoInitialize) {
super(context, autoInitialize);
mContentResolver = context.getContentResolver();
}
/**
* Called by the Android system in response to a request to run the sync adapter. The work
* required to read data from the network, parse it, and store it in the content provider is
* done here. Extending AbstractThreadedSyncAdapter ensures that all methods within SyncAdapter
* run on a background thread. For this reason, blocking I/O and other long-running tasks can be
* run <em>in situ</em>, and you don't have to set up a separate thread for them.
.
*
* <p>This is where we actually perform any work required to perform a sync.
* {@link android.content.AbstractThreadedSyncAdapter} guarantees that this will be called on a non-UI thread,
* so it is safe to peform blocking I/O here.
*
* <p>The syncResult argument allows you to pass information back to the method that triggered
* the sync.
*/
@Override
public void onPerformSync(Account account, Bundle extras, String authority,
ContentProviderClient provider, SyncResult syncResult) {
Log.i(TAG, "Beginning network synchronization");
try {
// final URL location = new URL(TITLE_URL);
URL location;
InputStream stream = null;
try {
Cursor cursor = getContext()
.getContentResolver()
.query(
TitleContract.Title.CONTENT_URI,
new String[] {"count(*) AS count"},
null,
null,
null
);
assert cursor != null;
cursor.moveToFirst();
int count = cursor.getInt(0);
cursor.close();
if ( count == 0 ) {
location = new URL(TITLE_URL);
} else {
location = new URL(TITLE_LAST5_URL);
}
Log.i(TAG, "Streaming data from network: " + location);
stream = downloadUrl(location);
updateLocalFeedData(stream, syncResult);
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (stream != null) {
stream.close();
}
}
} catch (MalformedURLException e) {
Log.e(TAG, "Feed URL is malformed", e);
syncResult.stats.numParseExceptions++;
return;
} catch (IOException e) {
Log.e(TAG, "Error reading from network: " + e.toString());
syncResult.stats.numIoExceptions++;
return;
} catch (RemoteException e) {
Log.e(TAG, "Error updating database: " + e.toString());
syncResult.databaseError = true;
return;
} catch (OperationApplicationException e) {
Log.e(TAG, "Error updating database: " + e.toString());
syncResult.databaseError = true;
return;
}
Log.i(TAG, "Network synchronization complete");
}
private void updateLocalFeedData(final InputStream stream, final SyncResult syncResult)
throws IOException, RemoteException,
OperationApplicationException {
final ContentResolver contentResolver = getContext().getContentResolver();
Log.i(TAG, "Parsing stream");
final List<Title> titles = parseTitle(stream);
Log.i(TAG, "Parsing complete. Found " + titles.size() + " titles");
ArrayList<ContentProviderOperation> batch = new ArrayList<>();
// Build hash table of incoming titles
HashMap<Double, Title> entryMap = new HashMap<>();
for (Title e : titles) {
entryMap.put(e.chapter, e);
}
// Get list of all items
Log.i(TAG, "Fetching local titles for merge");
Uri uri = TitleContract.Title.CONTENT_URI; // Get all titles
Cursor c = contentResolver.query(uri, PROJECTION, null, null, null);
assert c != null;
Log.i(TAG, "Found " + c.getCount() + " local titles. Computing merge solution...");
// Find stale data
int id;
Double chapter;
String title;
while (c.moveToNext()) {
syncResult.stats.numEntries++;
id = c.getInt(COLUMN_ID);
chapter = c.getDouble(COLUMN_CHAPTER);
title = c.getString(COLUMN_TITLE);
Title match = entryMap.get(chapter);
if (match != null) {
// Entry exists. Remove from entry map to prevent insert later.
entryMap.remove(chapter);
// Check to see if the entry needs to be updated
Uri existingUri = TitleContract.Title.CONTENT_URI.buildUpon()
.appendPath(Integer.toString(id)).build();
if ((match.title != null && !match.title.equals(title)) ||
(match.chapter != null && !match.chapter.equals(chapter))) {
// Update existing record
Log.i(TAG, "Scheduling update: " + existingUri);
batch.add(ContentProviderOperation.newUpdate(existingUri)
.withValue(TitleContract.Title.COLUMN_NAME_CHAPTER, match.chapter)
.withValue(TitleContract.Title.COLUMN_NAME_TITLE, match.title)
.build());
syncResult.stats.numUpdates++;
} else {
Log.i(TAG, "No action: " + existingUri);
}
} else {
// Entry doesn't exist. Remove it from the database.
Uri deleteUri = TitleContract.Title.CONTENT_URI.buildUpon()
.appendPath(Integer.toString(id)).build();
Log.i(TAG, "Scheduling delete: " + deleteUri);
batch.add(ContentProviderOperation.newDelete(deleteUri).build());
syncResult.stats.numDeletes++;
}
}
c.close();
// Add new items
for (Title e : entryMap.values()) {
Log.i(TAG, "Scheduling insert: chapter=" + e.chapter);
batch.add(ContentProviderOperation.newInsert(TitleContract.Title.CONTENT_URI)
.withValue(TitleContract.Title.COLUMN_NAME_CHAPTER, e.chapter)
.withValue(TitleContract.Title.COLUMN_NAME_TITLE, e.title)
.build());
syncResult.stats.numInserts++;
}
Log.i(TAG, "Merge solution ready. Applying batch update");
mContentResolver.applyBatch(TitleContract.CONTENT_AUTHORITY, batch);
mContentResolver.notifyChange(
TitleContract.Title.CONTENT_URI, // URI where data was modified
null, // No local observer
false); // IMPORTANT: Do not sync to network
// This sample doesn't support uploads, but if *your* code does, make sure you set
// syncToNetwork=false in the line above to prevent duplicate syncs.
}
@SuppressWarnings("TryFinallyCanBeTryWithResources")
private List<Title> parseTitle(InputStream stream) throws IOException {
JsonReader reader = new JsonReader(new InputStreamReader(stream, "UTF-8"));
try {
return readTitleArray(reader);
} finally {
reader.close();
}
}
private List<Title> readTitleArray(JsonReader reader) throws IOException{
List<Title> titles = new ArrayList<>();
reader.beginArray();
while (reader.hasNext()) {
titles.add(readTitle(reader));
}
reader.endArray();
return titles;
}
private Title readTitle(JsonReader reader) throws IOException {
Double chapter = 0D;
String title = "";
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
switch (name) {
case "chapter":
String _chapter = reader.nextString();
chapter = Double.valueOf(_chapter);
break;
case "title":
title = reader.nextString();
break;
default:
reader.skipValue();
break;
}
}
reader.endObject();
return new Title(chapter, title);
}
/**
* Given a string representation of a URL, sets up a connection and gets an input stream.
*/
private InputStream downloadUrl(final URL url) throws IOException {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(NET_READ_TIMEOUT_MILLIS /* milliseconds */);
conn.setConnectTimeout(NET_CONNECT_TIMEOUT_MILLIS /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
return conn.getInputStream();
}
private class Title {
private final Double chapter;
private final String title;
Title(Double chapter, String title) {
this.chapter = chapter;
this.title = title;
}
}
}
|
package com.kickstarter.libs.gcm;
import android.app.IntentService;
import android.content.Intent;
import android.support.annotation.NonNull;
import com.google.android.gms.gcm.GcmPubSub;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;
import com.kickstarter.KSApplication;
import com.kickstarter.R;
import com.kickstarter.services.ApiClient;
import java.io.IOException;
import javax.inject.Inject;
import timber.log.Timber;
public class RegistrationService extends IntentService {
private static final String WORKER_THREAD_NAME = "RegistrationService";
private static final String[] TOPICS = {"global"};
@Inject protected ApiClient apiClient;
public RegistrationService() {
super(WORKER_THREAD_NAME);
}
@Override
public void onCreate() {
super.onCreate();
((KSApplication) getApplicationContext()).component().inject(this);
}
@Override
protected void onHandleIntent(@NonNull final Intent intent) {
Timber.d("onHandleIntent");
try {
// This initially hits the network to retrieve the token, subsequent calls are local
final InstanceID instanceID = InstanceID.getInstance(this);
// R.string.gcm_defaultSenderId is derived from google-services.json
final String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId),
GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
Timber.d("Token: " + token);
sendTokenToAppServers(token);
subscribeTopics(token);
} catch (final Exception e) {
Timber.e("Failed to complete token refresh", e);
}
}
/**
* Persist token to app servers.
*
* @param token The new token.
*/
private void sendTokenToAppServers(@NonNull final String token) {
//apiClient.registerPushToken(token);
}
/**
* Subscribe to any topics of interest, as defined by the TOPICS constant.
*
* @throws IOException if unable to reach the GCM PubSub service
*/
private void subscribeTopics(@NonNull final String token) throws IOException {
final GcmPubSub pubSub = GcmPubSub.getInstance(this);
for (final String topic : TOPICS) {
pubSub.subscribe(token, "/topics/" + topic, null);
}
}
}
|
package com.malytic.altituden.fragments;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.model.Marker;
import com.malytic.altituden.R;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsFragment extends Fragment implements OnMapReadyCallback, GoogleMap.OnMarkerClickListener, GoogleMap.OnMapClickListener,
GoogleMap.OnMarkerDragListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
private LatLng start,dest;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_maps_fragment, null, false);
SupportMapFragment mapFragment = (SupportMapFragment) this.getChildFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(getContext())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
return view;
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setOnMarkerClickListener(this);
mMap.setOnMapClickListener(this);
mMap.setOnMarkerDragListener(this);
}
@Override
public boolean onMarkerClick(Marker marker) {
return false;
}
@Override
public void onMapClick(LatLng latLng) {
if(start == null || dest == null) {
if (start == null) {
start = latLng;
mMap.addMarker(new MarkerOptions().position(latLng).
title("Start")).setDraggable(true);
} else if (dest == null) {
dest = latLng;
mMap.addMarker(new MarkerOptions().position(latLng).
title("Destination")).setDraggable(true);
}
}else{ Toast.makeText(getActivity(), "You have already places a start and end marker",
Toast.LENGTH_LONG).show();
}
}
@Override
public void onMarkerDragStart(Marker marker) {
marker.hideInfoWindow ();
}
@Override
public void onMarkerDrag(Marker marker) {
}
@Override
public void onMarkerDragEnd(Marker marker) {
//TODO
//On release re-calculate route
}
@Override
public void
onConnectionFailed(ConnectionResult result){
}
@Override
public void onStart() {
mGoogleApiClient.connect();
super.onStart();
}
@Override
public void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
@Override
public void onConnected(Bundle connectionHint) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
mMap.setMyLocationEnabled(true);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mLastLocation.getLatitude(),mLastLocation.getLongitude()), 15));
}
@Override
public void onConnectionSuspended(int i) {
}
}
|
package com.malytic.altituden.fragments;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.location.Location;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.malytic.altituden.MainActivity;
import com.malytic.altituden.classes.ElevationPoint;
import com.malytic.altituden.classes.FileHandler;
import com.malytic.altituden.classes.PathData;
import com.malytic.altituden.events.DirectionsEvent;
import com.malytic.altituden.events.ElevationEvent;
import com.malytic.altituden.classes.HttpRequestHandler;
import com.malytic.altituden.R;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.malytic.altituden.events.ElevationUpdateEvent;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
public class MapsFragment extends Fragment implements OnMapReadyCallback, GoogleMap.OnMarkerClickListener, GoogleMap.OnMapClickListener,
GoogleMap.OnMarkerDragListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{
private GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
private MarkerOptions origin,dest;
private Polyline path;
private HttpRequestHandler httpReq;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_maps_fragment, null, false);
SupportMapFragment mapFragment = (SupportMapFragment) this.getChildFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(getContext())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
httpReq = new HttpRequestHandler(getContext());
path = null;
return view;
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setOnMarkerClickListener(this);
mMap.setOnMapClickListener(this);
mMap.setOnMarkerDragListener(this);
}
@Override
public boolean onMarkerClick(Marker marker) {
return false;
}
/**
* On map click, if start or destination markers are not
* already placed, place them at latLng
*/
@Override
public void onMapClick(LatLng latLng) {
if (origin == null) {
origin = new MarkerOptions().position(latLng).title("Origin").draggable(true).snippet(latLng.toString());
mMap.addMarker(origin);
} else if (dest == null) {
dest = new MarkerOptions().position(latLng).title("Destination").draggable(true).snippet(latLng.toString());
mMap.addMarker(dest);
updateDirections(origin.getPosition(), dest.getPosition());
}else {
// markers already placed --
}
}
@Override
public void onMarkerDragStart(Marker marker) {
if(marker.getTitle().equals(origin.getTitle())) {
origin.position(marker.getPosition());
} else if(marker.getTitle().equals(dest.getTitle())) {
dest.position(marker.getPosition());
}
//marker.setSnippet(marker.getPosition().toString());
marker.hideInfoWindow();
}
@Override
public void onMarkerDrag(Marker marker) {
// TODO
}
@Override
public void onMarkerDragEnd(Marker marker) {
if(marker.getTitle().equals(origin.getTitle())) {
origin.position(marker.getPosition());
} else if(marker.getTitle().equals(dest.getTitle())) {
dest.position(marker.getPosition());
}
if(dest != null && origin != null) updateDirections(origin.getPosition(), dest.getPosition());
}
@Override
public void
onConnectionFailed(ConnectionResult result){
}
@Override
public void onStart() {
mGoogleApiClient.connect();
super.onStart();
EventBus.getDefault().register(this);
}
@Override
public void onStop() {
EventBus.getDefault().unregister(this);
mGoogleApiClient.disconnect();
super.onStop();
}
@Override
public void onConnected(Bundle connectionHint){
try {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
mMap.setMyLocationEnabled(true);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude()), 15));
}catch(Exception e){
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.frame, new FormFragment(),"crash").commit();
}
}
@Override
public void onConnectionSuspended(int i) {
}
private void updateDirections(LatLng origin, LatLng dest) {
httpReq.directionsRequest(PathData.getDirectionsUrl(getContext(), origin, dest));
}
private void updateElevation(JSONObject elevationResponse) {
try {
httpReq.elevationRequest(PathData.getElevationUrl(elevationResponse,getContext()));
} catch (JSONException e) {
e.printStackTrace();
}
}
@Subscribe
public void onDirectionsResponseEvent(DirectionsEvent event) {
try {
MainActivity.pathData.updatePath(event.directionsResponse);
PolylineOptions thePath = new PolylineOptions()
.color(Color.parseColor("#CC00CAB8"))
.width(15)
.addAll(MainActivity.pathData.points);
if (path != null) path.remove();
path = mMap.addPolyline(thePath);
} catch (JSONException e) {
e.printStackTrace();
}
updateElevation(event.directionsResponse);
}
@Subscribe
public void onElevationResponseEvent(ElevationEvent response) {
try {
MainActivity.pathData.updateElevation(response.elevationResponse, getContext());
EventBus.getDefault().post(new ElevationUpdateEvent(""));
} catch (JSONException e) {
System.out.println("JSONException.");
}
}
}
|
package com.marverenic.music.activity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuItem;
import com.marverenic.heterogeneousadapter.HeterogeneousAdapter;
import com.marverenic.music.JockeyApplication;
import com.marverenic.music.R;
import com.marverenic.music.data.store.MusicStore;
import com.marverenic.music.data.store.PlaylistStore;
import com.marverenic.music.instances.Album;
import com.marverenic.music.instances.Artist;
import com.marverenic.music.instances.Genre;
import com.marverenic.music.instances.Playlist;
import com.marverenic.music.instances.Song;
import com.marverenic.music.instances.section.AlbumSection;
import com.marverenic.music.instances.section.ArtistSection;
import com.marverenic.music.instances.section.BasicEmptyState;
import com.marverenic.music.instances.section.GenreSection;
import com.marverenic.music.instances.section.HeaderSection;
import com.marverenic.music.instances.section.PlaylistSection;
import com.marverenic.music.instances.section.SongSection;
import com.marverenic.music.player.PlayerController;
import com.marverenic.music.view.BackgroundDecoration;
import com.marverenic.music.view.DividerDecoration;
import com.marverenic.music.view.GridSpacingDecoration;
import com.marverenic.music.view.ViewUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.inject.Inject;
import rx.Observable;
import rx.subjects.BehaviorSubject;
import timber.log.Timber;
public class SearchActivity extends BaseActivity implements SearchView.OnQueryTextListener {
private static final String KEY_SAVED_QUERY = "SearchActivity.LAST_QUERY";
public static Intent newIntent(Context context) {
return new Intent(context, SearchActivity.class);
}
@Inject MusicStore mMusicStore;
@Inject PlaylistStore mPlaylistStore;
private SearchView searchView;
private BehaviorSubject<String> mQueryObservable;
private RecyclerView mRecyclerView;
private HeterogeneousAdapter mAdapter;
private PlaylistSection mPlaylistSection;
private SongSection mSongSection;
private AlbumSection mAlbumSection;
private ArtistSection mArtistSection;
private GenreSection mGenreSection;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_instance);
JockeyApplication.getComponent(this).inject(this);
String lastQuery;
if (savedInstanceState != null) {
lastQuery = savedInstanceState.getString(KEY_SAVED_QUERY);
} else {
lastQuery = "";
}
mQueryObservable = BehaviorSubject.create(lastQuery);
// Set up the RecyclerView's adapter
mRecyclerView = (RecyclerView) findViewById(R.id.list);
initAdapter();
mQueryObservable
.flatMap(query -> mPlaylistStore.searchForPlaylists(query))
.compose(bindToLifecycle())
.subscribe(playlists -> {
mPlaylistSection.setData(playlists);
mAdapter.notifyDataSetChanged();
}, throwable -> {
Timber.e(throwable, "Failed to search for playlists");
});
mQueryObservable
.flatMap(query -> mMusicStore.searchForSongs(query))
.compose(bindToLifecycle())
.subscribe(songs -> {
mSongSection.setData(songs);
mAdapter.notifyDataSetChanged();
}, throwable -> {
Timber.e(throwable, "Failed to search for songs");
});
mQueryObservable
.flatMap(query -> mMusicStore.searchForAlbums(query))
.compose(bindToLifecycle())
.subscribe(albums -> {
mAlbumSection.setData(albums);
mAdapter.notifyDataSetChanged();
}, throwable -> {
Timber.e(throwable, "Failed to search for albums");
});
mQueryObservable
.flatMap(query -> mMusicStore.searchForArtists(query))
.compose(bindToLifecycle())
.subscribe(artists -> {
mArtistSection.setData(artists);
mAdapter.notifyDataSetChanged();
}, throwable -> {
Timber.e(throwable, "Failed to search for artists");
});
mQueryObservable
.flatMap(query -> mMusicStore.searchForGenres(query))
.compose(bindToLifecycle())
.subscribe(genres -> {
mGenreSection.setData(genres);
mAdapter.notifyDataSetChanged();
}, throwable -> {
Timber.e(throwable, "Failed to search for genres");
});
handleIntent(getIntent());
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(KEY_SAVED_QUERY, mQueryObservable.getValue());
}
private void initAdapter() {
mPlaylistSection = new PlaylistSection(Collections.emptyList());
mSongSection = new SongSection(this, Collections.emptyList());
mAlbumSection = new AlbumSection(this, Collections.emptyList());
mArtistSection = new ArtistSection(this, Collections.emptyList());
mGenreSection = new GenreSection(this, Collections.emptyList());
mAdapter = new HeterogeneousAdapter()
.addSection(new HeaderSection(getString(R.string.header_playlists)))
.addSection(mPlaylistSection)
.addSection(new HeaderSection(getString(R.string.header_songs)))
.addSection(mSongSection)
.addSection(new HeaderSection(getString(R.string.header_albums)))
.addSection(mAlbumSection)
.addSection(new HeaderSection(getString(R.string.header_artists)))
.addSection(mArtistSection)
.addSection(new HeaderSection(getString(R.string.header_genres)))
.addSection(mGenreSection);
mAdapter.setEmptyState(new BasicEmptyState() {
@Override
public String getMessage() {
String query = mQueryObservable.getValue();
return (query == null || query.isEmpty())
? ""
: getString(R.string.empty_search);
}
});
mRecyclerView.setAdapter(mAdapter);
final int numColumns = ViewUtils.getNumberOfGridColumns(this);
GridLayoutManager layoutManager = new GridLayoutManager(this, numColumns);
layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
if (mAdapter.getItemViewType(position) == mAlbumSection.getTypeId()) {
return 1;
}
return numColumns;
}
});
mRecyclerView.setLayoutManager(layoutManager);
// Add item decorations
mRecyclerView.addItemDecoration(new GridSpacingDecoration(
(int) getResources().getDimension(R.dimen.grid_margin),
numColumns, mAlbumSection.getTypeId()));
mRecyclerView.addItemDecoration(
new BackgroundDecoration(R.id.subheaderFrame));
mRecyclerView.addItemDecoration(
new DividerDecoration(this,
R.id.albumInstance, R.id.subheaderFrame, R.id.empty_layout));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_search, menu);
MenuItem searchItem = menu.findItem(R.id.search);
searchView = (SearchView) searchItem.getActionView();
searchView.setOnQueryTextListener(this);
searchView.setIconified(false);
String query = mQueryObservable.getValue();
if (query != null && !query.isEmpty()) {
searchView.setQuery(query, true);
} else {
searchView.requestFocus();
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
navigateHome();
return true;
case R.id.search:
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) onSearchRequested();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void navigateHome() {
Intent mainActivity = new Intent(this, LibraryActivity.class);;
mainActivity.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(mainActivity);
}
@Override
public boolean onQueryTextSubmit(String query) {
search(query);
searchView.clearFocus();
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
search(newText);
return true;
}
private void search(String query) {
if (!mQueryObservable.getValue().equals(query)) {
mQueryObservable.onNext(query);
}
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
handleIntent(intent);
}
private List<Playlist> getPlaylistResults() {
return mPlaylistSection.getData();
}
private List<Song> getSongResults() {
return mSongSection.getData();
}
private List<Artist> getArtistResults() {
return mArtistSection.getData();
}
private List<Album> getAlbumResults() {
return mAlbumSection.getData();
}
private List<Genre> getGenreResults() {
return mGenreSection.getData();
}
private void handleIntent(Intent intent) {
if (intent != null) {
// Handle standard searches
if (Intent.ACTION_SEARCH.equals(intent.getAction())
|| MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(intent.getAction())) {
search(intent.getStringExtra(SearchManager.QUERY));
} else if (MediaStore.INTENT_ACTION_MEDIA_PLAY_FROM_SEARCH.equals(intent.getAction())) {
// Handle play from search actions
search(intent.getStringExtra(SearchManager.QUERY));
String focus = intent.getStringExtra(MediaStore.EXTRA_MEDIA_FOCUS);
String query = mQueryObservable.getValue();
if (MediaStore.Audio.Playlists.ENTRY_CONTENT_TYPE.equals(focus)) {
playPlaylistResults(query);
} else if (MediaStore.Audio.Artists.ENTRY_CONTENT_TYPE.equals(focus)) {
playArtistResults();
} else if (MediaStore.Audio.Albums.ENTRY_CONTENT_TYPE.equals(focus)) {
playAlbumResults(query);
} else if (focus.equals(MediaStore.Audio.Genres.ENTRY_CONTENT_TYPE)) {
playGenreResults(query);
} else {
playSongResults();
}
}
}
}
private void playSongResults() {
if (!getSongResults().isEmpty()) {
PlayerController.setQueue(getSongResults(), 0);
PlayerController.begin();
}
}
private void playPlaylistResults(String query) {
if (getPlaylistResults().isEmpty()) {
return;
}
// If there is a playlist with this exact name, use it, otherwise fallback
// to the first result
Playlist playlist = getPlaylistResults().get(0);
for (Playlist p : getPlaylistResults()) {
if (p.getPlaylistName().equalsIgnoreCase(query)) {
playlist = p;
break;
}
}
mPlaylistStore.getSongs(playlist).subscribe(
songs -> {
PlayerController.setQueue(songs, 0);
PlayerController.begin();
}, throwable -> {
Timber.e(throwable, "Failed to play playlist from intent");
});
}
private void playArtistResults() {
if (getGenreResults().isEmpty()) {
return;
}
// If one or more artists with this name exist, play songs by all of them (Ideally this only
// includes collaborating artists and keeps the search relevant)
Observable<List<Song>> combinedSongs = Observable.just(new ArrayList<>());
for (Artist a : getArtistResults()) {
combinedSongs = Observable.combineLatest(
combinedSongs, mMusicStore.getSongs(a), (left, right) -> {
left.addAll(right);
return left;
});
}
combinedSongs.subscribe(
songs -> {
PlayerController.setQueue(songs, 0);
PlayerController.begin();
},
throwable -> {
Timber.e(throwable, "Failed to play artist from intent");
});
}
private void playAlbumResults(String query) {
if (getAlbumResults().isEmpty()) {
return;
}
// If albums with this name exist, look for an exact match
// If we find one then use it, otherwise fallback to the first result
Album album = getAlbumResults().get(0);
for (Album a : getAlbumResults()) {
if (a.getAlbumName().equalsIgnoreCase(query)) {
album = a;
break;
}
}
mMusicStore.getSongs(album).subscribe(
songs -> {
PlayerController.setQueue(songs, 0);
PlayerController.begin();
}, throwable -> {
Timber.e(throwable, "Failed to play album from intent");
});
}
private void playGenreResults(String query) {
if (!getGenreResults().isEmpty()) {
return;
}
// If genres with this name exist, look for an exact match
// If we find one then use it, otherwise fallback to the first result
Genre genre = getGenreResults().get(0);
for (Genre g : getGenreResults()) {
if (g.getGenreName().equalsIgnoreCase(query)) {
genre = g;
break;
}
}
mMusicStore.getSongs(genre).subscribe(
songs -> {
PlayerController.setQueue(songs, 0);
PlayerController.begin();
}, throwable -> {
Timber.e(throwable, "Failed to play genre from intent");
});
}
}
|
package com.marverenic.music.fragments;
import android.content.res.Configuration;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.NinePatchDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.ItemDecoration;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.marverenic.heterogeneousadapter.DragDropAdapter;
import com.marverenic.heterogeneousadapter.DragDropDecoration;
import com.marverenic.music.R;
import com.marverenic.music.instances.section.LibraryEmptyState;
import com.marverenic.music.instances.section.QueueSection;
import com.marverenic.music.instances.section.SpacerSingleton;
import com.marverenic.music.player.PlayerController;
import com.marverenic.music.view.DragBackgroundDecoration;
import com.marverenic.music.view.DragDividerDecoration;
import com.marverenic.music.view.InsetDecoration;
import com.marverenic.music.view.QueueAnimator;
import com.marverenic.music.view.SnappingScroller;
import static android.content.res.Configuration.ORIENTATION_LANDSCAPE;
public class QueueFragment extends Fragment implements PlayerController.UpdateListener {
private int lastPlayIndex;
private RecyclerView mRecyclerView;
private DragDropAdapter mAdapter;
private QueueSection mQueueSection;
private SpacerSingleton[] mBottomSpacers;
private SnappingScroller mScroller;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.list, container, false);
mRecyclerView = (RecyclerView) view.findViewById(R.id.list);
mScroller = new SnappingScroller(getContext(), SnappingScroller.SNAP_TO_START);
setupAdapter();
setupRecyclerView();
// Remove the list padding on landscape tablets
Configuration config = getResources().getConfiguration();
if (config.orientation == ORIENTATION_LANDSCAPE
&& config.smallestScreenWidthDp >= 600) {
view.setPadding(0, 0, 0, 0);
}
/*
Because of the way that CoordinatorLayout lays out children, there isn't a way to get
the height of this list until it's about to be shown. Since this fragment is dependent
on having an accurate height of the list (in order to pad the bottom of the list so that
the playing song is always at the top of the list), we need to have a way to be informed
when the list has a valid height before it's shown to the user.
This post request will be run after the layout has been assigned a height and before
it's shown to the user so that we can set the bottom padding correctly.
*/
view.post(this::scrollToNowPlaying);
return view;
}
private void setupAdapter() {
if (mQueueSection == null) {
mAdapter = new DragDropAdapter();
mAdapter.attach(mRecyclerView);
mRecyclerView.setItemAnimator(new QueueAnimator());
mQueueSection = new QueueSection(this, PlayerController.getQueue());
mAdapter.setDragSection(mQueueSection);
// Wait for a layout pass before calculating bottom spacing since it is dependent on the
// height of the RecyclerView (which has not been computed yet)
mRecyclerView.post(this::setupSpacers);
mAdapter.setEmptyState(new LibraryEmptyState(getActivity()) {
@Override
public String getEmptyMessage() {
return getString(R.string.empty_queue);
}
@Override
public String getEmptyMessageDetail() {
return getString(R.string.empty_queue_detail);
}
@Override
public String getEmptyAction1Label() {
return "";
}
@Override
public String getEmptyAction2Label() {
return "";
}
});
} else if (!mQueueSection.getData().equals(PlayerController.getQueue())) {
mQueueSection.setData(PlayerController.getQueue());
mAdapter.notifyDataSetChanged();
}
}
private void setupSpacers() {
if (mBottomSpacers != null) {
return;
}
int itemHeight = (int) getResources().getDimension(R.dimen.list_height);
int dividerHeight = (int) getResources().getDisplayMetrics().density;
int listHeight = mRecyclerView.getMeasuredHeight();
int listItemHeight = itemHeight + dividerHeight;
int numberOfSpacers = (int) Math.ceil(listHeight / (float) listItemHeight) - 1;
int remainingListHeight = listHeight - listItemHeight;
mBottomSpacers = new SpacerSingleton[numberOfSpacers];
for (int i = 0; i < numberOfSpacers; i++) {
int height;
if (remainingListHeight % listItemHeight > 0) {
height = remainingListHeight % listItemHeight;
} else {
height = listItemHeight;
}
remainingListHeight -= height;
mBottomSpacers[i] = new SpacerSingleton(height);
mAdapter.addSection(mBottomSpacers[i]);
}
mAdapter.notifyDataSetChanged();
smoothScrollToNowPlaying();
}
private void setupRecyclerView() {
Drawable shadow = ContextCompat.getDrawable(getContext(), R.drawable.list_drag_shadow);
ItemDecoration background = new DragBackgroundDecoration();
ItemDecoration divider = new DragDividerDecoration(getContext(), true, R.id.instance_blank);
ItemDecoration dragShadow = new DragDropDecoration((NinePatchDrawable) shadow);
mRecyclerView.addItemDecoration(background);
mRecyclerView.addItemDecoration(divider);
mRecyclerView.addItemDecoration(dragShadow);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
boolean portrait = getResources().getConfiguration().orientation != ORIENTATION_LANDSCAPE;
boolean tablet = getResources().getConfiguration().smallestScreenWidthDp < 600;
if (portrait || tablet) {
// Add an inner shadow on phones and portrait tablets
mRecyclerView.addItemDecoration(new InsetDecoration(
ContextCompat.getDrawable(getContext(), R.drawable.inset_shadow),
(int) getResources().getDimension(R.dimen.inset_shadow_height)));
}
}
@Override
public void onResume() {
super.onResume();
PlayerController.registerUpdateListener(this);
// Assume this fragment's data has gone stale since it was last in the foreground
onUpdate();
scrollToNowPlaying();
}
@Override
public void onPause() {
super.onPause();
PlayerController.unregisterUpdateListener(this);
}
@Override
public void onUpdate() {
setupAdapter();
int currentIndex = PlayerController.getQueuePosition();
int previousIndex = lastPlayIndex;
if (currentIndex != lastPlayIndex) {
lastPlayIndex = currentIndex;
mAdapter.notifyItemChanged(previousIndex);
mAdapter.notifyItemChanged(currentIndex);
if (shouldScrollToCurrent()) {
smoothScrollToNowPlaying();
}
}
}
/**
* @return true if the currently playing song is above or below the current item by the
* list's height, if the queue has been restarted, or if repeat all is enabled and
* the user wrapped from the front of the queue to the end of the queue
*/
private boolean shouldScrollToCurrent() {
int queueSize = mQueueSection.getData().size();
View topView = mRecyclerView.getChildAt(0);
View bottomView = mRecyclerView.getChildAt(mRecyclerView.getChildCount() - 1);
int topIndex = mRecyclerView.getChildAdapterPosition(topView);
int bottomIndex = mRecyclerView.getChildAdapterPosition(bottomView);
return Math.abs(topIndex - lastPlayIndex) <= (bottomIndex - topIndex)
|| (queueSize - bottomIndex <= 2 && lastPlayIndex == 0)
|| (bottomIndex - queueSize <= 2 && lastPlayIndex == queueSize - 1);
}
private void updateSpacers() {
if (mBottomSpacers == null) {
return;
}
int queueSize = mQueueSection.getData().size();
int visibleSpacers = mBottomSpacers.length - (queueSize - lastPlayIndex) + 1;
visibleSpacers = Math.max(0, visibleSpacers);
int prevVisibleSpacers = 0;
for (int i = 0; i < mBottomSpacers.length; i++) {
if (mBottomSpacers[i].showSection()) {
prevVisibleSpacers++;
}
mBottomSpacers[i].setShowSection(i < visibleSpacers);
}
if (visibleSpacers > prevVisibleSpacers) {
int addedSpacers = visibleSpacers - prevVisibleSpacers;
mAdapter.notifyItemRangeInserted(queueSize, addedSpacers);
} else if (visibleSpacers < prevVisibleSpacers) {
int firstSpacerIndex = queueSize + visibleSpacers;
int removedSpacers = prevVisibleSpacers - visibleSpacers;
mAdapter.notifyItemRangeRemoved(firstSpacerIndex, removedSpacers);
}
}
private void smoothScrollToNowPlaying() {
updateSpacers();
mScroller.setTargetPosition(lastPlayIndex);
mRecyclerView.getLayoutManager().startSmoothScroll(mScroller);
}
private void scrollToNowPlaying() {
updateSpacers();
((LinearLayoutManager) mRecyclerView.getLayoutManager())
.scrollToPositionWithOffset(lastPlayIndex, 0);
}
public void updateShuffle() {
setupAdapter();
lastPlayIndex = PlayerController.getQueuePosition();
scrollToNowPlaying();
}
}
|
package com.marverenic.music.viewmodel;
import android.content.Context;
import android.databinding.BaseObservable;
import android.support.v4.app.FragmentManager;
import android.support.v7.widget.PopupMenu;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import com.marverenic.music.JockeyApplication;
import com.marverenic.music.R;
import com.marverenic.music.activity.NowPlayingActivity;
import com.marverenic.music.activity.instance.AlbumActivity;
import com.marverenic.music.activity.instance.ArtistActivity;
import com.marverenic.music.data.store.MusicStore;
import com.marverenic.music.data.store.PreferencesStore;
import com.marverenic.music.dialog.AppendPlaylistDialogFragment;
import com.marverenic.music.instances.Song;
import com.marverenic.music.player.PlayerController;
import com.marverenic.music.utils.Navigate;
import java.util.List;
import javax.inject.Inject;
public class SongViewModel extends BaseObservable {
private static final String TAG = "SongViewModel";
private static final String TAG_PLAYLIST_DIALOG = "SongViewModel.PlaylistDialog";
@Inject MusicStore mMusicStore;
@Inject PreferencesStore mPrefStore;
private Context mContext;
private FragmentManager mFragmentManager;
private List<Song> mSongList;
private int mIndex;
private Song mReference;
public SongViewModel(Context context, FragmentManager fragmentManager, List<Song> songs) {
mContext = context;
mFragmentManager = fragmentManager;
mSongList = songs;
JockeyApplication.getComponent(mContext).inject(this);
}
public void setIndex(int index) {
setSong(mSongList, index);
}
protected int getIndex() {
return mIndex;
}
protected Song getReference() {
return mReference;
}
protected List<Song> getSongs() {
return mSongList;
}
public void setSong(List<Song> songList, int index) {
mSongList = songList;
mIndex = index;
mReference = songList.get(index);
notifyChange();
}
public String getTitle() {
return mReference.getSongName();
}
public String getDetail() {
return mContext.getString(R.string.format_compact_song_info,
mReference.getArtistName(), mReference.getAlbumName());
}
public View.OnClickListener onClickSong() {
return v -> {
PlayerController.setQueue(mSongList, mIndex);
PlayerController.begin();
if (mPrefStore.openNowPlayingOnNewQueue()) {
Navigate.to(mContext, NowPlayingActivity.class);
}
};
}
public View.OnClickListener onClickMenu() {
return v -> {
final PopupMenu menu = new PopupMenu(mContext, v, Gravity.END);
String[] options = mContext.getResources()
.getStringArray(R.array.queue_options_song);
for (int i = 0; i < options.length; i++) {
menu.getMenu().add(Menu.NONE, i, i, options[i]);
}
menu.setOnMenuItemClickListener(onMenuItemClick(v));
menu.show();
};
}
private PopupMenu.OnMenuItemClickListener onMenuItemClick(View view) {
return menuItem -> {
switch (menuItem.getItemId()) {
case 0: //Queue this song next
PlayerController.queueNext(mReference);
return true;
case 1: //Queue this song last
PlayerController.queueLast(mReference);
return true;
case 2: //Go to artist
mMusicStore.findArtistById(mReference.getArtistId()).subscribe(
artist -> {
Navigate.to(mContext, ArtistActivity.class,
ArtistActivity.ARTIST_EXTRA, artist);
}, throwable -> {
Log.e(TAG, "Failed to find artist", throwable);
});
return true;
case 3: // Go to album
mMusicStore.findAlbumById(mReference.getAlbumId()).subscribe(
album -> {
Navigate.to(mContext, AlbumActivity.class,
AlbumActivity.ALBUM_EXTRA, album);
}, throwable -> {
Log.e(TAG, "Failed to find album", throwable);
});
return true;
case 4: //Add to playlist...
AppendPlaylistDialogFragment.newInstance()
.setSong(mReference)
.show(mFragmentManager, TAG_PLAYLIST_DIALOG);
return true;
}
return false;
};
}
}
|
package com.muzima.utils.smartcard;
import android.util.Log;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.muzima.MuzimaApplication;
import com.muzima.api.model.Concept;
import com.muzima.api.model.Encounter;
import com.muzima.api.model.FormData;
import com.muzima.api.model.Location;
import com.muzima.api.model.Observation;
import com.muzima.api.model.Patient;
import com.muzima.api.model.PatientIdentifier;
import com.muzima.api.model.Person;
import com.muzima.api.model.PersonAddress;
import com.muzima.api.model.PersonName;
import com.muzima.api.model.SmartCardRecord;
import com.muzima.controller.ConceptController;
import com.muzima.controller.EncounterController;
import com.muzima.controller.FormController;
import com.muzima.controller.ObservationController;
import com.muzima.controller.PatientController;
import com.muzima.controller.SmartCardController;
import com.muzima.model.observation.EncounterWithObservations;
import com.muzima.model.observation.Encounters;
import com.muzima.model.shr.kenyaemr.ExternalPatientId;
import com.muzima.model.shr.kenyaemr.HIVTest;
import com.muzima.model.shr.kenyaemr.Immunization;
import com.muzima.model.shr.kenyaemr.InternalPatientId;
import com.muzima.model.shr.kenyaemr.KenyaEmrShrModel;
import com.muzima.model.shr.kenyaemr.PatientAddress;
import com.muzima.model.shr.kenyaemr.PatientIdentification;
import com.muzima.model.shr.kenyaemr.PatientName;
import com.muzima.model.shr.kenyaemr.PhysicalAddress;
import com.muzima.model.shr.kenyaemr.ProviderDetails;
import com.muzima.service.HTMLFormObservationCreator;
import com.muzima.utils.Constants;
import com.muzima.utils.Constants.Shr.KenyaEmr.PersonIdentifierType;
import com.muzima.utils.Constants.Shr.KenyaEmr.CONCEPTS;
import com.muzima.utils.DateUtils;
import com.muzima.utils.LocationUtils;
import com.muzima.utils.PatientIdentifierUtils;
import com.muzima.utils.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import static com.muzima.utils.Constants.STATUS_COMPLETE;
public class KenyaEmrShrMapper {
private static final String TAG = KenyaEmrShrMapper.class.getSimpleName();
/**
* Converts an SHR model from JSON representation to KenyaEmrShrModel
* @param jsonSHRModel the JSON representation of the SHR model
* @return Representation of the JSON input as KenyaEmrShrModel object
* @throws IOException
*/
public static KenyaEmrShrModel createSHRModelFromJson(String jsonSHRModel) throws ShrParseException {
ObjectMapper objectMapper = new ObjectMapper();
KenyaEmrShrModel shrModel = null;
try {
shrModel = objectMapper.readValue(jsonSHRModel,KenyaEmrShrModel.class);
} catch (IOException e) {
throw new ShrParseException(e);
}
return shrModel;
}
/**
* Converts a KenyaEmrShrModel representation of SHR to JSON representation
* @param shrModel the KenyaEmrShrModel Object representation of the SHR model
* @return JSON representation of SHR model
* @throws IOException
*/
public static String createJsonFromSHRModel(KenyaEmrShrModel shrModel) throws ShrParseException{
ObjectMapper objectMapper = new ObjectMapper();
try {
return objectMapper.writeValueAsString(shrModel);
} catch (IOException e) {
throw new ShrParseException(e);
}
}
/**
* Extracts a Patient object from a JSON SHR model
* @param shrModel the JSON representation of the SHR model
* @return Patient object extracted from SHR model
* @throws IOException
*/
public static Patient extractPatientFromShrModel(MuzimaApplication muzimaApplication,String shrModel) throws ShrParseException{
KenyaEmrShrModel kenyaEmrShrModel = createSHRModelFromJson(shrModel);
return extractPatientFromShrModel(muzimaApplication, kenyaEmrShrModel);
}
/**
* Extracts a Patient Object from a KenyaEmrShrModel Object of SHR model
* @param shrModel the KenyaEmrShrModel Object representation of the SHR model
* @return Patient object extracted from SHR model
* @throws IOException
*/
public static Patient extractPatientFromShrModel(MuzimaApplication muzimaApplication, KenyaEmrShrModel shrModel) throws ShrParseException{
try {
Patient patient = new Patient();
PatientIdentification identification = shrModel.getPatientIdentification();
List<PersonName> names = extractPatientNamesFromShrModel(shrModel);
patient.setNames(names);
//set Identifiers
List<PatientIdentifier> identifiers = extractPatientIdentifiersFromShrModel(muzimaApplication, shrModel);
if(!identifiers.isEmpty()) {
patient.setIdentifiers(identifiers);
}
//date of birth
Date dob = DateUtils.parseDateByPattern(identification.getDateOfBirth(),"yyyyMMdd");
patient.setBirthdate(dob);
//Gender
String gender = identification.getSex();
if(gender.equalsIgnoreCase("M")){
patient.setGender("M");
} else if (gender.equalsIgnoreCase("F")){
patient.setGender("F");
} else {
throw new ShrParseException("Could not determine gender from SHR model");
}
return patient;
} catch (ParseException e){
throw new ShrParseException(e);
}
}
/**
*
* @param shrModel
* @return
*/
public static List<PersonName> extractPatientNamesFromShrModel(KenyaEmrShrModel shrModel) throws ShrParseException {
PatientIdentification identification = shrModel.getPatientIdentification();
if(identification != null && identification.getPatientName()!= null) {
final PersonName personName = new PersonName();
personName.setFamilyName(identification.getPatientName().getFirstName());
personName.setGivenName(identification.getPatientName().getLastName());
personName.setMiddleName(identification.getPatientName().getMiddleName());
List<PersonName> names = new ArrayList<PersonName>(){{
add(personName);
}};
return names;
} else {
throw new ShrParseException("Could not find patient names");
}
}
public static KenyaEmrShrModel putIdentifiersIntoShrModel(KenyaEmrShrModel shrModel,List<PatientIdentifier> identifiers ) throws ShrParseException {
PatientIdentification patientIdentification = shrModel.getPatientIdentification();
if(patientIdentification == null){
patientIdentification = new PatientIdentification();
}
List<InternalPatientId> internalPatientIds = patientIdentification.getInternalPatientIds();
if(internalPatientIds == null){
internalPatientIds = new ArrayList<>();
}
for(PatientIdentifier identifier:identifiers){
try {
String shrIdentifierTypeName = null;
String assigningAuthority = null;
String assigningFacility = "10829";// LocationUtils.getKenyaEmrMasterFacilityListCode(identifier.getLocation());
if(StringUtils.isEmpty(assigningFacility)) {
throw new ShrParseException("Cannot get Facility MFL code from identifier location");
}
switch (identifier.getIdentifierType().getName()) {
case PersonIdentifierType.GODS_NUMBER.name:
ExternalPatientId externalPatientId = patientIdentification.getExternalPatientId();
if(externalPatientId == null){
externalPatientId = new ExternalPatientId();
}
externalPatientId.setIdentifierType(PersonIdentifierType.GODS_NUMBER.shr_name);
externalPatientId.setID(identifier.getIdentifier());
externalPatientId.setAssigningAuthority("MPI");
externalPatientId.setAssigningFacility(assigningFacility);
patientIdentification.setExternalPatientId(externalPatientId);
break;
case PersonIdentifierType.CARD_SERIAL_NUMBER.name:
shrIdentifierTypeName = PersonIdentifierType.CARD_SERIAL_NUMBER.shr_name;
assigningAuthority = "CARD_REGISTRY";
break;
case PersonIdentifierType.CCC_NUMBER.name:
shrIdentifierTypeName = PersonIdentifierType.CCC_NUMBER.shr_name;
assigningAuthority = "CCC";
break;
case PersonIdentifierType.HEI_NUMBER.name:
shrIdentifierTypeName = PersonIdentifierType.HEI_NUMBER.shr_name;
assigningAuthority = "MCH";
break;
case PersonIdentifierType.HTS_NUMBER.name:
shrIdentifierTypeName = PersonIdentifierType.HTS_NUMBER.shr_name;
assigningAuthority = "HTS";
break;
case PersonIdentifierType.NATIONAL_ID.name:
shrIdentifierTypeName = PersonIdentifierType.NATIONAL_ID.shr_name;
assigningAuthority = "GK";
break;
case CONCEPTS.ANC_NUMBER.name:
shrIdentifierTypeName = CONCEPTS.ANC_NUMBER.shr_name;
assigningAuthority = "ANC";
break;
}
if(!StringUtils.isEmpty(shrIdentifierTypeName) && !StringUtils.isEmpty(identifier.getIdentifier())){
InternalPatientId internalPatientId = new InternalPatientId();
internalPatientId.setIdentifierType(shrIdentifierTypeName);
internalPatientId.setAssigningAuthority(assigningAuthority);
internalPatientId.setID(identifier.getIdentifier());
internalPatientId.setAssigningFacility(assigningFacility);
internalPatientIds.add(internalPatientId);
}
}catch(Exception e){
Log.e(TAG,"Could not add identifier",e);
}
}
patientIdentification.setInternalPatientIds(internalPatientIds);
shrModel.setPatientIdentification(patientIdentification);
return shrModel;
}
public static List<PatientIdentifier> extractPatientIdentifiersFromShrModel(MuzimaApplication muzimaApplication,KenyaEmrShrModel shrModel){
List<PatientIdentifier> identifiers = new ArrayList<PatientIdentifier>();
try {
PatientIdentification identification = shrModel.getPatientIdentification();
PatientIdentifier patientIdentifier = null;
//External ID
ExternalPatientId externalPatientId = identification.getExternalPatientId();
if(!externalPatientId.lacksMandatoryValues()) {
patientIdentifier = PatientIdentifierUtils.getOrCreateKenyaEmrIdentifierType(muzimaApplication, externalPatientId.getID(),
externalPatientId.getIdentifierType(), externalPatientId.getAssigningFacility());
identifiers.add(patientIdentifier);
}
//Internal IDs
List<InternalPatientId> internalPatientIds = identification.getInternalPatientIds();
for (InternalPatientId internalPatientId : internalPatientIds) {
if(!internalPatientId.lacksMandatoryValues()) {
patientIdentifier = PatientIdentifierUtils.getOrCreateKenyaEmrIdentifierType(muzimaApplication, internalPatientId.getID(),
internalPatientId.getIdentifierType(), internalPatientId.getAssigningFacility());
identifiers.add(patientIdentifier);
}
}
} catch (Exception e){
Log.e("KenyaEmrShrMapper","Could not create Kenyaemr identifier",e);
}
return identifiers;
}
public static void createNewObservationsAndEncountersFromShrModel(MuzimaApplication muzimaApplication, KenyaEmrShrModel shrModel, final Patient patient)
throws ShrParseException {
Log.e("KenyaEmrShrMapper","Saving encounters data ");
List<String> payloads = createJsonEncounterPayloadFromShrModel(muzimaApplication, shrModel, patient);
for(final String payload:payloads) {
Log.e("KenyaEmrShrMapper","Saving payload data ");
final String newFormDataUuid = UUID.randomUUID().toString();
HTMLFormObservationCreator htmlFormObservationCreator = new HTMLFormObservationCreator(muzimaApplication);
htmlFormObservationCreator.createObservationsAndRelatedEntities(payload, newFormDataUuid);
List<Concept> newConcepts = new ArrayList();
newConcepts.addAll(htmlFormObservationCreator.getNewConceptList());
if(!newConcepts.isEmpty()){
ConceptController conceptController = muzimaApplication.getConceptController();
try {
conceptController.saveConcepts(newConcepts);
} catch (ConceptController.ConceptSaveException e) {
Log.e("ShrMapper","Could not save new Concepts",e);
}
}
Encounter encounter = htmlFormObservationCreator.getEncounter();
EncounterController encounterController = muzimaApplication.getEncounterController();
try {
encounterController.saveEncounter(encounter);
} catch (EncounterController.SaveEncounterException e) {
Log.e("ShrMapper","Could not save Encounter",e);
}
List<Observation> observations = htmlFormObservationCreator.getObservations();
ObservationController observationController = muzimaApplication.getObservationController();
try {
observationController.saveObservations(observations);
} catch (ObservationController.SaveObservationException e) {
Log.e("ShrMapper","Could not save Observations",e);
}
final FormData formData = new FormData( ) {{
setUuid(newFormDataUuid);
setPatientUuid(patient.getUuid( ));
setUserUuid("userUuid");
setStatus(STATUS_COMPLETE);
setTemplateUuid(StringUtils.defaultString(CONCEPTS.HIV_TESTS.FORM.FORM_UUID));
setDiscriminator(Constants.FORM_JSON_DISCRIMINATOR_ENCOUNTER);
setJsonPayload(payload);
}};
FormController formController = muzimaApplication.getFormController();
try {
Log.e("KenyaEmrShrMapper","Saving form data ");
formController.saveFormData(formData);
} catch (FormController.FormDataSaveException e) {
Log.e("ShrMapper","Could not save Form Data",e);
}
}
}
public static List<String> createJsonEncounterPayloadFromShrModel(MuzimaApplication muzimaApplication, KenyaEmrShrModel shrModel, Patient patient) throws ShrParseException {
try {
Log.e("KenyaEmrShrMapper","Obtaining payloads ");
List<String> encounters = new ArrayList<>();
List<HIVTest> hivTests = shrModel.getHivTests();
if(hivTests != null) {
for (HIVTest hivTest : hivTests) {
if(!hivTest.lacksMandatoryValues()) {
encounters.add(createJsonEncounterPayloadFromHivTest(muzimaApplication, hivTest, patient));
}
}
} else {
Log.e("KenyaEmrShrMapper","No HIV Tests found");
}
List<Immunization> immunizations = shrModel.getImmunizations();
if(immunizations != null) {
for (Immunization immunization : immunizations) {
if (!immunization.lacksMandatoryValues()) {
encounters.add(createJsonEncounterPayloadFromImmunization(immunization, patient));
}
}
} else {
Log.e("KenyaEmrShrMapper","No Immunizations found");
}
return encounters;
} catch(ParseException e){
throw new ShrParseException("Could not parse SHR model",e);
} catch(JSONException e){
throw new ShrParseException("Could not parse SHR model",e);
}
}
public static String createJsonEncounterPayloadFromHivTest(MuzimaApplication muzimaApplication,HIVTest hivTest, Patient patient) throws ShrParseException {
System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
System.out.println(" createJsonEncounterPayloadFromHivTest() ");
System.out.println(" DATE: "+hivTest.getDate());
System.out.println(" RESULT: "+hivTest.getResult());
System.out.println(" TYPE: "+hivTest.getType());
System.out.println(" STRATEGY: "+hivTest.getStrategy());
System.out.println(" FACILITY: "+hivTest.getFacility());
System.out.println(" PROVIDER DETAILS: ID : "+hivTest.getProviderDetails().getId());
System.out.println(" NAME : "+hivTest.getProviderDetails().getName());
System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
JSONObject encounterJSON = new JSONObject();
JSONObject patientDetails = new JSONObject();
JSONObject observationDetails = new JSONObject();
JSONObject encounterDetails = new JSONObject();
Log.e("KenyaEmrShrMapper","Processing HIV test ");
try {
encounterDetails.put("encounter.provider_id", hivTest.getProviderDetails().getId());
Location location = LocationUtils.getOrCreateDummyLocationByKenyaEmrMasterFacilityListCode(muzimaApplication, hivTest.getFacility());
encounterDetails.put("encounter.location_id", location.getId());
Date encounterDateTime = DateUtils.parseDateByPattern(hivTest.getDate(), "yyyyMMdd");
encounterDetails.put("encounter.encounter_datetime", DateUtils.getFormattedDate(encounterDateTime));
encounterDetails.put("encounter.form_uuid", StringUtils.defaultString(CONCEPTS.HIV_TESTS.FORM.FORM_UUID));
encounterJSON.put("encounter", encounterDetails);
patientDetails.put("patient.medical_record_number", StringUtils.defaultString(patient.getIdentifier()));
patientDetails.put("patient.given_name", StringUtils.defaultString(patient.getGivenName()));
patientDetails.put("patient.middle_name", StringUtils.defaultString(patient.getMiddleName()));
patientDetails.put("patient.family_name", StringUtils.defaultString(patient.getFamilyName()));
patientDetails.put("patient.sex", StringUtils.defaultString(patient.getGender()));
patientDetails.put("patient.uuid", StringUtils.defaultString(patient.getUuid()));
if (patient.getBirthdate() != null) {
patientDetails.put("patient.birth_date", DateUtils.getFormattedDate(patient.getBirthdate()));
}
encounterJSON.put("patient", patientDetails);
//Test Result
String answer = null;
String testResult = hivTest.getResult();
switch (testResult) {
case CONCEPTS.HIV_TESTS.TEST_RESULT.ANSWERS.POSITIVE.name:
answer = CONCEPTS.HIV_TESTS.TEST_RESULT.ANSWERS.POSITIVE.concept_id + "^"
+ CONCEPTS.HIV_TESTS.TEST_RESULT.ANSWERS.POSITIVE.name + "^" + "99DCT";
break;
case CONCEPTS.HIV_TESTS.TEST_RESULT.ANSWERS.NEGATIVE.name:
answer = CONCEPTS.HIV_TESTS.TEST_RESULT.ANSWERS.NEGATIVE.concept_id + "^"
+ CONCEPTS.HIV_TESTS.TEST_RESULT.ANSWERS.NEGATIVE.name + "^" + "99DCT";
break;
case CONCEPTS.HIV_TESTS.TEST_RESULT.ANSWERS.INCONCLUSIVE.name:
answer = CONCEPTS.HIV_TESTS.TEST_RESULT.ANSWERS.INCONCLUSIVE.concept_id + "^"
+ CONCEPTS.HIV_TESTS.TEST_RESULT.ANSWERS.INCONCLUSIVE.name + "^" + "99DCT";
}
if (!StringUtils.isEmpty(answer)) {
String conceptQuestion = CONCEPTS.HIV_TESTS.TEST_RESULT.concept_id + "^"
+ CONCEPTS.HIV_TESTS.TEST_RESULT.name + "^" + "99DCT";
observationDetails.put(conceptQuestion, answer);
}
//Test Type
answer = null;
String testType = hivTest.getType();
switch (testType) {
case CONCEPTS.HIV_TESTS.TEST_TYPE.ANSWERS.SCREENING.name:
answer = CONCEPTS.HIV_TESTS.TEST_TYPE.ANSWERS.SCREENING.concept_id + "^"
+ CONCEPTS.HIV_TESTS.TEST_TYPE.ANSWERS.SCREENING.name + "^" + "99DCT";
break;
case CONCEPTS.HIV_TESTS.TEST_TYPE.ANSWERS.CONFIRMATORY.name:
answer = CONCEPTS.HIV_TESTS.TEST_TYPE.ANSWERS.CONFIRMATORY.concept_id + "^"
+ CONCEPTS.HIV_TESTS.TEST_TYPE.ANSWERS.CONFIRMATORY.name + "^" + "99DCT";
}
if (!StringUtils.isEmpty(answer)) {
String conceptQuestion = CONCEPTS.HIV_TESTS.TEST_TYPE.concept_id + "^"
+ CONCEPTS.HIV_TESTS.TEST_TYPE.name + "^" + "99DCT";
observationDetails.put(conceptQuestion, answer);
}
//Test Strategy
answer = null;
String testStrategy = hivTest.getStrategy();
switch (testStrategy) {
case CONCEPTS.HIV_TESTS.TEST_STRATEGY.ANSWERS.HP.name:
answer = CONCEPTS.HIV_TESTS.TEST_STRATEGY.ANSWERS.HP.concept_id + "^"
+ CONCEPTS.HIV_TESTS.TEST_STRATEGY.ANSWERS.HP.name + "^" + "99DCT";
break;
case CONCEPTS.HIV_TESTS.TEST_STRATEGY.ANSWERS.NP.name:
answer = CONCEPTS.HIV_TESTS.TEST_STRATEGY.ANSWERS.NP.concept_id + "^"
+ CONCEPTS.HIV_TESTS.TEST_STRATEGY.ANSWERS.NP.name + "^" + "99DCT";
break;
case CONCEPTS.HIV_TESTS.TEST_STRATEGY.ANSWERS.VI.name:
answer = CONCEPTS.HIV_TESTS.TEST_STRATEGY.ANSWERS.VI.concept_id + "^"
+ CONCEPTS.HIV_TESTS.TEST_STRATEGY.ANSWERS.VI.name + "^" + "99DCT";
break;
case CONCEPTS.HIV_TESTS.TEST_STRATEGY.ANSWERS.VS.name:
answer = CONCEPTS.HIV_TESTS.TEST_STRATEGY.ANSWERS.VS.concept_id + "^"
+ CONCEPTS.HIV_TESTS.TEST_STRATEGY.ANSWERS.VS.name + "^" + "99DCT";
break;
case CONCEPTS.HIV_TESTS.TEST_STRATEGY.ANSWERS.HB.name:
answer = CONCEPTS.HIV_TESTS.TEST_STRATEGY.ANSWERS.HB.concept_id + "^"
+ CONCEPTS.HIV_TESTS.TEST_STRATEGY.ANSWERS.HB.name + "^" + "99DCT";
break;
case CONCEPTS.HIV_TESTS.TEST_STRATEGY.ANSWERS.MO.name:
answer = CONCEPTS.HIV_TESTS.TEST_STRATEGY.ANSWERS.MO.concept_id + "^"
+ CONCEPTS.HIV_TESTS.TEST_STRATEGY.ANSWERS.MO.name + "^" + "99DCT";
break;
}
if (!StringUtils.isEmpty(answer)) {
String conceptQuestion = CONCEPTS.HIV_TESTS.TEST_STRATEGY.concept_id + "^"
+ CONCEPTS.HIV_TESTS.TEST_STRATEGY.name + "^" + "99DCT";
observationDetails.put(conceptQuestion, answer);
}
//Test Facility
String facility = hivTest.getFacility();
if (!StringUtils.isEmpty(facility)) {
String conceptQuestion = CONCEPTS.HIV_TESTS.TEST_FACILITY.concept_id + "^"
+ CONCEPTS.HIV_TESTS.TEST_FACILITY.name + "^" + "99DCT";
observationDetails.put(conceptQuestion, facility);
}
//Test Details
ProviderDetails providerDetails = hivTest.getProviderDetails();
if (providerDetails != null) {
String conceptQuestion = CONCEPTS.HIV_TESTS.PROVIDER_DETAILS.NAME.concept_id + "^"
+ CONCEPTS.HIV_TESTS.PROVIDER_DETAILS.NAME.name + "^" + "99DCT";
observationDetails.put(conceptQuestion, providerDetails.getName());
conceptQuestion = CONCEPTS.HIV_TESTS.PROVIDER_DETAILS.ID.concept_id + "^"
+ CONCEPTS.HIV_TESTS.PROVIDER_DETAILS.ID.name + "^" + "99DCT";
observationDetails.put(conceptQuestion, providerDetails.getId());
}
encounterJSON.put("patient", patientDetails);
encounterJSON.put("observation", observationDetails);
encounterJSON.put("encounter", encounterDetails);
return encounterJSON.toString();
} catch (Exception e){
throw new ShrParseException(e);
}
}
public static String createJsonEncounterPayloadFromImmunization(Immunization immunization, Patient patient) throws JSONException, ParseException{
JSONObject encounterJSON = new JSONObject();
JSONObject patientDetails = new JSONObject();
JSONObject observationDetails = new JSONObject();
JSONObject encounterDetails = new JSONObject();
Log.e("KenyaEmrShrMapper","Processing Immunization ");
encounterDetails.put("encounter.provider_id", "DEFAULT_SHR_USER");
encounterDetails.put("encounter.location_mfl_id", "DEFAULT_SHR_FACILITY");
Date encounterDateTime = DateUtils.parseDateByPattern(immunization.getDateAdministered(), "yyyyMMdd");
encounterDetails.put("encounter.encounter_datetime", DateUtils.getFormattedDate(encounterDateTime));
encounterDetails.put("encounter.form_uuid", StringUtils.defaultString(CONCEPTS.IMMUNIZATION.FORM.FORM_UUID));
encounterJSON.put("encounter",encounterDetails);
patientDetails.put("patient.medical_record_number", StringUtils.defaultString(patient.getIdentifier()));
patientDetails.put("patient.given_name", StringUtils.defaultString(patient.getGivenName()));
patientDetails.put("patient.middle_name", StringUtils.defaultString(patient.getMiddleName()));
patientDetails.put("patient.family_name", StringUtils.defaultString(patient.getFamilyName()));
patientDetails.put("patient.sex", StringUtils.defaultString(patient.getGender()));
patientDetails.put("patient.uuid", StringUtils.defaultString(patient.getUuid()));
if (patient.getBirthdate() != null) {
patientDetails.put("patient.birth_date", DateUtils.getFormattedDate(patient.getBirthdate()));
}
encounterJSON.put("patient",patientDetails);
JSONObject vaccineJson = new JSONObject();
String answer = null;
int sequence = -1;
String vaccine = immunization.getName();
switch (vaccine){
case CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.BCG.name:
answer = CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.BCG.concept_id + "^"
+ CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.BCG.name + "^" + "99DCT";
break;
case CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.IPV.name:
answer = CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.IPV.concept_id + "^"
+ CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.IPV.name + "^" + "99DCT";
sequence = CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.IPV.sequence;
break;
case CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.MEASLES6.name:
answer = CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.MEASLES6.concept_id + "^"
+ CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.MEASLES6.name + "^" + "99DCT";
sequence = CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.MEASLES6.sequence;
break;
case CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.MEASLES9.name:
answer = CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.MEASLES9.concept_id + "^"
+ CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.MEASLES9.name + "^" + "99DCT";
sequence = CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.MEASLES9.sequence;
break;
case CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.MEASLES18.name:
answer = CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.MEASLES18.concept_id + "^"
+ CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.MEASLES18.name + "^" + "99DCT";
sequence = CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.MEASLES18.sequence;
break;
case CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.OPV1.name:
answer = CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.OPV1.concept_id + "^"
+ CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.OPV1.name + "^" + "99DCT";
sequence = CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.OPV1.sequence;
break;
case CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.OPV2.name:
answer = CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.OPV2.concept_id + "^"
+ CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.OPV2.name + "^" + "99DCT";
sequence = CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.OPV2.sequence;
break;
case CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.OPV3.name:
answer = CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.OPV3.concept_id + "^"
+ CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.OPV3.name + "^" + "99DCT";
sequence = CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.OPV3.sequence;
break;
case CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.OPV_AT_BIRTH.name:
answer = CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.OPV_AT_BIRTH.concept_id + "^"
+ CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.OPV_AT_BIRTH.name + "^" + "99DCT";
sequence = CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.OPV_AT_BIRTH.sequence;
break;
case CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.PCV10_1.name:
answer = CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.PCV10_1.concept_id + "^"
+ CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.PCV10_1.name + "^" + "99DCT";
sequence = CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.PCV10_1.sequence;
break;
case CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.PCV10_2.name:
answer = CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.PCV10_2.concept_id + "^"
+ CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.PCV10_2.name + "^" + "99DCT";
sequence = CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.PCV10_2.sequence;
break;
case CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.PCV10_3.name:
answer = CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.PCV10_3.concept_id + "^"
+ CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.PCV10_3.name + "^" + "99DCT";
sequence = CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.PCV10_3.sequence;
break;
case CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.PENTA1.name:
answer = CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.PENTA1.concept_id + "^"
+ CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.PENTA1.name + "^" + "99DCT";
sequence = CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.PENTA1.sequence;
break;
case CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.PENTA2.name:
answer = CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.PENTA2.concept_id + "^"
+ CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.PENTA2.name + "^" + "99DCT";
sequence = CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.PENTA2.sequence;
break;
case CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.PENTA3.name:
answer = CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.PENTA3.concept_id + "^"
+ CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.PENTA3.name + "^" + "99DCT";
sequence = CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.PENTA3.sequence;
break;
case CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.ROTA1.name:
answer = CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.ROTA1.concept_id + "^"
+ CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.ROTA1.name + "^" + "99DCT";
sequence = CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.ROTA1.sequence;
break;
case CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.ROTA2.name:
answer = CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.ROTA2.concept_id + "^"
+ CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.ROTA2.name + "^" + "99DCT";
sequence = CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.ROTA2.sequence;
}
if(sequence != -1){
String conceptQuestion = CONCEPTS.IMMUNIZATION.VACCINE.concept_id + "^"
+ CONCEPTS.IMMUNIZATION.VACCINE.name + "^" + "99DCT";
vaccineJson.put(conceptQuestion, answer);
}
if(!StringUtils.isEmpty(answer)){
String conceptQuestion = CONCEPTS.IMMUNIZATION.VACCINE.concept_id + "^"
+ CONCEPTS.IMMUNIZATION.VACCINE.name + "^" + "99DCT";
vaccineJson.put(conceptQuestion, answer);
String groupConceptQuestion = CONCEPTS.IMMUNIZATION.GROUP.concept_id + "^"
+ CONCEPTS.IMMUNIZATION.GROUP.name + "^" + "99DCT";
observationDetails.put(groupConceptQuestion,vaccineJson);
encounterJSON.put("observation",observationDetails);
}
encounterJSON.put("patient",patientDetails);
encounterJSON.put("encounter",encounterDetails);
Log.e("KenyaEmrShrMapper","IMMUNIZATION PAYLOAD: "+encounterJSON.toString());
return encounterJSON.toString();
}
public static void updateSHRSmartCardRecordForPatient(MuzimaApplication application, String patientUuid) throws ShrParseException {
try {
ObservationController observationController = application.getObservationController();
SmartCardController smartCardController = application.getSmartCardController();
PatientController patientController = application.getPatientController();
SmartCardRecord smartCardRecord = smartCardController.getSmartCardRecordByPersonUuid(patientUuid);
Patient patient = patientController.getPatientByUuid(patientUuid);
if(patient == null){
throw new PatientController.PatientLoadException("Could not find patient with Uuid: "+patientUuid);
}
if(smartCardRecord == null ){
KenyaEmrShrModel shrModel = KenyaEmrShrMapper.createInitialSHRModelForPatient(application,patient);
String jsonShr = KenyaEmrShrMapper.createJsonFromSHRModel(shrModel);
smartCardRecord = new SmartCardRecord();
smartCardRecord.setPlainPayload(jsonShr);
smartCardRecord.setPersonUuid(patient.getUuid());
smartCardRecord.setUuid(UUID.randomUUID().toString());
smartCardController.updateSmartCardRecord(smartCardRecord);
} else {
Encounters encountersWithObservations = observationController.getEncountersWithObservations(patient.getUuid());
Encounters newEncountersWithObservations = new Encounters();
KenyaEmrShrModel shrModel = KenyaEmrShrMapper.createSHRModelFromJson(smartCardRecord.getPlainPayload());
Date latHivShrUpdateDateTime = null;
List<HIVTest> hivTests = shrModel.getHivTests();
for(HIVTest hivTest:hivTests){
if(hivTest.getDate() != null) {
Date date = DateUtils.parseDateByPattern(hivTest.getDate(), "yyyyMMdd");
if (latHivShrUpdateDateTime == null) {
latHivShrUpdateDateTime = date;
} else if (latHivShrUpdateDateTime.before(date)) {
latHivShrUpdateDateTime = date;
}
}
}
for (EncounterWithObservations encounter:encountersWithObservations){
Date encounterDateTime = encounter.getEncounter().getEncounterDatetime();
if(latHivShrUpdateDateTime == null){
newEncountersWithObservations.add(encounter);
} else if(latHivShrUpdateDateTime.before(encounterDateTime)){
newEncountersWithObservations.add(encounter);
}
}
shrModel = KenyaEmrShrMapper.addEncounterObservationsToShrModel(shrModel, newEncountersWithObservations);
String jsonShr = KenyaEmrShrMapper.createJsonFromSHRModel(shrModel);
smartCardRecord.setPlainPayload(jsonShr);
smartCardController.updateSmartCardRecord(smartCardRecord);
}
} catch (Throwable e) {
Log.e(TAG, "Cannot add encounters to patient SHR ",e);
throw new ShrParseException(e);
}
}
/**
* Creates a new SHR Model for a given Patient. Iterates through patient demographics, identifiers, addresses and
* attributes to construct this model
* @param patient the Patient Object for which to create new SHR
* @return KenyaEmrShrModel representation of newlyCreatedSHR
* @throws IOException
*/
public static KenyaEmrShrModel createInitialSHRModelForPatient(MuzimaApplication application, Patient patient) throws ShrParseException{
KenyaEmrShrModel shrModel = new KenyaEmrShrModel();
PatientIdentification identification = new PatientIdentification();
PatientName patientName = new PatientName();
patientName.setFirstName(patient.getFamilyName());
patientName.setLastName(patient.getGivenName());
patientName.setMiddleName(patient.getMiddleName());
identification.setPatientName(patientName);
String dateOfBirth = DateUtils.getFormattedDate(patient.getBirthdate(),"yyyyMMdd");
identification.setDateOfBirth(dateOfBirth);
String dateObBirthPrecision = "EXACT";
if(patient.getBirthdateEstimated()){
dateObBirthPrecision = "ESTIMATED";
}
identification.setDateOfBirthPrecision(dateObBirthPrecision);
PersonAddress kenyaEmrPersonAddress = null;
try{
kenyaEmrPersonAddress = patient.getPreferredAddress();
} catch(NullPointerException e){
Log.e(TAG,"Could not get preferred Address");
}
if(kenyaEmrPersonAddress == null){
List<PersonAddress> kenyaEmrPersonAddresses = patient.getAddresses();
if(kenyaEmrPersonAddresses.size() > 0){
kenyaEmrPersonAddress = kenyaEmrPersonAddresses.get(0);
}
}
if(kenyaEmrPersonAddress != null){
PatientAddress shrAddress = identification.getPatientAddress();
if(shrAddress == null){
shrAddress = new PatientAddress();
}
PhysicalAddress physicalAddress = shrAddress.getPhysicalAddress();
if(physicalAddress == null){
physicalAddress = new PhysicalAddress();
}
physicalAddress.setCounty(kenyaEmrPersonAddress.getCountry());
physicalAddress.setSubcounty(kenyaEmrPersonAddress.getCountyDistrict());
physicalAddress.setWard(kenyaEmrPersonAddress.getAddress4());
physicalAddress.setNearestLandmark(kenyaEmrPersonAddress.getAddress2());
physicalAddress.setVillage(kenyaEmrPersonAddress.getCityVillage());
shrAddress.setPostalAddress(kenyaEmrPersonAddress.getAddress1());
identification.setPatientAddress(shrAddress);
}
shrModel.setPatientIdentification(identification);
shrModel = putIdentifiersIntoShrModel(shrModel,patient.getIdentifiers());
EncounterController encounterController = application.getEncounterController();
ObservationController observationController = application.getObservationController();
try {
List<Encounter> encounters = encounterController.getEncountersByEncounterTypeUuidAndPatientUuid(
CONCEPTS.HIV_TESTS.ENCOUNTER.ENCOUNTER_TYPE_UUID, patient.getUuid());
Encounters encountersWithObservations = new Encounters();
for(Encounter encounter:encounters) {
Encounters encounterObs = observationController.getObservationsByEncounterUuid(encounter.getUuid());
if(!encounters.isEmpty()){
encountersWithObservations.addAll(encounterObs);
}
}
if(!encountersWithObservations.isEmpty()){
shrModel = addEncounterObservationsToShrModel(shrModel,encountersWithObservations);
}
} catch (EncounterController.DownloadEncounterException e) {
Log.e(TAG,"Could not obtain encounterType");
} catch (ObservationController.LoadObservationException e) {
Log.e(TAG,"Could not obtain Observations");
}
return shrModel;
}
/**
* Adds Observations to an SHR model
* @param shrModel
* @param encountersWithObservations
* @return
* @throws IOException
*/
public static KenyaEmrShrModel addEncounterObservationsToShrModel(KenyaEmrShrModel shrModel, Encounters encountersWithObservations ) throws ShrParseException{
List<HIVTest> hivTests = shrModel.getHivTests() == null ? new ArrayList<HIVTest>() : shrModel.getHivTests();
List<Immunization> immunizations = shrModel.getImmunizations() == null ? new ArrayList<Immunization>() : shrModel.getImmunizations();
for(EncounterWithObservations encounterWithObservations: encountersWithObservations){
Encounter encounter = encounterWithObservations.getEncounter();
//if(encounter.getEncounterType().getUuid().equalsIgnoreCase(CONCEPTS.HIV_TESTS.ENCOUNTER.ENCOUNTER_TYPE_UUID)){
HIVTest hivTest = getHivTestFromEncounter(encounterWithObservations);
if(hivTest != null){
hivTests.add(hivTest);
} else {
//} else if(encounter.getEncounterType().getUuid().equalsIgnoreCase(CONCEPTS.IMMUNIZATION.ENCOUNTER.ENCOUNTER_TYPE_UUID)){
Immunization immunization = getImmunizationFromEncounter(encounterWithObservations);
if (immunization != null) {
immunizations.add(immunization);
}
}
}
shrModel.setHivTests(hivTests);
shrModel.setImmunizations(immunizations);
return shrModel;
}
public static HIVTest getHivTestFromEncounter(EncounterWithObservations encounterWithObservations) throws ShrParseException {
List<Observation> observations = encounterWithObservations.getObservations();
HIVTest hivTest = new HIVTest();
ProviderDetails providerDetails = null;
boolean isHivEncounter = false;
for(Observation observation:observations){
Concept answerConcept = null;
String shrAnswer = null;
switch(observation.getConcept().getId()){
case CONCEPTS.HIV_TESTS.TEST_RESULT.concept_id:
isHivEncounter = true;
answerConcept = observation.getValueCoded();
if(answerConcept!= null) {
switch (answerConcept.getId()) {
case CONCEPTS.HIV_TESTS.TEST_RESULT.ANSWERS.POSITIVE.concept_id:
shrAnswer = CONCEPTS.HIV_TESTS.TEST_RESULT.ANSWERS.POSITIVE.name;
break;
case CONCEPTS.HIV_TESTS.TEST_RESULT.ANSWERS.NEGATIVE.concept_id:
shrAnswer = CONCEPTS.HIV_TESTS.TEST_RESULT.ANSWERS.NEGATIVE.name;
break;
case CONCEPTS.HIV_TESTS.TEST_RESULT.ANSWERS.INCONCLUSIVE.concept_id:
shrAnswer = CONCEPTS.HIV_TESTS.TEST_RESULT.ANSWERS.INCONCLUSIVE.name;
break;
}
if(!StringUtils.isEmpty(shrAnswer)){
hivTest.setResult(shrAnswer);
}
}
break;
case CONCEPTS.HIV_TESTS.TEST_TYPE.concept_id:
isHivEncounter = true;
answerConcept = observation.getValueCoded();
if(answerConcept!= null) {
switch (answerConcept.getId()) {
case CONCEPTS.HIV_TESTS.TEST_TYPE.ANSWERS.CONFIRMATORY.concept_id:
shrAnswer = CONCEPTS.HIV_TESTS.TEST_TYPE.ANSWERS.CONFIRMATORY.name;
break;
case CONCEPTS.HIV_TESTS.TEST_TYPE.ANSWERS.SCREENING.concept_id:
shrAnswer = CONCEPTS.HIV_TESTS.TEST_TYPE.ANSWERS.SCREENING.name;
break;
}
if(!StringUtils.isEmpty(shrAnswer)){
hivTest.setType(shrAnswer);
}
}
break;
case CONCEPTS.HIV_TESTS.TEST_STRATEGY.concept_id:
isHivEncounter = true;
answerConcept = observation.getValueCoded();
if(answerConcept!= null) {
switch (answerConcept.getId()) {
case CONCEPTS.HIV_TESTS.TEST_STRATEGY.ANSWERS.NP.concept_id:
shrAnswer = CONCEPTS.HIV_TESTS.TEST_STRATEGY.ANSWERS.NP.name;
break;
case CONCEPTS.HIV_TESTS.TEST_STRATEGY.ANSWERS.HB.concept_id:
shrAnswer = CONCEPTS.HIV_TESTS.TEST_STRATEGY.ANSWERS.HB.name;
break;
case CONCEPTS.HIV_TESTS.TEST_STRATEGY.ANSWERS.HP.concept_id:
shrAnswer = CONCEPTS.HIV_TESTS.TEST_STRATEGY.ANSWERS.HB.name;
break;
case CONCEPTS.HIV_TESTS.TEST_STRATEGY.ANSWERS.MO.concept_id:
shrAnswer = CONCEPTS.HIV_TESTS.TEST_STRATEGY.ANSWERS.MO.name;
break;
case CONCEPTS.HIV_TESTS.TEST_STRATEGY.ANSWERS.VI.concept_id:
shrAnswer = CONCEPTS.HIV_TESTS.TEST_STRATEGY.ANSWERS.VI.name;
break;
case CONCEPTS.HIV_TESTS.TEST_STRATEGY.ANSWERS.VS.concept_id:
shrAnswer = CONCEPTS.HIV_TESTS.TEST_STRATEGY.ANSWERS.VS.name;
break;
}
if(!StringUtils.isEmpty(shrAnswer)){
hivTest.setStrategy(shrAnswer);
}
}
break;
case CONCEPTS.HIV_TESTS.TEST_FACILITY.concept_id:
hivTest.setFacility(observation.getValueAsString());
break;
case CONCEPTS.HIV_TESTS.PROVIDER_DETAILS.ID.concept_id:
if(providerDetails == null){
providerDetails = new ProviderDetails();
}
providerDetails.setId(observation.getValueAsString());
break;
case CONCEPTS.HIV_TESTS.PROVIDER_DETAILS.NAME.concept_id:
if(providerDetails == null){
providerDetails = new ProviderDetails();
}
providerDetails.setName(observation.getValueAsString());
break;
}
}
if(isHivEncounter == false){
return null;
}
if(hivTest.getFacility() == null){
Location location = encounterWithObservations.getEncounter().getLocation();
String facility = "10829";//LocationUtils.getKenyaEmrMasterFacilityListCode(location);
if(!StringUtils.isEmpty(facility)) {
hivTest.setFacility(facility);
} else {
throw new ShrParseException("Cannot get Facility MFL code from encounter location");
}
}
if(providerDetails == null){
providerDetails = new ProviderDetails();
Person provider = encounterWithObservations.getEncounter().getProvider();
if(provider != null){
providerDetails.setId(provider.getMiddleName());
providerDetails.setName(provider.getDisplayName());
}
}
if(providerDetails != null){
hivTest.setProviderDetails(providerDetails);
}
Date encounterDate = encounterWithObservations.getEncounter().getEncounterDatetime();
if(encounterDate != null) {
String date = DateUtils.getFormattedDate(encounterDate, "yyyyMMdd");
hivTest.setDate(date);
} else {
throw new ShrParseException("Cannot get encounter date from encounter");
}
//Add date
String date = DateUtils.getFormattedDate(encounterWithObservations.getEncounter().getEncounterDatetime(),"yyyyMMdd");
hivTest.setDate(date);
return hivTest;
}
public static Immunization getImmunizationFromEncounter(EncounterWithObservations encounterWithObservations){
List<Observation> observations = encounterWithObservations.getObservations();
Immunization immunization = new Immunization();
boolean isImmunizationEncounter = false;
for(Observation observation:observations){
String answer = null;
Concept concept = observation.getConcept();
Concept valueCoded = observation.getValueCoded();
if(concept.getId() == CONCEPTS.IMMUNIZATION.VACCINE.concept_id && valueCoded!= null) {
isImmunizationEncounter = true;
switch (valueCoded.getId()) {
case CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.BCG.concept_id:
answer = CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.BCG.name;
break;
case CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.IPV.concept_id:
answer = CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.IPV.name;
break;
case CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.MEASLES6.concept_id:
answer = CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.MEASLES6.name;
break;
case CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.MEASLES9.concept_id:
answer = valueCoded.getName();
break;
case CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.OPV2.concept_id:
answer = CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.IPV.name;
break;
case CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.PCV10_1.concept_id:
answer = valueCoded.getName();
break;
case CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.PENTA1.concept_id:
answer = valueCoded.getName();
break;
case CONCEPTS.IMMUNIZATION.VACCINE.ANSWERS.ROTA1.concept_id:
answer = valueCoded.getName();
}
if(!StringUtils.isEmpty(answer)){
immunization.setName(answer);
Date obsDateTime = observation.getObservationDatetime();
String dateAdministered = DateUtils.getFormattedDate(obsDateTime, "yyyyMMdd");
immunization.setDateAdministered(dateAdministered);
break;
}
}
}
if(isImmunizationEncounter == false){
return null;
}
return immunization;
}
public static class ShrParseException extends Throwable {
ShrParseException(Throwable throwable) {
super(throwable);
}
ShrParseException(String message) {
super(message);
}
ShrParseException(String message, Throwable e) {
super(message,e);
}
}
}
|
package com.pa.devbox.ui.viewModel;
import android.Manifest;
import android.annotation.TargetApi;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.databinding.BaseObservable;
import android.databinding.Bindable;
import android.net.Uri;
import android.util.Log;
import android.view.View;
import com.pa.devbox.BR;
import com.pa.devbox.R;
import com.pa.devbox.domain.delegate.FileDownloadCallback;
import com.pa.devbox.domain.delegate.LastCommitInfoCallback;
import com.pa.devbox.domain.entity.Library;
import com.pa.devbox.ui.aty.LibDetailActivity;
import com.pa.devbox.ui.modle.LibDetailModel;
import com.pa.devbox.util.FileUtils;
import com.pa.devbox.util.PluginManager;
import java.io.File;
public class LibDetailAtyModel extends BaseObservable implements FileDownloadCallback, LibDetailActivity.PermissionRequestCallback, LastCommitInfoCallback {
public static final String SELECTEDITEM = "selectedItem";
private LibDetailActivity context;
@Bindable
Library library;
@Bindable
int circularProgress;
@Bindable
String lastCommitDate;
@Bindable
String lastCommitMsg;
@Bindable
boolean indeterminateProgressMode;
@Bindable
String btnText;
private String savePath;
private final int REQUEST_CODE_ASK_STORAGE_PERMISSIONS = 123;
private LibDetailModel libDetailModel;
public LibDetailAtyModel(LibDetailActivity context) {
this.context = context;
this.context.setPermissionRequestCallback(this);
this.setCircularProgress(0);
}
public void parseArguments(Intent intent) {
if (intent != null)
library = (Library) intent.getSerializableExtra(SELECTEDITEM);
this.setBtnText(getApkSizeStr());
savePath = FileUtils.getSdCardPath()
+ "DevBox" + File.separator
+ library.getName() + ".apk";
if (new File(savePath).exists())
this.setCircularProgress(100);
this.libDetailModel = new LibDetailModel(library);
this.libDetailModel.setFileDownloadCallback(this);
this.libDetailModel.setLastCommitInfoCallback(this);
}
public void githubAddressOnClick(View view) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(this.library.getGithubAddress()));
context.startActivity(browserIntent);
}
@TargetApi(23)
public void circularBtnOnClick(View view) {
if (android.os.Build.VERSION.SDK_INT >= 23) { // Do something for M and above versions } else{ // do something for phones running an SDK before froyo }
int hasWriteContactsPermission = context.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (hasWriteContactsPermission != PackageManager.PERMISSION_GRANTED) {
context.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_CODE_ASK_STORAGE_PERMISSIONS);
return;
}
}
File apkFile = new File(savePath);
if (!apkFile.exists()) {
download();
} else {
new PluginManager(context).openApk(apkFile);
}
}
private void download() {
libDetailModel.download(library.getApk().getUrl(), savePath);
this.setIndeterminateProgressMode(true);
}
@Override
public void onSuccess(File file) {
PluginManager pm = new PluginManager(context);
pm.installApk(file);
}
@Override
public void onFailure(Throwable t) {
Log.e("-->", "onFailure");
}
@Override
public void onProgress(long bytesRead, long contentLength, boolean done) {
int percentage = (int) (1.0f * bytesRead / contentLength * 100);
if (done)
this.setCircularProgress(100);
else
this.setCircularProgress(percentage);
}
public String getApkSizeStr() {
double size = this.library.getApk().getMetaData().getSize() / 1000.0 / 1000.0;
double sizeFinal = Math.round(size * 100) / 100.0;
return context.getString(R.string.download) + sizeFinal + "MB)";
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_ASK_STORAGE_PERMISSIONS:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
download();
// else
// default:
}
}
@Override
public void onCompleted() {
}
@Override
public void onError() {
}
@Override
public void onSuccess(String name, String msg) {
this.setLastCommitDate(name);
this.setLastCommitMsg(msg);
}
public boolean isIndeterminateProgressMode() {
return indeterminateProgressMode;
}
public void setIndeterminateProgressMode(boolean indeterminateProgressMode) {
this.indeterminateProgressMode = indeterminateProgressMode;
notifyPropertyChanged(BR.swipeRefreshLayoutStatus);
}
public void setBtnText(String btnText) {
this.btnText = btnText;
notifyPropertyChanged(BR.btnText);
}
public String getBtnText() {
return btnText;
}
public void setLibrary(Library library) {
this.library = library;
notifyPropertyChanged(BR.library);
}
public void setLastCommitDate(String lastCommitDate) {
this.lastCommitDate = lastCommitDate;
notifyPropertyChanged(BR.lastCommitDate);
}
public void setLastCommitMsg(String lastCommitMsg) {
this.lastCommitMsg = lastCommitMsg;
notifyPropertyChanged(BR.lastCommitMsg);
}
public int getCircularProgress() {
return circularProgress;
}
public void setCircularProgress(int circularProgress) {
this.circularProgress = circularProgress;
notifyPropertyChanged(BR.circularProgress);
}
public String getLastCommitMsg() {
return lastCommitMsg;
}
public String getDescription() {
return library.getEnDescription();
}
public String getTitle() {
return library.getName();
}
public String getMinSdkVersion() {
return library.getMinSdkVersion();
}
public String getGithubAddress() {
return library.getGithubAddress();
}
public String getAuthor() {
return library.getAuthor();
}
public String getLicense() {
return library.getLicense();
}
public String getLastCommitDate() {
return lastCommitDate;
}
}
|
package com.pr0gramm.app.services;
import android.net.Uri;
import android.util.Log;
import com.google.common.base.Charsets;
import com.google.common.collect.Iterables;
import com.google.common.hash.Hashing;
import com.google.common.io.BaseEncoding;
import com.google.common.io.ByteStreams;
import com.google.common.primitives.Ints;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import static com.google.common.base.MoreObjects.firstNonNull;
import static java.lang.System.currentTimeMillis;
@Singleton
public class SimpleProxyService extends NanoHttpServer {
private final String nonce;
private final OkHttpClient okHttpClient;
@Inject
public SimpleProxyService(OkHttpClient okHttpClient) {
super(getRandomPort());
this.okHttpClient = okHttpClient;
this.nonce = Hashing.md5().hashLong(currentTimeMillis()).toString();
Log.i("Proxy", "Open simple proxy on port " + getMyPort());
}
/**
* Tries to get a random free port.
*
* @return A random free port number
*/
private static int getRandomPort() {
return (int) (20000 + (Math.random() * 40000));
}
public String getProxyUrl(String url) {
String encoded = BaseEncoding.base64Url().encode(url.getBytes(Charsets.UTF_8));
return new Uri.Builder()
.scheme("http")
.encodedAuthority("127.0.0.1:" + getMyPort())
.appendPath(nonce)
.appendPath(encoded)
.toString();
}
@Override
public Response serve(IHTTPSession session) {
Uri uri = Uri.parse(session.getUri());
if(!nonce.equals(Iterables.getFirst(uri.getPathSegments(), null)))
return new Response(Response.Status.FORBIDDEN, "text/plain", "");
String encodedUrl = uri.getLastPathSegment();
Log.i("Proxy", "Request " + encodedUrl);
String url = new String(
BaseEncoding.base64Url().decode(encodedUrl),
Charsets.UTF_8).trim();
try {
Request request = buildRequest(url, session);
com.squareup.okhttp.Response response = okHttpClient.newCall(request).execute();
Response.IStatus status = translateStatus(response.code(), response.message());
String contentType = response.header("Content-Type", "application/octet-stream");
InputStream stream;
final Integer length = Ints.tryParse(response.header("Content-Length", ""));
if (length != null && length > 0) {
stream = new FilterInputStream(response.body().byteStream()) {
// int read = 0;
// @Override
// public int read(byte[] buffer, int byteOffset, int byteCount) throws IOException {
// int result = super.read(buffer, byteOffset, byteCount);
// if(read / 100_000 != (read + result) / 100_000) {
// Log.i("Proxy", format("Approx %1d%% loaded", 100 * read / length));
// read += result;
// return result;
@Override
public int available() throws IOException {
// fake a large value here, so ByteStreams.limit can fix it :/
return Integer.MAX_VALUE;
}
};
stream = ByteStreams.limit(stream, length.longValue());
} else {
stream = response.body().byteStream();
}
Response result = new Response(status, contentType, stream);
result.addHeader("Accept-Range", "bytes");
result.addHeader("Connection", "close");
result.setChunkedTransfer(length == null);
// forward content range header
String contentRange = response.header("Content-Range");
if(contentRange != null)
result.addHeader("Content-Range", contentRange);
return result;
} catch (IOException e) {
Log.e("Proxy", "Could not proxy for url " + url, e);
return new Response(Response.Status.INTERNAL_ERROR, "text/plain", e.toString());
}
}
private static Request buildRequest(String url, IHTTPSession session) {
Request.Builder req = new Request.Builder().url(url);
// forward the range header
String range = session.getHeaders().get("range");
if(range != null)
req = req.addHeader("Range", range);
return req.build();
}
private static Response.IStatus translateStatus(int code, String description) {
return new Response.IStatus() {
@Override
public int getRequestStatus() {
return code;
}
@Override
public String getDescription() {
return code + " " + firstNonNull(description, "unknown");
}
};
}
}
|
package de.melvil.stacksrs.view;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.media.AudioManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import cz.msebera.android.httpclient.Header;
import de.melvil.stacksrs.adapter.DownloadableDeckInfoAdapter;
import de.melvil.stacksrs.model.Card;
import de.melvil.stacksrs.model.Deck;
import de.melvil.stacksrs.model.DeckCollection;
import de.melvil.stacksrs.model.DownloadableDeckInfo;
/**
* This activity connects to the deck server and presents all downloadable decks along with
* descriptions. The user can download a deck by clicking on it.
*/
public class DeckDownloadActivity extends AppCompatActivity {
private final String SERVER_URL = "https://stacksrs.droppages.com/";
private DownloadableDeckInfoAdapter deckListAdapter;
private List<DownloadableDeckInfo> deckNames = new ArrayList<>();
private ProgressBar circle;
private AsyncHttpClient httpClient = new AsyncHttpClient();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_deck_download);
setTitle(getString(R.string.download_deck));
ListView deckListView = (ListView) findViewById(R.id.deck_list);
deckListAdapter = new DownloadableDeckInfoAdapter(this, deckNames);
deckListView.setAdapter(deckListAdapter);
deckListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final DownloadableDeckInfo deckInfo = deckNames.get(position);
// check if there already is a deck with the same name
DeckCollection deckCollection = new DeckCollection();
try {
deckCollection.reload(DeckCollection.stackSRSDir);
} catch(IOException e){
e.printStackTrace();
}
if(deckCollection.deckWithNameExists(deckInfo.getName())){
Toast.makeText(getApplicationContext(),
getString(R.string.deck_exists_please_rename, deckInfo.getName()),
Toast.LENGTH_SHORT).show();
return;
}
// show download dialog
AlertDialog.Builder builder = new AlertDialog.Builder(DeckDownloadActivity.this);
builder.setTitle(getString(R.string.download_deck));
builder.setMessage(getString(R.string.really_download_deck, deckInfo.getName()));
builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.setPositiveButton(getString(R.string.download_deck), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
downloadDeck(deckInfo.getFile(), 2);
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
circle = (ProgressBar) findViewById(R.id.circle);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
}
@Override
protected void onResume() {
super.onResume();
circle.setVisibility(View.VISIBLE);
reloadDeckList();
}
public void reloadDeckList() {
httpClient.get(SERVER_URL + "decks.txt", null, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
deckNames.clear();
try {
JSONArray deckListArray = response.getJSONArray("decks");
for (int i = 0; i < deckListArray.length(); ++i) {
DownloadableDeckInfo deckInfo = new DownloadableDeckInfo(
deckListArray.getJSONObject(i));
deckNames.add(deckInfo);
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(),
getString(R.string.could_not_load_deck_list_from_server),
Toast.LENGTH_SHORT).show();
}
deckListAdapter.notifyDataSetChanged();
circle.setVisibility(View.INVISIBLE);
}
@Override
public void onFailure(int statusCode, Header[] headers, String responseString,
Throwable throwable) {
Toast.makeText(getApplicationContext(),
getString(R.string.could_not_connect_to_server),
Toast.LENGTH_SHORT).show();
}
});
}
public void downloadDeck(final String file, final int level) {
httpClient.get(SERVER_URL + file + ".txt", null, new JsonHttpResponseHandler(){
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
try {
String deckName = response.getString("name");
Deck newDeck = new Deck(deckName, response.getString("back"));
JSONArray cardArray = response.getJSONArray("cards");
List<Card> cards = new ArrayList<>();
for(int i = 0; i < cardArray.length(); ++i) {
JSONObject cardObject = cardArray.getJSONObject(i);
Card c = new Card(cardObject.getString("front"),
cardObject.getString("back"), level);
cards.add(c);
}
newDeck.fillWithCards(cards);
Toast.makeText(getApplicationContext(),
getString(R.string.downloaded_deck, deckName),
Toast.LENGTH_SHORT).show();
} catch(JSONException e) {
Toast.makeText(getApplicationContext(), getString(R.string.could_not_load_deck),
Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(int statusCode, Header[] headers, String responseString,
Throwable throwable) {
Toast.makeText(getApplicationContext(), getString(R.string.downloading_deck_failed),
Toast.LENGTH_SHORT).show();
}
});
}
}
|
package acceptance;
import com.tagmycode.plugin.Framework;
import com.tagmycode.plugin.StorageEngine;
import com.tagmycode.plugin.gui.form.LoginDialog;
import org.junit.Test;
import support.AbstractTestBase;
import javax.swing.*;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
public class FrameworkAcceptanceTest extends AbstractTestBase {
@Test
public void notAuthenticatedUserShouldSeeAuthorizationDialog() throws Exception {
Framework frameworkSpy = createSpyFramework();
frameworkSpy.canOperate();
assertFalse(frameworkSpy.isInitialized());
verify(frameworkSpy, times(1)).showLoginDialog();
}
@Test
public void afterLoginInitializeIsCalled() throws Exception {
Framework framework = createFramework(createStorageEngineWithData());
Framework frameworkSpy = spy(framework);
final LoginDialog loginDialog = frameworkSpy.showLoginDialog();
String verificationCode = "verification-code";
loginDialog.getVerificationCodeTextField().setText(verificationCode);
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
loginDialog.getButtonOk().doClick();
}
});
Thread.sleep(200);
verify(frameworkSpy, times(1)).initialize(verificationCode);
}
@Test
public void afterLogoutLSetLastSnippetsUpdateIsCleared() throws Exception {
Framework framework = createFramework(createStorageEngineWithData());
framework.start();
mockTagMyCodeReturningValidAccountData(framework);
Framework frameworkSpy = spy(framework);
assertTrue(frameworkSpy.isInitialized());
assertDataIsValid(framework.getData());
framework.logout();
assertDataIsCleared(framework.getData());
}
@Test
public void selectASnippetAndSeeDetailsOnRightPanel() throws Exception {
Framework framework = createFramework(createStorageEngineWithData());
mockTagMyCodeReturningValidAccountData(framework);
framework.getData().setAccount(resourceGenerate.aUser());
framework.getData().setSnippets(resourceGenerate.aSnippetCollection());
framework.getData().saveAll();
framework.start();
JFrame jFrame = new JFrame();
jFrame.add(framework.getMainWindow().getMainComponent());
jFrame.pack();
JPanel snippetViewFormPane = framework.getMainWindow().getSnippetsTab().getSnippetViewFormPane();
assertEquals("welcome view", snippetViewFormPane.getComponent(0).getName());
framework.getMainWindow().getSnippetsTab().getSnippetsTable().getSnippetsComponent().setRowSelectionInterval(1, 1);
assertEquals("snippet view", snippetViewFormPane.getComponent(0).getName());
}
@Test
public void networkingEnabledAfterRestart() throws Exception {
StorageEngine storage = createStorageEngineWithData();
storage.saveNetworkingEnabledFlag(true);
Framework framework = createFramework(storage);
mockTagMyCodeReturningValidAccountData(framework);
framework.start();
assertTrue(framework.getData().isNetworkingEnabled());
assertTrue(framework.getMainWindow().getSnippetsTab().getButtonNetworking().getIcon().toString().contains("/icons/connected.png"));
}
@Test
public void networkingDisabledAfterRestart() throws Exception {
Framework framework = acceptanceFramework();
framework.start();
Thread.sleep(300);
assertFalse(framework.getData().isNetworkingEnabled());
assertTrue(framework.getMainWindow().getSnippetsTab().getButtonNetworking().getIcon().toString().contains("/icons/disconnected.png"));
}
private Framework acceptanceFramework() throws Exception {
StorageEngine storage = createStorageEngineWithData();
storage.saveNetworkingEnabledFlag(false);
Framework framework = createFramework(storage);
mockTagMyCodeReturningValidAccountData(framework);
return framework;
}
}
|
package com.github.ykrapiva.eventmap;
import android.animation.ValueAnimator;
import android.content.Context;
import android.opengl.GLSurfaceView;
import android.os.Build;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.widget.Scroller;
import com.github.ykrapiva.eventmap.gl.MatrixTrackingGL;
import javax.microedition.khronos.opengles.GL;
import java.util.concurrent.CountDownLatch;
public class EventMapView<T extends EventMapSeat> extends GLSurfaceView {
private static final String TAG = EventMapView.class.getSimpleName();
private static final float FLING_VELOCITY_DOWNSCALE = 1.0f;
private EventMapRenderer<T> mRenderer;
private GestureDetector mGestureDetector;
private ScaleGestureDetector mScaleDetector;
private Scroller mScroller;
private ValueAnimator mScrollAnimator;
private EventMap<T> mEventMap;
private EventMapClickListener<T> mClickListener;
public EventMapView(Context context) {
super(context);
init();
}
public EventMapView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
mGestureDetector = new GestureDetector(getContext(), new GestureListener());
mScaleDetector = new ScaleGestureDetector(getContext(), new ScaleListener());
mRenderer = new EventMapRenderer<T>();
setRenderer(mRenderer);
setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
setGLWrapper(new GLSurfaceView.GLWrapper() {
public GL wrap(GL gl) {
return new MatrixTrackingGL(gl);
}
});
// Create a Scroller to handle the fling gesture.
if (Build.VERSION.SDK_INT < 11) {
mScroller = new Scroller(getContext());
} else {
mScroller = new Scroller(getContext(), null, true);
}
// The scroller doesn't have any built-in animation functions--it just supplies
// values when we ask it to. So we have to have a way to call it every frame
// until the fling ends. This code (ab)uses a ValueAnimator object to generate
// a callback on every animation frame. We don't use the animated value at all.
if (Build.VERSION.SDK_INT >= 11) {
mScrollAnimator = ValueAnimator.ofFloat(0, 1);
mScrollAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
public void onAnimationUpdate(ValueAnimator valueAnimator) {
tickScrollAnimation();
}
});
}
}
public void setBackgroundColor(int color) {
mRenderer.setClearColor(color);
}
public void setClickListener(EventMapClickListener<T> mClickListener) {
this.mClickListener = mClickListener;
}
public void updateSeatColor(T seat) {
if (mEventMap != null) {
mEventMap.updateColor(seat);
requestRender();
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
boolean scaleResult = mScaleDetector.onTouchEvent(event);
boolean result = mGestureDetector.onTouchEvent(event);
// If the GestureDetector doesn't want this event, do some custom processing.
// This code just tries to detect when the user is done scrolling by looking
// for ACTION_UP events.
if (!result) {
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
// User is done scrolling, it's now safe to do things like autocenter
stopScrolling();
break;
}
}
return scaleResult | result;
}
private void onSeatClicked(T seat) {
if (mClickListener != null) {
mClickListener.onSeatClicked(seat);
}
}
public void setEventMap(EventMap<T> eventMap) {
mEventMap = eventMap;
mRenderer.setEventMap(mEventMap);
requestRender();
}
public EventMap<T> getEventMap() {
return mEventMap;
}
public float getScaleFactor() {
return mRenderer.getScaleFactor();
}
private void tickScrollAnimation() {
if (!mScroller.isFinished()) {
mScroller.computeScrollOffset();
int currX = mScroller.getCurrX();
int currY = mScroller.getCurrY();
mRenderer.setOffset(currX, currY);
} else {
if (Build.VERSION.SDK_INT >= 11) {
mScrollAnimator.cancel();
}
onScrollFinished();
}
requestRender();
}
/**
* Force a stop to all pie motion. Called when the user taps during a fling.
*/
private void stopScrolling() {
mScroller.forceFinished(true);
onScrollFinished();
}
private void onScrollFinished() {
// nothing for now
}
private boolean isAnimationRunning() {
return !mScroller.isFinished();
}
private class GestureListener extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, final float distanceX, final float distanceY) {
float offsetX = mRenderer.getOffsetX();
float offsetY = mRenderer.getOffsetY();
float scaleFactor = mRenderer.getScaleFactor();
offsetX = offsetX - distanceX * scaleFactor;
offsetY = offsetY + distanceY * scaleFactor;
//Log.v(TAG, "onScroll(), new offset: [" + offsetX + "," + offsetY + "]");
mRenderer.setOffset(offsetX, offsetY);
requestRender();
return true;
}
@Override
public boolean onSingleTapUp(final MotionEvent e) {
final CountDownLatch clickResultReadyLatch = new CountDownLatch(1);
int[] location = new int[2];
getLocationOnScreen(location);
float rawX = e.getRawX();
float rawY = e.getRawY();
final float x = rawX - location[0];
final float y = rawY - location[1];
queueEvent(new Runnable() {
@Override
public void run() {
mRenderer.onClick(x, y, clickResultReadyLatch);
}
});
requestRender();
try {
clickResultReadyLatch.await();
T seat = mRenderer.getClickedObject();
if (seat != null) {
onSeatClicked(seat);
}
} catch (InterruptedException e1) {
// ignore
}
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
float offsetX = mRenderer.getOffsetX();
float offsetY = mRenderer.getOffsetY();
//Log.v(TAG, "onFling(), from offset: [" + offsetX + "," + offsetY + "]");
mScroller.fling(
(int) offsetX, (int) offsetY,
(int) (velocityX / FLING_VELOCITY_DOWNSCALE), (int) (-velocityY / FLING_VELOCITY_DOWNSCALE),
Integer.MIN_VALUE, Integer.MAX_VALUE, Integer.MIN_VALUE, Integer.MAX_VALUE);
// mScroller.setFriction(1.0f);
// Start the animator and tell it to animate for the expected duration of the fling.
if (Build.VERSION.SDK_INT >= 11) {
mScrollAnimator.setDuration(mScroller.getDuration());
mScrollAnimator.start();
}
return true;
}
@Override
public boolean onDown(MotionEvent e) {
if (isAnimationRunning()) {
stopScrolling();
}
return true;
}
}
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
@Override
public boolean onScale(final ScaleGestureDetector detector) {
final float scaleFactor = detector.getScaleFactor();
mRenderer.onScale(scaleFactor);
requestRender();
return true;
}
}
public interface EventMapClickListener<T> {
void onSeatClicked(T seat);
}
}
|
import java.util.List;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Collections;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
public class WordTarget {
private static int MIN_LENGTH = 4;
private static int count = 0;
private static List<String> dict;
private static List<String> possArr;
public static void main(String[] args) {
if( args.length < 3 ) {
System.err.println(
"Usage: java Wordsquare <puzzle> <dictionary> <strFile>");
System.exit(1);
} else if( args.length == 4 ) {
MIN_LENGTH = Integer.parseInt(args[3]);
}
long startTime = System.currentTimeMillis();
char[] grid = loadPuzzle(args[0]);
loadDict(args[1]);
loadStrFile(args[2]);
List<String> results = findStrings(grid);
System.out.println("WORD GRID:");
System.out.println(grid[0] + " " + grid[1] + " " + grid[2] + "\n" +
grid[3] + " " + grid[4] + " " + grid[5] + "\n" +
grid[6] + " " + grid[7] + " " + grid[8] + "\n");
//Removes duplicates from array, then adds back into original array
HashSet<String> set = new HashSet<String>();
set.addAll(results);
results.clear();
results.addAll(set);
Collections.sort(results);
System.out.println("Found " + results.size() + " results with " +
MIN_LENGTH + " letters or more");
for(int i = MIN_LENGTH; i <= grid.length; i++) {
ArrayList<String> tmp = new ArrayList<String>();
for(String s: results) {
if(s.length() == i ) {
tmp.add(s);
}
}
System.out.println("Found " + tmp.size() + " results with " + i +
" letters: ");
for(String s: tmp) {
System.out.println(" - " + s);
}
}
Runtime r = Runtime.getRuntime();
r.gc();
long endTime = System.currentTimeMillis();
System.out.println("\n\n\nTime taken: " + (endTime - startTime) +
" milliseconds");
System.out.println("Memory used: " +
((r.totalMemory() - r.freeMemory())/1024) + " kB");
System.out.println("Strings produced: " + count);
System.exit(0);
}
/**
* Private method to load a puzzle text file into a char array
* @param filename The name of the file to load
* @return The char array containing the text file, with the "centre" letter
* in upper case to avoid finding duplicate letters when searching
* in the permute method.
*/
private static char[] loadPuzzle(String filename) {
char[] grid = new char[9];
try {
BufferedReader in = new BufferedReader(new FileReader(filename));
String line;
int n = 0;
while( (line = in.readLine()) != null ) {
String[] row = line.split("\\s");
for(int i = 0; i < 3; i++) {
if( n != MIN_LENGTH ) {
grid[n] = Character.toLowerCase(
row[i].charAt(0));
} else {
grid[n] = Character.toUpperCase(
row[i].charAt(0));
}
n++;
}
}
} catch( IOException e ) {
System.err.println("A file error occurred: " + filename +
"Error message: " + e.getMessage() +
e.getStackTrace());
System.exit(1);
}
return grid;
}
/**
* A method that loads a dictionary text file into a tree structure
* @param filename The dictionary file to load
* @return The ArrayList containing the dictionary
*/
private static void loadDict(String filename) {
dict = new ArrayList<String>();
try {
BufferedReader in = new BufferedReader(
new FileReader(filename));
String word;
while( (word = in.readLine()) != null ) {
dict.add(word);
}
} catch( IOException e ) {
System.err.println("A file error occurred: " + filename +
"Error message: " + e.getMessage() +
e.getStackTrace());
System.exit(1);
}
}
/**
* A method that loads a dictionary text file into a tree structure
* @param filename The dictionary file to load
* @return The ArrayList containing the dictionary
*/
private static void loadStrFile(String filename) {
possArr = new ArrayList<String>();
try {
BufferedReader in = new BufferedReader(
new FileReader(filename));
String word;
while( (word = in.readLine()) != null ) {
possArr.add(word);
}
} catch( IOException e ) {
System.err.println("A file error occurred: " + filename +
"Error message: " + e.getMessage() +
e.getStackTrace());
System.exit(1);
}
}
/**
* Private method to call the permute function, provides a List to
* populate and the "centre" character.
* @param grid The puzzle grid to solve
* @return The List containing the words found in the puzzle
*/
private static List<String> findStrings(char[] grid){
List<String> tmp = new ArrayList<String>();
String str = new String(grid);
char centre = grid[4];
tmp = permute(tmp, str, String.valueOf(centre));
return tmp;
}
/**
* Outer function to call the recursive permute function
* @param words The ArrayList to populate
* @param str The string containing the letters to permute, the "centre"
* letter is capitalised.
* @param centre The "centre" letter that each word must contain
* @return The ArrayList of all dictionary words found in str
*/
private static List<String> permute(List<String> words, String str,
CharSequence centre) {
permute("", str, words, centre);
return words;
}
/**
* The recursive permute function. Generates every permutation of every
* length from 0-the length of the string. Checks whether each string is
* larger than the minimum length supplied, contains the "centre" letter,
* and is contained in the dictionary. If so, adds it to the ArrayList
* of strings to be returned.
*/
private static void permute(String prefix, String str, List<String> words,
CharSequence centre) {
count++;
int length = str.length();
String lowPre = prefix.toLowerCase();
if(prefix.length() == 4 || prefix.length() == 3) {
if(Collections.binarySearch(possArr, lowPre) <= 0) {
return;
}
}
if(prefix.length() >= MIN_LENGTH && prefix.contains(centre) &&
Collections.binarySearch(dict, lowPre) >= 0) {
words.add(lowPre);
}
if( length != 0 ) {
for(int i = 0; i < length; i++) {
permute(prefix + str.charAt(i),
str.substring(0, i) + str.substring(i+1, length),
words, centre);
}
}
}
}
|
package de.metalmatze.krautreporter.entities;
import java.net.URL;
import java.util.Date;
public class Article {
private String uuid;
private String title;
private Date date;
private URL link;
private URL image;
private String content;
public Article() {
}
public Article(String uuid, String title, Date date, URL link, URL image, String content) {
this.uuid = uuid;
this.title = title;
this.date = date;
this.link = link;
this.image = image;
this.content = content;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public URL getLink() {
return link;
}
public void setLink(URL link) {
this.link = link;
}
public URL getImage() {
return image;
}
public void setImage(URL image) {
this.image = image;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Override
public String toString() {
return "Article{" +
"uuid='" + uuid + '\'' +
", title='" + title + '\'' +
", date=" + date +
", link=" + link +
", image=" + image +
// ", content='" + content + '\'' +
'}';
}
}
|
package com.zeroone.conceal;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import com.facebook.crypto.CryptoConfig;
import com.zeroone.conceal.helper.ConverterListUtils;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static android.content.Context.MODE_PRIVATE;
/**
* @author : hafiq on 23/03/2017.
*/
public class ConcealPrefRepository {
private Context mContext;
private CryptoConfig mKeyChain = CryptoConfig.KEY_256;
private boolean mEnabledCrypto = false;
private boolean mEnableCryptKey = false;
private String mEntityPasswordRaw = null;
private static SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
static ConcealCrypto concealCrypto;
@SuppressLint("CommitPrefEdits")
ConcealPrefRepository(PreferencesBuilder builder){
mContext = builder.mContext;
mKeyChain = builder.mKeyChain;
mEnabledCrypto = builder.mEnabledCrypto;
mEnableCryptKey = builder.mEnableCryptKey;
sharedPreferences = builder.sharedPreferences;
mEntityPasswordRaw = builder.mEntityPasswordRaw;
//init editor
editor = sharedPreferences.edit();
//init crypto
concealCrypto = new ConcealCrypto.CryptoBuilder(mContext)
.createPassword(mEntityPasswordRaw)
.setKeyChain(mKeyChain)
.setEnableCrypto(mEnabledCrypto)
.setEnableKeyCrypto(mEnableCryptKey)
.create();
}
/* Destroy Files*/
public void destroyCrypto(){
concealCrypto.clearCrypto();
}
public void destroySharedPreferences(){
editor.clear().apply();
destroyCrypto();
}
/* Save Data */
public void putString(String key, String value) {
editor.putString(concealCrypto.hashKey(key), concealCrypto.obscure(value)).apply();
}
public void putInt(String key, int value) {
editor.putString(concealCrypto.hashKey(key), concealCrypto.obscure(Integer.toString(value))).apply();
}
public void putLong(String key, long value) {
editor.putString(concealCrypto.hashKey(key), concealCrypto.obscure(Long.toString(value))).apply();
}
public void putDouble(String key, double value) {
editor.putString(concealCrypto.hashKey(key), concealCrypto.obscure(Double.toString(value))).apply();
}
public void putFloat(String key, float value) {
editor.putString(concealCrypto.hashKey(key), concealCrypto.obscure(Float.toString(value))).apply();
}
public void putBoolean(String key, boolean value) {
editor.putString(concealCrypto.hashKey(key), concealCrypto.obscure(Boolean.toString(value))).apply();
}
public void putListString(String key, List<String> value){
editor.putString(concealCrypto.hashKey(key),concealCrypto.obscure(value.toString())).apply();
}
public void putListFloat(String key, List<Float> value){
editor.putString(concealCrypto.hashKey(key),concealCrypto.obscure(value.toString())).apply();
}
public void putListInteger(String key, List<Integer> value){
editor.putString(concealCrypto.hashKey(key),concealCrypto.obscure(value.toString())).apply();
}
public void putListDouble(String key, List<Double> value){
editor.putString(concealCrypto.hashKey(key),concealCrypto.obscure(value.toString())).apply();
}
public void putListLong(String key, List<Long> value){
editor.putString(concealCrypto.hashKey(key),concealCrypto.obscure(value.toString())).apply();
}
public void putListBoolean(String key, List<Boolean> value){
editor.putString(concealCrypto.hashKey(key),concealCrypto.obscure(value.toString())).apply();
}
public void putMap(String key,Map<String,String> values){
editor.putString(concealCrypto.hashKey(key),concealCrypto.obscure(ConverterListUtils.convertMapToString(values))).apply();
}
/* Fetch Data */
public String getString(String key){
return concealCrypto.deObscure(sharedPreferences.getString(concealCrypto.hashKey(key),null));
}
public String getString(String key,String def){
return concealCrypto.deObscure(sharedPreferences.getString(concealCrypto.hashKey(key),def));
}
public Integer getInt(String key){
try {
String value = getString(key);
if (value == null)
return -99;
return Integer.parseInt(value);
}
catch (Exception e){
throwRunTimeException("Unable to convert to INteger data type",e);
return -99;
}
}
public Integer getInt(String key,int def){
try {
String value = getString(key);
if (value == null)
return def;
return Integer.parseInt(value);
}
catch (Exception e){
throwRunTimeException("Unable to convert to Integer data type",e);
return -99;
}
}
public Float getFloat(String key){
try {
String value = getString(key);
if (value == null)
return 0f;
return Float.parseFloat(value);
}
catch (Exception e){
throwRunTimeException("Unable to convert to Float data type",e);
return 0f;
}
}
public Float getFloat(String key,float def){
try {
String value = getString(key);
if (value == null)
return def;
return Float.parseFloat(value);
}
catch (Exception e){
throwRunTimeException("Unable to convert to Float data type",e);
return def;
}
}
public Double getDouble(String key){
try {
String value = getString(key);
if (value == null)
return 0D;
return Double.parseDouble(value);
}
catch (Exception e){
throwRunTimeException("Unable to convert to Double data type",e);
return 0D;
}
}
public Double getDouble(String key,double def){
try {
String value = getString(key);
if (value == null)
return def;
return Double.parseDouble(value);
}
catch (Exception e){
throwRunTimeException("Unable to convert to Double data type",e);
return def;
}
}
public Long getLong(String key){
try {
String value = getString(key);
if (value == null)
return 0L;
return Long.parseLong(value);
}
catch (Exception e){
throwRunTimeException("Unable to convert to Long data type",e);
return 0L;
}
}
public Long getLong(String key,long def){
try {
String value = getString(key);
if (value == null)
return def;
return Long.parseLong(value);
}
catch (Exception e){
throwRunTimeException("Unable to convert to Long data type",e);
return def;
}
}
public Boolean getBoolean(String key){
try {
String value = getString(key);
return value != null && Boolean.parseBoolean(value);
}
catch (Exception e){
throwRunTimeException("Unable to convert to Boolean data type",e);
return false;
}
}
public Boolean getBoolean(String key,boolean def){
try {
String value = getString(key);
if (value == null)
return def;
return Boolean.parseBoolean(value);
}
catch (Exception e){
throwRunTimeException("Unable to convert to Boolean data type",e);
return false;
}
}
public List<String> getListString(String key){
return ConverterListUtils.toStringArray(getString(key));
}
public List<Float> getListFloat(String key){
return ConverterListUtils.toFloatArray(getString(key));
}
public List<Double> getListDouble(String key){
return ConverterListUtils.toDoubleArray(getString(key));
}
public List<Boolean> getListBoolean(String key){
return ConverterListUtils.toBooleanArray(getString(key));
}
public List<Integer> getListInteger(String key){
return ConverterListUtils.toIntArray(getString(key));
}
public List<Long> getListLong(String key){
return ConverterListUtils.toLongArray(getString(key));
}
public LinkedHashMap<String,String> getMaps(String key){
return ConverterListUtils.convertStringToMap(getString(key));
}
public static final class Editor {
private SharedPreferences.Editor mEditor;
@SuppressLint("CommitPrefEdits")
public Editor() {
mEditor = sharedPreferences.edit();
}
public Editor putString(String key, String value) {
mEditor.putString(concealCrypto.hashKey(key), concealCrypto.obscure(value));
return this;
}
public Editor putInt(String key, int value) {
mEditor.putString(concealCrypto.hashKey(key), concealCrypto.obscure(Integer.toString(value)));
return this;
}
public Editor putLong(String key, long value) {
mEditor.putString(concealCrypto.hashKey(key), concealCrypto.obscure(Long.toString(value)));
return this;
}
public Editor putDouble(String key, double value) {
mEditor.putString(concealCrypto.hashKey(key), concealCrypto.obscure(Double.toString(value)));
return this;
}
public Editor putFloat(String key, float value) {
mEditor.putString(concealCrypto.hashKey(key), concealCrypto.obscure(Float.toString(value)));
return this;
}
public Editor putBoolean(String key, boolean value) {
mEditor.putString(concealCrypto.hashKey(key), concealCrypto.obscure(Boolean.toString(value)));
return this;
}
public Editor putListString(String key, List<String> value){
mEditor.putString(concealCrypto.hashKey(key),concealCrypto.obscure(value.toString()));
return this;
}
public Editor putListFloat(String key, List<Float> value){
mEditor.putString(concealCrypto.hashKey(key),concealCrypto.obscure(value.toString()));
return this;
}
public Editor putListInteger(String key, List<Integer> value){
mEditor.putString(concealCrypto.hashKey(key),concealCrypto.obscure(value.toString()));
return this;
}
public Editor putListDouble(String key, List<Double> value){
mEditor.putString(concealCrypto.hashKey(key),concealCrypto.obscure(value.toString()));
return this;
}
public Editor putListLong(String key, List<Long> value){
mEditor.putString(concealCrypto.hashKey(key),concealCrypto.obscure(value.toString()));
return this;
}
public Editor putListBoolean(String key, List<Boolean> value){
mEditor.putString(concealCrypto.hashKey(key),concealCrypto.obscure(value.toString()));
return this;
}
public Editor remove(String key) {
mEditor.remove(concealCrypto.hashKey(key));
return this;
}
public Editor putMap(String key,Map<String,String> values){
mEditor.putString(concealCrypto.hashKey(key),concealCrypto.obscure(ConverterListUtils.convertMapToString(values)));
return this;
}
public Editor clear() {
mEditor.clear();
return this;
}
public boolean commit() {
return mEditor.commit();
}
public void apply() {
mEditor.apply();
}
}
public static class PreferencesBuilder{
private Context mContext;
private CryptoConfig mKeyChain = CryptoConfig.KEY_256;
private String mPrefname;
private boolean mEnabledCrypto = false;
private boolean mEnableCryptKey = false;
private String mEntityPasswordRaw = null;
private SharedPreferences sharedPreferences;
public PreferencesBuilder(Context context) {
mContext = context;
}
public PreferencesBuilder useDefaultPrefStorage(){
return this;
}
public PreferencesBuilder useThisPrefStorage(String prefName){
mPrefname = prefName;
return this;
}
public PreferencesBuilder enableCrypto(boolean enabled,boolean cryptKey){
mEnabledCrypto = enabled;
mEnableCryptKey = cryptKey;
return this;
}
public PreferencesBuilder sharedPrefsBackedKeyChain(CryptoConfig keyChain){
mKeyChain = keyChain;
return this;
}
public PreferencesBuilder createPassword(String password){
mEntityPasswordRaw = password;
return this;
}
public ConcealPrefRepository create(){
if (mPrefname!=null){
sharedPreferences = mContext.getSharedPreferences(mPrefname, MODE_PRIVATE);
}
else{
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
}
return new ConcealPrefRepository(this);
}
}
private void throwRunTimeException(String message, Throwable throwable){
new RuntimeException(message,throwable).printStackTrace();
}
}
|
package liquibase.database;
import liquibase.Scope;
import liquibase.database.core.UnsupportedDatabase;
import liquibase.exception.DatabaseException;
import liquibase.exception.UnexpectedLiquibaseException;
import liquibase.logging.Logger;
import liquibase.resource.ResourceAccessor;
import liquibase.util.StringUtil;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.Driver;
import java.util.*;
public class DatabaseFactory {
private static final Logger LOG = Scope.getCurrentScope().getLog(DatabaseFactory.class);
private static DatabaseFactory instance;
private Map<String, SortedSet<Database>> implementedDatabases = new HashMap<>();
private Map<String, SortedSet<Database>> internalDatabases = new HashMap<>();
private DatabaseFactory() {
try {
for (Database database : Scope.getCurrentScope().getServiceLocator().findInstances(Database.class)) {
register(database);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static synchronized DatabaseFactory getInstance() {
if (instance == null) {
instance = new DatabaseFactory();
}
return instance;
}
/**
* Set singleton instance. Primarily used in testing
*/
public static synchronized void setInstance(DatabaseFactory databaseFactory) {
instance = databaseFactory;
}
public static synchronized void reset() {
instance = new DatabaseFactory();
}
/**
* Returns instances of all implemented database types.
*/
public List<Database> getImplementedDatabases() {
List<Database> returnList = new ArrayList<>();
for (SortedSet<Database> set : implementedDatabases.values()) {
returnList.add(set.iterator().next());
}
return returnList;
}
/**
* Returns instances of all "internal" database types.
*/
public List<Database> getInternalDatabases() {
List<Database> returnList = new ArrayList<>();
for (SortedSet<Database> set : internalDatabases.values()) {
returnList.add(set.iterator().next());
}
return returnList;
}
public void register(Database database) {
Map<String, SortedSet<Database>> map = null;
if (database instanceof InternalDatabase) {
map = internalDatabases;
} else {
map = implementedDatabases;
}
if (!map.containsKey(database.getShortName())) {
map.put(database.getShortName(), new TreeSet<>(new TreeSet<>(new DatabaseComparator())));
}
map.get(database.getShortName()).add(database);
}
public Database findCorrectDatabaseImplementation(DatabaseConnection connection) throws DatabaseException {
SortedSet<Database> foundDatabases = new TreeSet<>(new DatabaseComparator());
for (Database implementedDatabase : getImplementedDatabases()) {
if (connection instanceof OfflineConnection) {
if (((OfflineConnection) connection).isCorrectDatabaseImplementation(implementedDatabase)) {
foundDatabases.add(implementedDatabase);
}
} else {
if (implementedDatabase.isCorrectDatabaseImplementation(connection)) {
foundDatabases.add(implementedDatabase);
}
}
}
if (foundDatabases.isEmpty()) {
LOG.warning("Unknown database: " + connection.getDatabaseProductName());
UnsupportedDatabase unsupportedDB = new UnsupportedDatabase();
unsupportedDB.setConnection(connection);
return unsupportedDB;
}
Database returnDatabase;
try {
returnDatabase = foundDatabases.iterator().next().getClass().getConstructor().newInstance();
} catch (Exception e) {
throw new UnexpectedLiquibaseException(e);
}
returnDatabase.setConnection(connection);
return returnDatabase;
}
public Database openDatabase(String url,
String username,
String password,
String propertyProviderClass,
ResourceAccessor resourceAccessor) throws DatabaseException {
return openDatabase(url, username, password, null, null, null, propertyProviderClass, resourceAccessor);
}
public Database openDatabase(String url,
String username,
String password,
String driver,
String databaseClass,
String driverPropertiesFile,
String propertyProviderClass,
ResourceAccessor resourceAccessor) throws DatabaseException {
return this.findCorrectDatabaseImplementation(openConnection(url, username, password, driver, databaseClass, driverPropertiesFile, propertyProviderClass, resourceAccessor));
}
public Database openDatabase(String url,
String username,
String driver,
String databaseClass,
Properties driverProperties,
ResourceAccessor resourceAccessor) throws DatabaseException {
return this.findCorrectDatabaseImplementation(openConnection(url, username, driver, databaseClass, driverProperties, resourceAccessor));
}
public DatabaseConnection openConnection(String url,
String username,
String password,
String propertyProvider,
ResourceAccessor resourceAccessor) throws DatabaseException {
return openConnection(url, username, password, null, null, null, propertyProvider, resourceAccessor);
}
public DatabaseConnection openConnection(String url,
String username,
String password,
String driver,
String databaseClass,
String driverPropertiesFile,
String propertyProviderClass,
ResourceAccessor resourceAccessor) throws DatabaseException {
Properties driverProperties;
try {
driverProperties = buildDriverProperties(username, password, driverPropertiesFile, propertyProviderClass);
} catch (Exception e) {
throw new DatabaseException(e);
}
return openConnection(url, username, driver, databaseClass, driverProperties, resourceAccessor);
}
public DatabaseConnection openConnection(String url,
String username,
String driver,
String databaseClass,
Properties driverProperties,
ResourceAccessor resourceAccessor) throws DatabaseException {
if (url.startsWith("offline:")) {
OfflineConnection offlineConnection = new OfflineConnection(url, resourceAccessor);
offlineConnection.setConnectionUserName(username);
return offlineConnection;
}
DatabaseConnection databaseConnection;
try {
DatabaseFactory databaseFactory = DatabaseFactory.getInstance();
if (databaseClass != null) {
databaseFactory.clearRegistry();
databaseFactory.register((Database) Class.forName(databaseClass, true, Scope.getCurrentScope().getClassLoader()).getConstructor().newInstance());
}
String selectedDriverClass = findDriverClass(url, driver, databaseFactory);
Driver driverObject = loadDriver(selectedDriverClass);
if (driverObject instanceof LiquibaseExtDriver) {
((LiquibaseExtDriver) driverObject).setResourceAccessor(resourceAccessor);
}
if(selectedDriverClass.contains("oracle")) {
driverProperties.put("remarksReporting", "true");
} else if(selectedDriverClass.contains("mysql")) {
driverProperties.put("useInformationSchema", "true");
}
LOG.fine("Connecting to the URL:'" + url + "' using driver:'" + driverObject.getClass().getName() + "'");
databaseConnection = ConnectionServiceFactory.getInstance().create(url, driverObject, driverProperties);
LOG.fine("Connection has been created");
} catch (Exception e) {
throw new DatabaseException(e);
}
return databaseConnection;
}
/**
* Returns the Java class name of the JDBC driver class (e.g. "org.mariadb.jdbc.Driver")
* for the specified JDBC URL, if any Database class supports that URL.
*
* @param url the JDBC URL to analyse
* @return a Database object supporting the URL. May also return null if the JDBC URL is unknown to all handlers.
*/
public String findDefaultDriver(String url) {
for (Database database : this.getImplementedDatabases()) {
String defaultDriver = database.getDefaultDriver(url);
if (defaultDriver != null) {
return defaultDriver;
}
}
return null;
}
/**
* Removes all registered databases, even built in ones. Useful for forcing a particular database implementation
*/
public void clearRegistry() {
implementedDatabases.clear();
}
public Database getDatabase(String shortName) {
if (!implementedDatabases.containsKey(shortName)) {
return null;
}
return implementedDatabases.get(shortName).iterator().next();
}
private String findDriverClass(String url, String driver, DatabaseFactory databaseFactory) {
String selectedDriverClass = StringUtil.trimToNull(driver);
if (selectedDriverClass == null) {
selectedDriverClass = databaseFactory.findDefaultDriver(url);
}
if (selectedDriverClass == null) {
throw new RuntimeException("Driver class was not specified and could not be determined from the url (" + url + ")");
}
return selectedDriverClass;
}
private Driver loadDriver(String driverClass) {
Driver driverObject;
try {
driverObject = (Driver) Class.forName(driverClass, true, Scope.getCurrentScope().getClassLoader()).getConstructor().newInstance();
} catch (Exception e) {
throw new RuntimeException("Cannot find database driver: " + e.getMessage());
}
return driverObject;
}
private Properties buildDriverProperties(String username, String password, String driverPropertiesFile, String propertyProviderClass) {
Properties driverProperties;
try {
if (propertyProviderClass == null) {
driverProperties = new Properties();
} else {
driverProperties = (Properties) Class.forName(propertyProviderClass, true, Scope.getCurrentScope().getClassLoader()).getConstructor().newInstance();
}
if (username != null) {
driverProperties.put("user", username);
}
if (password != null) {
driverProperties.put("password", password);
}
if (null != driverPropertiesFile) {
File propertiesFile = new File(driverPropertiesFile);
if (propertiesFile.exists()) {
LOG.fine(
"Loading properties from the file:'" + driverPropertiesFile + "'"
);
FileInputStream inputStream = new FileInputStream(propertiesFile);
try {
driverProperties.load(inputStream);
} finally {
inputStream.close();
}
} else {
throw new RuntimeException("Can't open JDBC Driver specific properties from the file: '"
+ driverPropertiesFile + "'");
}
}
} catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException | ClassNotFoundException | IOException e) {
throw new RuntimeException("Exception opening JDBC Driver specific properties from the file: '"
+ driverPropertiesFile + "'", e);
}
LOG.fine("Properties:");
for (Map.Entry<Object, Object> entry : driverProperties.entrySet()) {
if (entry.getKey().toString().toLowerCase().contains("password")) {
Scope.getCurrentScope().getLog(getClass()).fine("Key:'" + entry.getKey().toString() + "' Value:'**********'");
} else {
LOG.fine("Key:'" + entry.getKey().toString() + "' Value:'" + entry.getValue().toString() + "'");
}
}
return driverProperties;
}
private static class DatabaseComparator implements Comparator<Database> {
@Override
public int compare(Database o1, Database o2) {
return -1 * Integer.valueOf(o1.getPriority()).compareTo(o2.getPriority());
}
}
}
|
package info.nightscout.androidaps.db;
import android.content.Context;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.support.annotation.Nullable;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.CloseableIterator;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.PreparedQuery;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.Where;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.events.EventCareportalEventChange;
import info.nightscout.androidaps.events.EventExtendedBolusChange;
import info.nightscout.androidaps.events.EventFoodDatabaseChanged;
import info.nightscout.androidaps.events.EventNewBG;
import info.nightscout.androidaps.events.EventProfileSwitchChange;
import info.nightscout.androidaps.events.EventRefreshOverview;
import info.nightscout.androidaps.events.EventReloadProfileSwitchData;
import info.nightscout.androidaps.events.EventReloadTempBasalData;
import info.nightscout.androidaps.events.EventReloadTreatmentData;
import info.nightscout.androidaps.events.EventTempBasalChange;
import info.nightscout.androidaps.events.EventTempTargetChange;
import info.nightscout.androidaps.events.EventTreatmentChange;
import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventNewHistoryData;
import info.nightscout.androidaps.plugins.PumpDanaR.activities.DanaRNSHistorySync;
import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin;
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static Logger log = LoggerFactory.getLogger(DatabaseHelper.class);
public static final String DATABASE_NAME = "AndroidAPSDb";
public static final String DATABASE_BGREADINGS = "BgReadings";
public static final String DATABASE_TEMPORARYBASALS = "TemporaryBasals";
public static final String DATABASE_EXTENDEDBOLUSES = "ExtendedBoluses";
public static final String DATABASE_TEMPTARGETS = "TempTargets";
public static final String DATABASE_TREATMENTS = "Treatments";
public static final String DATABASE_DANARHISTORY = "DanaRHistory";
public static final String DATABASE_DBREQUESTS = "DBRequests";
public static final String DATABASE_CAREPORTALEVENTS = "CareportalEvents";
public static final String DATABASE_PROFILESWITCHES = "ProfileSwitches";
public static final String DATABASE_FOODS = "Foods";
private static final int DATABASE_VERSION = 8;
private static Long earliestDataChange = null;
private static final ScheduledExecutorService bgWorker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture<?> scheduledBgPost = null;
private static final ScheduledExecutorService treatmentsWorker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture<?> scheduledTratmentPost = null;
private static final ScheduledExecutorService tempBasalsWorker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture<?> scheduledTemBasalsPost = null;
private static final ScheduledExecutorService tempTargetWorker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture<?> scheduledTemTargetPost = null;
private static final ScheduledExecutorService extendedBolusWorker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture<?> scheduledExtendedBolusPost = null;
private static final ScheduledExecutorService careportalEventWorker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture<?> scheduledCareportalEventPost = null;
private static final ScheduledExecutorService profileSwitchEventWorker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture<?> scheduledProfileSwitchEventPost = null;
public FoodHelper foodHelper = new FoodHelper(this);
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
onCreate(getWritableDatabase(), getConnectionSource());
//onUpgrade(getWritableDatabase(), getConnectionSource(), 1,1);
}
@Override
public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
try {
log.info("onCreate");
TableUtils.createTableIfNotExists(connectionSource, TempTarget.class);
TableUtils.createTableIfNotExists(connectionSource, Treatment.class);
TableUtils.createTableIfNotExists(connectionSource, BgReading.class);
TableUtils.createTableIfNotExists(connectionSource, DanaRHistoryRecord.class);
TableUtils.createTableIfNotExists(connectionSource, DbRequest.class);
TableUtils.createTableIfNotExists(connectionSource, TemporaryBasal.class);
TableUtils.createTableIfNotExists(connectionSource, ExtendedBolus.class);
TableUtils.createTableIfNotExists(connectionSource, CareportalEvent.class);
TableUtils.createTableIfNotExists(connectionSource, ProfileSwitch.class);
TableUtils.createTableIfNotExists(connectionSource, Food.class);
} catch (SQLException e) {
log.error("Can't create database", e);
throw new RuntimeException(e);
}
}
@Override
public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
try {
if (oldVersion == 7 && newVersion == 8) {
log.debug("Upgrading database from v7 to v8");
TableUtils.dropTable(connectionSource, Treatment.class, true);
TableUtils.createTableIfNotExists(connectionSource, Treatment.class);
} else {
log.info(DatabaseHelper.class.getName(), "onUpgrade");
TableUtils.dropTable(connectionSource, TempTarget.class, true);
TableUtils.dropTable(connectionSource, Treatment.class, true);
TableUtils.dropTable(connectionSource, BgReading.class, true);
TableUtils.dropTable(connectionSource, DanaRHistoryRecord.class, true);
TableUtils.dropTable(connectionSource, DbRequest.class, true);
TableUtils.dropTable(connectionSource, TemporaryBasal.class, true);
TableUtils.dropTable(connectionSource, ExtendedBolus.class, true);
TableUtils.dropTable(connectionSource, CareportalEvent.class, true);
TableUtils.dropTable(connectionSource, ProfileSwitch.class, true);
TableUtils.dropTable(connectionSource, Food.class, true);
onCreate(database, connectionSource);
}
} catch (SQLException e) {
log.error("Can't drop databases", e);
throw new RuntimeException(e);
}
}
/**
* Close the database connections and clear any cached DAOs.
*/
@Override
public void close() {
super.close();
}
public void cleanUpDatabases() {
// TODO: call it somewhere
log.debug("Before BgReadings size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_BGREADINGS));
getWritableDatabase().delete(DATABASE_BGREADINGS, "date" + " < '" + (System.currentTimeMillis() - Constants.hoursToKeepInDatabase * 60 * 60 * 1000L) + "'", null);
log.debug("After BgReadings size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_BGREADINGS));
log.debug("Before TempTargets size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_TEMPTARGETS));
getWritableDatabase().delete(DATABASE_TEMPTARGETS, "date" + " < '" + (System.currentTimeMillis() - Constants.hoursToKeepInDatabase * 60 * 60 * 1000L) + "'", null);
log.debug("After TempTargets size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_TEMPTARGETS));
log.debug("Before Treatments size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_TREATMENTS));
getWritableDatabase().delete(DATABASE_TREATMENTS, "date" + " < '" + (System.currentTimeMillis() - Constants.hoursToKeepInDatabase * 60 * 60 * 1000L) + "'", null);
log.debug("After Treatments size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_TREATMENTS));
log.debug("Before History size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_DANARHISTORY));
getWritableDatabase().delete(DATABASE_DANARHISTORY, "recordDate" + " < '" + (System.currentTimeMillis() - Constants.daysToKeepHistoryInDatabase * 24 * 60 * 60 * 1000L) + "'", null);
log.debug("After History size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_DANARHISTORY));
log.debug("Before TemporaryBasals size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_TEMPORARYBASALS));
getWritableDatabase().delete(DATABASE_TEMPORARYBASALS, "recordDate" + " < '" + (System.currentTimeMillis() - Constants.daysToKeepHistoryInDatabase * 24 * 60 * 60 * 1000L) + "'", null);
log.debug("After TemporaryBasals size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_TEMPORARYBASALS));
log.debug("Before ExtendedBoluses size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_EXTENDEDBOLUSES));
getWritableDatabase().delete(DATABASE_EXTENDEDBOLUSES, "recordDate" + " < '" + (System.currentTimeMillis() - Constants.daysToKeepHistoryInDatabase * 24 * 60 * 60 * 1000L) + "'", null);
log.debug("After ExtendedBoluses size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_EXTENDEDBOLUSES));
log.debug("Before CareportalEvent size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_CAREPORTALEVENTS));
getWritableDatabase().delete(DATABASE_CAREPORTALEVENTS, "recordDate" + " < '" + (System.currentTimeMillis() - Constants.daysToKeepHistoryInDatabase * 24 * 60 * 60 * 1000L) + "'", null);
log.debug("After CareportalEvent size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_CAREPORTALEVENTS));
log.debug("Before ProfileSwitch size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_PROFILESWITCHES));
getWritableDatabase().delete(DATABASE_PROFILESWITCHES, "recordDate" + " < '" + (System.currentTimeMillis() - Constants.daysToKeepHistoryInDatabase * 24 * 60 * 60 * 1000L) + "'", null);
log.debug("After ProfileSwitch size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_PROFILESWITCHES));
}
public long size(String database) {
return DatabaseUtils.queryNumEntries(getReadableDatabase(), database);
}
public void resetDatabases() {
try {
TableUtils.dropTable(connectionSource, TempTarget.class, true);
TableUtils.dropTable(connectionSource, Treatment.class, true);
TableUtils.dropTable(connectionSource, BgReading.class, true);
TableUtils.dropTable(connectionSource, DanaRHistoryRecord.class, true);
TableUtils.dropTable(connectionSource, DbRequest.class, true);
TableUtils.dropTable(connectionSource, TemporaryBasal.class, true);
TableUtils.dropTable(connectionSource, ExtendedBolus.class, true);
TableUtils.dropTable(connectionSource, CareportalEvent.class, true);
TableUtils.dropTable(connectionSource, ProfileSwitch.class, true);
TableUtils.createTableIfNotExists(connectionSource, TempTarget.class);
TableUtils.createTableIfNotExists(connectionSource, Treatment.class);
TableUtils.createTableIfNotExists(connectionSource, BgReading.class);
TableUtils.createTableIfNotExists(connectionSource, DanaRHistoryRecord.class);
TableUtils.createTableIfNotExists(connectionSource, DbRequest.class);
TableUtils.createTableIfNotExists(connectionSource, TemporaryBasal.class);
TableUtils.createTableIfNotExists(connectionSource, ExtendedBolus.class);
TableUtils.createTableIfNotExists(connectionSource, CareportalEvent.class);
TableUtils.createTableIfNotExists(connectionSource, ProfileSwitch.class);
foodHelper.resetFood();
updateEarliestDataChange(0);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
VirtualPumpPlugin.setFakingStatus(true);
scheduleBgChange(); // trigger refresh
scheduleTemporaryBasalChange();
scheduleTreatmentChange();
scheduleExtendedBolusChange();
scheduleTemporaryTargetChange();
scheduleCareportalEventChange();
scheduleProfileSwitchChange();
foodHelper.scheduleFoodChange();
new java.util.Timer().schedule(
new java.util.TimerTask() {
@Override
public void run() {
MainApp.bus().post(new EventRefreshOverview("resetDatabases"));
}
},
3000
);
}
public void resetTreatments() {
try {
TableUtils.dropTable(connectionSource, Treatment.class, true);
TableUtils.createTableIfNotExists(connectionSource, Treatment.class);
updateEarliestDataChange(0);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
scheduleTreatmentChange();
}
public void resetTempTargets() {
try {
TableUtils.dropTable(connectionSource, TempTarget.class, true);
TableUtils.createTableIfNotExists(connectionSource, TempTarget.class);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
scheduleTemporaryTargetChange();
}
public void resetTemporaryBasals() {
try {
TableUtils.dropTable(connectionSource, TemporaryBasal.class, true);
TableUtils.createTableIfNotExists(connectionSource, TemporaryBasal.class);
updateEarliestDataChange(0);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
VirtualPumpPlugin.setFakingStatus(false);
scheduleTemporaryBasalChange();
}
public void resetExtededBoluses() {
try {
TableUtils.dropTable(connectionSource, ExtendedBolus.class, true);
TableUtils.createTableIfNotExists(connectionSource, ExtendedBolus.class);
updateEarliestDataChange(0);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
scheduleExtendedBolusChange();
}
public void resetCareportalEvents() {
try {
TableUtils.dropTable(connectionSource, CareportalEvent.class, true);
TableUtils.createTableIfNotExists(connectionSource, CareportalEvent.class);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
scheduleCareportalEventChange();
}
public void resetProfileSwitch() {
try {
TableUtils.dropTable(connectionSource, ProfileSwitch.class, true);
TableUtils.createTableIfNotExists(connectionSource, ProfileSwitch.class);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
scheduleProfileSwitchChange();
}
private Dao<TempTarget, Long> getDaoTempTargets() throws SQLException {
return getDao(TempTarget.class);
}
private Dao<Treatment, Long> getDaoTreatments() throws SQLException {
return getDao(Treatment.class);
}
private Dao<BgReading, Long> getDaoBgReadings() throws SQLException {
return getDao(BgReading.class);
}
private Dao<DanaRHistoryRecord, String> getDaoDanaRHistory() throws SQLException {
return getDao(DanaRHistoryRecord.class);
}
private Dao<DbRequest, String> getDaoDbRequest() throws SQLException {
return getDao(DbRequest.class);
}
private Dao<TemporaryBasal, Long> getDaoTemporaryBasal() throws SQLException {
return getDao(TemporaryBasal.class);
}
private Dao<ExtendedBolus, Long> getDaoExtendedBolus() throws SQLException {
return getDao(ExtendedBolus.class);
}
private Dao<CareportalEvent, Long> getDaoCareportalEvents() throws SQLException {
return getDao(CareportalEvent.class);
}
private Dao<ProfileSwitch, Long> getDaoProfileSwitch() throws SQLException {
return getDao(ProfileSwitch.class);
}
public long roundDateToSec(long date) {
return date - date % 1000;
}
public boolean createIfNotExists(BgReading bgReading, String from) {
try {
bgReading.date = roundDateToSec(bgReading.date);
BgReading old = getDaoBgReadings().queryForId(bgReading.date);
if (old == null) {
getDaoBgReadings().create(bgReading);
log.debug("BG: New record from: " + from + " " + bgReading.toString());
scheduleBgChange();
return true;
}
if (!old.isEqual(bgReading)) {
log.debug("BG: Similiar found: " + old.toString());
old.copyFrom(bgReading);
getDaoBgReadings().update(old);
log.debug("BG: Updating record from: " + from + " New data: " + old.toString());
scheduleBgChange();
return false;
}
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return false;
}
private static void scheduleBgChange() {
class PostRunnable implements Runnable {
public void run() {
log.debug("Firing EventNewBg");
MainApp.bus().post(new EventNewBG());
scheduledBgPost = null;
}
}
// prepare task for execution in 1 sec
// cancel waiting task to prevent sending multiple posts
if (scheduledBgPost != null)
scheduledBgPost.cancel(false);
Runnable task = new PostRunnable();
final int sec = 1;
scheduledBgPost = bgWorker.schedule(task, sec, TimeUnit.SECONDS);
}
/*
* Return last BgReading from database or null if db is empty
*/
@Nullable
public static BgReading lastBg() {
List<BgReading> bgList = null;
try {
Dao<BgReading, Long> daoBgReadings = MainApp.getDbHelper().getDaoBgReadings();
QueryBuilder<BgReading, Long> queryBuilder = daoBgReadings.queryBuilder();
queryBuilder.orderBy("date", false);
queryBuilder.limit(1L);
queryBuilder.where().gt("value", 38);
PreparedQuery<BgReading> preparedQuery = queryBuilder.prepare();
bgList = daoBgReadings.query(preparedQuery);
} catch (SQLException e) {
log.debug(e.getMessage(), e);
}
if (bgList != null && bgList.size() > 0)
return bgList.get(0);
else
return null;
}
/*
* Return bg reading if not old ( <9 min )
* or null if older
*/
@Nullable
public static BgReading actualBg() {
BgReading lastBg = lastBg();
if (lastBg == null)
return null;
if (lastBg.date > System.currentTimeMillis() - 9 * 60 * 1000)
return lastBg;
return null;
}
public List<BgReading> getBgreadingsDataFromTime(long mills, boolean ascending) {
try {
Dao<BgReading, Long> daoBgreadings = getDaoBgReadings();
List<BgReading> bgReadings;
QueryBuilder<BgReading, Long> queryBuilder = daoBgreadings.queryBuilder();
queryBuilder.orderBy("date", ascending);
Where where = queryBuilder.where();
where.ge("date", mills).and().gt("value", 38);
PreparedQuery<BgReading> preparedQuery = queryBuilder.prepare();
bgReadings = daoBgreadings.query(preparedQuery);
return bgReadings;
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return new ArrayList<BgReading>();
}
public void create(DbRequest dbr) {
try {
getDaoDbRequest().create(dbr);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
}
public int delete(DbRequest dbr) {
try {
return getDaoDbRequest().delete(dbr);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return 0;
}
public int deleteDbRequest(String nsClientId) {
try {
return getDaoDbRequest().deleteById(nsClientId);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return 0;
}
public int deleteDbRequestbyMongoId(String action, String id) {
try {
QueryBuilder<DbRequest, String> queryBuilder = getDaoDbRequest().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", id).and().eq("action", action);
queryBuilder.limit(10L);
PreparedQuery<DbRequest> preparedQuery = queryBuilder.prepare();
List<DbRequest> dbList = getDaoDbRequest().query(preparedQuery);
if (dbList.size() != 1) {
log.error("deleteDbRequestbyMongoId query size: " + dbList.size());
} else {
//log.debug("Treatment findTreatmentById found: " + trList.get(0).log());
return delete(dbList.get(0));
}
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return 0;
}
public void deleteAllDbRequests() {
try {
TableUtils.clearTable(connectionSource, DbRequest.class);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
}
public CloseableIterator getDbRequestInterator() {
try {
return getDaoDbRequest().closeableIterator();
} catch (SQLException e) {
log.error("Unhandled exception", e);
return null;
}
}
// return true if new record is created
public boolean createOrUpdate(Treatment treatment) {
try {
Treatment old;
treatment.date = roundDateToSec(treatment.date);
if (treatment.source == Source.PUMP) {
// check for changed from pump change in NS
QueryBuilder<Treatment, Long> queryBuilder = getDaoTreatments().queryBuilder();
Where where = queryBuilder.where();
where.eq("pumpId", treatment.pumpId);
PreparedQuery<Treatment> preparedQuery = queryBuilder.prepare();
List<Treatment> trList = getDaoTreatments().query(preparedQuery);
if (trList.size() > 0) {
// do nothing, pump history record cannot be changed
return false;
}
getDaoTreatments().create(treatment);
log.debug("TREATMENT: New record from: " + Source.getString(treatment.source) + " " + treatment.toString());
updateEarliestDataChange(treatment.date);
scheduleTreatmentChange();
return true;
}
if (treatment.source == Source.NIGHTSCOUT) {
old = getDaoTreatments().queryForId(treatment.date);
if (old != null) {
if (!old.isEqual(treatment)) {
boolean historyChange = old.isDataChanging(treatment);
long oldDate = old.date;
getDaoTreatments().delete(old); // need to delete/create because date may change too
old.copyFrom(treatment);
getDaoTreatments().create(old);
log.debug("TREATMENT: Updating record by date from: " + Source.getString(treatment.source) + " " + old.toString());
if (historyChange) {
updateEarliestDataChange(oldDate);
updateEarliestDataChange(old.date);
}
scheduleTreatmentChange();
return true;
}
return false;
}
// find by NS _id
if (treatment._id != null) {
QueryBuilder<Treatment, Long> queryBuilder = getDaoTreatments().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", treatment._id);
PreparedQuery<Treatment> preparedQuery = queryBuilder.prepare();
List<Treatment> trList = getDaoTreatments().query(preparedQuery);
if (trList.size() > 0) {
old = trList.get(0);
if (!old.isEqual(treatment)) {
boolean historyChange = old.isDataChanging(treatment);
long oldDate = old.date;
getDaoTreatments().delete(old); // need to delete/create because date may change too
old.copyFrom(treatment);
getDaoTreatments().create(old);
log.debug("TREATMENT: Updating record by _id from: " + Source.getString(treatment.source) + " " + old.toString());
if (historyChange) {
updateEarliestDataChange(oldDate);
updateEarliestDataChange(old.date);
}
scheduleTreatmentChange();
return true;
}
}
}
getDaoTreatments().create(treatment);
log.debug("TREATMENT: New record from: " + Source.getString(treatment.source) + " " + treatment.toString());
updateEarliestDataChange(treatment.date);
scheduleTreatmentChange();
return true;
}
if (treatment.source == Source.USER) {
getDaoTreatments().create(treatment);
log.debug("TREATMENT: New record from: " + Source.getString(treatment.source) + " " + treatment.toString());
updateEarliestDataChange(treatment.date);
scheduleTreatmentChange();
return true;
}
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return false;
}
public void delete(Treatment treatment) {
try {
getDaoTreatments().delete(treatment);
updateEarliestDataChange(treatment.date);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
scheduleTreatmentChange();
}
public void update(Treatment treatment) {
try {
getDaoTreatments().update(treatment);
updateEarliestDataChange(treatment.date);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
scheduleTreatmentChange();
}
public void deleteTreatmentById(String _id) {
Treatment stored = findTreatmentById(_id);
if (stored != null) {
log.debug("TREATMENT: Removing Treatment record from database: " + stored.toString());
delete(stored);
updateEarliestDataChange(stored.date);
scheduleTreatmentChange();
}
}
@Nullable
public Treatment findTreatmentById(String _id) {
try {
Dao<Treatment, Long> daoTreatments = getDaoTreatments();
QueryBuilder<Treatment, Long> queryBuilder = daoTreatments.queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", _id);
queryBuilder.limit(10L);
PreparedQuery<Treatment> preparedQuery = queryBuilder.prepare();
List<Treatment> trList = daoTreatments.query(preparedQuery);
if (trList.size() != 1) {
//log.debug("Treatment findTreatmentById query size: " + trList.size());
return null;
} else {
//log.debug("Treatment findTreatmentById found: " + trList.get(0).log());
return trList.get(0);
}
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return null;
}
private void updateEarliestDataChange(long newDate) {
if (earliestDataChange == null) {
earliestDataChange = newDate;
return;
}
if (newDate < earliestDataChange) {
earliestDataChange = newDate;
}
}
private static void scheduleTreatmentChange() {
class PostRunnable implements Runnable {
public void run() {
log.debug("Firing EventTreatmentChange");
MainApp.bus().post(new EventReloadTreatmentData(new EventTreatmentChange()));
if (earliestDataChange != null)
MainApp.bus().post(new EventNewHistoryData(earliestDataChange));
earliestDataChange = null;
scheduledTratmentPost = null;
}
}
// prepare task for execution in 1 sec
// cancel waiting task to prevent sending multiple posts
if (scheduledTratmentPost != null)
scheduledTratmentPost.cancel(false);
Runnable task = new PostRunnable();
final int sec = 1;
scheduledTratmentPost = treatmentsWorker.schedule(task, sec, TimeUnit.SECONDS);
}
public List<Treatment> getTreatmentDataFromTime(long mills, boolean ascending) {
try {
Dao<Treatment, Long> daoTreatments = getDaoTreatments();
List<Treatment> treatments;
QueryBuilder<Treatment, Long> queryBuilder = daoTreatments.queryBuilder();
queryBuilder.orderBy("date", ascending);
Where where = queryBuilder.where();
where.ge("date", mills);
PreparedQuery<Treatment> preparedQuery = queryBuilder.prepare();
treatments = daoTreatments.query(preparedQuery);
return treatments;
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return new ArrayList<Treatment>();
}
public void createTreatmentFromJsonIfNotExists(JSONObject trJson) {
try {
Treatment treatment = new Treatment();
treatment.source = Source.NIGHTSCOUT;
treatment.date = roundDateToSec(trJson.getLong("mills"));
treatment.carbs = trJson.has("carbs") ? trJson.getDouble("carbs") : 0;
treatment.insulin = trJson.has("insulin") ? trJson.getDouble("insulin") : 0d;
treatment.pumpId = trJson.has("pumpId") ? trJson.getLong("pumpId") : 0;
treatment._id = trJson.getString("_id");
if (trJson.has("isSMB"))
treatment.isSMB = trJson.getBoolean("isSMB");
if (trJson.has("eventType")) {
treatment.mealBolus = !trJson.get("eventType").equals("Correction Bolus");
double carbs = treatment.carbs;
if (trJson.has("boluscalc")) {
JSONObject boluscalc = trJson.getJSONObject("boluscalc");
if (boluscalc.has("carbs")) {
carbs = Math.max(boluscalc.getDouble("carbs"), carbs);
}
}
if (carbs <= 0)
treatment.mealBolus = false;
}
createOrUpdate(treatment);
} catch (JSONException e) {
log.error("Unhandled exception", e);
}
}
public List<TempTarget> getTemptargetsDataFromTime(long mills, boolean ascending) {
try {
Dao<TempTarget, Long> daoTempTargets = getDaoTempTargets();
List<TempTarget> tempTargets;
QueryBuilder<TempTarget, Long> queryBuilder = daoTempTargets.queryBuilder();
queryBuilder.orderBy("date", ascending);
Where where = queryBuilder.where();
where.ge("date", mills);
PreparedQuery<TempTarget> preparedQuery = queryBuilder.prepare();
tempTargets = daoTempTargets.query(preparedQuery);
return tempTargets;
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return new ArrayList<TempTarget>();
}
public boolean createOrUpdate(TempTarget tempTarget) {
try {
TempTarget old;
tempTarget.date = roundDateToSec(tempTarget.date);
if (tempTarget.source == Source.NIGHTSCOUT) {
old = getDaoTempTargets().queryForId(tempTarget.date);
if (old != null) {
if (!old.isEqual(tempTarget)) {
getDaoTempTargets().delete(old); // need to delete/create because date may change too
old.copyFrom(tempTarget);
getDaoTempTargets().create(old);
log.debug("TEMPTARGET: Updating record by date from: " + Source.getString(tempTarget.source) + " " + old.toString());
scheduleTemporaryTargetChange();
return true;
}
return false;
}
// find by NS _id
if (tempTarget._id != null) {
QueryBuilder<TempTarget, Long> queryBuilder = getDaoTempTargets().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", tempTarget._id);
PreparedQuery<TempTarget> preparedQuery = queryBuilder.prepare();
List<TempTarget> trList = getDaoTempTargets().query(preparedQuery);
if (trList.size() > 0) {
old = trList.get(0);
if (!old.isEqual(tempTarget)) {
getDaoTempTargets().delete(old); // need to delete/create because date may change too
old.copyFrom(tempTarget);
getDaoTempTargets().create(old);
log.debug("TEMPTARGET: Updating record by _id from: " + Source.getString(tempTarget.source) + " " + old.toString());
scheduleTemporaryTargetChange();
return true;
}
}
}
getDaoTempTargets().create(tempTarget);
log.debug("TEMPTARGET: New record from: " + Source.getString(tempTarget.source) + " " + tempTarget.toString());
scheduleTemporaryTargetChange();
return true;
}
if (tempTarget.source == Source.USER) {
getDaoTempTargets().create(tempTarget);
log.debug("TEMPTARGET: New record from: " + Source.getString(tempTarget.source) + " " + tempTarget.toString());
scheduleTemporaryTargetChange();
return true;
}
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return false;
}
public void delete(TempTarget tempTarget) {
try {
getDaoTempTargets().delete(tempTarget);
scheduleTemporaryTargetChange();
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
}
private static void scheduleTemporaryTargetChange() {
class PostRunnable implements Runnable {
public void run() {
log.debug("Firing EventTempTargetChange");
MainApp.bus().post(new EventTempTargetChange());
scheduledTemTargetPost = null;
}
}
// prepare task for execution in 1 sec
// cancel waiting task to prevent sending multiple posts
if (scheduledTemTargetPost != null)
scheduledTemTargetPost.cancel(false);
Runnable task = new PostRunnable();
final int sec = 1;
scheduledTemTargetPost = tempTargetWorker.schedule(task, sec, TimeUnit.SECONDS);
}
/*
{
"_id": "58795998aa86647ba4d68ce7",
"enteredBy": "",
"eventType": "Temporary Target",
"reason": "Eating Soon",
"targetTop": 80,
"targetBottom": 80,
"duration": 120,
"created_at": "2017-01-13T22:50:00.782Z",
"carbs": null,
"insulin": null
}
*/
public void createTemptargetFromJsonIfNotExists(JSONObject trJson) {
try {
String units = MainApp.getConfigBuilder().getProfileUnits();
TempTarget tempTarget = new TempTarget();
tempTarget.date = trJson.getLong("mills");
tempTarget.durationInMinutes = trJson.getInt("duration");
tempTarget.low = Profile.toMgdl(trJson.getDouble("targetBottom"), units);
tempTarget.high = Profile.toMgdl(trJson.getDouble("targetTop"), units);
tempTarget.reason = trJson.getString("reason");
tempTarget._id = trJson.getString("_id");
tempTarget.source = Source.NIGHTSCOUT;
createOrUpdate(tempTarget);
} catch (JSONException e) {
log.error("Unhandled exception", e);
}
}
public void deleteTempTargetById(String _id) {
TempTarget stored = findTempTargetById(_id);
if (stored != null) {
log.debug("TEMPTARGET: Removing TempTarget record from database: " + stored.toString());
delete(stored);
scheduleTemporaryTargetChange();
}
}
public TempTarget findTempTargetById(String _id) {
try {
QueryBuilder<TempTarget, Long> queryBuilder = getDaoTempTargets().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", _id);
PreparedQuery<TempTarget> preparedQuery = queryBuilder.prepare();
List<TempTarget> list = getDaoTempTargets().query(preparedQuery);
if (list.size() == 1) {
return list.get(0);
} else {
return null;
}
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return null;
}
public void createOrUpdate(DanaRHistoryRecord record) {
try {
getDaoDanaRHistory().createOrUpdate(record);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
}
public List<DanaRHistoryRecord> getDanaRHistoryRecordsByType(byte type) {
List<DanaRHistoryRecord> historyList;
try {
QueryBuilder<DanaRHistoryRecord, String> queryBuilder = getDaoDanaRHistory().queryBuilder();
queryBuilder.orderBy("recordDate", false);
Where where = queryBuilder.where();
where.eq("recordCode", type);
queryBuilder.limit(200L);
PreparedQuery<DanaRHistoryRecord> preparedQuery = queryBuilder.prepare();
historyList = getDaoDanaRHistory().query(preparedQuery);
} catch (SQLException e) {
log.error("Unhandled exception", e);
historyList = new ArrayList<>();
}
return historyList;
}
public void updateDanaRHistoryRecordId(JSONObject trJson) {
try {
QueryBuilder<DanaRHistoryRecord, String> queryBuilder = getDaoDanaRHistory().queryBuilder();
Where where = queryBuilder.where();
where.ge("bytes", trJson.get(DanaRNSHistorySync.DANARSIGNATURE));
PreparedQuery<DanaRHistoryRecord> preparedQuery = queryBuilder.prepare();
List<DanaRHistoryRecord> list = getDaoDanaRHistory().query(preparedQuery);
if (list.size() == 0) {
// Record does not exists. Ignore
} else if (list.size() == 1) {
DanaRHistoryRecord record = list.get(0);
if (record._id == null || !record._id.equals(trJson.getString("_id"))) {
if (Config.logIncommingData)
log.debug("Updating _id in DanaR history database: " + trJson.getString("_id"));
record._id = trJson.getString("_id");
getDaoDanaRHistory().update(record);
} else {
// already set
}
}
} catch (SQLException | JSONException e) {
log.error("Unhandled exception", e);
}
}
//return true if new record was created
public boolean createOrUpdate(TemporaryBasal tempBasal) {
try {
TemporaryBasal old;
tempBasal.date = roundDateToSec(tempBasal.date);
if (tempBasal.source == Source.PUMP) {
// check for changed from pump change in NS
QueryBuilder<TemporaryBasal, Long> queryBuilder = getDaoTemporaryBasal().queryBuilder();
Where where = queryBuilder.where();
where.eq("pumpId", tempBasal.pumpId);
PreparedQuery<TemporaryBasal> preparedQuery = queryBuilder.prepare();
List<TemporaryBasal> trList = getDaoTemporaryBasal().query(preparedQuery);
if (trList.size() > 0) {
// do nothing, pump history record cannot be changed
log.debug("TEMPBASAL: Already exists from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString());
return false;
}
getDaoTemporaryBasal().create(tempBasal);
log.debug("TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString());
updateEarliestDataChange(tempBasal.date);
scheduleTemporaryBasalChange();
return true;
}
if (tempBasal.source == Source.NIGHTSCOUT) {
old = getDaoTemporaryBasal().queryForId(tempBasal.date);
if (old != null) {
if (!old.isAbsolute && tempBasal.isAbsolute) { // converted to absolute by "ns_sync_use_absolute"
// so far ignore, do not convert back because it may not be accurate
return false;
}
if (!old.isEqual(tempBasal)) {
long oldDate = old.date;
getDaoTemporaryBasal().delete(old); // need to delete/create because date may change too
old.copyFrom(tempBasal);
getDaoTemporaryBasal().create(old);
log.debug("TEMPBASAL: Updating record by date from: " + Source.getString(tempBasal.source) + " " + old.toString());
updateEarliestDataChange(oldDate);
updateEarliestDataChange(old.date);
scheduleTemporaryBasalChange();
return true;
}
return false;
}
// find by NS _id
if (tempBasal._id != null) {
QueryBuilder<TemporaryBasal, Long> queryBuilder = getDaoTemporaryBasal().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", tempBasal._id);
PreparedQuery<TemporaryBasal> preparedQuery = queryBuilder.prepare();
List<TemporaryBasal> trList = getDaoTemporaryBasal().query(preparedQuery);
if (trList.size() > 0) {
old = trList.get(0);
if (!old.isEqual(tempBasal)) {
long oldDate = old.date;
getDaoTemporaryBasal().delete(old); // need to delete/create because date may change too
old.copyFrom(tempBasal);
getDaoTemporaryBasal().create(old);
log.debug("TEMPBASAL: Updating record by _id from: " + Source.getString(tempBasal.source) + " " + old.toString());
updateEarliestDataChange(oldDate);
updateEarliestDataChange(old.date);
scheduleTemporaryBasalChange();
return true;
}
}
}
getDaoTemporaryBasal().create(tempBasal);
log.debug("TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString());
updateEarliestDataChange(tempBasal.date);
scheduleTemporaryBasalChange();
return true;
}
if (tempBasal.source == Source.USER) {
getDaoTemporaryBasal().create(tempBasal);
log.debug("TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString());
updateEarliestDataChange(tempBasal.date);
scheduleTemporaryBasalChange();
return true;
}
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return false;
}
public void delete(TemporaryBasal tempBasal) {
try {
getDaoTemporaryBasal().delete(tempBasal);
updateEarliestDataChange(tempBasal.date);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
scheduleTemporaryBasalChange();
}
public List<TemporaryBasal> getTemporaryBasalsDataFromTime(long mills, boolean ascending) {
try {
List<TemporaryBasal> tempbasals;
QueryBuilder<TemporaryBasal, Long> queryBuilder = getDaoTemporaryBasal().queryBuilder();
queryBuilder.orderBy("date", ascending);
Where where = queryBuilder.where();
where.ge("date", mills);
PreparedQuery<TemporaryBasal> preparedQuery = queryBuilder.prepare();
tempbasals = getDaoTemporaryBasal().query(preparedQuery);
return tempbasals;
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return new ArrayList<TemporaryBasal>();
}
private static void scheduleTemporaryBasalChange() {
class PostRunnable implements Runnable {
public void run() {
log.debug("Firing EventTempBasalChange");
MainApp.bus().post(new EventReloadTempBasalData());
MainApp.bus().post(new EventTempBasalChange());
if (earliestDataChange != null)
MainApp.bus().post(new EventNewHistoryData(earliestDataChange));
earliestDataChange = null;
scheduledTemBasalsPost = null;
}
}
// prepare task for execution in 1 sec
// cancel waiting task to prevent sending multiple posts
if (scheduledTemBasalsPost != null)
scheduledTemBasalsPost.cancel(false);
Runnable task = new PostRunnable();
final int sec = 1;
scheduledTemBasalsPost = tempBasalsWorker.schedule(task, sec, TimeUnit.SECONDS);
}
/*
{
"_id": "59232e1ddd032d04218dab00",
"eventType": "Temp Basal",
"duration": 60,
"percent": -50,
"created_at": "2017-05-22T18:29:57Z",
"enteredBy": "AndroidAPS",
"notes": "Basal Temp Start 50% 60.0 min",
"NSCLIENT_ID": 1495477797863,
"mills": 1495477797000,
"mgdl": 194.5,
"endmills": 1495481397000
}
*/
public void createTempBasalFromJsonIfNotExists(JSONObject trJson) {
try {
if (trJson.has("originalExtendedAmount")) { // extended bolus uploaded as temp basal
ExtendedBolus extendedBolus = new ExtendedBolus();
extendedBolus.source = Source.NIGHTSCOUT;
extendedBolus.date = trJson.getLong("mills");
extendedBolus.pumpId = trJson.has("pumpId") ? trJson.getLong("pumpId") : 0;
extendedBolus.durationInMinutes = trJson.getInt("duration");
extendedBolus.insulin = trJson.getDouble("originalExtendedAmount");
extendedBolus._id = trJson.getString("_id");
if (!VirtualPumpPlugin.getFakingStatus()) {
VirtualPumpPlugin.setFakingStatus(true);
updateEarliestDataChange(0);
scheduleTemporaryBasalChange();
}
createOrUpdate(extendedBolus);
} else if (trJson.has("isFakedTempBasal")) { // extended bolus end uploaded as temp basal end
ExtendedBolus extendedBolus = new ExtendedBolus();
extendedBolus.source = Source.NIGHTSCOUT;
extendedBolus.date = trJson.getLong("mills");
extendedBolus.pumpId = trJson.has("pumpId") ? trJson.getLong("pumpId") : 0;
extendedBolus.durationInMinutes = 0;
extendedBolus.insulin = 0;
extendedBolus._id = trJson.getString("_id");
if (!VirtualPumpPlugin.getFakingStatus()) {
VirtualPumpPlugin.setFakingStatus(true);
updateEarliestDataChange(0);
scheduleTemporaryBasalChange();
}
createOrUpdate(extendedBolus);
} else {
TemporaryBasal tempBasal = new TemporaryBasal();
tempBasal.date = trJson.getLong("mills");
tempBasal.source = Source.NIGHTSCOUT;
tempBasal.pumpId = trJson.has("pumpId") ? trJson.getLong("pumpId") : 0;
if (trJson.has("duration")) {
tempBasal.durationInMinutes = trJson.getInt("duration");
}
if (trJson.has("percent")) {
tempBasal.percentRate = trJson.getInt("percent") + 100;
tempBasal.isAbsolute = false;
}
if (trJson.has("absolute")) {
tempBasal.absoluteRate = trJson.getDouble("absolute");
tempBasal.isAbsolute = true;
}
tempBasal._id = trJson.getString("_id");
createOrUpdate(tempBasal);
}
} catch (JSONException e) {
log.error("Unhandled exception", e);
}
}
public void deleteTempBasalById(String _id) {
TemporaryBasal stored = findTempBasalById(_id);
if (stored != null) {
log.debug("TEMPBASAL: Removing TempBasal record from database: " + stored.toString());
delete(stored);
updateEarliestDataChange(stored.date);
scheduleTemporaryBasalChange();
}
}
public TemporaryBasal findTempBasalById(String _id) {
try {
QueryBuilder<TemporaryBasal, Long> queryBuilder = null;
queryBuilder = getDaoTemporaryBasal().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", _id);
PreparedQuery<TemporaryBasal> preparedQuery = queryBuilder.prepare();
List<TemporaryBasal> list = getDaoTemporaryBasal().query(preparedQuery);
if (list.size() != 1) {
return null;
} else {
return list.get(0);
}
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return null;
}
public boolean createOrUpdate(ExtendedBolus extendedBolus) {
try {
ExtendedBolus old;
extendedBolus.date = roundDateToSec(extendedBolus.date);
if (extendedBolus.source == Source.PUMP) {
// check for changed from pump change in NS
QueryBuilder<ExtendedBolus, Long> queryBuilder = getDaoExtendedBolus().queryBuilder();
Where where = queryBuilder.where();
where.eq("pumpId", extendedBolus.pumpId);
PreparedQuery<ExtendedBolus> preparedQuery = queryBuilder.prepare();
List<ExtendedBolus> trList = getDaoExtendedBolus().query(preparedQuery);
if (trList.size() > 0) {
// do nothing, pump history record cannot be changed
return false;
}
getDaoExtendedBolus().create(extendedBolus);
log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.toString());
updateEarliestDataChange(extendedBolus.date);
scheduleExtendedBolusChange();
return true;
}
if (extendedBolus.source == Source.NIGHTSCOUT) {
old = getDaoExtendedBolus().queryForId(extendedBolus.date);
if (old != null) {
if (!old.isEqual(extendedBolus)) {
long oldDate = old.date;
getDaoExtendedBolus().delete(old); // need to delete/create because date may change too
old.copyFrom(extendedBolus);
getDaoExtendedBolus().create(old);
log.debug("EXTENDEDBOLUS: Updating record by date from: " + Source.getString(extendedBolus.source) + " " + old.toString());
updateEarliestDataChange(oldDate);
updateEarliestDataChange(old.date);
scheduleExtendedBolusChange();
return true;
}
return false;
}
// find by NS _id
if (extendedBolus._id != null) {
QueryBuilder<ExtendedBolus, Long> queryBuilder = getDaoExtendedBolus().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", extendedBolus._id);
PreparedQuery<ExtendedBolus> preparedQuery = queryBuilder.prepare();
List<ExtendedBolus> trList = getDaoExtendedBolus().query(preparedQuery);
if (trList.size() > 0) {
old = trList.get(0);
if (!old.isEqual(extendedBolus)) {
long oldDate = old.date;
getDaoExtendedBolus().delete(old); // need to delete/create because date may change too
old.copyFrom(extendedBolus);
getDaoExtendedBolus().create(old);
log.debug("EXTENDEDBOLUS: Updating record by _id from: " + Source.getString(extendedBolus.source) + " " + old.toString());
updateEarliestDataChange(oldDate);
updateEarliestDataChange(old.date);
scheduleExtendedBolusChange();
return true;
}
}
}
getDaoExtendedBolus().create(extendedBolus);
log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.toString());
updateEarliestDataChange(extendedBolus.date);
scheduleExtendedBolusChange();
return true;
}
if (extendedBolus.source == Source.USER) {
getDaoExtendedBolus().create(extendedBolus);
log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.toString());
updateEarliestDataChange(extendedBolus.date);
scheduleExtendedBolusChange();
return true;
}
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return false;
}
public void delete(ExtendedBolus extendedBolus) {
try {
getDaoExtendedBolus().delete(extendedBolus);
updateEarliestDataChange(extendedBolus.date);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
scheduleExtendedBolusChange();
}
public List<ExtendedBolus> getExtendedBolusDataFromTime(long mills, boolean ascending) {
try {
List<ExtendedBolus> extendedBoluses;
QueryBuilder<ExtendedBolus, Long> queryBuilder = getDaoExtendedBolus().queryBuilder();
queryBuilder.orderBy("date", ascending);
Where where = queryBuilder.where();
where.ge("date", mills);
PreparedQuery<ExtendedBolus> preparedQuery = queryBuilder.prepare();
extendedBoluses = getDaoExtendedBolus().query(preparedQuery);
return extendedBoluses;
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return new ArrayList<ExtendedBolus>();
}
public void deleteExtendedBolusById(String _id) {
ExtendedBolus stored = findExtendedBolusById(_id);
if (stored != null) {
log.debug("EXTENDEDBOLUS: Removing ExtendedBolus record from database: " + stored.toString());
delete(stored);
updateEarliestDataChange(stored.date);
scheduleExtendedBolusChange();
}
}
public ExtendedBolus findExtendedBolusById(String _id) {
try {
QueryBuilder<ExtendedBolus, Long> queryBuilder = null;
queryBuilder = getDaoExtendedBolus().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", _id);
PreparedQuery<ExtendedBolus> preparedQuery = queryBuilder.prepare();
List<ExtendedBolus> list = getDaoExtendedBolus().query(preparedQuery);
if (list.size() == 1) {
return list.get(0);
} else {
return null;
}
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return null;
}
/*
{
"_id": "5924898d577eb0880e355337",
"eventType": "Combo Bolus",
"duration": 120,
"splitNow": 0,
"splitExt": 100,
"enteredinsulin": 1,
"relative": 1,
"created_at": "2017-05-23T19:12:14Z",
"enteredBy": "AndroidAPS",
"NSCLIENT_ID": 1495566734628,
"mills": 1495566734000,
"mgdl": 106
}
*/
public void createExtendedBolusFromJsonIfNotExists(JSONObject trJson) {
try {
QueryBuilder<ExtendedBolus, Long> queryBuilder = null;
queryBuilder = getDaoExtendedBolus().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", trJson.getString("_id")).or().eq("date", trJson.getLong("mills"));
PreparedQuery<ExtendedBolus> preparedQuery = queryBuilder.prepare();
List<ExtendedBolus> list = getDaoExtendedBolus().query(preparedQuery);
ExtendedBolus extendedBolus;
if (list.size() == 0) {
extendedBolus = new ExtendedBolus();
extendedBolus.source = Source.NIGHTSCOUT;
if (Config.logIncommingData)
log.debug("Adding ExtendedBolus record to database: " + trJson.toString());
// Record does not exists. add
} else if (list.size() == 1) {
extendedBolus = list.get(0);
if (Config.logIncommingData)
log.debug("Updating ExtendedBolus record in database: " + trJson.toString());
} else {
log.error("Something went wrong");
return;
}
extendedBolus.date = trJson.getLong("mills");
extendedBolus.durationInMinutes = trJson.has("duration") ? trJson.getInt("duration") : 0;
extendedBolus.insulin = trJson.getDouble("relative");
extendedBolus._id = trJson.getString("_id");
createOrUpdate(extendedBolus);
} catch (SQLException | JSONException e) {
log.error("Unhandled exception", e);
}
}
private static void scheduleExtendedBolusChange() {
class PostRunnable implements Runnable {
public void run() {
log.debug("Firing EventExtendedBolusChange");
MainApp.bus().post(new EventReloadTreatmentData(new EventExtendedBolusChange()));
if (earliestDataChange != null)
MainApp.bus().post(new EventNewHistoryData(earliestDataChange));
earliestDataChange = null;
scheduledExtendedBolusPost = null;
}
}
// prepare task for execution in 1 sec
// cancel waiting task to prevent sending multiple posts
if (scheduledExtendedBolusPost != null)
scheduledExtendedBolusPost.cancel(false);
Runnable task = new PostRunnable();
final int sec = 1;
scheduledExtendedBolusPost = extendedBolusWorker.schedule(task, sec, TimeUnit.SECONDS);
}
public void createOrUpdate(CareportalEvent careportalEvent) {
careportalEvent.date = careportalEvent.date - careportalEvent.date % 1000;
try {
getDaoCareportalEvents().createOrUpdate(careportalEvent);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
scheduleCareportalEventChange();
}
public void delete(CareportalEvent careportalEvent) {
try {
getDaoCareportalEvents().delete(careportalEvent);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
scheduleCareportalEventChange();
}
@Nullable
public CareportalEvent getLastCareportalEvent(String event) {
try {
List<CareportalEvent> careportalEvents;
QueryBuilder<CareportalEvent, Long> queryBuilder = getDaoCareportalEvents().queryBuilder();
queryBuilder.orderBy("date", false);
Where where = queryBuilder.where();
where.eq("eventType", event);
queryBuilder.limit(1L);
PreparedQuery<CareportalEvent> preparedQuery = queryBuilder.prepare();
careportalEvents = getDaoCareportalEvents().query(preparedQuery);
if (careportalEvents.size() == 1)
return careportalEvents.get(0);
else
return null;
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return null;
}
public List<CareportalEvent> getCareportalEventsFromTime(long mills, boolean ascending) {
try {
List<CareportalEvent> careportalEvents;
QueryBuilder<CareportalEvent, Long> queryBuilder = getDaoCareportalEvents().queryBuilder();
queryBuilder.orderBy("date", ascending);
Where where = queryBuilder.where();
where.ge("date", mills);
PreparedQuery<CareportalEvent> preparedQuery = queryBuilder.prepare();
careportalEvents = getDaoCareportalEvents().query(preparedQuery);
return careportalEvents;
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return new ArrayList<CareportalEvent>();
}
public void deleteCareportalEventById(String _id) {
try {
QueryBuilder<CareportalEvent, Long> queryBuilder = null;
queryBuilder = getDaoCareportalEvents().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", _id);
PreparedQuery<CareportalEvent> preparedQuery = queryBuilder.prepare();
List<CareportalEvent> list = getDaoCareportalEvents().query(preparedQuery);
if (list.size() == 1) {
CareportalEvent record = list.get(0);
if (Config.logIncommingData)
log.debug("Removing CareportalEvent record from database: " + record.log());
delete(record);
} else {
if (Config.logIncommingData)
log.debug("CareportalEvent not found database: " + _id);
}
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
}
public void createCareportalEventFromJsonIfNotExists(JSONObject trJson) {
try {
QueryBuilder<CareportalEvent, Long> queryBuilder = null;
queryBuilder = getDaoCareportalEvents().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", trJson.getString("_id")).or().eq("date", trJson.getLong("mills"));
PreparedQuery<CareportalEvent> preparedQuery = queryBuilder.prepare();
List<CareportalEvent> list = getDaoCareportalEvents().query(preparedQuery);
CareportalEvent careportalEvent;
if (list.size() == 0) {
careportalEvent = new CareportalEvent();
careportalEvent.source = Source.NIGHTSCOUT;
if (Config.logIncommingData)
log.debug("Adding CareportalEvent record to database: " + trJson.toString());
// Record does not exists. add
} else if (list.size() == 1) {
careportalEvent = list.get(0);
if (Config.logIncommingData)
log.debug("Updating CareportalEvent record in database: " + trJson.toString());
} else {
log.error("Something went wrong");
return;
}
careportalEvent.date = trJson.getLong("mills");
careportalEvent.eventType = trJson.getString("eventType");
careportalEvent.json = trJson.toString();
careportalEvent._id = trJson.getString("_id");
createOrUpdate(careportalEvent);
} catch (SQLException | JSONException e) {
log.error("Unhandled exception", e);
}
}
private static void scheduleCareportalEventChange() {
class PostRunnable implements Runnable {
public void run() {
log.debug("Firing scheduleCareportalEventChange");
MainApp.bus().post(new EventCareportalEventChange());
scheduledCareportalEventPost = null;
}
}
// prepare task for execution in 1 sec
// cancel waiting task to prevent sending multiple posts
if (scheduledCareportalEventPost != null)
scheduledCareportalEventPost.cancel(false);
Runnable task = new PostRunnable();
final int sec = 1;
scheduledCareportalEventPost = careportalEventWorker.schedule(task, sec, TimeUnit.SECONDS);
}
public List<ProfileSwitch> getProfileSwitchData(boolean ascending) {
try {
Dao<ProfileSwitch, Long> daoProfileSwitch = getDaoProfileSwitch();
List<ProfileSwitch> profileSwitches;
QueryBuilder<ProfileSwitch, Long> queryBuilder = daoProfileSwitch.queryBuilder();
queryBuilder.orderBy("date", ascending);
queryBuilder.limit(20L);
PreparedQuery<ProfileSwitch> preparedQuery = queryBuilder.prepare();
profileSwitches = daoProfileSwitch.query(preparedQuery);
return profileSwitches;
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return new ArrayList<ProfileSwitch>();
}
public boolean createOrUpdate(ProfileSwitch profileSwitch) {
try {
ProfileSwitch old;
profileSwitch.date = roundDateToSec(profileSwitch.date);
if (profileSwitch.source == Source.NIGHTSCOUT) {
old = getDaoProfileSwitch().queryForId(profileSwitch.date);
if (old != null) {
if (!old.isEqual(profileSwitch)) {
profileSwitch.source = old.source;
profileSwitch.profileName = old.profileName; // preserver profileName to prevent multiple CPP extension
getDaoProfileSwitch().delete(old); // need to delete/create because date may change too
getDaoProfileSwitch().create(profileSwitch);
log.debug("PROFILESWITCH: Updating record by date from: " + Source.getString(profileSwitch.source) + " " + old.toString());
scheduleProfileSwitchChange();
return true;
}
return false;
}
// find by NS _id
if (profileSwitch._id != null) {
QueryBuilder<ProfileSwitch, Long> queryBuilder = getDaoProfileSwitch().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", profileSwitch._id);
PreparedQuery<ProfileSwitch> preparedQuery = queryBuilder.prepare();
List<ProfileSwitch> trList = getDaoProfileSwitch().query(preparedQuery);
if (trList.size() > 0) {
old = trList.get(0);
if (!old.isEqual(profileSwitch)) {
getDaoProfileSwitch().delete(old); // need to delete/create because date may change too
old.copyFrom(profileSwitch);
getDaoProfileSwitch().create(old);
log.debug("PROFILESWITCH: Updating record by _id from: " + Source.getString(profileSwitch.source) + " " + old.toString());
scheduleProfileSwitchChange();
return true;
}
}
}
getDaoProfileSwitch().create(profileSwitch);
log.debug("PROFILESWITCH: New record from: " + Source.getString(profileSwitch.source) + " " + profileSwitch.toString());
scheduleProfileSwitchChange();
return true;
}
if (profileSwitch.source == Source.USER) {
getDaoProfileSwitch().create(profileSwitch);
log.debug("PROFILESWITCH: New record from: " + Source.getString(profileSwitch.source) + " " + profileSwitch.toString());
scheduleProfileSwitchChange();
return true;
}
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return false;
}
public void delete(ProfileSwitch profileSwitch) {
try {
getDaoProfileSwitch().delete(profileSwitch);
scheduleProfileSwitchChange();
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
}
private static void scheduleProfileSwitchChange() {
class PostRunnable implements Runnable {
public void run() {
log.debug("Firing EventProfileSwitchChange");
MainApp.bus().post(new EventReloadProfileSwitchData());
MainApp.bus().post(new EventProfileSwitchChange());
scheduledProfileSwitchEventPost = null;
}
}
// prepare task for execution in 1 sec
// cancel waiting task to prevent sending multiple posts
if (scheduledProfileSwitchEventPost != null)
scheduledProfileSwitchEventPost.cancel(false);
Runnable task = new PostRunnable();
final int sec = 1;
scheduledProfileSwitchEventPost = profileSwitchEventWorker.schedule(task, sec, TimeUnit.SECONDS);
}
/*
{
"_id":"592fa43ed97496a80da913d2",
"created_at":"2017-06-01T05:20:06Z",
"eventType":"Profile Switch",
"profile":"2016 +30%",
"units":"mmol",
"enteredBy":"sony",
"NSCLIENT_ID":1496294454309,
}
*/
public void createProfileSwitchFromJsonIfNotExists(JSONObject trJson) {
try {
ProfileSwitch profileSwitch = new ProfileSwitch();
profileSwitch.date = trJson.getLong("mills");
if (trJson.has("duration"))
profileSwitch.durationInMinutes = trJson.getInt("duration");
profileSwitch._id = trJson.getString("_id");
profileSwitch.profileName = trJson.getString("profile");
profileSwitch.isCPP = trJson.has("CircadianPercentageProfile");
profileSwitch.source = Source.NIGHTSCOUT;
if (trJson.has("timeshift"))
profileSwitch.timeshift = trJson.getInt("timeshift");
if (trJson.has("percentage"))
profileSwitch.percentage = trJson.getInt("percentage");
if (trJson.has("profileJson"))
profileSwitch.profileJson = trJson.getString("profileJson");
if (trJson.has("profilePlugin"))
profileSwitch.profilePlugin = trJson.getString("profilePlugin");
createOrUpdate(profileSwitch);
} catch (JSONException e) {
log.error("Unhandled exception", e);
}
}
public void deleteProfileSwitchById(String _id) {
ProfileSwitch stored = findProfileSwitchById(_id);
if (stored != null) {
log.debug("PROFILESWITCH: Removing ProfileSwitch record from database: " + stored.toString());
delete(stored);
scheduleTemporaryTargetChange();
}
}
public ProfileSwitch findProfileSwitchById(String _id) {
try {
QueryBuilder<ProfileSwitch, Long> queryBuilder = getDaoProfileSwitch().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", _id);
PreparedQuery<ProfileSwitch> preparedQuery = queryBuilder.prepare();
List<ProfileSwitch> list = getDaoProfileSwitch().query(preparedQuery);
if (list.size() == 1) {
return list.get(0);
} else {
return null;
}
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return null;
}
}
|
package com.clust4j.algo;
import org.junit.Test;
import com.clust4j.algo.ParallelChunkingTask.ChunkingStrategy;
import com.clust4j.algo.ParallelChunkingTask.SimpleChunkingStrategy;
import com.clust4j.algo.ParallelChunkingTask.CoreRestrictiveChunkingStrategy;
import com.clust4j.utils.MatUtils;
public class ParallelTaskTests {
@Test
public void test() {
double[][] X = MatUtils.randomGaussian(750, 2);
ChunkingStrategy strat = new SimpleChunkingStrategy();
strat.map(X); // want to make sure it works.
strat = new CoreRestrictiveChunkingStrategy(1);
strat.map(X);
}
}
|
package nanomsg;
import java.nio.charset.Charset;
import com.sun.jna.Pointer;
import com.sun.jna.Memory;
import com.sun.jna.Native;
import com.sun.jna.ptr.PointerByReference;
import com.sun.jna.ptr.IntByReference;
import nanomsg.NativeLibrary;
import nanomsg.Nanomsg;
import nanomsg.Message;
import nanomsg.ISocket;
import nanomsg.exceptions.IOException;
public abstract class Socket implements ISocket {
private final int domain;
private final int protocol;
private final int socket;
private boolean closed = false;
private boolean opened = false;
public Socket(final int domain, final int protocol) {
this.domain = domain;
this.protocol = protocol;
this.socket = NativeLibrary.nn_socket(domain, protocol);
this.opened = true;
this.setSendTimeout(10000);
this.setRecvTimeout(10000);
}
public void close() throws IOException {
if (this.opened && !this.closed) {
this.closed = true;
final int rc = NativeLibrary.nn_close(this.socket);
if (rc < 0) {
final int errno = Nanomsg.getErrorNumber();
final String msg = Nanomsg.getError();
throw new IOException(msg, errno);
}
}
}
public int getNativeSocket() {
return this.socket;
}
public void bind(final String dir) throws IOException {
final int rc = NativeLibrary.nn_bind(this.socket, dir);
if (rc < 0) {
final int errno = Nanomsg.getErrorNumber();
final String msg = Nanomsg.getError();
throw new IOException(msg, errno);
}
}
public void connect(final String dir) throws IOException {
final int rc = NativeLibrary.nn_connect(this.socket, dir);
if (rc < 0) {
final int errno = Nanomsg.getErrorNumber();
final String msg = Nanomsg.getError();
throw new IOException(msg, errno);
}
}
/**
* Send string to socket with option to set blocking flag.
*
* @param data string value that represents a message.
* @param blocking set blocking or non blocking flag.
* @return number of sended bytes.
*/
public int sendString(final String data, final boolean blocking) throws IOException {
final Charset encoding = Charset.forName("UTF-8");
return this.sendBytes(data.getBytes(encoding), blocking);
}
/**
* Send string to socket.
*
* This operation is blocking by default.
*
* @param data string value that represents a message.
* @return number of sended bytes.
*/
public int sendString(final String data) throws IOException {
return this.sendString(data, true);
}
/**
* Send bytes array to socket with option to set blocking flag.
*
* @param data a bytes array that represents a message.
* @param blocking set blocking or non blocking flag.
* @return number of sended bytes.
*/
public synchronized int sendBytes(final byte[] data, final boolean blocking) throws IOException {
final int socket = getNativeSocket();
final int rc = NativeLibrary.nn_send(socket, data, data.length, blocking ? 0 : Nanomsg.constants.NN_DONTWAIT);
if (rc < 0) {
final int errno = Nanomsg.getErrorNumber();
final String msg = Nanomsg.getError();
throw new IOException(msg, errno);
}
return rc;
}
/**
* Send bytes array to socket.
*
* This operation is blocking by default.
*
* @param data a bytes array that represents a message.
* @return number of sended bytes.
*/
public int sendBytes(final byte[] data) throws IOException {
return this.sendBytes(data, true);
}
/**
* Receive message from socket as string with option for set blocking flag.
*
* This method uses utf-8 encoding for converts a bytes array
* to string.
*
* @param blocking set blocking or non blocking flag.
* @return receved data as unicode string.
*/
public String recvString(final boolean blocking) throws IOException {
final byte[] received = this.recvBytes(blocking);
final Charset encoding = Charset.forName("UTF-8");
return new String(received, encoding);
}
/**
* Receive message from socket as string.
*
* This method uses utf-8 encoding for converts a bytes array
* to string.
*
* @return receved data as unicode string.
*/
public String recvString() throws IOException {
return this.recvString(true);
}
/**
* Receive message from socket as bytes array with option for set blocking flag.
*
* @param blocking set blocking or non blocking flag.
* @return receved data as bytes array
*/
public synchronized byte[] recvBytes(boolean blocking) throws IOException {
final PointerByReference ptrBuff = new PointerByReference();
final int socket = getNativeSocket();
final int received = NativeLibrary.nn_recv(socket, ptrBuff, Nanomsg.constants.NN_MSG, blocking ? 0: Nanomsg.constants.NN_DONTWAIT);
if (received < 0) {
final int errno = Nanomsg.getErrorNumber();
final String msg = Nanomsg.getError();
throw new IOException(msg, errno);
}
final Pointer result = ptrBuff.getValue();
final byte[] bytesResult = result.getByteArray(0, received);
NativeLibrary.nn_freemsg(result);
return bytesResult;
}
/**
* Receive message from socket as bytes array.
*
* This operation is blocking by default.
*
* @return receved data as bytes array
*/
public byte[] recvBytes() throws IOException {
return this.recvBytes(true);
}
/**
* High level function for send a message.
*
* This operation is blocking by default.
*
* @return number of sended bytes.
*/
public int send(final Message msg) throws IOException {
return sendBytes(msg.toBytes());
}
/**
* High level function for send a message with option for set blocking flag.
*
* @param blocking set blocking or non blocking flag.
* @return number of sended bytes.
*/
public int send(final Message msg, boolean blocking) throws IOException {
return sendBytes(msg.toBytes(), blocking);
}
/**
* High level function for receive message.
*
* This operation is blocking by default.
*
* @return Message instance.
*/
public Message recv() throws IOException {
return new Message(recvBytes());
}
/**
* High level function for receive message with option for set blocking flag.
*
* @param blocking set blocking or non blocking flag.
* @return Message instance.
*/
public Message recv(final boolean blocking) throws IOException {
return new Message(recvBytes(blocking));
}
public void subscribe(final String data) throws IOException {
throw new UnsupportedOperationException("This socket can not support subscribe method.");
}
public int getFd(final int flag) throws IOException {
final IntByReference fd = new IntByReference();
final IntByReference size_t = new IntByReference(Native.SIZE_T_SIZE);
final int rc = NativeLibrary.nn_getsockopt(this.socket, Nanomsg.constants.NN_SOL_SOCKET, flag, fd.getPointer(), size_t.getPointer());
if (rc < 0) {
throw new IOException(Nanomsg.getError());
}
if (rc < 0) {
final int errno = Nanomsg.getErrorNumber();
final String msg = Nanomsg.getError();
throw new IOException(msg, errno);
}
return fd.getValue();
}
public void setSendTimeout(final int milis) {
final int socket = getNativeSocket();
/* IntByReference timeout = new IntByReference(milis); */
/* Pointer ptr = timeout.getPointer(); */
Memory ptr = new Memory(Native.LONG_SIZE/2);
ptr.setInt(0, milis);
final int rc = NativeLibrary.nn_setsockopt(socket, Nanomsg.constants.NN_SOL_SOCKET, Nanomsg.constants.NN_SNDTIMEO, ptr, Native.LONG_SIZE/2);
/* if (rc < 0) { */
/* final int errno = Nanomsg.getErrorNumber(); */
/* final String msg = Nanomsg.getError(); */
/* throw new IOException(msg, errno); */
}
public void setRecvTimeout(int milis) {
final int socket = getNativeSocket();
Memory ptr = new Memory(Native.LONG_SIZE/2);
ptr.setInt(0, milis);
final int rc = NativeLibrary.nn_setsockopt(socket, Nanomsg.constants.NN_SOL_SOCKET, Nanomsg.constants.NN_RCVTIMEO, ptr, Native.LONG_SIZE/2);
/* if (rc < 0) { */
/* final int errno = Nanomsg.getErrorNumber(); */
/* final String msg = Nanomsg.getError(); */
/* throw new IOException(msg, errno); */
}
}
|
package com.tngtech.jenkins.notification;
import com.tngtech.jenkins.notification.camel.CamelApplication;
import com.tngtech.jenkins.notification.endpoints.MissileEndpoint;
import com.tngtech.jenkins.notification.endpoints.TtsEndpoint;
import com.tngtech.jenkins.notification.model.Config;
import com.tngtech.missile.usb.MissileController;
import com.tngtech.missile.usb.MissileLauncher;
import org.apache.commons.lang.ArrayUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Bootstrap {
public static void main(String[] args) throws Exception {
Config config = new ConfigLoader().load();
String command = args[0];
if (args.length == 1) {
switch (command) {
case "fire":
getMissileController().fire();
break;
case "ledOn":
getMissileController().ledOn();
break;
case "ledOff":
getMissileController().ledOff();
break;
case "stalk":
new CamelApplication(config).run();
break;
default:
throw new IllegalArgumentException("Could not parse commandline");
}
}
if (args.length >= 2) {
switch (command) {
case "shootAt":
MissileEndpoint missileEndpoint = new MissileEndpoint(config.getMissile());
List<String> culprits = new ArrayList<>();
culprits.addAll(Arrays.asList(args).subList(1, args.length));
missileEndpoint.shootAt(culprits);
break;
case "say":
TtsEndpoint ttsEndpoint = new TtsEndpoint(config.getTts());
List<String> words = new ArrayList<>(Arrays.asList(args));
words.remove(0);
ttsEndpoint.say(words);
break;
default:
MissileLauncher.Command direction =
MissileLauncher.Command.valueOf(args[0].toUpperCase());
int time = Integer.parseInt(args[1]);
getMissileController().move(direction, time);
break;
}
}
}
private static MissileController getMissileController() throws Exception {
return new MissileController(MissileLauncher.findMissileLauncher());
}
}
|
package info.nightscout.androidaps.db;
import android.content.Context;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.support.annotation.Nullable;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.CloseableIterator;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.PreparedQuery;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.Where;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.data.OverlappingIntervals;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.ProfileStore;
import info.nightscout.androidaps.events.EventCareportalEventChange;
import info.nightscout.androidaps.events.EventExtendedBolusChange;
import info.nightscout.androidaps.events.EventNewBG;
import info.nightscout.androidaps.events.EventProfileNeedsUpdate;
import info.nightscout.androidaps.events.EventRefreshOverview;
import info.nightscout.androidaps.events.EventReloadProfileSwitchData;
import info.nightscout.androidaps.events.EventReloadTempBasalData;
import info.nightscout.androidaps.events.EventReloadTreatmentData;
import info.nightscout.androidaps.events.EventTempBasalChange;
import info.nightscout.androidaps.events.EventTempTargetChange;
import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventNewHistoryData;
import info.nightscout.androidaps.plugins.pump.danaR.activities.DanaRNSHistorySync;
import info.nightscout.androidaps.plugins.pump.danaR.comm.RecordTypes;
import info.nightscout.androidaps.plugins.pump.insight.database.InsightBolusID;
import info.nightscout.androidaps.plugins.pump.insight.database.InsightHistoryOffset;
import info.nightscout.androidaps.plugins.pump.insight.database.InsightPumpID;
import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin;
import info.nightscout.androidaps.utils.JsonHelper;
import info.nightscout.androidaps.utils.PercentageSplitter;
import info.nightscout.androidaps.utils.ToastUtils;
/**
* This Helper contains all resource to provide a central DB management functionality. Only methods handling
* data-structure (and not the DB content) should be contained in here (meaning DDL and not SQL).
* <p>
* This class can safely be called from Services, but should not call Services to avoid circular dependencies.
* One major issue with this (right now) are the scheduled events, which are put into the service. Therefor all
* direct calls to the corresponding methods (eg. resetDatabases) should be done by a central service.
*/
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static Logger log = LoggerFactory.getLogger(L.DATABASE);
public static final String DATABASE_NAME = "AndroidAPSDb";
public static final String DATABASE_BGREADINGS = "BgReadings";
public static final String DATABASE_TEMPORARYBASALS = "TemporaryBasals";
public static final String DATABASE_EXTENDEDBOLUSES = "ExtendedBoluses";
public static final String DATABASE_TEMPTARGETS = "TempTargets";
public static final String DATABASE_DANARHISTORY = "DanaRHistory";
public static final String DATABASE_DBREQUESTS = "DBRequests";
public static final String DATABASE_CAREPORTALEVENTS = "CareportalEvents";
public static final String DATABASE_PROFILESWITCHES = "ProfileSwitches";
public static final String DATABASE_TDDS = "TDDs";
public static final String DATABASE_INSIGHT_HISTORY_OFFSETS = "InsightHistoryOffsets";
public static final String DATABASE_INSIGHT_BOLUS_IDS = "InsightBolusIDs";
public static final String DATABASE_INSIGHT_PUMP_IDS = "InsightPumpIDs";
private static final int DATABASE_VERSION = 11;
public static Long earliestDataChange = null;
private static final ScheduledExecutorService bgWorker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture<?> scheduledBgPost = null;
private static final ScheduledExecutorService tempBasalsWorker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture<?> scheduledTemBasalsPost = null;
private static final ScheduledExecutorService tempTargetWorker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture<?> scheduledTemTargetPost = null;
private static final ScheduledExecutorService extendedBolusWorker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture<?> scheduledExtendedBolusPost = null;
private static final ScheduledExecutorService careportalEventWorker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture<?> scheduledCareportalEventPost = null;
private static final ScheduledExecutorService profileSwitchEventWorker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture<?> scheduledProfileSwitchEventPost = null;
private int oldVersion = 0;
private int newVersion = 0;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
onCreate(getWritableDatabase(), getConnectionSource());
//onUpgrade(getWritableDatabase(), getConnectionSource(), 1,1);
}
@Override
public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
try {
if (L.isEnabled(L.DATABASE))
log.info("onCreate");
TableUtils.createTableIfNotExists(connectionSource, TempTarget.class);
TableUtils.createTableIfNotExists(connectionSource, BgReading.class);
TableUtils.createTableIfNotExists(connectionSource, DanaRHistoryRecord.class);
TableUtils.createTableIfNotExists(connectionSource, DbRequest.class);
TableUtils.createTableIfNotExists(connectionSource, TemporaryBasal.class);
TableUtils.createTableIfNotExists(connectionSource, ExtendedBolus.class);
TableUtils.createTableIfNotExists(connectionSource, CareportalEvent.class);
TableUtils.createTableIfNotExists(connectionSource, ProfileSwitch.class);
TableUtils.createTableIfNotExists(connectionSource, TDD.class);
TableUtils.createTableIfNotExists(connectionSource, InsightHistoryOffset.class);
TableUtils.createTableIfNotExists(connectionSource, InsightBolusID.class);
TableUtils.createTableIfNotExists(connectionSource, InsightPumpID.class);
database.execSQL("INSERT INTO sqlite_sequence (name, seq) SELECT \"" + DATABASE_INSIGHT_BOLUS_IDS + "\", " + System.currentTimeMillis() + " " +
"WHERE NOT EXISTS (SELECT 1 FROM sqlite_sequence WHERE name = \"" + DATABASE_INSIGHT_BOLUS_IDS + "\")");
database.execSQL("INSERT INTO sqlite_sequence (name, seq) SELECT \"" + DATABASE_INSIGHT_PUMP_IDS + "\", " + System.currentTimeMillis() + " " +
"WHERE NOT EXISTS (SELECT 1 FROM sqlite_sequence WHERE name = \"" + DATABASE_INSIGHT_PUMP_IDS + "\")");
} catch (SQLException e) {
log.error("Can't create database", e);
throw new RuntimeException(e);
}
}
@Override
public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
try {
this.oldVersion = oldVersion;
this.newVersion = newVersion;
if (oldVersion < 7) {
log.info(DatabaseHelper.class.getName(), "onUpgrade");
TableUtils.dropTable(connectionSource, TempTarget.class, true);
TableUtils.dropTable(connectionSource, BgReading.class, true);
TableUtils.dropTable(connectionSource, DanaRHistoryRecord.class, true);
TableUtils.dropTable(connectionSource, DbRequest.class, true);
TableUtils.dropTable(connectionSource, TemporaryBasal.class, true);
TableUtils.dropTable(connectionSource, ExtendedBolus.class, true);
TableUtils.dropTable(connectionSource, CareportalEvent.class, true);
TableUtils.dropTable(connectionSource, ProfileSwitch.class, true);
onCreate(database, connectionSource);
} else if (oldVersion < 10) {
TableUtils.createTableIfNotExists(connectionSource, InsightHistoryOffset.class);
TableUtils.createTableIfNotExists(connectionSource, InsightBolusID.class);
TableUtils.createTableIfNotExists(connectionSource, InsightPumpID.class);
database.execSQL("INSERT INTO sqlite_sequence (name, seq) SELECT \"" + DATABASE_INSIGHT_BOLUS_IDS + "\", " + System.currentTimeMillis() + " " +
"WHERE NOT EXISTS (SELECT 1 FROM sqlite_sequence WHERE name = \"" + DATABASE_INSIGHT_BOLUS_IDS + "\")");
database.execSQL("INSERT INTO sqlite_sequence (name, seq) SELECT \"" + DATABASE_INSIGHT_PUMP_IDS + "\", " + System.currentTimeMillis() + " " +
"WHERE NOT EXISTS (SELECT 1 FROM sqlite_sequence WHERE name = \"" + DATABASE_INSIGHT_PUMP_IDS + "\")");
} else if (oldVersion < 11) {
database.execSQL("UPDATE sqlite_sequence SET seq = " + System.currentTimeMillis() + " WHERE name = \"" + DATABASE_INSIGHT_BOLUS_IDS + "\"");
database.execSQL("UPDATE sqlite_sequence SET seq = " + System.currentTimeMillis() + " WHERE name = \"" + DATABASE_INSIGHT_PUMP_IDS + "\"");
}
} catch (SQLException e) {
log.error("Can't drop databases", e);
throw new RuntimeException(e);
}
}
@Override
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
log.info("Do nothing for downgrading...");
log.debug("oldVersion: {}, newVersion: {}", oldVersion, newVersion);
}
public int getOldVersion() {
return oldVersion;
}
public int getNewVersion() {
return newVersion;
}
/**
* Close the database connections and clear any cached DAOs.
*/
@Override
public void close() {
super.close();
}
public long size(String database) {
return DatabaseUtils.queryNumEntries(getReadableDatabase(), database);
}
public void resetDatabases() {
try {
TableUtils.dropTable(connectionSource, TempTarget.class, true);
TableUtils.dropTable(connectionSource, BgReading.class, true);
TableUtils.dropTable(connectionSource, DanaRHistoryRecord.class, true);
TableUtils.dropTable(connectionSource, DbRequest.class, true);
TableUtils.dropTable(connectionSource, TemporaryBasal.class, true);
TableUtils.dropTable(connectionSource, ExtendedBolus.class, true);
TableUtils.dropTable(connectionSource, CareportalEvent.class, true);
TableUtils.dropTable(connectionSource, ProfileSwitch.class, true);
TableUtils.dropTable(connectionSource, TDD.class, true);
TableUtils.createTableIfNotExists(connectionSource, TempTarget.class);
TableUtils.createTableIfNotExists(connectionSource, BgReading.class);
TableUtils.createTableIfNotExists(connectionSource, DanaRHistoryRecord.class);
TableUtils.createTableIfNotExists(connectionSource, DbRequest.class);
TableUtils.createTableIfNotExists(connectionSource, TemporaryBasal.class);
TableUtils.createTableIfNotExists(connectionSource, ExtendedBolus.class);
TableUtils.createTableIfNotExists(connectionSource, CareportalEvent.class);
TableUtils.createTableIfNotExists(connectionSource, ProfileSwitch.class);
TableUtils.createTableIfNotExists(connectionSource, TDD.class);
updateEarliestDataChange(0);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
VirtualPumpPlugin.getPlugin().setFakingStatus(true);
scheduleBgChange(null); // trigger refresh
scheduleTemporaryBasalChange();
scheduleExtendedBolusChange();
scheduleTemporaryTargetChange();
scheduleCareportalEventChange();
scheduleProfileSwitchChange();
new java.util.Timer().schedule(
new java.util.TimerTask() {
@Override
public void run() {
MainApp.bus().post(new EventRefreshOverview("resetDatabases"));
}
},
3000
);
}
public void resetTempTargets() {
try {
TableUtils.dropTable(connectionSource, TempTarget.class, true);
TableUtils.createTableIfNotExists(connectionSource, TempTarget.class);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
scheduleTemporaryTargetChange();
}
public void resetTemporaryBasals() {
try {
TableUtils.dropTable(connectionSource, TemporaryBasal.class, true);
TableUtils.createTableIfNotExists(connectionSource, TemporaryBasal.class);
updateEarliestDataChange(0);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
VirtualPumpPlugin.getPlugin().setFakingStatus(false);
scheduleTemporaryBasalChange();
}
public void resetExtededBoluses() {
try {
TableUtils.dropTable(connectionSource, ExtendedBolus.class, true);
TableUtils.createTableIfNotExists(connectionSource, ExtendedBolus.class);
updateEarliestDataChange(0);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
scheduleExtendedBolusChange();
}
public void resetCareportalEvents() {
try {
TableUtils.dropTable(connectionSource, CareportalEvent.class, true);
TableUtils.createTableIfNotExists(connectionSource, CareportalEvent.class);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
scheduleCareportalEventChange();
}
public void resetProfileSwitch() {
try {
TableUtils.dropTable(connectionSource, ProfileSwitch.class, true);
TableUtils.createTableIfNotExists(connectionSource, ProfileSwitch.class);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
scheduleProfileSwitchChange();
}
public void resetTDDs() {
try {
TableUtils.dropTable(connectionSource, TDD.class, true);
TableUtils.createTableIfNotExists(connectionSource, TDD.class);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
}
private Dao<TempTarget, Long> getDaoTempTargets() throws SQLException {
return getDao(TempTarget.class);
}
private Dao<BgReading, Long> getDaoBgReadings() throws SQLException {
return getDao(BgReading.class);
}
private Dao<DanaRHistoryRecord, String> getDaoDanaRHistory() throws SQLException {
return getDao(DanaRHistoryRecord.class);
}
private Dao<TDD, String> getDaoTDD() throws SQLException {
return getDao(TDD.class);
}
private Dao<DbRequest, String> getDaoDbRequest() throws SQLException {
return getDao(DbRequest.class);
}
private Dao<TemporaryBasal, Long> getDaoTemporaryBasal() throws SQLException {
return getDao(TemporaryBasal.class);
}
private Dao<ExtendedBolus, Long> getDaoExtendedBolus() throws SQLException {
return getDao(ExtendedBolus.class);
}
private Dao<CareportalEvent, Long> getDaoCareportalEvents() throws SQLException {
return getDao(CareportalEvent.class);
}
private Dao<ProfileSwitch, Long> getDaoProfileSwitch() throws SQLException {
return getDao(ProfileSwitch.class);
}
private Dao<InsightPumpID, Long> getDaoInsightPumpID() throws SQLException {
return getDao(InsightPumpID.class);
}
private Dao<InsightBolusID, Long> getDaoInsightBolusID() throws SQLException {
return getDao(InsightBolusID.class);
}
private Dao<InsightHistoryOffset, String> getDaoInsightHistoryOffset() throws SQLException {
return getDao(InsightHistoryOffset.class);
}
public static long roundDateToSec(long date) {
long rounded = date - date % 1000;
if (rounded != date)
if (L.isEnabled(L.DATABASE))
log.debug("Rounding " + date + " to " + rounded);
return rounded;
}
public boolean createIfNotExists(BgReading bgReading, String from) {
try {
bgReading.date = roundDateToSec(bgReading.date);
BgReading old = getDaoBgReadings().queryForId(bgReading.date);
if (old == null) {
getDaoBgReadings().create(bgReading);
if (L.isEnabled(L.DATABASE))
log.debug("BG: New record from: " + from + " " + bgReading.toString());
scheduleBgChange(bgReading);
return true;
}
if (!old.isEqual(bgReading)) {
if (L.isEnabled(L.DATABASE))
log.debug("BG: Similiar found: " + old.toString());
old.copyFrom(bgReading);
getDaoBgReadings().update(old);
if (L.isEnabled(L.DATABASE))
log.debug("BG: Updating record from: " + from + " New data: " + old.toString());
scheduleBgChange(bgReading);
return false;
}
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return false;
}
public void update(BgReading bgReading) {
bgReading.date = roundDateToSec(bgReading.date);
try {
getDaoBgReadings().update(bgReading);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
}
private static void scheduleBgChange(@Nullable final BgReading bgReading) {
class PostRunnable implements Runnable {
public void run() {
if (L.isEnabled(L.DATABASE))
log.debug("Firing EventNewBg");
MainApp.bus().post(new EventNewBG(bgReading));
scheduledBgPost = null;
}
}
// prepare task for execution in 1 sec
// cancel waiting task to prevent sending multiple posts
if (scheduledBgPost != null)
scheduledBgPost.cancel(false);
Runnable task = new PostRunnable();
final int sec = 1;
scheduledBgPost = bgWorker.schedule(task, sec, TimeUnit.SECONDS);
}
/*
* Return last BgReading from database or null if db is empty
*/
@Nullable
public static BgReading lastBg() {
List<BgReading> bgList = IobCobCalculatorPlugin.getPlugin().getBgReadings();
if (bgList == null)
return null;
for (int i = 0; i < bgList.size(); i++)
if (bgList.get(i).value > 39)
return bgList.get(i);
return null;
}
/*
* Return bg reading if not old ( <9 min )
* or null if older
*/
@Nullable
public static BgReading actualBg() {
BgReading lastBg = lastBg();
if (lastBg == null)
return null;
if (lastBg.date > System.currentTimeMillis() - 9 * 60 * 1000)
return lastBg;
return null;
}
public List<BgReading> getBgreadingsDataFromTime(long mills, boolean ascending) {
try {
Dao<BgReading, Long> daoBgreadings = getDaoBgReadings();
List<BgReading> bgReadings;
QueryBuilder<BgReading, Long> queryBuilder = daoBgreadings.queryBuilder();
queryBuilder.orderBy("date", ascending);
Where where = queryBuilder.where();
where.ge("date", mills).and().ge("value", 39).and().eq("isValid", true);
PreparedQuery<BgReading> preparedQuery = queryBuilder.prepare();
bgReadings = daoBgreadings.query(preparedQuery);
return bgReadings;
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return new ArrayList<>();
}
public List<BgReading> getBgreadingsDataFromTime(long start, long end, boolean ascending) {
try {
Dao<BgReading, Long> daoBgreadings = getDaoBgReadings();
List<BgReading> bgReadings;
QueryBuilder<BgReading, Long> queryBuilder = daoBgreadings.queryBuilder();
queryBuilder.orderBy("date", ascending);
Where where = queryBuilder.where();
where.between("date", start, end).and().ge("value", 39).and().eq("isValid", true);
PreparedQuery<BgReading> preparedQuery = queryBuilder.prepare();
bgReadings = daoBgreadings.query(preparedQuery);
return bgReadings;
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return new ArrayList<>();
}
public List<BgReading> getAllBgreadingsDataFromTime(long mills, boolean ascending) {
try {
Dao<BgReading, Long> daoBgreadings = getDaoBgReadings();
List<BgReading> bgReadings;
QueryBuilder<BgReading, Long> queryBuilder = daoBgreadings.queryBuilder();
queryBuilder.orderBy("date", ascending);
Where where = queryBuilder.where();
where.ge("date", mills);
PreparedQuery<BgReading> preparedQuery = queryBuilder.prepare();
bgReadings = daoBgreadings.query(preparedQuery);
return bgReadings;
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return new ArrayList<BgReading>();
}
public void createOrUpdateTDD(TDD tdd) {
try {
Dao<TDD, String> dao = getDaoTDD();
dao.createOrUpdate(tdd);
} catch (SQLException e) {
ToastUtils.showToastInUiThread(MainApp.instance(), "createOrUpdate-Exception");
log.error("Unhandled exception", e);
}
}
public List<TDD> getTDDs() {
List<TDD> tddList;
try {
QueryBuilder<TDD, String> queryBuilder = getDaoTDD().queryBuilder();
queryBuilder.orderBy("date", false);
queryBuilder.limit(10L);
PreparedQuery<TDD> preparedQuery = queryBuilder.prepare();
tddList = getDaoTDD().query(preparedQuery);
} catch (SQLException e) {
log.error("Unhandled exception", e);
tddList = new ArrayList<>();
}
return tddList;
}
public void create(DbRequest dbr) {
try {
getDaoDbRequest().create(dbr);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
}
public int delete(DbRequest dbr) {
try {
return getDaoDbRequest().delete(dbr);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return 0;
}
public int deleteDbRequest(String nsClientId) {
try {
return getDaoDbRequest().deleteById(nsClientId);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return 0;
}
public void deleteDbRequestbyMongoId(String action, String id) {
try {
QueryBuilder<DbRequest, String> queryBuilder = getDaoDbRequest().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", id).and().eq("action", action);
queryBuilder.limit(10L);
PreparedQuery<DbRequest> preparedQuery = queryBuilder.prepare();
List<DbRequest> dbList = getDaoDbRequest().query(preparedQuery);
for (DbRequest r : dbList) {
delete(r);
}
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
}
public void deleteAllDbRequests() {
try {
TableUtils.clearTable(connectionSource, DbRequest.class);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
}
public CloseableIterator getDbRequestInterator() {
try {
return getDaoDbRequest().closeableIterator();
} catch (SQLException e) {
log.error("Unhandled exception", e);
return null;
}
}
public static void updateEarliestDataChange(long newDate) {
if (earliestDataChange == null) {
earliestDataChange = newDate;
return;
}
if (newDate < earliestDataChange) {
earliestDataChange = newDate;
}
}
public List<TempTarget> getTemptargetsDataFromTime(long mills, boolean ascending) {
try {
Dao<TempTarget, Long> daoTempTargets = getDaoTempTargets();
List<TempTarget> tempTargets;
QueryBuilder<TempTarget, Long> queryBuilder = daoTempTargets.queryBuilder();
queryBuilder.orderBy("date", ascending);
Where where = queryBuilder.where();
where.ge("date", mills);
PreparedQuery<TempTarget> preparedQuery = queryBuilder.prepare();
tempTargets = daoTempTargets.query(preparedQuery);
return tempTargets;
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return new ArrayList<TempTarget>();
}
public boolean createOrUpdate(TempTarget tempTarget) {
try {
TempTarget old;
tempTarget.date = roundDateToSec(tempTarget.date);
if (tempTarget.source == Source.NIGHTSCOUT) {
old = getDaoTempTargets().queryForId(tempTarget.date);
if (old != null) {
if (!old.isEqual(tempTarget)) {
getDaoTempTargets().delete(old); // need to delete/create because date may change too
old.copyFrom(tempTarget);
getDaoTempTargets().create(old);
if (L.isEnabled(L.DATABASE))
log.debug("TEMPTARGET: Updating record by date from: " + Source.getString(tempTarget.source) + " " + old.toString());
scheduleTemporaryTargetChange();
return true;
}
return false;
}
// find by NS _id
if (tempTarget._id != null) {
QueryBuilder<TempTarget, Long> queryBuilder = getDaoTempTargets().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", tempTarget._id);
PreparedQuery<TempTarget> preparedQuery = queryBuilder.prepare();
List<TempTarget> trList = getDaoTempTargets().query(preparedQuery);
if (trList.size() > 0) {
old = trList.get(0);
if (!old.isEqual(tempTarget)) {
getDaoTempTargets().delete(old); // need to delete/create because date may change too
old.copyFrom(tempTarget);
getDaoTempTargets().create(old);
if (L.isEnabled(L.DATABASE))
log.debug("TEMPTARGET: Updating record by _id from: " + Source.getString(tempTarget.source) + " " + old.toString());
scheduleTemporaryTargetChange();
return true;
}
}
}
getDaoTempTargets().create(tempTarget);
if (L.isEnabled(L.DATABASE))
log.debug("TEMPTARGET: New record from: " + Source.getString(tempTarget.source) + " " + tempTarget.toString());
scheduleTemporaryTargetChange();
return true;
}
if (tempTarget.source == Source.USER) {
getDaoTempTargets().create(tempTarget);
if (L.isEnabled(L.DATABASE))
log.debug("TEMPTARGET: New record from: " + Source.getString(tempTarget.source) + " " + tempTarget.toString());
scheduleTemporaryTargetChange();
return true;
}
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return false;
}
public void delete(TempTarget tempTarget) {
try {
getDaoTempTargets().delete(tempTarget);
scheduleTemporaryTargetChange();
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
}
private static void scheduleTemporaryTargetChange() {
class PostRunnable implements Runnable {
public void run() {
if (L.isEnabled(L.DATABASE))
log.debug("Firing EventTempTargetChange");
MainApp.bus().post(new EventTempTargetChange());
scheduledTemTargetPost = null;
}
}
// prepare task for execution in 1 sec
// cancel waiting task to prevent sending multiple posts
if (scheduledTemTargetPost != null)
scheduledTemTargetPost.cancel(false);
Runnable task = new PostRunnable();
final int sec = 1;
scheduledTemTargetPost = tempTargetWorker.schedule(task, sec, TimeUnit.SECONDS);
}
/*
{
"_id": "58795998aa86647ba4d68ce7",
"enteredBy": "",
"eventType": "Temporary Target",
"reason": "Eating Soon",
"targetTop": 80,
"targetBottom": 80,
"duration": 120,
"created_at": "2017-01-13T22:50:00.782Z",
"carbs": null,
"insulin": null
}
*/
public void createTemptargetFromJsonIfNotExists(JSONObject trJson) {
try {
String units = JsonHelper.safeGetString(trJson, "units", Constants.MGDL);
TempTarget tempTarget = new TempTarget()
.date(trJson.getLong("mills"))
.duration(JsonHelper.safeGetInt(trJson, "duration"))
.low(Profile.toMgdl(trJson.getDouble("targetBottom"), units))
.high(Profile.toMgdl(trJson.getDouble("targetTop"), units))
.reason(JsonHelper.safeGetString(trJson, "reason", ""))
._id(trJson.getString("_id"))
.source(Source.NIGHTSCOUT);
createOrUpdate(tempTarget);
} catch (JSONException e) {
log.error("Unhandled exception: " + trJson.toString(), e);
}
}
public void deleteTempTargetById(String _id) {
TempTarget stored = findTempTargetById(_id);
if (stored != null) {
log.debug("TEMPTARGET: Removing TempTarget record from database: " + stored.toString());
delete(stored);
scheduleTemporaryTargetChange();
}
}
public TempTarget findTempTargetById(String _id) {
try {
QueryBuilder<TempTarget, Long> queryBuilder = getDaoTempTargets().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", _id);
PreparedQuery<TempTarget> preparedQuery = queryBuilder.prepare();
List<TempTarget> list = getDaoTempTargets().query(preparedQuery);
if (list.size() == 1) {
return list.get(0);
} else {
return null;
}
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return null;
}
public void createOrUpdate(DanaRHistoryRecord record) {
try {
getDaoDanaRHistory().createOrUpdate(record);
//If it is a TDD, store it for stats also.
if (record.recordCode == RecordTypes.RECORD_TYPE_DAILY) {
createOrUpdateTDD(new TDD(record.recordDate, record.recordDailyBolus, record.recordDailyBasal, 0));
}
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
}
public List<DanaRHistoryRecord> getDanaRHistoryRecordsByType(byte type) {
List<DanaRHistoryRecord> historyList;
try {
QueryBuilder<DanaRHistoryRecord, String> queryBuilder = getDaoDanaRHistory().queryBuilder();
queryBuilder.orderBy("recordDate", false);
Where where = queryBuilder.where();
where.eq("recordCode", type);
queryBuilder.limit(200L);
PreparedQuery<DanaRHistoryRecord> preparedQuery = queryBuilder.prepare();
historyList = getDaoDanaRHistory().query(preparedQuery);
} catch (SQLException e) {
log.error("Unhandled exception", e);
historyList = new ArrayList<>();
}
return historyList;
}
public void updateDanaRHistoryRecordId(JSONObject trJson) {
try {
QueryBuilder<DanaRHistoryRecord, String> queryBuilder = getDaoDanaRHistory().queryBuilder();
Where where = queryBuilder.where();
where.ge("bytes", trJson.get(DanaRNSHistorySync.DANARSIGNATURE));
PreparedQuery<DanaRHistoryRecord> preparedQuery = queryBuilder.prepare();
List<DanaRHistoryRecord> list = getDaoDanaRHistory().query(preparedQuery);
if (list.size() == 0) {
// Record does not exists. Ignore
} else if (list.size() == 1) {
DanaRHistoryRecord record = list.get(0);
if (record._id == null || !record._id.equals(trJson.getString("_id"))) {
if (L.isEnabled(L.DATABASE))
log.debug("Updating _id in DanaR history database: " + trJson.getString("_id"));
record._id = trJson.getString("_id");
getDaoDanaRHistory().update(record);
} else {
// already set
}
}
} catch (SQLException | JSONException e) {
log.error("Unhandled exception: " + trJson.toString(), e);
}
}
//return true if new record was created
public boolean createOrUpdate(TemporaryBasal tempBasal) {
try {
TemporaryBasal old;
tempBasal.date = roundDateToSec(tempBasal.date);
if (tempBasal.source == Source.PUMP) {
// check for changed from pump change in NS
QueryBuilder<TemporaryBasal, Long> queryBuilder = getDaoTemporaryBasal().queryBuilder();
Where where = queryBuilder.where();
where.eq("pumpId", tempBasal.pumpId);
PreparedQuery<TemporaryBasal> preparedQuery = queryBuilder.prepare();
List<TemporaryBasal> trList = getDaoTemporaryBasal().query(preparedQuery);
if (trList.size() > 0) {
// do nothing, pump history record cannot be changed
if (L.isEnabled(L.DATABASE))
log.debug("TEMPBASAL: Already exists from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString());
return false;
}
getDaoTemporaryBasal().create(tempBasal);
if (L.isEnabled(L.DATABASE))
log.debug("TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString());
updateEarliestDataChange(tempBasal.date);
scheduleTemporaryBasalChange();
return true;
}
if (tempBasal.source == Source.NIGHTSCOUT) {
old = getDaoTemporaryBasal().queryForId(tempBasal.date);
if (old != null) {
if (!old.isAbsolute && tempBasal.isAbsolute) { // converted to absolute by "ns_sync_use_absolute"
// so far ignore, do not convert back because it may not be accurate
return false;
}
if (!old.isEqual(tempBasal)) {
long oldDate = old.date;
getDaoTemporaryBasal().delete(old); // need to delete/create because date may change too
old.copyFrom(tempBasal);
getDaoTemporaryBasal().create(old);
if (L.isEnabled(L.DATABASE))
log.debug("TEMPBASAL: Updating record by date from: " + Source.getString(tempBasal.source) + " " + old.toString());
updateEarliestDataChange(oldDate);
updateEarliestDataChange(old.date);
scheduleTemporaryBasalChange();
return true;
}
return false;
}
// find by NS _id
if (tempBasal._id != null) {
QueryBuilder<TemporaryBasal, Long> queryBuilder = getDaoTemporaryBasal().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", tempBasal._id);
PreparedQuery<TemporaryBasal> preparedQuery = queryBuilder.prepare();
List<TemporaryBasal> trList = getDaoTemporaryBasal().query(preparedQuery);
if (trList.size() > 0) {
old = trList.get(0);
if (!old.isEqual(tempBasal)) {
long oldDate = old.date;
getDaoTemporaryBasal().delete(old); // need to delete/create because date may change too
old.copyFrom(tempBasal);
getDaoTemporaryBasal().create(old);
if (L.isEnabled(L.DATABASE))
log.debug("TEMPBASAL: Updating record by _id from: " + Source.getString(tempBasal.source) + " " + old.toString());
updateEarliestDataChange(oldDate);
updateEarliestDataChange(old.date);
scheduleTemporaryBasalChange();
return true;
}
}
}
getDaoTemporaryBasal().create(tempBasal);
if (L.isEnabled(L.DATABASE))
log.debug("TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString());
updateEarliestDataChange(tempBasal.date);
scheduleTemporaryBasalChange();
return true;
}
if (tempBasal.source == Source.USER) {
getDaoTemporaryBasal().create(tempBasal);
if (L.isEnabled(L.DATABASE))
log.debug("TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString());
updateEarliestDataChange(tempBasal.date);
scheduleTemporaryBasalChange();
return true;
}
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return false;
}
public void delete(TemporaryBasal tempBasal) {
try {
getDaoTemporaryBasal().delete(tempBasal);
updateEarliestDataChange(tempBasal.date);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
scheduleTemporaryBasalChange();
}
public List<TemporaryBasal> getTemporaryBasalsDataFromTime(long mills, boolean ascending) {
try {
List<TemporaryBasal> tempbasals;
QueryBuilder<TemporaryBasal, Long> queryBuilder = getDaoTemporaryBasal().queryBuilder();
queryBuilder.orderBy("date", ascending);
Where where = queryBuilder.where();
where.ge("date", mills);
PreparedQuery<TemporaryBasal> preparedQuery = queryBuilder.prepare();
tempbasals = getDaoTemporaryBasal().query(preparedQuery);
return tempbasals;
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return new ArrayList<TemporaryBasal>();
}
private static void scheduleTemporaryBasalChange() {
class PostRunnable implements Runnable {
public void run() {
if (L.isEnabled(L.DATABASE))
log.debug("Firing EventTempBasalChange");
MainApp.bus().post(new EventReloadTempBasalData());
MainApp.bus().post(new EventTempBasalChange());
if (earliestDataChange != null)
MainApp.bus().post(new EventNewHistoryData(earliestDataChange));
earliestDataChange = null;
scheduledTemBasalsPost = null;
}
}
// prepare task for execution in 1 sec
// cancel waiting task to prevent sending multiple posts
if (scheduledTemBasalsPost != null)
scheduledTemBasalsPost.cancel(false);
Runnable task = new PostRunnable();
final int sec = 1;
scheduledTemBasalsPost = tempBasalsWorker.schedule(task, sec, TimeUnit.SECONDS);
}
/*
{
"_id": "59232e1ddd032d04218dab00",
"eventType": "Temp Basal",
"duration": 60,
"percent": -50,
"created_at": "2017-05-22T18:29:57Z",
"enteredBy": "AndroidAPS",
"notes": "Basal Temp Start 50% 60.0 min",
"NSCLIENT_ID": 1495477797863,
"mills": 1495477797000,
"mgdl": 194.5,
"endmills": 1495481397000
}
*/
public void createTempBasalFromJsonIfNotExists(JSONObject trJson) {
try {
if (trJson.has("originalExtendedAmount")) { // extended bolus uploaded as temp basal
ExtendedBolus extendedBolus = new ExtendedBolus()
.source(Source.NIGHTSCOUT)
.date(trJson.getLong("mills"))
.pumpId(trJson.has("pumpId") ? trJson.getLong("pumpId") : 0)
.durationInMinutes(trJson.getInt("duration"))
.insulin(trJson.getDouble("originalExtendedAmount"))
._id(trJson.getString("_id"));
// if faking found in NS, adapt AAPS to use it too
if (!VirtualPumpPlugin.getPlugin().getFakingStatus()) {
VirtualPumpPlugin.getPlugin().setFakingStatus(true);
updateEarliestDataChange(0);
scheduleTemporaryBasalChange();
}
createOrUpdate(extendedBolus);
} else if (trJson.has("isFakedTempBasal")) { // extended bolus end uploaded as temp basal end
ExtendedBolus extendedBolus = new ExtendedBolus();
extendedBolus.source = Source.NIGHTSCOUT;
extendedBolus.date = trJson.getLong("mills");
extendedBolus.pumpId = trJson.has("pumpId") ? trJson.getLong("pumpId") : 0;
extendedBolus.durationInMinutes = 0;
extendedBolus.insulin = 0;
extendedBolus._id = trJson.getString("_id");
// if faking found in NS, adapt AAPS to use it too
if (!VirtualPumpPlugin.getPlugin().getFakingStatus()) {
VirtualPumpPlugin.getPlugin().setFakingStatus(true);
updateEarliestDataChange(0);
scheduleTemporaryBasalChange();
}
createOrUpdate(extendedBolus);
} else {
TemporaryBasal tempBasal = new TemporaryBasal()
.date(trJson.getLong("mills"))
.source(Source.NIGHTSCOUT)
.pumpId(trJson.has("pumpId") ? trJson.getLong("pumpId") : 0);
if (trJson.has("duration")) {
tempBasal.durationInMinutes = trJson.getInt("duration");
}
if (trJson.has("percent")) {
tempBasal.percentRate = trJson.getInt("percent") + 100;
tempBasal.isAbsolute = false;
}
if (trJson.has("absolute")) {
tempBasal.absoluteRate = trJson.getDouble("absolute");
tempBasal.isAbsolute = true;
}
tempBasal._id = trJson.getString("_id");
createOrUpdate(tempBasal);
}
} catch (JSONException e) {
log.error("Unhandled exception: " + trJson.toString(), e);
}
}
public void deleteTempBasalById(String _id) {
TemporaryBasal stored = findTempBasalById(_id);
if (stored != null) {
if (L.isEnabled(L.DATABASE))
log.debug("TEMPBASAL: Removing TempBasal record from database: " + stored.toString());
delete(stored);
updateEarliestDataChange(stored.date);
scheduleTemporaryBasalChange();
}
}
public TemporaryBasal findTempBasalById(String _id) {
try {
QueryBuilder<TemporaryBasal, Long> queryBuilder = null;
queryBuilder = getDaoTemporaryBasal().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", _id);
PreparedQuery<TemporaryBasal> preparedQuery = queryBuilder.prepare();
List<TemporaryBasal> list = getDaoTemporaryBasal().query(preparedQuery);
if (list.size() != 1) {
return null;
} else {
return list.get(0);
}
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return null;
}
public boolean createOrUpdate(ExtendedBolus extendedBolus) {
try {
if (L.isEnabled(L.DATABASE))
log.debug("EXTENDEDBOLUS: createOrUpdate: " + Source.getString(extendedBolus.source) + " " + extendedBolus.log());
ExtendedBolus old;
extendedBolus.date = roundDateToSec(extendedBolus.date);
if (extendedBolus.source == Source.PUMP) {
// if pumpId == 0 do not check for existing pumpId
// used with pumps without history
// and insight where record as added first without pumpId
// and then is record updated with pumpId
if (extendedBolus.pumpId == 0) {
getDaoExtendedBolus().createOrUpdate(extendedBolus);
} else {
QueryBuilder<ExtendedBolus, Long> queryBuilder = getDaoExtendedBolus().queryBuilder();
Where where = queryBuilder.where();
where.eq("pumpId", extendedBolus.pumpId);
PreparedQuery<ExtendedBolus> preparedQuery = queryBuilder.prepare();
List<ExtendedBolus> trList = getDaoExtendedBolus().query(preparedQuery);
if (trList.size() > 1) {
log.error("EXTENDEDBOLUS: Multiple records found for pumpId: " + extendedBolus.pumpId);
return false;
}
getDaoExtendedBolus().createOrUpdate(extendedBolus);
}
if (L.isEnabled(L.DATABASE))
log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.log());
updateEarliestDataChange(extendedBolus.date);
scheduleExtendedBolusChange();
return true;
}
if (extendedBolus.source == Source.NIGHTSCOUT) {
old = getDaoExtendedBolus().queryForId(extendedBolus.date);
if (old != null) {
if (!old.isEqual(extendedBolus)) {
long oldDate = old.date;
getDaoExtendedBolus().delete(old); // need to delete/create because date may change too
old.copyFrom(extendedBolus);
getDaoExtendedBolus().create(old);
if (L.isEnabled(L.DATABASE))
log.debug("EXTENDEDBOLUS: Updating record by date from: " + Source.getString(extendedBolus.source) + " " + old.log());
updateEarliestDataChange(oldDate);
updateEarliestDataChange(old.date);
scheduleExtendedBolusChange();
return true;
}
return false;
}
// find by NS _id
if (extendedBolus._id != null) {
QueryBuilder<ExtendedBolus, Long> queryBuilder = getDaoExtendedBolus().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", extendedBolus._id);
PreparedQuery<ExtendedBolus> preparedQuery = queryBuilder.prepare();
List<ExtendedBolus> trList = getDaoExtendedBolus().query(preparedQuery);
if (trList.size() > 0) {
old = trList.get(0);
if (!old.isEqual(extendedBolus)) {
long oldDate = old.date;
getDaoExtendedBolus().delete(old); // need to delete/create because date may change too
old.copyFrom(extendedBolus);
getDaoExtendedBolus().create(old);
if (L.isEnabled(L.DATABASE))
log.debug("EXTENDEDBOLUS: Updating record by _id from: " + Source.getString(extendedBolus.source) + " " + old.log());
updateEarliestDataChange(oldDate);
updateEarliestDataChange(old.date);
scheduleExtendedBolusChange();
return true;
}
}
}
getDaoExtendedBolus().create(extendedBolus);
if (L.isEnabled(L.DATABASE))
log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.log());
updateEarliestDataChange(extendedBolus.date);
scheduleExtendedBolusChange();
return true;
}
if (extendedBolus.source == Source.USER) {
getDaoExtendedBolus().create(extendedBolus);
if (L.isEnabled(L.DATABASE))
log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.log());
updateEarliestDataChange(extendedBolus.date);
scheduleExtendedBolusChange();
return true;
}
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return false;
}
public ExtendedBolus getExtendedBolusByPumpId(long pumpId) {
try {
return getDaoExtendedBolus().queryBuilder()
.where().eq("pumpId", pumpId)
.queryForFirst();
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return null;
}
public void delete(ExtendedBolus extendedBolus) {
try {
getDaoExtendedBolus().delete(extendedBolus);
updateEarliestDataChange(extendedBolus.date);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
scheduleExtendedBolusChange();
}
public List<ExtendedBolus> getExtendedBolusDataFromTime(long mills, boolean ascending) {
try {
List<ExtendedBolus> extendedBoluses;
QueryBuilder<ExtendedBolus, Long> queryBuilder = getDaoExtendedBolus().queryBuilder();
queryBuilder.orderBy("date", ascending);
Where where = queryBuilder.where();
where.ge("date", mills);
PreparedQuery<ExtendedBolus> preparedQuery = queryBuilder.prepare();
extendedBoluses = getDaoExtendedBolus().query(preparedQuery);
return extendedBoluses;
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return new ArrayList<ExtendedBolus>();
}
public void deleteExtendedBolusById(String _id) {
ExtendedBolus stored = findExtendedBolusById(_id);
if (stored != null) {
if (L.isEnabled(L.DATABASE))
log.debug("EXTENDEDBOLUS: Removing ExtendedBolus record from database: " + stored.toString());
delete(stored);
updateEarliestDataChange(stored.date);
scheduleExtendedBolusChange();
}
}
public ExtendedBolus findExtendedBolusById(String _id) {
try {
QueryBuilder<ExtendedBolus, Long> queryBuilder = null;
queryBuilder = getDaoExtendedBolus().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", _id);
PreparedQuery<ExtendedBolus> preparedQuery = queryBuilder.prepare();
List<ExtendedBolus> list = getDaoExtendedBolus().query(preparedQuery);
if (list.size() == 1) {
return list.get(0);
} else {
return null;
}
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return null;
}
/*
{
"_id": "5924898d577eb0880e355337",
"eventType": "Combo Bolus",
"duration": 120,
"splitNow": 0,
"splitExt": 100,
"enteredinsulin": 1,
"relative": 1,
"created_at": "2017-05-23T19:12:14Z",
"enteredBy": "AndroidAPS",
"NSCLIENT_ID": 1495566734628,
"mills": 1495566734000,
"mgdl": 106
}
*/
public void createExtendedBolusFromJsonIfNotExists(JSONObject json) {
ExtendedBolus extendedBolus = ExtendedBolus.createFromJson(json);
if (extendedBolus != null)
createOrUpdate(extendedBolus);
}
private static void scheduleExtendedBolusChange() {
class PostRunnable implements Runnable {
public void run() {
if (L.isEnabled(L.DATABASE))
log.debug("Firing EventExtendedBolusChange");
MainApp.bus().post(new EventReloadTreatmentData(new EventExtendedBolusChange()));
if (earliestDataChange != null)
MainApp.bus().post(new EventNewHistoryData(earliestDataChange));
earliestDataChange = null;
scheduledExtendedBolusPost = null;
}
}
// prepare task for execution in 1 sec
// cancel waiting task to prevent sending multiple posts
if (scheduledExtendedBolusPost != null)
scheduledExtendedBolusPost.cancel(false);
Runnable task = new PostRunnable();
final int sec = 1;
scheduledExtendedBolusPost = extendedBolusWorker.schedule(task, sec, TimeUnit.SECONDS);
}
public void createOrUpdate(CareportalEvent careportalEvent) {
careportalEvent.date = careportalEvent.date - careportalEvent.date % 1000;
try {
getDaoCareportalEvents().createOrUpdate(careportalEvent);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
scheduleCareportalEventChange();
}
public void delete(CareportalEvent careportalEvent) {
try {
getDaoCareportalEvents().delete(careportalEvent);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
scheduleCareportalEventChange();
}
public CareportalEvent getCareportalEventFromTimestamp(long timestamp) {
try {
return getDaoCareportalEvents().queryForId(timestamp);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return null;
}
@Nullable
public CareportalEvent getLastCareportalEvent(String event) {
try {
List<CareportalEvent> careportalEvents;
QueryBuilder<CareportalEvent, Long> queryBuilder = getDaoCareportalEvents().queryBuilder();
queryBuilder.orderBy("date", false);
Where where = queryBuilder.where();
where.eq("eventType", event);
queryBuilder.limit(1L);
PreparedQuery<CareportalEvent> preparedQuery = queryBuilder.prepare();
careportalEvents = getDaoCareportalEvents().query(preparedQuery);
if (careportalEvents.size() == 1)
return careportalEvents.get(0);
else
return null;
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return null;
}
public List<CareportalEvent> getCareportalEventsFromTime(long mills, boolean ascending) {
try {
List<CareportalEvent> careportalEvents;
QueryBuilder<CareportalEvent, Long> queryBuilder = getDaoCareportalEvents().queryBuilder();
queryBuilder.orderBy("date", ascending);
Where where = queryBuilder.where();
where.ge("date", mills);
PreparedQuery<CareportalEvent> preparedQuery = queryBuilder.prepare();
careportalEvents = getDaoCareportalEvents().query(preparedQuery);
preprocessOpenAPSOfflineEvents(careportalEvents);
return careportalEvents;
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return new ArrayList<>();
}
public void preprocessOpenAPSOfflineEvents(List<CareportalEvent> list) {
OverlappingIntervals offlineEvents = new OverlappingIntervals();
for (int i = 0; i < list.size(); i++) {
CareportalEvent event = list.get(i);
if (!event.eventType.equals(CareportalEvent.OPENAPSOFFLINE)) continue;
offlineEvents.add(event);
}
}
public List<CareportalEvent> getCareportalEventsFromTime(long mills, String type, boolean ascending) {
try {
List<CareportalEvent> careportalEvents;
QueryBuilder<CareportalEvent, Long> queryBuilder = getDaoCareportalEvents().queryBuilder();
queryBuilder.orderBy("date", ascending);
Where where = queryBuilder.where();
where.ge("date", mills).and().eq("eventType", type);
PreparedQuery<CareportalEvent> preparedQuery = queryBuilder.prepare();
careportalEvents = getDaoCareportalEvents().query(preparedQuery);
preprocessOpenAPSOfflineEvents(careportalEvents);
return careportalEvents;
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return new ArrayList<>();
}
public List<CareportalEvent> getCareportalEvents(boolean ascending) {
try {
List<CareportalEvent> careportalEvents;
QueryBuilder<CareportalEvent, Long> queryBuilder = getDaoCareportalEvents().queryBuilder();
queryBuilder.orderBy("date", ascending);
PreparedQuery<CareportalEvent> preparedQuery = queryBuilder.prepare();
careportalEvents = getDaoCareportalEvents().query(preparedQuery);
preprocessOpenAPSOfflineEvents(careportalEvents);
return careportalEvents;
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return new ArrayList<>();
}
public void deleteCareportalEventById(String _id) {
try {
QueryBuilder<CareportalEvent, Long> queryBuilder;
queryBuilder = getDaoCareportalEvents().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", _id);
PreparedQuery<CareportalEvent> preparedQuery = queryBuilder.prepare();
List<CareportalEvent> list = getDaoCareportalEvents().query(preparedQuery);
if (list.size() == 1) {
CareportalEvent record = list.get(0);
if (L.isEnabled(L.DATABASE))
log.debug("Removing CareportalEvent record from database: " + record.toString());
delete(record);
} else {
if (L.isEnabled(L.DATABASE))
log.debug("CareportalEvent not found database: " + _id);
}
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
}
public void createCareportalEventFromJsonIfNotExists(JSONObject trJson) {
try {
QueryBuilder<CareportalEvent, Long> queryBuilder;
queryBuilder = getDaoCareportalEvents().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", trJson.getString("_id")).or().eq("date", trJson.getLong("mills"));
PreparedQuery<CareportalEvent> preparedQuery = queryBuilder.prepare();
List<CareportalEvent> list = getDaoCareportalEvents().query(preparedQuery);
CareportalEvent careportalEvent;
if (list.size() == 0) {
careportalEvent = new CareportalEvent();
careportalEvent.source = Source.NIGHTSCOUT;
if (L.isEnabled(L.DATABASE))
log.debug("Adding CareportalEvent record to database: " + trJson.toString());
// Record does not exists. add
} else if (list.size() == 1) {
careportalEvent = list.get(0);
if (L.isEnabled(L.DATABASE))
log.debug("Updating CareportalEvent record in database: " + trJson.toString());
} else {
log.error("Something went wrong");
return;
}
careportalEvent.date = trJson.getLong("mills");
careportalEvent.eventType = trJson.getString("eventType");
careportalEvent.json = trJson.toString();
careportalEvent._id = trJson.getString("_id");
createOrUpdate(careportalEvent);
} catch (SQLException | JSONException e) {
log.error("Unhandled exception: " + trJson.toString(), e);
}
}
private static void scheduleCareportalEventChange() {
class PostRunnable implements Runnable {
public void run() {
if (L.isEnabled(L.DATABASE))
log.debug("Firing scheduleCareportalEventChange");
MainApp.bus().post(new EventCareportalEventChange());
scheduledCareportalEventPost = null;
}
}
// prepare task for execution in 1 sec
// cancel waiting task to prevent sending multiple posts
if (scheduledCareportalEventPost != null)
scheduledCareportalEventPost.cancel(false);
Runnable task = new PostRunnable();
final int sec = 1;
scheduledCareportalEventPost = careportalEventWorker.schedule(task, sec, TimeUnit.SECONDS);
}
public List<ProfileSwitch> getProfileSwitchData(boolean ascending) {
try {
Dao<ProfileSwitch, Long> daoProfileSwitch = getDaoProfileSwitch();
List<ProfileSwitch> profileSwitches;
QueryBuilder<ProfileSwitch, Long> queryBuilder = daoProfileSwitch.queryBuilder();
queryBuilder.orderBy("date", ascending);
queryBuilder.limit(100L);
PreparedQuery<ProfileSwitch> preparedQuery = queryBuilder.prepare();
profileSwitches = daoProfileSwitch.query(preparedQuery);
return profileSwitches;
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return new ArrayList<>();
}
public List<ProfileSwitch> getProfileSwitchEventsFromTime(long mills, boolean ascending) {
try {
Dao<ProfileSwitch, Long> daoProfileSwitch = getDaoProfileSwitch();
List<ProfileSwitch> profileSwitches;
QueryBuilder<ProfileSwitch, Long> queryBuilder = daoProfileSwitch.queryBuilder();
queryBuilder.orderBy("date", ascending);
queryBuilder.limit(100L);
Where where = queryBuilder.where();
where.ge("date", mills);
PreparedQuery<ProfileSwitch> preparedQuery = queryBuilder.prepare();
profileSwitches = daoProfileSwitch.query(preparedQuery);
return profileSwitches;
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return new ArrayList<>();
}
public boolean createOrUpdate(ProfileSwitch profileSwitch) {
try {
ProfileSwitch old;
profileSwitch.date = roundDateToSec(profileSwitch.date);
if (profileSwitch.source == Source.NIGHTSCOUT) {
old = getDaoProfileSwitch().queryForId(profileSwitch.date);
if (old != null) {
if (!old.isEqual(profileSwitch)) {
profileSwitch.source = old.source;
profileSwitch.profileName = old.profileName; // preserver profileName to prevent multiple CPP extension
getDaoProfileSwitch().delete(old); // need to delete/create because date may change too
getDaoProfileSwitch().create(profileSwitch);
if (L.isEnabled(L.DATABASE))
log.debug("PROFILESWITCH: Updating record by date from: " + Source.getString(profileSwitch.source) + " " + old.toString());
scheduleProfileSwitchChange();
return true;
}
return false;
}
// find by NS _id
if (profileSwitch._id != null) {
QueryBuilder<ProfileSwitch, Long> queryBuilder = getDaoProfileSwitch().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", profileSwitch._id);
PreparedQuery<ProfileSwitch> preparedQuery = queryBuilder.prepare();
List<ProfileSwitch> trList = getDaoProfileSwitch().query(preparedQuery);
if (trList.size() > 0) {
old = trList.get(0);
if (!old.isEqual(profileSwitch)) {
getDaoProfileSwitch().delete(old); // need to delete/create because date may change too
old.copyFrom(profileSwitch);
getDaoProfileSwitch().create(old);
if (L.isEnabled(L.DATABASE))
log.debug("PROFILESWITCH: Updating record by _id from: " + Source.getString(profileSwitch.source) + " " + old.toString());
scheduleProfileSwitchChange();
return true;
}
}
}
// look for already added percentage from NS
profileSwitch.profileName = PercentageSplitter.pureName(profileSwitch.profileName);
getDaoProfileSwitch().create(profileSwitch);
if (L.isEnabled(L.DATABASE))
log.debug("PROFILESWITCH: New record from: " + Source.getString(profileSwitch.source) + " " + profileSwitch.toString());
scheduleProfileSwitchChange();
return true;
}
if (profileSwitch.source == Source.USER) {
getDaoProfileSwitch().create(profileSwitch);
if (L.isEnabled(L.DATABASE))
log.debug("PROFILESWITCH: New record from: " + Source.getString(profileSwitch.source) + " " + profileSwitch.toString());
scheduleProfileSwitchChange();
return true;
}
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return false;
}
public void delete(ProfileSwitch profileSwitch) {
try {
getDaoProfileSwitch().delete(profileSwitch);
scheduleProfileSwitchChange();
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
}
private static void scheduleProfileSwitchChange() {
class PostRunnable implements Runnable {
public void run() {
if (L.isEnabled(L.DATABASE))
log.debug("Firing EventProfileNeedsUpdate");
MainApp.bus().post(new EventReloadProfileSwitchData());
MainApp.bus().post(new EventProfileNeedsUpdate());
scheduledProfileSwitchEventPost = null;
}
}
// prepare task for execution in 1 sec
// cancel waiting task to prevent sending multiple posts
if (scheduledProfileSwitchEventPost != null)
scheduledProfileSwitchEventPost.cancel(false);
Runnable task = new PostRunnable();
final int sec = 1;
scheduledProfileSwitchEventPost = profileSwitchEventWorker.schedule(task, sec, TimeUnit.SECONDS);
}
/*
{
"_id":"592fa43ed97496a80da913d2",
"created_at":"2017-06-01T05:20:06Z",
"eventType":"Profile Switch",
"profile":"2016 +30%",
"units":"mmol",
"enteredBy":"sony",
"NSCLIENT_ID":1496294454309,
}
*/
public void createProfileSwitchFromJsonIfNotExists(JSONObject trJson) {
try {
ProfileSwitch profileSwitch = new ProfileSwitch();
profileSwitch.date = trJson.getLong("mills");
if (trJson.has("duration"))
profileSwitch.durationInMinutes = trJson.getInt("duration");
profileSwitch._id = trJson.getString("_id");
profileSwitch.profileName = trJson.getString("profile");
profileSwitch.isCPP = trJson.has("CircadianPercentageProfile");
profileSwitch.source = Source.NIGHTSCOUT;
if (trJson.has("timeshift"))
profileSwitch.timeshift = trJson.getInt("timeshift");
if (trJson.has("percentage"))
profileSwitch.percentage = trJson.getInt("percentage");
if (trJson.has("profileJson"))
profileSwitch.profileJson = trJson.getString("profileJson");
else {
ProfileInterface profileInterface = ConfigBuilderPlugin.getPlugin().getActiveProfileInterface();
if (profileInterface != null) {
ProfileStore store = profileInterface.getProfile();
if (store != null) {
Profile profile = store.getSpecificProfile(profileSwitch.profileName);
if (profile != null) {
profileSwitch.profileJson = profile.getData().toString();
if (L.isEnabled(L.DATABASE))
log.debug("Profile switch prefilled with JSON from local store");
// Update data in NS
NSUpload.updateProfileSwitch(profileSwitch);
} else {
if (L.isEnabled(L.DATABASE))
log.debug("JSON for profile switch doesn't exist. Ignoring: " + trJson.toString());
return;
}
} else {
if (L.isEnabled(L.DATABASE))
log.debug("Store for profile switch doesn't exist. Ignoring: " + trJson.toString());
return;
}
} else {
if (L.isEnabled(L.DATABASE))
log.debug("No active profile interface. Ignoring: " + trJson.toString());
return;
}
}
if (trJson.has("profilePlugin"))
profileSwitch.profilePlugin = trJson.getString("profilePlugin");
createOrUpdate(profileSwitch);
} catch (JSONException e) {
log.error("Unhandled exception: " + trJson.toString(), e);
}
}
public void deleteProfileSwitchById(String _id) {
ProfileSwitch stored = findProfileSwitchById(_id);
if (stored != null) {
if (L.isEnabled(L.DATABASE))
log.debug("PROFILESWITCH: Removing ProfileSwitch record from database: " + stored.toString());
delete(stored);
scheduleTemporaryTargetChange();
}
}
public ProfileSwitch findProfileSwitchById(String _id) {
try {
QueryBuilder<ProfileSwitch, Long> queryBuilder = getDaoProfileSwitch().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", _id);
PreparedQuery<ProfileSwitch> preparedQuery = queryBuilder.prepare();
List<ProfileSwitch> list = getDaoProfileSwitch().query(preparedQuery);
if (list.size() == 1) {
return list.get(0);
} else {
return null;
}
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return null;
}
public void createOrUpdate(InsightHistoryOffset offset) {
try {
getDaoInsightHistoryOffset().createOrUpdate(offset);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
}
public InsightHistoryOffset getInsightHistoryOffset(String pumpSerial) {
try {
return getDaoInsightHistoryOffset().queryForId(pumpSerial);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return null;
}
public void createOrUpdate(InsightBolusID bolusID) {
try {
getDaoInsightBolusID().createOrUpdate(bolusID);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
}
public InsightBolusID getInsightBolusID(String pumpSerial, int bolusID, long timestamp) {
try {
return getDaoInsightBolusID().queryBuilder()
.where().eq("pumpSerial", pumpSerial)
.and().eq("bolusID", bolusID)
.and().between("timestamp", timestamp - 259200000, timestamp + 259200000)
.queryForFirst();
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return null;
}
public void createOrUpdate(InsightPumpID pumpID) {
try {
getDaoInsightPumpID().createOrUpdate(pumpID);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
}
public InsightPumpID getPumpStoppedEvent(String pumpSerial, long before) {
try {
return getDaoInsightPumpID().queryBuilder()
.orderBy("timestamp", false)
.where().eq("pumpSerial", pumpSerial)
.and().in("eventType", "PumpStopped", "PumpPaused")
.and().lt("timestamp", before)
.queryForFirst();
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return null;
}
}
|
package com.github.arteam.jdit;
import com.github.arteam.jdit.annotations.DBIHandle;
import com.github.arteam.jdit.annotations.DataSet;
import com.github.arteam.jdit.annotations.JditProperties;
import com.github.arteam.jdit.annotations.TestedSqlObject;
import com.github.arteam.jdit.domain.PlayerSqlObject;
import com.google.common.collect.ImmutableList;
import org.jdbi.v3.core.Handle;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.Date;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assume.assumeTrue;
@JditProperties("jdit-mysql.properties")
@RunWith(DBIRunner.class)
public class MySqlDbTest {
@BeforeClass
public static void beforeInit() {
assumeTrue(Boolean.parseBoolean(System.getenv("TRAVIS")));
}
private static final DateTimeFormatter fmt = ISODateTimeFormat.date().withZoneUTC();
@TestedSqlObject
private PlayerSqlObject playerDao;
@DBIHandle
private Handle handle;
@Test
@DataSet("playerDao/getInitials.sql")
public void testCreatePlayer() {
Long playerId = playerDao.createPlayer("Joel", "Edmunson",
date("1993-06-28"), 193, 94);
assertEquals(playerId.longValue(), 2L);
Map<String, Object> row = handle.select("select * from players where id=?", 2)
.mapToMap()
.findOnly();
assertEquals(row.get("id"), 2);
assertEquals(row.get("first_name"), "Joel");
assertEquals(row.get("last_name"), "Edmunson");
assertEquals(row.get("weight"), 94);
assertEquals(row.get("height"), 193);
assertEquals(row.get("birth_date").toString(), "1993-06-28");
}
@Test
@DataSet("playerDao/getInitials.sql")
public void testCreateAnotherPlayer() {
Long playerId = playerDao.createPlayer("Nail", "Yakupov",
date("1993-10-06"), 178, 75);
assertEquals(playerId.longValue(), 2L);
Map<String, Object> row = handle.select("select * from players where id=?", 2)
.mapToMap()
.findOnly();
assertEquals(row.get("id"), 2);
assertEquals(row.get("first_name"), "Nail");
assertEquals(row.get("last_name"), "Yakupov");
assertEquals(row.get("weight"), 75);
assertEquals(row.get("height"), 178);
assertEquals(row.get("birth_date").toString(), "1993-10-06");
}
@Test
@DataSet("playerDao/getInitials.sql")
public void testGetLastNames() {
List<String> lastNames = playerDao.getLastNames();
assertEquals(lastNames, ImmutableList.of("Tarasenko"));
}
private static Date date(String textDate) {
return fmt.parseDateTime(textDate).toDate();
}
}
|
package io.github.xwz.abciview.views;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Handler;
import android.support.v17.leanback.widget.BaseCardView;
import android.support.v17.leanback.widget.ImageCardView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.SurfaceView;
import android.view.View;
import android.view.accessibility.CaptioningManager;
import android.widget.MediaController;
import android.widget.TextView;
import com.google.android.exoplayer.AspectRatioFrameLayout;
import com.google.android.exoplayer.ExoPlayer;
import com.google.android.exoplayer.text.CaptionStyleCompat;
import com.google.android.exoplayer.text.Cue;
import com.google.android.exoplayer.text.SubtitleLayout;
import com.google.android.exoplayer.util.DebugTextViewHelper;
import com.google.android.exoplayer.util.Util;
import java.util.Arrays;
import java.util.List;
import io.github.xwz.abciview.R;
import io.github.xwz.abciview.models.EpisodeModel;
import io.github.xwz.abciview.player.VideoPlayer;
public class VideoPlayerView {
private static final String TAG = "VideoPlayerView";
private final View shutterView;
private final AspectRatioFrameLayout videoFrame;
private final SurfaceView surfaceView;
private final TextView debugTextView;
private final TextView playerStateTextView;
private final View debugView;
private final TextView statusTextView;
private final SubtitleLayout subtitleLayout;
private final EpisodeCardView nextEpisode;
private final View nextEpisodeCard;
private final View episodeDetails;
private final TextView episodeTitle;
private final TextView seriesTitle;
private final TextView duration;
private DebugTextViewHelper debugViewHelper;
private final Context mContext;
private final MediaController mediaController;
private MediaController.MediaPlayerControl mPlayer;
private static final List<Integer> PLAY_PAUSE_EVENTS = Arrays.asList(
KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE,
KeyEvent.KEYCODE_MEDIA_PLAY,
KeyEvent.KEYCODE_MEDIA_STOP,
KeyEvent.KEYCODE_DPAD_CENTER
);
private static final List<Integer> PLAYER_EVENTS = Arrays.asList(
KeyEvent.KEYCODE_VOLUME_DOWN,
KeyEvent.KEYCODE_VOLUME_UP,
KeyEvent.KEYCODE_VOLUME_MUTE,
KeyEvent.KEYCODE_CAMERA
);
public VideoPlayerView(Context context, MediaController controller, View root) {
mContext = context;
mediaController = controller;
shutterView = root.findViewById(R.id.shutter);
videoFrame = (AspectRatioFrameLayout) root.findViewById(R.id.video_frame);
surfaceView = (SurfaceView) root.findViewById(R.id.surface_view);
debugTextView = (TextView) root.findViewById(R.id.debug_text_view);
debugView = root.findViewById(R.id.debug_view);
statusTextView = (TextView) root.findViewById(R.id.status);
playerStateTextView = (TextView) root.findViewById(R.id.player_state_view);
subtitleLayout = (SubtitleLayout) root.findViewById(R.id.subtitles);
nextEpisodeCard = root.findViewById(R.id.next_episode_card);
episodeDetails = root.findViewById(R.id.episode_details);
episodeTitle = (TextView) root.findViewById(R.id.episode_title);
seriesTitle = (TextView) root.findViewById(R.id.series_title);
duration = (TextView) root.findViewById(R.id.duration);
ImageCardView card = (ImageCardView) root.findViewById(R.id.next_episode);
card.setFocusable(true);
card.setFocusableInTouchMode(true);
card.setInfoVisibility(View.VISIBLE);
card.setExtraVisibility(View.VISIBLE);
nextEpisode = new EpisodeCardView(context, card);
nextEpisode.getImageCardView().setCardType(BaseCardView.CARD_TYPE_INFO_OVER);
debugView.setVisibility(View.GONE);
root.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
return handleTouchEvents(view, motionEvent);
}
});
root.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
return handleKeyEvents(v, keyCode, event);
}
});
}
private boolean handleKeyEvents(View v, int keyCode, KeyEvent event) {
final boolean uniqueDown = event.getRepeatCount() == 0 && event.getAction() == KeyEvent.ACTION_DOWN;
if (uniqueDown) {
Log.d(TAG, "keyCode:" + keyCode + ", event:" + event);
}
if (PLAY_PAUSE_EVENTS.contains(keyCode) && uniqueDown) {
doPauseResume();
return true;
} else if (PLAYER_EVENTS.contains(keyCode)){
return mediaController.dispatchKeyEvent(event);
}
return false;
}
private boolean handleTouchEvents(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
toggleControlsVisibility();
} else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
view.performClick();
}
return true;
}
private void doPauseResume() {
Log.d(TAG, "doPauseResume:" + mPlayer);
if (mPlayer != null) {
if (mPlayer.isPlaying()) {
mPlayer.pause();
showControls();
} else {
mPlayer.start();
hideControlsDelayed();
}
}
}
public void setEpisode(EpisodeModel episode) {
episodeTitle.setText(episode.getTitle());
seriesTitle.setText(episode.getSeriesTitle());
duration.setText(episode.getDurationText());
showShutter(true);
showEpisodeDetails();
}
public void setMediaPlayer(MediaController.MediaPlayerControl player) {
mPlayer = player;
}
public void resetView() {
nextEpisodeCard.setVisibility(View.GONE);
}
public void setVideoFrameAspectRatio(float ratio) {
videoFrame.setAspectRatio(ratio);
}
public void showShutter(boolean show) {
shutterView.setVisibility(show ? View.VISIBLE : View.GONE);
}
public void setCues(List<Cue> cues) {
subtitleLayout.setCues(cues);
}
public void startDebugView(VideoPlayer player) {
debugViewHelper = new DebugTextViewHelper(player, debugTextView);
debugViewHelper.start();
}
public void stopDebugView() {
debugViewHelper.stop();
debugViewHelper = null;
}
private void toggleControlsVisibility() {
if (mediaController.isShowing()) {
hideControls();
} else {
showControls();
}
}
public void showControls() {
Log.d(TAG, "Show controls");
mediaController.show(0);
showEpisodeDetails();
}
private void showEpisodeDetails() {
episodeDetails.setVisibility(View.VISIBLE);
}
private void hideControls() {
Log.d(TAG, "Hide controls");
mediaController.hide();
episodeDetails.setVisibility(View.GONE);
}
public void configureSubtitleView() {
CaptionStyleCompat captionStyle;
float captionFontScale;
if (Util.SDK_INT >= 19) {
captionStyle = getUserCaptionStyleV19();
captionFontScale = getUserCaptionFontScaleV19();
} else {
captionStyle = CaptionStyleCompat.DEFAULT;
captionFontScale = 1.0f;
}
subtitleLayout.setStyle(captionStyle);
subtitleLayout.setFontScale(captionFontScale);
}
public Surface getVideoSurface() {
return surfaceView.getHolder().getSurface();
}
public void onStateChanged(boolean playWhenReady, int playbackState) {
if (playbackState == ExoPlayer.STATE_ENDED) {
showControls();
}
String text = "playWhenReady=" + playWhenReady + ", playbackState=";
switch (playbackState) {
case ExoPlayer.STATE_BUFFERING:
text += "buffering";
showStatusText(R.string.buffering);
break;
case ExoPlayer.STATE_ENDED:
text += "ended";
break;
case ExoPlayer.STATE_IDLE:
text += "idle";
break;
case ExoPlayer.STATE_PREPARING:
text += "preparing";
showStatusText(R.string.loading);
break;
case ExoPlayer.STATE_READY:
text += "ready";
hideStatusText();
showShutter(false);
if (mPlayer != null && mPlayer.isPlaying()) {
hideControlsDelayed();
}
break;
default:
text += "unknown";
break;
}
playerStateTextView.setText(text);
}
private void hideControlsDelayed() {
final Handler handler = new Handler();
Log.d(TAG, "hideControlsDelayed");
handler.postDelayed(new Runnable() {
@Override
public void run() {
hideControls();
}
}, 3000);
}
public void suggestNextEpisode(EpisodeModel episode) {
nextEpisode.setEpisode(episode);
nextEpisodeCard.setVisibility(View.VISIBLE);
}
private void showStatusText(int resId) {
showStatusText(mContext.getResources().getString(resId));
}
private void hideStatusText() {
statusTextView.setVisibility(View.GONE);
}
private void showStatusText(String text) {
statusTextView.setVisibility(View.VISIBLE);
statusTextView.setText(text);
}
@TargetApi(19)
private float getUserCaptionFontScaleV19() {
CaptioningManager captioningManager =
(CaptioningManager) mContext.getSystemService(Context.CAPTIONING_SERVICE);
return captioningManager.getFontScale();
}
@TargetApi(19)
private CaptionStyleCompat getUserCaptionStyleV19() {
CaptioningManager captioningManager =
(CaptioningManager) mContext.getSystemService(Context.CAPTIONING_SERVICE);
return CaptionStyleCompat.createFromCaptionStyle(captioningManager.getUserStyle());
}
}
|
package no005.longest.palindrom.substring;
public class Solution {
/**
* Validate if the substring of s is a palindrome string between supplied indexs.
*
* @param s A string
* @param start A start index
* @param end A end index
* @return {@link true} If it is a palindrome string or {@link false} if not. If the length is 1 it
* treats as like a palindrome string.
*/
public static boolean isPalindrome(String s, int start, int end) {
int length = end - start + 1;
if (length == 1) {
return true;
}
if (s.charAt(start) == s.charAt(end)) {
return length == 2 || isPalindrome(s, start + 1, end - 1);
}
return false;
}
public static String longestPalindrome(String s) {
int length = s.length();
for (int i = length - 1; i > 0; i
for (int j = 0; j <= length - i - 1; j++) {
if (isPalindrome(s, j, i + j)) {
return s.substring(j, j + i + 1);
}
}
}
return s.substring(0, 1);
}
public static void main(String[] args) {
System.out.println("bab".equals(longestPalindrome("babad")));
System.out.println("aba".equals(longestPalindrome("aba")));
System.out.println("bb".equals(longestPalindrome("cbbd")));
System.out.println("a".equals(longestPalindrome("abcde")));
}
}
|
package bj.pranie.controller.week;
import bj.pranie.dao.ReservationDao;
import bj.pranie.dao.WashTimeDao;
import bj.pranie.entity.Reservation;
import bj.pranie.entity.User;
import bj.pranie.entity.WashTime;
import bj.pranie.model.TimeWeekModel;
import bj.pranie.service.UserAuthenticatedService;
import bj.pranie.util.ColorUtil;
import bj.pranie.util.TimeUtil;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.ui.Model;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
public class BaseWeekController {
private static final int RESET_TIME = 10;
static final DateTimeFormatter dateFormat = DateTimeFormat.forPattern("yyyy/MM/dd");
static final SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
@Autowired
ReservationDao reservationDao;
@Autowired
WashTimeDao washTimeDao;
@Autowired
private UserAuthenticatedService userAuthenticatedService;
@Value("${wmCount}")
int wmCount;
void setModel(String weekId, Model model) throws ParseException {
model.addAttribute("weekId", weekId);
model.addAttribute("weekFrame", getWeekFrame(weekId));
List<TimeWeekModel> timeWeekModels = getTimeWeekModels(weekId);
model.addAttribute("wmFree", getWmFree(timeWeekModels));
model.addAttribute("timesWeek", timeWeekModels);
model.addAttribute("user", userAuthenticatedService.getAuthenticatedUser());
}
/*
WeekId = year-weekOfYear
*/
String getCurrentWeekId() {
DateTime dateTime = TimeUtil.getCalendar();
int time = dateTime.getHourOfDay();
int today = dateTime.getDayOfWeek();
if (today == DateTimeConstants.SUNDAY && time >= RESET_TIME) {
dateTime = dateTime.plusWeeks(1);
}
return dateTime.getYear() + "-" + dateTime.getWeekOfWeekyear();
}
String getWeekFrame(String weekId) {
LocalDate localDate = getLocalDateByWeekId(weekId).withDayOfWeek(DateTimeConstants.MONDAY);
return localDate.toString(dateFormat) + " - " + localDate.plusDays(6).toString(dateFormat);
}
LocalDate getLocalDateByWeekId(String weekId) {
int year = Integer.parseInt(weekId.split("-")[0]);
int weekOfYear = Integer.parseInt(weekId.split("-")[1]);
return new LocalDate().withWeekyear(year).withWeekOfWeekyear(weekOfYear).withDayOfWeek(DateTimeConstants.MONDAY);
}
enum WEEK_TYPE {
PREV, NEXT
}
String getSpecificWeekId(String weekId, UserWeekController.WEEK_TYPE week_type) {
LocalDate localDate = getLocalDateByWeekId(weekId);
switch (week_type) {
case NEXT:
localDate = localDate.plusWeeks(1);
break;
case PREV:
localDate = localDate.minusWeeks(1);
break;
}
return localDate.getWeekyear() + "-" + localDate.getWeekOfWeekyear();
}
List<TimeWeekModel> getTimeWeekModels(String weekId) throws ParseException {
final List<TimeWeekModel> timeWeekModels = new ArrayList<>();
List<LocalDate> weekDays = getWeekDays(weekId);
Iterator<WashTime> washTimeIterator = washTimeDao.findAll().iterator();
while (washTimeIterator.hasNext()) {
WashTime washTime = washTimeIterator.next();
TimeWeekModel timeWeekModel = new TimeWeekModel();
timeWeekModel.setTime(timeFormat.format(washTime.getFromTime()) + " - " + timeFormat.format(washTime.getToTime()));
List<TimeWeekModel.WmDate> wmDates = new ArrayList<>();
for (LocalDate localDate : weekDays) {
TimeWeekModel.WmDate wmDate = timeWeekModel.new WmDate();
wmDate.setDate(localDate.toString(dateFormat));
boolean isPast = TimeUtil.isPast(washTime.getFromTime(), localDate);
List<Reservation> reservations = getReservationsByWashTimeAndDate(washTime.getId(), localDate);
int wmFree = wmCount;
if (isPast) {
wmFree = 0;
} else {
wmFree -= reservations.size();
}
wmDate.setWmFree(wmFree);
wmDate.setColor(getCellColor(wmFree, isPast, isUserAuthenticatedReservation(reservations)));
wmDates.add(wmDate);
}
timeWeekModel.setDates(wmDates);
timeWeekModels.add(timeWeekModel);
}
return timeWeekModels;
}
List<LocalDate> getWeekDays(String weekId) {
List<LocalDate> daysOfWeek = new ArrayList<>();
LocalDate localDate = getLocalDateByWeekId(weekId).withDayOfWeek(DateTimeConstants.MONDAY);
for (int i = 0; i < 6; i++) {
daysOfWeek.add(localDate.plusDays(i));
}
return daysOfWeek;
}
List<Reservation> getReservationsByWashTimeAndDate(long washTimeId, LocalDate date) throws ParseException {
java.sql.Date sqlDate = new java.sql.Date(date.toDate().getTime());
return reservationDao.findByWashTimeIdAndDate(washTimeId, sqlDate);
}
boolean isUserAuthenticatedReservation(List<Reservation> reservationUser) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication.getPrincipal() instanceof User) {
User currentUser = (User) authentication.getPrincipal();
for (Reservation reservation : reservationUser) {
if (currentUser.getId() == reservation.getUser().getId()) {
return true;
}
}
}
return false;
}
int getWmFree(List<TimeWeekModel> timeWeekModels) {
int freeWm = 0;
for (TimeWeekModel timeWeekModel : timeWeekModels) {
for (TimeWeekModel.WmDate wmDate : timeWeekModel.getDates()) {
freeWm += wmDate.getWmFree();
}
}
return freeWm;
}
String getCellColor(int freeSpace, boolean past, boolean myReservation) {
if (past) {
return ColorUtil.RESERVATION_UNAVAILABLE_COLOR;
} else if (myReservation) {
return ColorUtil.RESERVATION_MY_COLOR;
}
if (freeSpace > 2 && freeSpace <= wmCount) {
return ColorUtil.RESERVATION_FREE_COLOR;
}
switch (freeSpace) {
case 2:
return ColorUtil.RESERVATION_TWO_FREE_COLOR;
case 1:
return ColorUtil.RESERVATION_ONE_FREE_COLOR;
default:
return ColorUtil.RESERVATION_UNAVAILABLE_COLOR;
}
}
}
|
package io.sweers.catchup.rx.autodispose;
import io.reactivex.CompletableObserver;
import io.reactivex.Maybe;
import io.reactivex.MaybeObserver;
import io.reactivex.MaybeSource;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.SingleObserver;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.BiConsumer;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.sweers.catchup.rx.autodispose.internal.AutoDisposeUtil;
import java.util.concurrent.Callable;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
public final class AutoDispose {
private static final Function<Object, LifecycleEndEvent> TRANSFORM_TO_END =
o -> LifecycleEndEvent.INSTANCE;
private AutoDispose() {
throw new InstantiationError();
}
public static AutoDisposingSubscriberCreator flowable(LifecycleProvider<?> provider) {
return new AutoDisposingSubscriberCreator(provider);
}
public static AutoDisposingSubscriberCreator flowable(Observable<?> lifecycle) {
return new AutoDisposingSubscriberCreator(lifecycle);
}
public static AutoDisposingSubscriberCreator flowable(Maybe<?> lifecycle) {
return new AutoDisposingSubscriberCreator(lifecycle);
}
public static AutoDisposingObserverCreator observable(LifecycleProvider<?> provider) {
return new AutoDisposingObserverCreator(provider);
}
public static AutoDisposingObserverCreator observable(Observable<?> lifecycle) {
return new AutoDisposingObserverCreator(lifecycle);
}
public static AutoDisposingObserverCreator observable(Maybe<?> lifecycle) {
return new AutoDisposingObserverCreator(lifecycle);
}
public static AutoDisposingSingleObserverCreator single(LifecycleProvider<?> provider) {
return new AutoDisposingSingleObserverCreator(provider);
}
public static AutoDisposingSingleObserverCreator single(Observable<?> lifecycle) {
return new AutoDisposingSingleObserverCreator(lifecycle);
}
public static AutoDisposingSingleObserverCreator single(Maybe<?> lifecycle) {
return new AutoDisposingSingleObserverCreator(lifecycle);
}
public static AutoDisposingMaybeObserverCreator maybe(LifecycleProvider<?> provider) {
return new AutoDisposingMaybeObserverCreator(provider);
}
public static AutoDisposingMaybeObserverCreator maybe(Observable<?> lifecycle) {
return new AutoDisposingMaybeObserverCreator(lifecycle);
}
public static AutoDisposingMaybeObserverCreator maybe(Maybe<?> lifecycle) {
return new AutoDisposingMaybeObserverCreator(lifecycle);
}
public static AutoDisposingCompletableObserverCreator completable(LifecycleProvider<?> provider) {
return new AutoDisposingCompletableObserverCreator(provider);
}
public static AutoDisposingCompletableObserverCreator completable(Observable<?> lifecycle) {
return new AutoDisposingCompletableObserverCreator(lifecycle);
}
public static AutoDisposingCompletableObserverCreator completable(Maybe<?> lifecycle) {
return new AutoDisposingCompletableObserverCreator(lifecycle);
}
private static <E> Maybe<LifecycleEndEvent> deferredResolvedLifecycle(LifecycleProvider<E> provider) {
return Maybe.defer(new Callable<MaybeSource<LifecycleEndEvent>>() {
@Override
public MaybeSource<LifecycleEndEvent> call() throws Exception {
E lastEvent = provider.peekLifecycle();
if (lastEvent == null) {
throw new LifecycleNotStartedException();
}
E endEvent = provider.correspondingEvents()
.apply(lastEvent);
return mapEvents(provider.lifecycle(), endEvent);
}
});
}
private static <E> Maybe<LifecycleEndEvent> mapEvents(Observable<E> lifecycle, E endEvent) {
return lifecycle.skip(1)
.map(e -> e.equals(endEvent))
.filter(b -> b)
.map(TRANSFORM_TO_END)
.firstElement();
}
private enum LifecycleEndEvent {
INSTANCE
}
private static class Base {
protected final Maybe<?> lifecycle;
protected Base(LifecycleProvider<?> provider) {
this(deferredResolvedLifecycle(AutoDisposeUtil.checkNotNull(provider, "provider == null")));
}
protected Base(Observable<?> lifecycle) {
this(AutoDisposeUtil.checkNotNull(lifecycle, "lifecycle == null").firstElement());
}
protected Base(Maybe<?> lifecycle) {
this.lifecycle = AutoDisposeUtil.checkNotNull(lifecycle, "lifecycle == null");
}
}
public static class AutoDisposingSubscriberCreator extends Base {
private AutoDisposingSubscriberCreator(LifecycleProvider<?> provider) {
super(provider);
}
private AutoDisposingSubscriberCreator(Observable<?> lifecycle) {
super(lifecycle);
}
private AutoDisposingSubscriberCreator(Maybe<?> lifecycle) {
super(lifecycle);
}
public <T> Subscriber<T> empty() {
return around(AutoDisposeUtil.EMPTY_CONSUMER,
AutoDisposeUtil.DEFAULT_ERROR_CONSUMER,
AutoDisposeUtil.EMPTY_ACTION);
}
public <T> Subscriber<T> around(Consumer<? super T> onNext) {
AutoDisposeUtil.checkNotNull(onNext, "onNext == null");
return around(onNext, AutoDisposeUtil.DEFAULT_ERROR_CONSUMER, AutoDisposeUtil.EMPTY_ACTION);
}
public <T> Subscriber<T> around(Consumer<? super T> onNext,
Consumer<? super Throwable> onError) {
AutoDisposeUtil.checkNotNull(onNext, "onNext == null");
AutoDisposeUtil.checkNotNull(onError, "onError == null");
return around(onNext, onError, AutoDisposeUtil.EMPTY_ACTION);
}
public <T> Subscriber<T> around(Consumer<? super T> onNext,
Consumer<? super Throwable> onError,
Action onComplete) {
AutoDisposeUtil.checkNotNull(onNext, "onNext == null");
AutoDisposeUtil.checkNotNull(onError, "onError == null");
AutoDisposeUtil.checkNotNull(onComplete, "onComplete == null");
return around(onNext, onError, onComplete, AutoDisposeUtil.EMPTY_SUBSCRIPTION_CONSUMER);
}
public <T> Subscriber<T> around(Subscriber<T> subscriber) {
AutoDisposeUtil.checkNotNull(subscriber, "subscriber == null");
return around(subscriber::onNext,
subscriber::onError,
subscriber::onComplete,
subscriber::onSubscribe);
}
public <T> Subscriber<T> around(Consumer<? super T> onNext,
Consumer<? super Throwable> onError,
Action onComplete,
Consumer<? super Subscription> onSubscribe) {
AutoDisposeUtil.checkNotNull(onNext, "onNext == null");
AutoDisposeUtil.checkNotNull(onError, "onError == null");
AutoDisposeUtil.checkNotNull(onComplete, "onComplete == null");
AutoDisposeUtil.checkNotNull(onSubscribe, "onSubscribe == null");
return new AutoDisposingSubscriber<>(lifecycle, onNext, onError, onComplete, onSubscribe);
}
}
public static class AutoDisposingObserverCreator extends Base {
private AutoDisposingObserverCreator(LifecycleProvider<?> provider) {
super(provider);
}
private AutoDisposingObserverCreator(Observable<?> lifecycle) {
super(lifecycle);
}
private AutoDisposingObserverCreator(Maybe<?> lifecycle) {
super(lifecycle);
}
public <T> Observer<T> empty() {
return around(AutoDisposeUtil.EMPTY_CONSUMER);
}
public <T> Observer<T> around(Consumer<? super T> onNext) {
AutoDisposeUtil.checkNotNull(onNext, "onNext == null");
return around(onNext, AutoDisposeUtil.DEFAULT_ERROR_CONSUMER, AutoDisposeUtil.EMPTY_ACTION);
}
public <T> Observer<T> around(Consumer<? super T> onNext, Consumer<? super Throwable> onError) {
AutoDisposeUtil.checkNotNull(onNext, "onNext == null");
AutoDisposeUtil.checkNotNull(onError, "onError == null");
return around(onNext, onError, AutoDisposeUtil.EMPTY_ACTION);
}
public <T> Observer<T> around(Consumer<? super T> onNext,
Consumer<? super Throwable> onError,
Action onComplete) {
AutoDisposeUtil.checkNotNull(onNext, "onNext == null");
AutoDisposeUtil.checkNotNull(onError, "onError == null");
AutoDisposeUtil.checkNotNull(onComplete, "onComplete == null");
return around(onNext, onError, onComplete, AutoDisposeUtil.EMPTY_DISPOSABLE_CONSUMER);
}
public <T> Observer<T> around(Observer<T> observer) {
AutoDisposeUtil.checkNotNull(observer, "observer == null");
return around(observer::onNext,
observer::onError,
observer::onComplete,
observer::onSubscribe);
}
public <T> Observer<T> around(Consumer<? super T> onNext,
Consumer<? super Throwable> onError,
Action onComplete,
Consumer<? super Disposable> onSubscribe) {
AutoDisposeUtil.checkNotNull(onNext, "onNext == null");
AutoDisposeUtil.checkNotNull(onError, "onError == null");
AutoDisposeUtil.checkNotNull(onComplete, "onComplete == null");
AutoDisposeUtil.checkNotNull(onSubscribe, "onSubscribe == null");
return new AutoDisposingObserver<>(lifecycle, onNext, onError, onComplete, onSubscribe);
}
}
public static class AutoDisposingSingleObserverCreator extends Base {
private AutoDisposingSingleObserverCreator(LifecycleProvider<?> provider) {
super(provider);
}
private AutoDisposingSingleObserverCreator(Observable<?> lifecycle) {
super(lifecycle);
}
private AutoDisposingSingleObserverCreator(Maybe<?> lifecycle) {
super(lifecycle);
}
public <T> SingleObserver<T> empty() {
return around(AutoDisposeUtil.EMPTY_CONSUMER);
}
public <T> SingleObserver<T> around(Consumer<? super T> onSuccess) {
AutoDisposeUtil.checkNotNull(onSuccess, "onSuccess == null");
return around(onSuccess, AutoDisposeUtil.DEFAULT_ERROR_CONSUMER);
}
public <T> SingleObserver<T> around(BiConsumer<? super T, ? super Throwable> biConsumer) {
AutoDisposeUtil.checkNotNull(biConsumer, "biConsumer == null");
return around(v -> biConsumer.accept(v, null), t -> biConsumer.accept(null, t));
}
public <T> SingleObserver<T> around(Consumer<? super T> onSuccess,
Consumer<? super Throwable> onError) {
AutoDisposeUtil.checkNotNull(onSuccess, "onSuccess == null");
AutoDisposeUtil.checkNotNull(onError, "onError == null");
return around(onSuccess, onError, AutoDisposeUtil.EMPTY_DISPOSABLE_CONSUMER);
}
public <T> SingleObserver<T> around(SingleObserver<T> observer) {
AutoDisposeUtil.checkNotNull(observer, "observer == null");
return around(observer::onSuccess, observer::onError, observer::onSubscribe);
}
public <T> SingleObserver<T> around(Consumer<? super T> onSuccess,
Consumer<? super Throwable> onError,
Consumer<? super Disposable> onSubscribe) {
AutoDisposeUtil.checkNotNull(onSuccess, "onSuccess == null");
AutoDisposeUtil.checkNotNull(onError, "onError == null");
AutoDisposeUtil.checkNotNull(onSubscribe, "onSubscribe == null");
return new AutoDisposingSingleObserver<>(lifecycle, onSuccess, onError, onSubscribe);
}
}
public static class AutoDisposingMaybeObserverCreator extends Base {
private AutoDisposingMaybeObserverCreator(LifecycleProvider<?> provider) {
super(provider);
}
private AutoDisposingMaybeObserverCreator(Observable<?> lifecycle) {
super(lifecycle);
}
private AutoDisposingMaybeObserverCreator(Maybe<?> lifecycle) {
super(lifecycle);
}
public <T> MaybeObserver<T> empty() {
return around(AutoDisposeUtil.EMPTY_CONSUMER);
}
public <T> MaybeObserver<T> around(Consumer<? super T> onSuccess) {
AutoDisposeUtil.checkNotNull(onSuccess, "onSuccess == null");
return around(onSuccess,
AutoDisposeUtil.DEFAULT_ERROR_CONSUMER,
AutoDisposeUtil.EMPTY_ACTION);
}
public <T> MaybeObserver<T> around(Consumer<? super T> onSuccess,
Consumer<? super Throwable> onError) {
AutoDisposeUtil.checkNotNull(onSuccess, "onSuccess == null");
AutoDisposeUtil.checkNotNull(onError, "onError == null");
return around(onSuccess, onError, AutoDisposeUtil.EMPTY_ACTION);
}
public <T> MaybeObserver<T> around(Consumer<? super T> onSuccess,
Consumer<? super Throwable> onError,
Action onComplete) {
AutoDisposeUtil.checkNotNull(onSuccess, "onSuccess == null");
AutoDisposeUtil.checkNotNull(onError, "onError == null");
AutoDisposeUtil.checkNotNull(onComplete, "onComplete == null");
return around(onSuccess, onError, onComplete, AutoDisposeUtil.EMPTY_DISPOSABLE_CONSUMER);
}
public <T> MaybeObserver<T> around(MaybeObserver<T> observer) {
AutoDisposeUtil.checkNotNull(observer, "observer == null");
return around(observer::onSuccess, observer::onError, observer::onComplete);
}
public <T> MaybeObserver<T> around(Consumer<? super T> onSuccess,
Consumer<? super Throwable> onError,
Action onComplete,
Consumer<? super Disposable> onSubscribe) {
AutoDisposeUtil.checkNotNull(onSuccess, "onSuccess == null");
AutoDisposeUtil.checkNotNull(onError, "onError == null");
AutoDisposeUtil.checkNotNull(onComplete, "onComplete == null");
AutoDisposeUtil.checkNotNull(onSubscribe, "onSubscribe == null");
return new AutoDisposingMaybeObserver<>(lifecycle,
onSuccess,
onError,
onComplete,
onSubscribe);
}
}
public static class AutoDisposingCompletableObserverCreator extends Base {
private AutoDisposingCompletableObserverCreator(LifecycleProvider<?> provider) {
super(provider);
}
private AutoDisposingCompletableObserverCreator(Observable<?> lifecycle) {
super(lifecycle);
}
private AutoDisposingCompletableObserverCreator(Maybe<?> lifecycle) {
super(lifecycle);
}
public CompletableObserver empty() {
return around(AutoDisposeUtil.EMPTY_ACTION);
}
public CompletableObserver around(Action action) {
AutoDisposeUtil.checkNotNull(action, "action == null");
return around(action, AutoDisposeUtil.DEFAULT_ERROR_CONSUMER);
}
public CompletableObserver around(Action action, Consumer<? super Throwable> onError) {
AutoDisposeUtil.checkNotNull(action, "action == null");
AutoDisposeUtil.checkNotNull(onError, "onError == null");
return around(action, onError, AutoDisposeUtil.EMPTY_DISPOSABLE_CONSUMER);
}
public CompletableObserver around(CompletableObserver observer) {
AutoDisposeUtil.checkNotNull(observer, "observer == null");
return around(observer::onComplete, observer::onError);
}
public CompletableObserver around(Action action,
Consumer<? super Throwable> onError,
Consumer<? super Disposable> onSubscribe) {
AutoDisposeUtil.checkNotNull(action, "action == null");
AutoDisposeUtil.checkNotNull(onError, "onError == null");
AutoDisposeUtil.checkNotNull(onSubscribe, "onSubscribe == null");
return new AutoDisposingCompletableObserver(lifecycle, action, onError, onSubscribe);
}
}
}
|
package com.hubspot.jinjava.tree;
import static org.assertj.core.api.Assertions.assertThat;
import com.hubspot.jinjava.BaseInterpretingTest;
import org.junit.Test;
public class StripTest extends BaseInterpretingTest {
@Test
public void itStrips() {
String expression =
"{% for i in range(10) -%}\r\n{% for j in range(10) -%}\r\n{% endfor %}";
String render = interpreter.render(expression);
assertThat(render).isEqualTo("");
}
}
|
package com.quemb.qmbform;
import com.quemb.qmbform.adapter.FormAdapter;
import com.quemb.qmbform.descriptor.FormDescriptor;
import com.quemb.qmbform.descriptor.FormItemDescriptor;
import com.quemb.qmbform.descriptor.OnFormRowChangeListener;
import com.quemb.qmbform.descriptor.OnFormRowValueChangedListener;
import com.quemb.qmbform.descriptor.RowDescriptor;
import com.quemb.qmbform.descriptor.SectionDescriptor;
import com.quemb.qmbform.descriptor.Value;
import com.quemb.qmbform.view.Cell;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.HeaderViewListAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
public class FormManager implements OnFormRowChangeListener, OnFormRowValueChangedListener {
private FormDescriptor mFormDescriptor;
protected ListView mListView;
private FormAdapter adapter;
protected OnFormRowClickListener mOnFormRowClickListener;
private OnFormRowChangeListener mOnFormRowChangeListener;
private OnFormRowValueChangedListener mOnFormRowValueChangedListener;
public FormManager() {
}
public void setup(FormDescriptor formDescriptor, final ListView listView, Fragment fragment) {
setup(formDescriptor, listView, fragment.getActivity());
adapter.setFragment(fragment);
}
public void setup(FormDescriptor formDescriptor, final ListView listView, Activity activity) {
Context context = activity;
// activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
mFormDescriptor = formDescriptor;
mFormDescriptor.setOnFormRowChangeListener(this);
mFormDescriptor.setOnFormRowValueChangedListener(this);
adapter = FormAdapter.newInstance(mFormDescriptor, context);
listView.setAdapter(adapter);
listView.setDividerHeight(1);
listView.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
FormItemDescriptor itemDescriptor = (FormItemDescriptor)parent.getAdapter().getItem(position);
Cell cell = (Cell) view;
if (cell != null && itemDescriptor instanceof RowDescriptor) {
RowDescriptor rowDescriptor = (RowDescriptor) itemDescriptor;
if (!rowDescriptor.getDisabled()) {
cell.onCellSelected();
}
if (rowDescriptor.getRowType().equals(RowDescriptor.FormRowDescriptorTypeSectionSeperator)) {
return;
}
}
OnFormRowClickListener descriptorListener = itemDescriptor.getOnFormRowClickListener();
if (descriptorListener != null) {
descriptorListener.onFormRowClick(itemDescriptor);
}
if (mOnFormRowClickListener != null) {
mOnFormRowClickListener.onFormRowClick(itemDescriptor);
}
}
});
mListView = listView;
}
public OnFormRowClickListener getOnFormRowClickListener() {
return mOnFormRowClickListener;
}
public void setOnFormRowClickListener(OnFormRowClickListener onFormRowClickListener) {
mOnFormRowClickListener = onFormRowClickListener;
}
public void updateRows() {
ListAdapter listAdapter = mListView.getAdapter();
FormAdapter adapter = null;
if (listAdapter instanceof HeaderViewListAdapter) {
adapter = (FormAdapter)((HeaderViewListAdapter)listAdapter).getWrappedAdapter();
} else {
adapter = (FormAdapter) listAdapter;
}
if (adapter != null) {
adapter.notifyDataSetChanged();
}
}
public OnFormRowChangeListener getOnFormRowChangeListener() {
return mOnFormRowChangeListener;
}
public void setOnFormRowChangeListener(OnFormRowChangeListener onFormRowChangeListener) {
mOnFormRowChangeListener = onFormRowChangeListener;
}
@Override
public void onRowAdded(RowDescriptor rowDescriptor, SectionDescriptor sectionDescriptor) {
updateRows();
if (mOnFormRowChangeListener != null) {
mOnFormRowChangeListener.onRowAdded(rowDescriptor, sectionDescriptor);
}
}
@Override
public void onRowRemoved(RowDescriptor rowDescriptor, SectionDescriptor sectionDescriptor) {
updateRows();
if (mOnFormRowChangeListener != null) {
mOnFormRowChangeListener.onRowRemoved(rowDescriptor, sectionDescriptor);
}
}
@Override
public void onRowChanged(RowDescriptor rowDescriptor, SectionDescriptor sectionDescriptor) {
updateRows();
if (mOnFormRowChangeListener != null) {
mOnFormRowChangeListener.onRowChanged(rowDescriptor, sectionDescriptor);
}
}
@Override
public void onValueChanged(RowDescriptor rowDescriptor, Value<?> oldValue, Value<?> newValue) {
if (mOnFormRowValueChangedListener != null) {
mOnFormRowValueChangedListener.onValueChanged(rowDescriptor, oldValue, newValue);
}
}
public void setOnFormRowValueChangedListener(
OnFormRowValueChangedListener onFormRowValueChangedListener) {
mOnFormRowValueChangedListener = onFormRowValueChangedListener;
}
public FormDescriptor getFormDescriptor() {
return mFormDescriptor;
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
for(SectionDescriptor sectionDescriptor: mFormDescriptor.getSections()) {
for (RowDescriptor rowDescriptor: sectionDescriptor.getRows()) {
Cell cell = rowDescriptor.getCell();
if(cell != null && cell.isWaitingActivityResult()) {
cell.onActivityResult(requestCode, resultCode, data);
}
}
}
/*
for (int i=mListView.getFirstVisiblePosition();i<=mListView.getLastVisiblePosition();i++) {
View v = mListView.getChildAt(i);
if (v instanceof Cell) {
Cell cell = (Cell)v;
if(cell != null && cell.isWaitingActivityResult()) {
cell.onActivityResult(requestCode, resultCode, data);
}
}
}
*/
}
}
|
package com.apm4all.tracy.analysis.task;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.ThreadLocalRandom;
public class TaskAnalysis {
private long earliest;
private long latest;
private String filter;
private String sort;
private String application;
private String task;
private int offset;
private int limit;
private int records;
// tracyTasks 1-has->* tracyTask 1-has->* tracyEvents
private ArrayList<Object> tracyTasks;
public TaskAnalysis(String application, String task, long earliest, long latest, String filter, String sort, int limit, int offset) {
// TODO: handle params: earliest, latest, filter, sort
this.application = application;
this.task = task;
this.earliest = earliest;
this.latest = latest;
this.filter = filter;
this.sort = sort;
this.records = 18;
this.offset = offset;
this.limit = limit;
this.tracyTasks = new ArrayList<Object>(200);
}
public String getApplication() {
return this.application;
}
public String getTask() {
return this.task;
}
public HashMap<String,Object> getTracyTasksPage() {
//TODO: Return structure line below
HashMap<String,Object> tracyTasksPage = new HashMap<String,Object>();
tracyTasksPage.put("offset", this.offset);
tracyTasksPage.put("limit", this.limit);
tracyTasksPage.put("records", this.records);
ArrayList<Object> tracyTasks = new ArrayList<Object>();
tracyTasksPage.put("tracyTasks", tracyTasks);
// Create mocked up tracyTasks
for (int i=0 ; i<records ; i++) {
tracyTasks.add(generateTracyTask((latest-earliest)*i/limit));
}
return tracyTasksPage;
}
private HashMap<String, Object> generateTracyTask(long timeOffset) {
// TODO: Consider a class hierarchy for TracyTask,
// tracyTasks[] 1-has->* tracyTask{} 1-has->* tracyEvents[]
ArrayList<Object> tracyTaskEvents = new ArrayList<Object>(20);
HashMap<String, Object> tracyEvents = new HashMap<String, Object>();
HashMap<String, Object> tracyTask = new HashMap<String, Object>();
long rt = this.earliest;
// Add jitter to offset
timeOffset += ThreadLocalRandom.current().nextInt(0, 1000 + 1);;
//[675 TO 719]
String filterArray[] = this.filter.split(":");
System.out.println(filterArray[1]);
String limits[] = filterArray[1].split("\\Q[\\E|\\Q]\\E| TO ");
// System.out.println(limits.length);
// for (int i=0 ; i < limits.length ; i++) {
// System.out.println(limits[i]);
int ll = Integer.parseInt(limits[1]);
// int ul = Integer.parseInt(limits[2]);
// long offset = 10; // msecOffset
// long offset = 1010; // secOffset
// long offset = 61010; // minOffset
long offset = 3601000L; // hourOffset
if (this.task.contains("Static")) {
// msec unit
offset = (ll/10L);
}
else {
// hour unit
offset = ll*3601000L/10L;
}
String host = "ukdb807735-3.local";
tracyTaskEvents.add(createTracyEvent("TID-ab1234-x", "4F3D", "foo", "AD24", timeOffset+rt+offset*5, timeOffset+rt+offset*7, offset*2, host, "Service"));
tracyTaskEvents.add(createTracyEvent("TID-ab1234-x", "4F3D", "bar", "AE5F", timeOffset+rt+offset*3, timeOffset+rt+offset*5, offset*2, host, "Service"));
tracyTaskEvents.add(createTracyEvent("TID-ab1234-x", "23CF", "Http servlet", "4F3D", timeOffset+rt+offset*2, timeOffset+rt+offset*8, offset*6, host, "Service"));
tracyTaskEvents.add(createTracyEvent("TID-ab1234-x", "DBF5", "Service handler", "23CF", timeOffset+rt+offset, timeOffset+rt+offset*9, offset*8, host, "Proxy"));
tracyTaskEvents.add(createTracyEvent("TID-ab1234-x", "AAAA", "Client handler", "DBF5", timeOffset+rt, timeOffset+rt+offset*10, offset*10, host, "Proxy"));
tracyEvents.put("tracyEvents", tracyTaskEvents);
tracyTask.put("tracyTask", tracyEvents);
return tracyTask;
}
private HashMap<String, Object> createTracyEvent(
String taskId,
String parentOptId,
String label,
String optId,
Long msecBefore,
Long msecAfter,
Long msecElapsed,
String host,
String component) {
HashMap<String, Object> tracyEvent = new HashMap<String, Object>(10);
tracyEvent.put("taskId", taskId);
tracyEvent.put("parentOptId", parentOptId);
tracyEvent.put("label", label);
tracyEvent.put("optId", optId);
tracyEvent.put("msecBefore", msecBefore);
tracyEvent.put("msecAfter", msecAfter);
tracyEvent.put("msecElapsed", msecElapsed);
tracyEvent.put("host", host);
tracyEvent.put("component", component);
return tracyEvent;
}
public long getEarliest() {
return earliest;
}
public long getLatest() {
return latest;
}
public String getFilter() {
return filter;
}
public String getSort() {
return sort;
}
}
//"tracyTasksPage": {
// "offset": 0,
// "limit": 2,
// "records": 2,
// "tracyTasks": [
// "tracyTask": {
// "tracyEvents": [
// "taskId": "rrt017eudn-7245-675317-1",
// "parentOptId": "246A",
// "label": "transformEMF1ToJson",
// "optId": "CD54",
// "msecBefore": 1446163199518,
// "msecAfter": 1446163199518,
// "msecElapsed": 0,
// "component": "matchplus-ws",
// "host": "ip-10-241-0-39"
// "taskId": "rrt017eudn-7245-675317-1",
// "parentOptId": "AG50",
// "label": "getCleanseMatch",
// "optId": "246A",
// "msecBefore": 1446163198129,
// "msecAfter": 1446163199519,
// "msecElapsed": 1390,
// "subscriberType": "internal",
// "companyName": "Sarada Prasana Jena",
// "apigee.developer.app.name": "JenaS-Match-App-Prod",
// "lookupType": "NA",
// "reqParam": "MONSIEUR PIERRE CHALLET",
// "ctryCd": "FR",
// "component": "matchplus-ws",
// "sourceIp": "37.252.225.18",
// "apigee.developer.email": "jenas@dnb.com",
// "host": "ip-10-241-0-39",
// "subscriberNumber": "5008",
// "engineName": "GF"
// "taskId": "rrt017eudn-7245-675317-1",
// "parentOptId": "246A",
// "label": "transformJsonToEMF1",
// "optId": "9FD5",
// "msecBefore": 1446163198129,
// "msecAfter": 1446163198129,
// "msecElapsed": 0,
// "component": "matchplus-ws",
// "host": "ip-10-241-0-39"
// "taskId": "rrt017eudn-7245-675317-1",
// "parentOptId": "246A",
// "label": "matchEngineGF",
// "optId": "3278",
// "msecBefore": 1446163198129,
// "msecAfter": 1446163199518,
// "msecElapsed": 1389,
// "lookupType": "NA",
// "component": "matchplus-ws",
// "host": "ip-10-241-0-39",
// "engineName": "GF"
// "tracyTask": {
// "tracyEvents": [
// "taskId": "rrt056wodn-25309-693227-1",
// "parentOptId": "246A",
// "label": "transformEMF1ToJson",
// "optId": "CD54",
// "msecBefore": 1446163199518,
// "msecAfter": 1446163199518,
// "msecElapsed": 0,
// "component": "matchplus-ws",
// "host": "ip-10-241-0-39"
// "taskId": "rrt056wodn-25309-693227-1",
// "parentOptId": "AG50",
// "label": "getCleanseMatch",
// "optId": "246A",
// "msecBefore": 1446163198129,
// "msecAfter": 1446163199519,
// "msecElapsed": 1390,
// "subscriberType": "internal",
// "companyName": "Sarada Prasana Jena",
// "apigee.developer.app.name": "JenaS-Match-App-Prod",
// "lookupType": "NA",
// "reqParam": "MONSIEUR PIERRE CHALLET",
// "ctryCd": "FR",
// "component": "matchplus-ws",
// "sourceIp": "37.252.225.18",
// "apigee.developer.email": "jenas@dnb.com",
// "host": "ip-10-241-0-39",
// "subscriberNumber": "5008",
// "engineName": "GF"
// "taskId": "rrt056wodn-25309-693227-1",
// "parentOptId": "246A",
// "label": "transformJsonToEMF1",
// "optId": "9FD5",
// "msecBefore": 1446163198129,
// "msecAfter": 1446163198129,
// "msecElapsed": 0,
// "component": "matchplus-ws",
// "host": "ip-10-241-0-39"
// "taskId": "rrt056wodn-25309-693227-1",
// "parentOptId": "246A",
// "label": "matchEngineGF",
// "optId": "3278",
// "msecBefore": 1446163198129,
// "msecAfter": 1446163199518,
// "msecElapsed": 1389,
// "lookupType": "NA",
// "component": "matchplus-ws",
// "host": "ip-10-241-0-39",
// "engineName": "GF"
|
package com.axiomalaska.sos.xmlbuilder;
import java.io.StringWriter;
import java.util.Calendar;
import java.util.TimeZone;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
/**
* A base class for building SOS XML
*
* @author Lance Finfrock
*/
public abstract class SosXmlBuilder {
public abstract String build();
/**
* Get a string value from document
*
* @param doc - the document to build the string from.
* @return - the xml string from the document past in.
*/
protected String getString(Document doc) throws TransformerException{
//set up a transformer
TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans = transfac.newTransformer();
trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
trans.setOutputProperty(OutputKeys.INDENT, "yes");
//create string from xml tree
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(doc);
trans.transform(source, result);
String xmlString = sw.toString();
return xmlString;
}
/**
* Format calendar to 2012-04-17T20:02:05-0000
*
* @param calendar
* - date to be formated
* @return
*/
protected String formatCalendarIntoGMTTime(Calendar calendar) {
Calendar copyCalendar = (Calendar) calendar.clone();
copyCalendar.setTimeZone(TimeZone.getTimeZone("GMT"));
return (copyCalendar.get(Calendar.YEAR) + "-"
+ formatNumber(copyCalendar.get(Calendar.MONTH) + 1) + "-"
+ formatNumber(copyCalendar.get(Calendar.DAY_OF_MONTH)) + "T"
+ formatNumber(copyCalendar.get(Calendar.HOUR_OF_DAY)) + ":"
+ formatNumber(copyCalendar.get(Calendar.MINUTE)) + ":"
+ formatNumber(copyCalendar.get(Calendar.SECOND)) + "-0000");
}
private String formatNumber(int number) {
if (number >= 10) {
return number + "";
} else {
return "0" + number;
}
}
}
|
package sys.net.impl.providers.nio;
import static sys.Sys.Sys;
import static sys.net.impl.NetworkingConstants.NIO_CONNECTION_TIMEOUT;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Level;
import java.util.logging.Logger;
import sys.net.api.Endpoint;
import sys.net.api.Message;
import sys.net.api.TransportConnection;
import sys.net.impl.AbstractEndpoint;
import sys.net.impl.AbstractLocalEndpoint;
import sys.net.impl.FailedTransportConnection;
import sys.net.impl.NetworkingConstants.NIO_ReadBufferDispatchPolicy;
import sys.net.impl.NetworkingConstants.NIO_ReadBufferPoolPolicy;
import sys.net.impl.NetworkingConstants.NIO_WriteBufferPoolPolicy;
import sys.net.impl.providers.AbstractTransport;
import sys.net.impl.providers.BufferPool;
import sys.net.impl.providers.InitiatorInfo;
import sys.net.impl.providers.KryoInputBuffer;
import sys.net.impl.providers.KryoOutputBuffer;
import sys.net.impl.providers.MultiQueueExecutor;
import sys.net.impl.providers.RemoteEndpointUpdater;
import sys.utils.IO;
import sys.utils.Threading;
import com.esotericsoftware.kryo.KryoException;
public class TcpEndpoint extends AbstractLocalEndpoint implements Runnable {
private static Logger Log = Logger.getLogger(TcpEndpoint.class.getName());
ServerSocketChannel ssc;
MultiQueueExecutor executor = new MultiQueueExecutor();
public TcpEndpoint(Endpoint local, int tcpPort) throws IOException {
this.localEndpoint = local;
this.gid = Sys.rg.nextLong() >>> 1;
if (tcpPort >= 0) {
ssc = ServerSocketChannel.open();
ssc.socket().bind(new InetSocketAddress(tcpPort));
}
super.setSocketAddress(ssc == null ? 0 : ssc.socket().getLocalPort());
}
public void start() throws IOException {
handler = localEndpoint.getHandler();
if (ssc != null)
Threading.newThread("accept", true, this).start();
}
public TransportConnection connect(Endpoint remote) {
try {
if (((AbstractEndpoint) remote).isIncoming())
return new OutgoingConnection(remote);
else {
Log.info("Attempting to connect to an outgoing only endpoint. " + remote);
}
return new FailedTransportConnection(localEndpoint, remote, null);
} catch (Throwable t) {
Log.log(Level.WARNING, "Cannot connect to: <" + remote + "> :" + t.getMessage());
return new FailedTransportConnection(localEndpoint, remote, t);
}
}
@Override
public void run() {
try {
Log.finest("Bound to: " + this);
for (;;) {
SocketChannel channel = ssc.accept();
configureChannel(channel);
new IncomingConnection(channel);
}
} catch (Exception x) {
Log.log(Level.SEVERE, "Unexpected error in incoming endpoint: " + localEndpoint, x);
}
IO.close(ssc);
}
static void configureChannel(SocketChannel ch) {
try {
ch.socket().setTcpNoDelay(true);
ch.socket().setReceiveBufferSize(1 << 20);
ch.socket().setSendBufferSize(1500);
} catch (Exception x) {
x.printStackTrace();
}
}
abstract class AbstractConnection extends AbstractTransport implements RemoteEndpointUpdater, Runnable {
String type;
Throwable cause;
SocketChannel channel;
final BufferPool<KryoInputBuffer> readPool;
final BufferPool<KryoOutputBuffer> writePool;
NIO_ReadBufferPoolPolicy readPoolPolicy = NIO_ReadBufferPoolPolicy.POLLING;
NIO_WriteBufferPoolPolicy writePoolPolicy = NIO_WriteBufferPoolPolicy.POLLING;
NIO_ReadBufferDispatchPolicy execPolicy = NIO_ReadBufferDispatchPolicy.READER_EXECUTES;
public AbstractConnection() throws IOException {
super(localEndpoint, null);
this.readPool = new BufferPool<KryoInputBuffer>();
this.writePool = new BufferPool<KryoOutputBuffer>();
}
@Override
final public void run() {
while (this.readPool.remainingCapacity() > 0)
this.readPool.offer(new _ReadBuffer());
while (this.writePool.remainingCapacity() > 0)
this.writePool.offer(new KryoOutputBuffer());
try {
for (;;) {
KryoInputBuffer inBuf;
if (readPoolPolicy == NIO_ReadBufferPoolPolicy.BLOCKING)
inBuf = readPool.take();
else {
inBuf = readPool.poll();
if (inBuf == null)
inBuf = new _ReadBuffer();
}
if (inBuf.readFrom(channel)) {
if (execPolicy == NIO_ReadBufferDispatchPolicy.USE_THREAD_POOL)
executor.execute(this, inBuf);
else
inBuf.run();
} else {
this.readPool.offer(inBuf);
handler.onClose(this);
break;
}
}
} catch (Throwable t) {
Log.log(Level.FINEST, "Exception in connection to: " + remote, t);
// t.printStackTrace();
cause = t;
handler.onFailure(this);
}
isBroken = true;
IO.close(channel);
Log.fine("Closed connection to: " + remote);
}
final class _ReadBuffer extends KryoInputBuffer {
@Override
public void run() {
Message msg;
try {
msg = super.readClassAndObject();
msg.setSize(super.contentLength);
} catch (Throwable t) {
Log.log(Level.SEVERE, "Exception in connection to: " + remote, t);
return;
} finally {
readPool.offer(this);
}
try {
msg.deliverTo(AbstractConnection.this, TcpEndpoint.this.handler);
} catch (Throwable t) {
Log.log(Level.WARNING,"Dispatch Exception: " + t.getClass() + " caused by: " + msg.getClass()
+ " received from: " + remoteEndpoint() + " with " + super.contentLength, t);
}
}
}
final public boolean send(final Message m) {
KryoOutputBuffer outBuf = null;
try {
if (writePoolPolicy == NIO_WriteBufferPoolPolicy.BLOCKING)
outBuf = writePool.take();
else {
outBuf = writePool.poll();
if (outBuf == null)
outBuf = new KryoOutputBuffer();
}
int size = outBuf.writeClassAndObjectFrame(m, channel);
m.setSize(size);
return true;
} catch (Throwable t) {
if (t instanceof KryoException)
Log.log(Level.SEVERE, "Exception in connection to: " + remote, t);
else
Log.log(Level.WARNING, "Exception in connection to: " + remote, t);
cause = t;
isBroken = true;
IO.close(channel);
handler.onFailure(this);
} finally {
if (outBuf != null)
writePool.offer(outBuf);
}
return false;
}
public boolean sendNow(final Message m) {
try {
KryoOutputBuffer outBuf = new KryoOutputBuffer();
int size = outBuf.writeClassAndObjectFrame(m, channel);
m.setSize(size);
return true;
} catch (Throwable t) {
Log.log(Level.SEVERE, "Exception in connection to: " + remote, t);
}
return false;
}
public <T extends Message> T receive() {
throw new RuntimeException("Not implemented...");
// KryoBuffer inBuf = null;
// try {
// inBuf = rq.take();
// T msg = inBuf.readClassAndObject();
// return msg;
// } catch (Throwable t) {
// t.printStackTrace();
// } finally {
// if (inBuf != null)
// readPool.offer(inBuf);
// return null;
}
@Override
public Throwable causeOfFailure() {
return failed() ? cause : new Exception("?");
}
public String toString() {
return String.format("%s (%s->%s)", type, channel.socket().getLocalPort(), channel.socket()
.getRemoteSocketAddress());
}
public void setOption(String op, Object val) {
super.setOption(op, val);
if (op.equals("NIO_ReadBufferPoolPolicy"))
readPoolPolicy = (NIO_ReadBufferPoolPolicy) val;
else if (op.equals("NIO_ReadBufferPoolPolicy"))
execPolicy = (NIO_ReadBufferDispatchPolicy) val;
}
}
class IncomingConnection extends AbstractConnection {
public IncomingConnection(SocketChannel channel) throws IOException {
super.channel = channel;
super.type = "in";
Threading.newThread("incoming-tcp-channel-reader:" + local + " <-> " + remote, true, this).start();
}
}
class OutgoingConnection extends AbstractConnection implements Runnable {
public OutgoingConnection(Endpoint remote) throws IOException {
super.setRemoteEndpoint(remote);
super.type = "out";
init();
}
void init() throws IOException {
try {
channel = SocketChannel.open();
channel.socket().connect(((AbstractEndpoint) remote).sockAddress(), NIO_CONNECTION_TIMEOUT);
configureChannel(channel);
} catch (IOException x) {
cause = x;
isBroken = true;
IO.close(channel);
throw x;
}
this.send(new InitiatorInfo(localEndpoint));
handler.onConnect(this);
Threading.newThread("outgoing-tcp-channel-reader:" + local + " <-> " + remote, true, this).start();
// new Task(Sys.rg.nextDouble() * 10) {
// public void run() {
// sendNow(new TcpPing( Sys.currentTime() ) );
// this.reSchedule(5 + Sys.rg.nextDouble() * 10);
}
}
}
|
package org.fossasia.susi.ai.activities;
import android.Manifest;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.speech.tts.TextToSpeech;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.util.Pair;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Base64;
import android.util.Log;
import android.util.Patterns;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import org.fossasia.susi.ai.R;
import org.fossasia.susi.ai.adapters.recycleradapters.ChatFeedRecyclerAdapter;
import org.fossasia.susi.ai.helper.Constant;
import org.fossasia.susi.ai.helper.DateTimeHelper;
import org.fossasia.susi.ai.helper.MediaUtil;
import org.fossasia.susi.ai.helper.PrefManager;
import org.fossasia.susi.ai.model.ChatMessage;
import org.fossasia.susi.ai.model.MapData;
import org.fossasia.susi.ai.rest.clients.BaseUrl;
import org.fossasia.susi.ai.rest.ClientBuilder;
import org.fossasia.susi.ai.rest.clients.LocationClient;
import org.fossasia.susi.ai.rest.services.LocationService;
import org.fossasia.susi.ai.rest.responses.susi.Datum;
import org.fossasia.susi.ai.helper.LocationHelper;
import org.fossasia.susi.ai.rest.responses.others.LocationResponse;
import org.fossasia.susi.ai.rest.responses.susi.SusiResponse;
import org.fossasia.susi.ai.rest.responses.susi.MemoryResponse;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.regex.Matcher;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.realm.Case;
import io.realm.Realm;
import io.realm.RealmList;
import io.realm.RealmResults;
import pl.tajchert.sample.DotsTextView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static android.media.AudioManager.AUDIOFOCUS_LOSS_TRANSIENT;
public class MainActivity extends AppCompatActivity {
public static String TAG = MainActivity.class.getName();
private final int SELECT_PICTURE = 200;
private final int CROP_PICTURE = 400;
private boolean isEnabled = true;
@BindView(R.id.coordinator_layout)
CoordinatorLayout coordinatorLayout;
@BindView(R.id.rv_chat_feed)
RecyclerView rvChatFeed;
@BindView(R.id.et_message)
EditText ChatMessage;
@BindView(R.id.send_message_layout)
LinearLayout sendMessageLayout;
@BindView(R.id.btnSpeak)
protected ImageView btnSpeak;
@BindView(R.id.voice_input_text)
protected TextView voiceInputText;
@BindView(R.id.dots)
protected DotsTextView voiceDots;
@BindView(R.id.cancel)
protected ImageView cancelInput;
private boolean atHome = true;
private boolean backPressedOnce = false;
private FloatingActionButton fab_scrollToEnd;
// Global Variables used for the setMessage Method
private String answer;
private boolean isHavingLink = false;
private String actionType;
private MapData mapData = null;
private List<Datum> datumList = null;
private boolean micCheck;
private SearchView searchView;
private boolean check;
private Menu menu;
private int pointer;
private RealmResults<ChatMessage> results;
private int offset = 1;
private ChatFeedRecyclerAdapter recyclerAdapter;
private Realm realm;
public static String webSearch;
private TextToSpeech textToSpeech;
private BroadcastReceiver networkStateReceiver;
private ClientBuilder clientBuilder;
private Deque<Pair<String, Long>> nonDeliveredMessages = new LinkedList<>();
private SpeechRecognizer recognizer;
private ProgressDialog progressDialog;
private long newMessageIndex = 0;
private AudioManager.OnAudioFocusChangeListener afChangeListener =
new AudioManager.OnAudioFocusChangeListener() {
public void onAudioFocusChange(int focusChange) {
if (focusChange == AUDIOFOCUS_LOSS_TRANSIENT) {
textToSpeech.stop();
} else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
// Resume playback
} else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
textToSpeech.stop();
}
}
};
TextWatcher watch = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(final CharSequence charSequence, int i, int i1, int i2) {
if (charSequence.toString().trim().length() > 0 || !micCheck) {
btnSpeak.setImageResource(R.drawable.ic_send_fab);
btnSpeak.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
check = false;
switch (view.getId()) {
case R.id.btnSpeak:
String chat = ChatMessage.getText().toString();
String chat_message = chat.trim();
String splits[] = chat_message.split("\n");
String message = "";
for (String split : splits)
message = message.concat(split).concat(" ");
if (!TextUtils.isEmpty(chat_message)) {
sendMessage(message, chat);
ChatMessage.setText("");
}
break;
}
}
});
} else {
btnSpeak.setImageResource(R.drawable.ic_mic_white_24dp);
btnSpeak.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
check = true;
displayVoiceInput();
promptSpeechInput();
}
});
}
}
@Override
public void afterTextChanged(Editable editable) {
}
};
private void hideVoiceInput() {
voiceInputText.setText("");
voiceInputText.setVisibility(View.GONE);
cancelInput.setVisibility(View.GONE);
voiceDots.hideAndStop();
voiceDots.setVisibility(View.GONE);
ChatMessage.setVisibility(View.VISIBLE);
btnSpeak.setVisibility(View.VISIBLE);
}
private void displayVoiceInput() {
voiceDots.setVisibility(View.VISIBLE);
voiceInputText.setVisibility(View.VISIBLE);
cancelInput.setVisibility(View.VISIBLE);
ChatMessage.setVisibility(View.GONE);
btnSpeak.setVisibility(View.GONE);
}
@OnClick(R.id.cancel)
public void cancelSpeechInput() {
if(recognizer != null) {
recognizer.cancel();
recognizer.destroy();
recognizer=null;
}
hideVoiceInput();
}
public static List<String> extractUrls(String text) {
List<String> links = new ArrayList<>();
Matcher m = Patterns.WEB_URL.matcher(text);
while (m.find()) {
String url = m.group();
links.add(url);
}
return links;
}
public static boolean checkSpeechOutputPref() {
return PrefManager.getBoolean(Constant.SPEECH_OUTPUT, true);
}
public static boolean checkSpeechAlwaysPref() {
return PrefManager.getBoolean(Constant.SPEECH_ALWAYS, false);
}
public boolean checkMicInput() {
return micCheck = MediaUtil.isAvailableForVoiceInput(MainActivity.this);
}
private void parseSusiResponse(SusiResponse susiResponse, int i) {
actionType = susiResponse.getAnswers().get(0).getActions().get(i).getType();
datumList = null;
mapData = null;
webSearch = "";
isHavingLink = false;
switch(actionType) {
case Constant.ANCHOR :
try {
boolean isAnchor = susiResponse.getAnswers().get(0).getActions().get(i).getType().equals("anchor");
if(isAnchor)
answer = "<a href=\"" +susiResponse.getAnswers().get(0).getActions().get(i).getAnchorLink() + "\">" + susiResponse.getAnswers().get(0).getActions().get(1).getAnchorText() + "</a>";
} catch (Exception e) {
answer = getString(R.string.error_occurred_try_again);
}
break;
case Constant.ANSWER :
try {
answer = susiResponse.getAnswers().get(0).getActions()
.get(i).getExpression();
List<String> urlList = extractUrls(answer);
Log.d(TAG, urlList.toString());
isHavingLink = urlList != null;
if (urlList.size() == 0) isHavingLink = false;
} catch (Exception e ) {
answer = getString(R.string.error_occurred_try_again);
isHavingLink = false;
}
break;
case Constant.MAP :
try {
final double latitude = susiResponse.getAnswers().get(0).getActions().get(i).getLatitude();
final double longitude = susiResponse.getAnswers().get(0).getActions().get(i).getLongitude();
final double zoom = susiResponse.getAnswers().get(0).getActions().get(i).getZoom();
mapData = new MapData(latitude,longitude,zoom);
} catch (Exception e) {
mapData = null;
}
break;
case Constant.PIECHART :
try {
datumList = susiResponse.getAnswers().get(0).getData();
} catch (Exception e) {
datumList = null;
}
break;
case Constant.RSS :
try {
datumList = susiResponse.getAnswers().get(0).getData();
} catch (Exception e) {
datumList = null;
}
break;
case Constant.WEBSEARCH :
try {
webSearch = susiResponse.getAnswers().get(0).getActions().get(1).getQuery();
} catch (Exception e) {
webSearch = "";
}
break;
default:
answer = getString(R.string.error_occurred_try_again);
}
}
private void getOldMessages() {
if (isNetworkConnected()) {
Call<MemoryResponse> call = clientBuilder.getSusiApi().getChatHistory();
call.enqueue(new Callback<MemoryResponse>() {
@Override
public void onResponse(Call<MemoryResponse> call, Response<MemoryResponse> response) {
if (response != null && response.isSuccessful() && response.body() != null) {
List<SusiResponse> allMessages = response.body().getCognitionsList();
if(allMessages.size() == 0) {
showToast("No messages found");
} else {
updateDatabase(0, "", true, false, null, null, false, null);
long c = 1;
for (int i = allMessages.size() - 1; i >= 0; i
String query = allMessages.get(i).getQuery();
List<String> urlList = extractUrls(query);
Log.d(TAG, urlList.toString());
isHavingLink = urlList != null;
if (urlList.size() == 0) isHavingLink = false;
c = newMessageIndex;
updateDatabase(newMessageIndex,query, false, true, null, null, isHavingLink, null);
int actionSize = allMessages.get(i).getAnswers().get(0).getActions().size();
for(int j=0 ; j<actionSize ; j++) {
parseSusiResponse(allMessages.get(i),j);
updateDatabase(c, answer, false, false, actionType, mapData, isHavingLink, datumList);
}
}
}
progressDialog.dismiss();
} else {
if (!isNetworkConnected()) {
Snackbar snackbar = Snackbar.make(coordinatorLayout,
getString(R.string.no_internet_connection), Snackbar.LENGTH_LONG);
snackbar.show();
}
progressDialog.dismiss();
}
}
@Override
public void onFailure(Call<MemoryResponse> call, Throwable t) {
Log.e(TAG, t.toString());
progressDialog.dismiss();
}
});
} else {
Snackbar snackbar = Snackbar.make(coordinatorLayout,
getString(R.string.no_internet_connection), Snackbar.LENGTH_LONG);
snackbar.show();
progressDialog.dismiss();
}
}
private void retrieveOldMessages() {
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setCancelable(false);
progressDialog.setMessage(getString(R.string.dialog_retrieve_messages_title));
progressDialog.show();
Thread thread = new Thread() {
@Override
public void run() {
getOldMessages();
}
};
thread.start();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
clientBuilder = new ClientBuilder();
realm = Realm.getDefaultInstance();
Number temp = realm.where(ChatMessage.class).max(getString(R.string.id));
if (temp == null) {
newMessageIndex = 0;
} else {
newMessageIndex = (long) temp + 1;
}
boolean firstRun = getIntent().getBooleanExtra("FIRST_TIME",false);
if(firstRun && isNetworkConnected()) {
retrieveOldMessages();
}
if (PrefManager.getString(Constant.ACCESS_TOKEN, null) == null) {
throw new IllegalStateException("Not signed in, Cannot access resource!");
}
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this,
Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.RECORD_AUDIO}, 1);
} else if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 2);
} else if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, 3);
}
if(ActivityCompat.checkSelfPermission(this,
Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) {
PrefManager.putBoolean(Constant.MIC_INPUT, checkMicInput());
}
getLocationFromLocationService();
getLocationFromIP();
init();
compensateTTSDelay();
}
private void compensateTTSDelay() {
new Handler().post(new Runnable() {
@Override
public void run() {
textToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
Locale locale = textToSpeech.getLanguage();
textToSpeech.setLanguage(locale);
}
}
});
}
});
}
private void promptSpeechInput() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
"com.domain.app");
intent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS,true);
recognizer = SpeechRecognizer
.createSpeechRecognizer(this.getApplicationContext());
RecognitionListener listener = new RecognitionListener() {
@Override
public void onResults(Bundle results) {
ArrayList<String> voiceResults = results
.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
if (voiceResults == null) {
Log.e(TAG, "No voice results");
} else {
Log.d(TAG, "Printing matches: ");
for (String match : voiceResults) {
Log.d(TAG, match);
}
}
sendMessage(voiceResults.get(0),voiceResults.get(0));
recognizer.destroy();
hideVoiceInput();
}
@Override
public void onReadyForSpeech(Bundle params) {
Log.d(TAG, "Ready for speech");
voiceDots.show();
}
@Override
public void onError(int error) {
Log.d(TAG,
"Error listening for speech: " + error);
Toast.makeText(getApplicationContext(),"Could not recognize speech, try again.",Toast.LENGTH_SHORT).show();
recognizer.destroy();
hideVoiceInput();
}
@Override
public void onBeginningOfSpeech() {
Log.d(TAG, "Speech starting");
voiceDots.start();
}
@Override
public void onBufferReceived(byte[] buffer) {
// This method is intentionally empty
}
@Override
public void onEndOfSpeech() {
// This method is intentionally empty
}
@Override
public void onEvent(int eventType, Bundle params) {
// This method is intentionally empty
}
@Override
public void onPartialResults(Bundle partialResults) {
ArrayList<String> partial = partialResults
.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
voiceInputText.setText(partial.get(0));
}
@Override
public void onRmsChanged(float rmsdB) {
// This method is intentionally empty
}
};
recognizer.setRecognitionListener(listener);
recognizer.startListening(intent);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Handler mHandler = new Handler(Looper.getMainLooper());
switch (requestCode) {
case CROP_PICTURE: {
if (resultCode == RESULT_OK && null != data) {
mHandler.post(new Runnable() {
@Override
public void run() {
try {
Bundle extras = data.getExtras();
Bitmap thePic = extras.getParcelable("data");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
thePic.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
//SharePreference to store image
PrefManager.putString(Constant.IMAGE_DATA, encodedImage);
//set gallery image
setChatBackground();
} catch (NullPointerException e) {
Log.d(TAG, e.getLocalizedMessage());
}
}
});
}
break;
}
case SELECT_PICTURE: {
if (resultCode == RESULT_OK && null != data) {
mHandler.post(new Runnable() {
@Override
public void run() {
Uri selectedImageUri = data.getData();
InputStream imageStream;
Bitmap selectedImage;
try {
cropCapturedImage(getImageUrl(getApplicationContext(), selectedImageUri));
} catch (ActivityNotFoundException aNFE) {
//display an error message if user device doesn't support
showToast(getString(R.string.error_crop_not_supported));
try {
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(getImageUrl(getApplicationContext(), selectedImageUri), filePathColumn, null, null, null);
cursor.moveToFirst();
imageStream = getContentResolver().openInputStream(selectedImageUri);
selectedImage = BitmapFactory.decodeStream(imageStream);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
selectedImage.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
//SharePreference to store image
PrefManager.putString(Constant.IMAGE_DATA, encodedImage);
cursor.close();
//set gallery image
setChatBackground();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
});
}
break;
}
}
}
public static Uri writeToTempImage(Context inContext, Bitmap inImage) {
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
public static Uri getImageUrl(Context context, Uri uri) {
InputStream is = null;
if (uri.getAuthority() != null) {
try {
is = context.getContentResolver().openInputStream(uri);
Bitmap bmp = BitmapFactory.decodeStream(is);
return writeToTempImage(context, bmp);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
private void init() {
ButterKnife.bind(this);
fab_scrollToEnd = (FloatingActionButton) findViewById(R.id.btnScrollToEnd);
registerReceiver(networkStateReceiver, new IntentFilter(android.net.ConnectivityManager.CONNECTIVITY_ACTION));
networkStateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
new computeThread().start();
}
};
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle("");
getSupportActionBar().setIcon(R.drawable.susi);
nonDeliveredMessages.clear();
RealmResults<ChatMessage> nonDelivered = realm.where(ChatMessage.class).equalTo("isDelivered", false).findAll().sort("id");
for (ChatMessage each : nonDelivered) {
Log.d(TAG, each.getContent());
nonDeliveredMessages.add(new Pair(each.getContent(), each.getId()));
}
checkEnterKeyPref();
setupAdapter();
hideVoiceInput();
rvChatFeed.setOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
LinearLayoutManager linearLayoutManager = (LinearLayoutManager) rvChatFeed.getLayoutManager();
if (linearLayoutManager.findLastCompletelyVisibleItemPosition() < rvChatFeed.getAdapter().getItemCount() - 5) {
fab_scrollToEnd.setEnabled(true);
fab_scrollToEnd.setVisibility(View.VISIBLE);
} else {
fab_scrollToEnd.setEnabled(false);
fab_scrollToEnd.setVisibility(View.GONE);
}
}
});
ChatMessage.setMaxLines(4);
ChatMessage.setHorizontallyScrolling(false);
ChatMessage.addTextChangedListener(watch);
ChatMessage.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
boolean handled = false;
if (actionId == EditorInfo.IME_ACTION_SEND) {
String chat = ChatMessage.getText().toString();
String message = chat.trim();
if (!TextUtils.isEmpty(message)) {
sendMessage(message, chat);
ChatMessage.setText("");
}
handled = true;
}
return handled;
}
});
setChatBackground();
}
public void getLocationFromIP() {
final LocationService locationService =
LocationClient.getClient().create(LocationService.class);
Call<LocationResponse> call = locationService.getLocationUsingIP();
call.enqueue(new Callback<LocationResponse>() {
@Override
public void onResponse(Call<LocationResponse> call, Response<LocationResponse> response) {
if (response != null && response.isSuccessful() && response.body() != null) {
String loc = response.body().getLoc();
String s[] = loc.split(",");
Float f = new Float(0);
PrefManager.putFloat(Constant.LATITUDE, f.parseFloat(s[0]));
PrefManager.putFloat(Constant.LONGITUDE, f.parseFloat(s[1]));
PrefManager.putString(Constant.GEO_SOURCE, "ip");
} else {
PrefManager.putFloat(Constant.LATITUDE, 0);
PrefManager.putFloat(Constant.LONGITUDE, 0);
PrefManager.putString(Constant.GEO_SOURCE, "ip");
}
}
@Override
public void onFailure(Call<LocationResponse> call, Throwable t) {
Log.e(TAG, t.toString());
PrefManager.putFloat(Constant.LATITUDE, 0);
PrefManager.putFloat(Constant.LONGITUDE, 0);
PrefManager.putString(Constant.GEO_SOURCE, "ip");
}
});
}
public void getLocationFromLocationService() {
LocationHelper locationHelper = new LocationHelper(MainActivity.this);
if (locationHelper.canGetLocation()) {
float latitude = locationHelper.getLatitude();
float longitude = locationHelper.getLongitude();
String source = locationHelper.getSource();
PrefManager.putFloat(Constant.LATITUDE, latitude);
PrefManager.putFloat(Constant.LONGITUDE, longitude);
PrefManager.putString(Constant.GEO_SOURCE, source);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED ) {
LocationHelper locationHelper = new LocationHelper(MainActivity.this);
if (locationHelper.canGetLocation()) {
float latitude = locationHelper.getLatitude();
float longitude = locationHelper.getLongitude();
String source = locationHelper.getSource();
PrefManager.putFloat(Constant.LATITUDE, latitude);
PrefManager.putFloat(Constant.LONGITUDE, longitude);
PrefManager.putString(Constant.GEO_SOURCE, source);
}
}
if (grantResults.length == 0 || grantResults[1] != PackageManager.PERMISSION_GRANTED) {
micCheck = false;
PrefManager.putBoolean(Constant.MIC_INPUT, false);
} else {
PrefManager.putBoolean(Constant.MIC_INPUT, checkMicInput());
}
break;
}
case 2: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
LocationHelper locationHelper = new LocationHelper(MainActivity.this);
if (locationHelper.canGetLocation()) {
float latitude = locationHelper.getLatitude();
float longitude = locationHelper.getLongitude();
String source = locationHelper.getSource();
PrefManager.putFloat(Constant.LATITUDE, latitude);
PrefManager.putFloat(Constant.LONGITUDE, longitude);
PrefManager.putString(Constant.GEO_SOURCE, source);
}
}
break;
}
case 3: {
if (grantResults.length == 0 || grantResults[0] != PackageManager.PERMISSION_GRANTED) {
micCheck = false;
PrefManager.putBoolean(Constant.MIC_INPUT, false);
} else {
PrefManager.putBoolean(Constant.MIC_INPUT, checkMicInput());
}
}
}
}
private void voiceReply(final String reply, final boolean isHavingLink , final String actionType) {
if ( ((checkSpeechOutputPref() && check) || checkSpeechAlwaysPref()) && actionType.equals(Constant.ANSWER)) {
final AudioManager audiofocus = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
Handler handler = new Handler();
handler.post(new Runnable() {
@Override
public void run() {
int result = audiofocus.requestAudioFocus(afChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
textToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
Locale locale = textToSpeech.getLanguage();
textToSpeech.setLanguage(locale);
String spokenReply = reply;
if (isHavingLink) {
spokenReply = reply.substring(0, reply.indexOf("http"));
}
textToSpeech.speak(spokenReply, TextToSpeech.QUEUE_FLUSH, null);
audiofocus.abandonAudioFocus(afChangeListener);
}
}
});
}
}
});
}
}
protected void chatBackgroundActivity() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(R.string.dialog_action_complete);
builder.setItems(R.array.dialog_complete_action_items,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, SELECT_PICTURE);
break;
case 1:
PrefManager.putString(Constant.IMAGE_DATA,
getString(R.string.background_no_wall));
setChatBackground();
break;
}
}
});
builder.create().show();
}
public void cropCapturedImage(Uri picUri) {
Intent cropIntent = new Intent("com.android.camera.action.CROP");
|
package com.qiniu.storage;
import com.qiniu.TempFile;
import com.qiniu.TestConfig;
import com.qiniu.http.Response;
import com.qiniu.storage.persistent.FileRecorder;
import com.qiniu.util.UrlSafeBase64;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.*;
import static org.junit.Assert.*;
import static org.junit.Assert.assertTrue;
public class RecordUploadTest {
private boolean isDone = false;
private Response response = null;
private void template(int size) throws IOException {
isDone = false;
ExecutorService threadPool = Executors.newSingleThreadExecutor();
final String expectKey = "\r\n?&r=" + size + "k";
final File f = TempFile.createFile(size);
final String token = TestConfig.testAuth.uploadToken(TestConfig.bucket, expectKey);
final FileRecorder recorder = new FileRecorder(f.getParentFile());
final RecordKeyGenerator keyGen = new RecordKeyGenerator() {
@Override
public String gen(String key, File file) {
return key + "_._" + file.getAbsolutePath();
}
};
final String recordKey = keyGen.gen(expectKey, f);
UploadManager uploadManager = new UploadManager(recorder, keyGen);
// Response res = uploadManager.put(f, expectKey, token);
Up up = new Up(uploadManager, f, expectKey, token);
Thread showRecord = new Thread() {
public void run() {
for (; ; ) {
doSleep(30);
showRecord("normal: ", recorder, recordKey);
}
}
};
showRecord.setDaemon(true);
showRecord.start();
final String p = f.getParentFile().getAbsolutePath() + "\\" + UrlSafeBase64.encodeToString(recordKey);
System.out.println(p);
System.out.println(new File(p).exists());
final Random r = new Random();
boolean shutDown = true;
for (int i = 10; i > 0; i
final int t = r.nextInt(100) + 80;
System.out.println(i + " : " + t);
final Future<Response> future = threadPool.submit(up);
if (shutDown) {
new Thread() {
public void run() {
doSleep(t);
if (!future.isDone()) {
future.cancel(true);
}
}
}.start();
shutDown = false;
}
showRecord("new future: ", recorder, recordKey);
try {
Response res = future.get();
response = res;
showRecord("done: ", recorder, recordKey);
System.out.println("break");
break;
} catch (Exception e) {
System.out.println("Exception");
System.out.println(Thread.currentThread().getId() + " : future.isCancelled : " + future.isCancelled());
// e.printStackTrace();
if (isDone) {
break;
}
}
doSleep(30);
System.out.println(p);
System.out.println(new File(p).exists());
}
TempFile.remove(f);
assertFalse(new File(p).exists());
assertNotNull(response);
assertTrue(response.isOK());
showRecord("nodata: ", recorder, recordKey);
}
private void showRecord(String pre, FileRecorder recorder, String recordKey) {
try {
String jsonStr = pre;
byte[] data = recorder.get(recordKey);
if (data != null) {
jsonStr += new String(data);
}
System.out.println(jsonStr);
} catch (Exception e) {
//e.printStackTrace();
}
}
private void doSleep(int bm) {
try {
Thread.sleep(100 * bm);
} catch (InterruptedException e) {
//e.printStackTrace();
}
}
class Up implements Callable<Response> {
private final UploadManager uploadManager;
private final File file;
private final String key;
private final String token;
public Up(UploadManager uploadManager, File file, String key, String token) {
this.uploadManager = uploadManager;
this.file = file;
this.key = key;
this.token = token;
}
@Override
public Response call() throws Exception {
Response res = uploadManager.put(file, key, token);
System.out.println("up: " + res);
System.out.println("up: " + res.bodyString());
isDone = true;
response = res;
return res;
}
}
@Test
public void test1K() throws Throwable {
template(1);
}
@Test
public void test600k() throws Throwable {
template(600);
}
@Test
public void test4M() throws Throwable {
if (TestConfig.isTravis()) {
return;
}
template(1024 * 4);
}
@Test
public void test8M1k() throws Throwable {
if (TestConfig.isTravis()) {
return;
}
template(1024 * 8 + 1);
}
@Test
public void test25M1k() throws Throwable {
if (TestConfig.isTravis()) {
return;
}
template(1024 * 25 + 1);
}
}
|
package com.blamejared.mcbot.commands;
import java.io.StringWriter;
import java.security.AccessControlException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import java.util.function.BiFunction;
import java.util.function.Function;
import org.apache.commons.io.IOUtils;
import com.blamejared.mcbot.MCBot;
import com.blamejared.mcbot.commands.CommandQuote.Quote;
import com.blamejared.mcbot.commands.api.Command;
import com.blamejared.mcbot.commands.api.CommandBase;
import com.blamejared.mcbot.commands.api.CommandContext;
import com.blamejared.mcbot.commands.api.CommandException;
import com.blamejared.mcbot.commands.api.CommandRegistrar;
import com.blamejared.mcbot.trick.Trick;
import com.blamejared.mcbot.util.NonNull;
import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.collect.Maps;
import clojure.java.api.Clojure;
import clojure.lang.AFn;
import clojure.lang.IFn;
import clojure.lang.IPersistentMap;
import clojure.lang.PersistentArrayMap;
import clojure.lang.PersistentHashMap;
import clojure.lang.PersistentVector;
import clojure.lang.Var;
import lombok.SneakyThrows;
import lombok.val;
import sx.blah.discord.api.internal.DiscordUtils;
import sx.blah.discord.handle.obj.IGuild;
import sx.blah.discord.handle.obj.IMessage;
import sx.blah.discord.handle.obj.IUser;
import sx.blah.discord.handle.obj.Permissions;
@Command
public class CommandClojure extends CommandBase {
private static class BindingBuilder {
private Map<Object, Object> bindings = new HashMap<>();
public BindingBuilder bind(String name, Object val) {
this.bindings.put(Clojure.read(":" + name), val);
return this;
}
public IPersistentMap build() {
return PersistentHashMap.create(Maps.newHashMap(this.bindings));
}
}
private static final SentenceArgument ARG_EXPR = new SentenceArgument("expression", "The clojure expression to evaluate.", true);
private static final Class<?>[] BLACKLIST_CLASSES = {
Thread.class
};
// Blacklist accessing discord functions
private static final String[] BLACKLIST_PACKAGES = {
MCBot.class.getPackage().getName(),
"sx.blah.discord"
};
private final IFn sandbox;
@SneakyThrows
public CommandClojure() {
super("clj", false);
// Make sure to load in clojail
Clojure.var("clojure.core", "require").invoke(Clojure.read("[clojail core jvm testers]"));
// Convenience declarations of used functions
IFn read_string = Clojure.var("clojure.core", "read-string");
IFn sandboxfn = Clojure.var("clojail.core", "sandbox");
Var secure_tester = (Var) Clojure.var("clojail.testers", "secure-tester");
// Load these to add new blacklisted resources
IFn blacklist_objects = Clojure.var("clojail.testers", "blacklist-objects");
IFn blacklist_packages = Clojure.var("clojail.testers", "blacklist-packages");
// Create our tester with custom blacklist
Object tester = Clojure.var("clojure.core/conj").invoke(secure_tester.getRawRoot(),
blacklist_objects.invoke(PersistentVector.create((Object[]) BLACKLIST_CLASSES)),
blacklist_packages.invoke(PersistentVector.create((Object[]) BLACKLIST_PACKAGES)));
/* == Setting up Context == */
// Defining all the context vars and the functions to bind them for a given CommandContext
// A simple function that returns a map representing a user, given an IUser
BiFunction<IGuild, IUser, IPersistentMap> getBinding = (g, u) -> new BindingBuilder()
.bind("name", u.getName())
.bind("nick", u.getDisplayName(g))
.bind("id", u.getLongID())
.bind("presence", new BindingBuilder()
.bind("playing", u.getPresence().getPlayingText().orElse(null))
.bind("status", u.getPresence().getStatus().toString())
.bind("streamurl", u.getPresence().getStreamingUrl().orElse(null))
.build())
.bind("bot", u.isBot())
.build();
// Set up global context vars
// Create an easily accessible map for the sending user
addContextVar("author", ctx -> getBinding.apply(ctx.getGuild(), ctx.getAuthor()));
// Add a lookup function for looking up an arbitrary user in the guild
addContextVar("users", ctx -> new AFn() {
public Object invoke(Object id) {
IUser ret = ctx.getGuild().getUserByID(((Number)id).longValue());
if (ret == null) {
throw new IllegalArgumentException("Could not find user for ID");
}
return getBinding.apply(ctx.getGuild(), ret);
}
});
// Simple data bean representing the current channel
addContextVar("channel", ctx ->
new BindingBuilder()
.bind("name", ctx.getChannel().getName())
.bind("id", ctx.getChannel().getLongID())
.bind("topic", ctx.getChannel().getTopic())
.build());
// Simple data bean representing the current guild
addContextVar("guild", ctx ->
new BindingBuilder()
.bind("name", ctx.getGuild().getName())
.bind("id", ctx.getGuild().getLongID())
.bind("owner", ctx.getGuild().getOwner().getLongID())
.bind("region", ctx.getGuild().getRegion().getName())
.build());
// Add the current message ID
addContextVar("message", ctx -> ctx.getMessage().getLongID());
// Provide a lookup function for ID->message
addContextVar("messages", ctx -> new AFn() {
public Object invoke(Object arg1) {
IMessage msg = ctx.getGuild().getChannels().stream()
.filter(c -> c.getModifiedPermissions(MCBot.instance.getOurUser()).contains(Permissions.READ_MESSAGES))
.map(c -> c.getMessageByID(((Number)arg1).longValue()))
.filter(Objects::nonNull)
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("No message found"));
return new BindingBuilder()
.bind("content", msg.getContent())
.bind("fcontent", msg.getFormattedContent())
.bind("id", msg.getLongID())
.bind("author", msg.getAuthor().getLongID())
.bind("channel", msg.getChannel().getLongID())
.bind("timestamp", msg.getTimestamp())
.build();
}
});
// A function for looking up quotes, given an ID, or pass no arguments to return a vector of valid quote IDs
addContextVar("quotes", ctx -> new AFn() {
public Object invoke() {
return PersistentVector.create(((CommandQuote) CommandRegistrar.INSTANCE.findCommand("quote")).getData(ctx).keySet());
}
@Override
public Object invoke(Object arg1) {
Quote q = ((CommandQuote) CommandRegistrar.INSTANCE.findCommand("quote")).getData(ctx).get(((Number)arg1).intValue());
if (q == null) {
throw new IllegalArgumentException("No quote for ID " + arg1);
}
return new BindingBuilder()
.bind("quote", q.getQuote())
.bind("quotee", q.getQuotee())
.bind("owner", q.getOwner())
.bind("weight", q.getWeight())
.build();
}
});
// A function for looking up tricks, given a name. Optionally pass "true" as second param to force global lookup
addContextVar("tricks", ctx -> new AFn() {
@Override
public Object invoke(Object name) {
return invoke(name, false);
}
@Override
public Object invoke(Object name, Object global) {
Trick t = ((CommandTrick) CommandRegistrar.INSTANCE.findCommand("trick")).getTrick(ctx, (String) name, (Boolean) global);
// Return a function which allows invoking the trick
return new AFn() {
@Override
public Object invoke() {
return invoke(PersistentVector.create());
}
@Override
public Object invoke(Object args) {
return t.process(ctx, (Object[]) Clojure.var("clojure.core", "to-array").invoke(args));
}
};
}
});
// Create a sandbox, 2000ms timeout, under domain mcbot.sandbox, and running the sandbox-init.clj script before execution
this.sandbox = (IFn) sandboxfn.invoke(tester,
Clojure.read(":timeout"), 2000L,
Clojure.read(":namespace"), Clojure.read("mcbot.sandbox"),
Clojure.read(":refer-clojure"), false,
Clojure.read(":init"), read_string.invoke(Joiner.on('\n').join(
IOUtils.readLines(MCBot.class.getResourceAsStream("/sandbox-init.clj"), Charsets.UTF_8))));
}
private final Map<String, Function<@NonNull CommandContext, Object>> contextVars = new LinkedHashMap<>();
private void addContextVar(String name, Function<@NonNull CommandContext, Object> factory) {
String var = "*" + name + "*";
((Var) Clojure.var("mcbot.sandbox", var)).setDynamic().bindRoot(new PersistentArrayMap(new Object[0]));
contextVars.put(var, factory);
}
@Override
public void process(CommandContext ctx) throws CommandException {
ctx.replyBuffered("=> " + exec(ctx, ctx.getArg(ARG_EXPR)).toString());
}
public Object exec(CommandContext ctx, String code) throws CommandException {
try {
StringWriter sw = new StringWriter();
Map<Object, Object> bindings = new HashMap<>();
bindings.put(Clojure.var("clojure.core", "*out*"), sw);
for (val e : contextVars.entrySet()) {
bindings.put(Clojure.var("mcbot.sandbox", e.getKey()), e.getValue().apply(ctx));
}
Object res = sandbox.invoke(Clojure.read(code), PersistentArrayMap.create(bindings));
String output = sw.getBuffer().toString();
return res == null ? output : res.toString();
} catch (Exception e) {
e.printStackTrace();
final @NonNull Throwable cause;
if (e instanceof ExecutionException) {
cause = e.getCause();
} else {
cause = e;
}
// Can't catch TimeoutException because invoke() does not declare it as a possible checked exception
if (cause instanceof TimeoutException) {
throw new CommandException("That took too long to execute!");
} else if (cause instanceof AccessControlException || cause instanceof SecurityException) {
throw new CommandException("Sorry, you're not allowed to do that!");
}
throw new CommandException(cause);
}
}
@Override
public String getDescription() {
return "Evaluate some clojure code in a sandboxed REPL.\n\n"
+ "Available context vars: " + Joiner.on(", ").join(contextVars.keySet().stream().map(s -> "`" + s + "`").iterator()) + "."
+ " Run `!clj [var]` to preview their contents.";
}
}
|
// This file is part of Elveos.org.
// Elveos.org is free software: you can redistribute it and/or modify it
// option) any later version.
// Elveos.org is distributed in the hope that it will be useful, but WITHOUT
// more details.
package com.bloatit.framework.utils.i18n;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import org.xnap.commons.i18n.I18n;
import org.xnap.commons.i18n.I18nFactory;
import com.bloatit.common.Log;
import com.bloatit.framework.LocalesConfiguration;
import com.bloatit.framework.exceptions.highlevel.BadProgrammerException;
import com.bloatit.framework.utils.i18n.DateLocale.FormatStyle;
import com.bloatit.framework.webprocessor.components.form.DropDownElement;
import com.bloatit.framework.webprocessor.context.Context;
/**
* <p>
* Class that encapsulates all translation tools
* </p>
* <p>
* Tools provided are :
* <li>All static translation tools (for the UI) implemented with gettext</li>
* <li>All Dynamic translation tools (for the content), mostly for dates,
* currencies and time</li>
* <p>
* Class is immutable, if you need to change locale, create a new object
* </p>
* </p>
*/
public final class Localizator {
/** For parsing of available languages file */
private static final String LANGUAGE_CODE = "code";
/** Default user locale */
private static final Locale DEFAULT_LOCALE = new Locale("en", "US");
private static final String SEPARATORS_REGEX = "[_-]";
private static Map<String, LanguageDescriptor> availableLanguages = Collections.unmodifiableMap(initLanguageList());
private static Date availableLanguagesReload;
// translations cache
private static final Map<String, I18n> localesCache = Collections.synchronizedMap(new HashMap<String, I18n>());
static {
// By default, the Java default language is used as a fallback for
// gettext.
// We override this behavior by setting the default locale to english
Locale.setDefault(new Locale("en", "US"));
}
private Locale locale;
private I18n i18n;
private List<String> browserLangs;
public Localizator(final Locale language) {
this.locale = language;
this.i18n = getI18n(locale);
}
public Localizator(final String urlLang, final List<String> browserLangs) {
this(inferLocale(urlLang, browserLangs));
this.browserLangs = browserLangs;
}
/**
* Returns the Locale for the localizator
*
* @return the locale
*/
public Locale getLocale() {
return locale;
}
/**
* Shortcut for getLanguageCode()
*
* @see #getLanguageCode()
*/
public String getCode() {
return locale.getLanguage();
}
/**
* @return the ISO code for the language
*/
public String getLanguageCode() {
return locale.getLanguage();
}
/**
* @return the ISO code for the language
*/
public String getCountryCode() {
return locale.getCountry();
}
/**
* <p>
* Translates a constant String
* </p>
* <p>
* Returns <code>toTranslate</code> translated into the currently selected
* language. Every user-visible string in the program must be wrapped into
* this function
* </p>
*
* @param toTranslate the string to translate
* @return the translated string
*/
public String tr(final String toTranslate) {
return correctTr(i18n.tr(toTranslate));
}
public String tr(final String toTranslate, final Object... parameters) {
return correctTr(i18n.tr(toTranslate, parameters));
}
/**
* <p>
* Translates a constant string using plural
* </p>
* <p>
* Example :
* <p>
* <code>System.out.println(i18n.trn("Copied file.", "Copied files.", 4));<br>
* <code>//will print "Copied files."</code>
* </p>
* <p>
* <code>System.out.println(i18n.trn("Copied file.", "Copied files.", 4));<br> // will
* print "Copied files."</code>
* </p>
* </p>
*
* @param singular The singular version of the displayed string
* @param plural the plural version of the displayed string
* @param amount the <i>amount</i> of elements, 0 or 1 will be singular, >1
* will be plural
* @return the translated <i>singular</i> or <i>plural</i> string depending
* on value of <code>amount</code>
* @see #tr(String)
*/
public String trn(final String singular, final String plural, final long amount) {
if (locale.getLanguage().equals("fr")) {
// In french, 0 use the singular
return correctTr(i18n.trn(singular, plural, (amount > 1 ? amount : 1)));
}
return correctTr(i18n.trn(singular, plural, amount));
}
public String trn(final String singular, final String plural, final long amount, final Object... parameters) {
if (locale.getLanguage().equals("fr")) {
// In french, 0 use the singular
return correctTr(i18n.trn(singular, plural, (amount > 1 ? amount : 1), parameters));
}
return correctTr(i18n.trn(singular, plural, amount, parameters));
}
public String trc(final String context, final String text) {
return correctTr(i18n.trc(context, text));
}
/**
* Correctes the translated string and make it ready for html
*
* @param translation the translated string
* @return the string ready to be inputed in Html
*/
private String correctTr(final String translation) {
return translation.replaceAll(" ", " ");
}
public static Map<String, LanguageDescriptor> getAvailableLanguages() {
if (LocalesConfiguration.configuration.getLastReload().after(availableLanguagesReload)) {
Log.framework().trace("Reloading languages configuration file");
availableLanguages = initLanguageList();
}
return availableLanguages;
}
/**
* Parses the languages file and initializes the list of available languages
* Used in the init of the static field.
*/
private static Map<String, LanguageDescriptor> initLanguageList() {
final Map<String, LanguageDescriptor> languages = new HashMap<String, Localizator.LanguageDescriptor>();
final Properties properties;
properties = LocalesConfiguration.getLanguages();
for (final Entry<?, ?> property : properties.entrySet()) {
final String key = (String) property.getKey();
final String value = (String) property.getValue();
// Remove the .code or .name
final String lang = key.substring(0, key.lastIndexOf('.'));
LanguageDescriptor ld;
if (!languages.containsKey(lang)) {
ld = new LanguageDescriptor();
languages.put(lang, ld);
} else {
ld = languages.get(lang);
}
if (key.endsWith("." + LANGUAGE_CODE)) {
ld.code = value;
} else {
ld.name = value;
}
}
availableLanguagesReload = new Date();
return languages;
}
/**
* DO nothing !!
*/
public void setUserFavorite() {
assert false;
}
/**
* Describes a Language using a two letters code and a name
*/
public static class LanguageDescriptor implements DropDownElement {
private String code;
private String name;
@Override
public String getName() {
return name;
}
@Override
public String getCode() {
return code;
}
}
/**
* Gets the date pattern that matches the current user language in
* <i>SHORT</i> format, i.e. : dd/mm/yyyy if locale is french, or mm/dd/yyyy
* if locale is english.
*
* @return a String representing the date pattern
*/
public String getShortDatePattern() {
return DateLocale.getPattern(locale);
}
/**
* Gets the date pattern that matches the current user language in any
* format
*
* @param format the format
* @return the date pattern
*/
public String getDatePattern(final FormatStyle format) {
return DateLocale.getPattern(locale, format);
}
/**
* Returns a DateLocale representing the string version of the date
*/
public DateLocale getDate(final String dateString) throws DateParsingException {
return new DateLocale(dateString, locale);
}
/**
* Returns a DateLocale encapsulating the java date Use to display any date
*/
public DateLocale getDate(final Date date) {
return new DateLocale(date, locale);
}
/**
* Returns a CurrencyLocale to work on <code>euroAmount</code>
*/
public CurrencyLocale getCurrency(final BigDecimal euroAmount) {
try {
return new CurrencyLocale(euroAmount, locale);
} catch (final CurrencyNotAvailableException e) {
try {
return new CurrencyLocale(euroAmount, DEFAULT_LOCALE);
} catch (final CurrencyNotAvailableException e1) {
throw new BadProgrammerException("Fallback locale for currency " + DEFAULT_LOCALE.getLanguage() + "_" + DEFAULT_LOCALE.getCountry()
+ "not available", e);
}
}
}
/**
* Forces the current locale to the member user choice.
* <p>
* Use whenever the user explicitely asks to change the locale setting back
* to his favorite, or when he logs in
* </p>
*/
public void forceMemberChoice() {
if (Context.getSession().getMemberId() != null) {
locale = Context.getSession().getMemberLocale();
this.i18n = getI18n(locale);
}
}
/**
* Force the locale to a specific locale
*/
public void forceLanguage(final Locale language) {
locale = new Locale(language.getLanguage(), locale.getCountry());
this.i18n = getI18n(locale);
}
/**
* Forces a language reset
* <p>
* Language reset ignores the language selected in the URI
* </p>
*/
public void forceLanguageReset() {
if (Context.getSession().getMemberId() != null) {
forceMemberChoice();
return;
}
locale = browserLocaleHeuristic(browserLangs);
this.i18n = getI18n(locale);
}
/**
* Infers the locale based on various parameters
*/
private static Locale inferLocale(final String urlLang, final List<String> browserLangs) {
Locale locale = null;
if (urlLang != null && !urlLang.equals("default")) {
// Default language
String country;
if (Context.getSession().getMemberId() != null) {
country = Context.getSession().getMemberLocale().getCountry();
} else {
country = browserLocaleHeuristic(browserLangs).getCountry();
}
locale = new Locale(urlLang, country);
boolean found = false;
for (final Locale availablelocale : Locale.getAvailableLocales()) {
if (urlLang.equals(availablelocale.getLanguage())) {
found = true;
break;
}
}
if (!found) {
Log.framework().error("Strange language code " + urlLang);
}
} else {
// Other cases
if (Context.getSession().getMemberId() != null) {
Locale memberLocale = Context.getSession().getMemberLocale();
if (isAvailableLanguage(memberLocale.getLanguage())) {
locale = memberLocale;
} else {
locale = new Locale(DEFAULT_LOCALE.getLanguage(), memberLocale.getCountry());
}
} else {
locale = browserLocaleHeuristic(browserLangs);
}
}
return locale;
}
/**
* Indicates if the language described by <code>languageCode</code> exists or not
* @param languageCode the coce of the ISO language that wants to work
* @return <i>true</i> if <code>languageCode</code> exists, false otherwise
*/
public static boolean isAvailableLanguage(String languageCode){
for(Entry<String, LanguageDescriptor> e : getAvailableLanguages().entrySet()){
LanguageDescriptor ld = e.getValue();
if(ld.getCode().equals(languageCode)){
return true;
}
}
return false;
}
/**
* <p>
* Finds the dominant Locale for the user based on the browser transmitted
* parameters
* </p>
* <p>
* This method use preferences based on data transmitted by browser, but
* will always try to fetch a locale with a language and a country.
* </p>
* <p>
* Cases are :
* <li>The favorite locale has language and country : it is the selected
* locale</li>
* <li>The favorite locale has a language but no country : will try to
* select another locale with the <b>same language</b></li>
* <li>If no locale has a country, the favorite language as of browser
* preference will be used, and country will be set as US. If no language is
* set, the locale will be set using DEFAULT_LOCALE (currently en_US).
* </p>
*
* @return the favorite user locale
*/
private static Locale browserLocaleHeuristic(final List<String> browserLangs) {
Locale currentLocale = null;
float currentWeigth = 0;
Locale favLanguage = null;
float favLanguageWeigth = 0;
Locale favCountry = null;
float favCountryWeigth = 0;
for (final String lang : browserLangs) {
final String[] favLangs = lang.split(";");
float weigth;
if (favLangs.length > 1) {
weigth = Float.parseFloat(favLangs[1].trim().substring("q=".length()));
} else {
weigth = 1;
}
final String favLang[] = favLangs[0].split(SEPARATORS_REGEX);
Locale l;
if (favLang.length < 2 || (!favLang[1].toUpperCase().matches("[A-Z]{2}"))) {
l = new Locale(favLang[0]);
} else {
l = new Locale(favLang[0], favLang[1].toUpperCase());
}
if (!l.getLanguage().isEmpty() && l.getCountry().isEmpty()) {
// New FavoriteLanguage
if (favLanguageWeigth < weigth) {
favLanguageWeigth = weigth;
favLanguage = l;
}
}
if (!l.getLanguage().isEmpty() && !l.getCountry().isEmpty()) {
// New currentLocale
if (currentWeigth < weigth) {
currentWeigth = weigth;
currentLocale = l;
}
}
if (l.getLanguage().isEmpty() && !l.getCountry().isEmpty()) {
// New currentCountry
if (favCountryWeigth < weigth) {
favCountryWeigth = weigth;
favCountry = l;
}
}
}
// Filter available language
if (currentLocale != null) {
boolean valid = false;
for (LanguageDescriptor languageDescriptor : availableLanguages.values()) {
if (currentLocale.getLanguage().equals(languageDescriptor.getCode())) {
valid = true;
break;
}
}
if (!valid) {
currentLocale = new Locale(DEFAULT_LOCALE.getLanguage(), currentLocale.getCountry());
}
}
if (favLanguage != null) {
boolean valid = false;
for (LanguageDescriptor languageDescriptor : availableLanguages.values()) {
if (favLanguage.getLanguage().equals(languageDescriptor.getCode())) {
valid = true;
break;
}
}
if (!valid) {
favLanguage = new Locale(DEFAULT_LOCALE.getLanguage(), favLanguage.getCountry());
}
}
if (currentLocale == null && favLanguage == null) {
return DEFAULT_LOCALE;
}
if (currentLocale != null && favLanguage == null) {
return currentLocale;
}
if (currentLocale == null && favLanguage != null) {
if (favCountry == null) {
favCountry = Locale.US;
}
return new Locale(favLanguage.getLanguage(), favCountry.getCountry());
}
// Case where both CurrentLocale != null && FavLanguage != null
return currentLocale;
}
public NumberFormat getNumberFormat() {
return NumberFormat.getInstance(getLocale());
}
private I18n getI18n(final Locale locale) {
if (localesCache.containsKey(locale)) {
return localesCache.get(locale);
}
final I18n newI18n = I18nFactory.getI18n(Localizator.class, "i18n.Messages", locale);
localesCache.put(locale.getLanguage(), newI18n);
return newI18n;
}
}
|
package org.fossasia.susi.ai.activities;
import android.Manifest;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Geocoder;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.AlarmClock;
import android.provider.CalendarContract;
import android.provider.MediaStore;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.support.customtabs.CustomTabsIntent;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.util.Pair;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Base64;
import android.util.Log;
import android.util.Patterns;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import org.fossasia.susi.ai.R;
import org.fossasia.susi.ai.adapters.recycleradapters.ChatFeedRecyclerAdapter;
import org.fossasia.susi.ai.helper.Constant;
import org.fossasia.susi.ai.helper.DateTimeHelper;
import org.fossasia.susi.ai.helper.GetVideos;
import org.fossasia.susi.ai.helper.PrefManager;
import org.fossasia.susi.ai.model.ChatMessage;
import org.fossasia.susi.ai.rest.BaseUrl;
import org.fossasia.susi.ai.rest.ClientBuilder;
import org.fossasia.susi.ai.rest.LocationClient;
import org.fossasia.susi.ai.rest.LocationService;
import org.fossasia.susi.ai.rest.VideoSeachClient;
import org.fossasia.susi.ai.rest.VideoSearchApi;
import org.fossasia.susi.ai.rest.model.Datum;
import org.fossasia.susi.ai.rest.model.LocationHelper;
import org.fossasia.susi.ai.rest.model.LocationResponse;
import org.fossasia.susi.ai.rest.model.SusiResponse;
import org.fossasia.susi.ai.rest.model.VideoSearch;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.Deque;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import butterknife.BindView;
import butterknife.ButterKnife;
import io.realm.Case;
import io.realm.Realm;
import io.realm.RealmList;
import io.realm.RealmResults;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static android.media.AudioManager.AUDIOFOCUS_LOSS_TRANSIENT;
public class MainActivity extends AppCompatActivity {
public static String TAG = MainActivity.class.getName();
private final int REQ_CODE_SPEECH_INPUT = 100;
private final int SELECT_PICTURE = 200;
private final int CROP_PICTURE = 400;
private static final String GOOGLE_SEARCH = "https:
private boolean isEnabled = true;
@BindView(R.id.coordinator_layout)
CoordinatorLayout coordinatorLayout;
@BindView(R.id.rv_chat_feed)
RecyclerView rvChatFeed;
@BindView(R.id.et_message)
EditText ChatMessage;
@BindView(R.id.send_message_layout)
LinearLayout sendMessageLayout;
@BindView(R.id.btnSpeak)
ImageButton btnSpeak;
private boolean atHome = true;
private boolean backPressedOnce = false;
private FloatingActionButton fab_scrollToEnd;
// Global Variables used for the setMessage Method
private String answer;
private String actionType;
private boolean isMap, isPieChart = false;
private boolean isHavingLink;
private boolean isSearchResult;
private boolean isWebSearch;
private long delay = 0;
private List<Datum> datumList = null;
private RealmResults<ChatMessage> chatMessageDatabaseList;
private Boolean micCheck;
private SearchView searchView;
private Boolean check;
private Menu menu;
private int pointer;
private RealmResults<ChatMessage> results;
private int offset = 1;
private ChatFeedRecyclerAdapter recyclerAdapter;
private Realm realm;
public static String webSearch;
private String googlesearch_query = "";
private String video_query = "";
private TextToSpeech textToSpeech;
private String[] array;
private String timenow;
private int reminderQuery;
private String reminder;
private int count = 0;
private static final String[] id = new String[1];
private AudioManager.OnAudioFocusChangeListener afChangeListener =
new AudioManager.OnAudioFocusChangeListener() {
public void onAudioFocusChange(int focusChange) {
if (focusChange == AUDIOFOCUS_LOSS_TRANSIENT) {
textToSpeech.stop();
} else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
// Resume playback
} else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
textToSpeech.stop();
}
}
};
private ClientBuilder clientBuilder;
private Deque<Pair<String, Long>> nonDeliveredMessages = new LinkedList<>();
TextWatcher watch = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(final CharSequence charSequence, int i, int i1, int i2) {
if (charSequence.toString().trim().length() > 0 || !micCheck) {
btnSpeak.setImageResource(R.drawable.ic_send_fab);
btnSpeak.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
check = false;
switch (view.getId()) {
case R.id.btnSpeak:
String chat_message = ChatMessage.getText().toString();
chat_message = chat_message.trim();
String splits[] = chat_message.split("\n");
String message = "";
for (String split : splits)
message = message.concat(split).concat(" ");
if (!TextUtils.isEmpty(chat_message)) {
sendMessage(message);
ChatMessage.setText("");
}
break;
}
}
});
} else {
btnSpeak.setImageResource(R.drawable.ic_mic_white_24dp);
btnSpeak.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
check = true;
promptSpeechInput();
}
});
}
}
@Override
public void afterTextChanged(Editable editable) {
}
};
private BroadcastReceiver networkStateReceiver;
public static List<String> extractUrls(String text) {
List<String> links = new ArrayList<String>();
Matcher m = Patterns.WEB_URL.matcher(text);
while (m.find()) {
String url = m.group();
links.add(url);
}
return links;
}
public static Boolean checkSpeechOutputPref() {
Boolean checks = PrefManager.getBoolean(Constant.SPEECH_OUTPUT, false);
return checks;
}
public static Boolean checkSpeechAlwaysPref() {
Boolean checked = PrefManager.getBoolean(Constant.SPEECH_ALWAYS, false);
return checked;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (PrefManager.getString(Constant.ACCESS_TOKEN, null) == null) {
throw new IllegalStateException("Not signed in, Cannot access resource!");
}
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
getLocationFromLocationService();
clientBuilder = new ClientBuilder();
getLocationFromIP();
init();
}
private void promptSpeechInput() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, getString(R.string.speech_prompt));
try {
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
showToast(getString(R.string.speech_not_supported));
}
}
/**
* Receiving speech input
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Handler mHandler = new Handler(Looper.getMainLooper());
switch (requestCode) {
case REQ_CODE_SPEECH_INPUT: {
if (resultCode == RESULT_OK && null != data) {
mHandler.post(new Runnable() {
@Override
public void run() {
ArrayList<String> result = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
sendMessage(result.get(0));
}
});
}
break;
}
case CROP_PICTURE: {
if (resultCode == RESULT_OK && null != data) {
mHandler.post(new Runnable() {
@Override
public void run() {
try {
Bundle extras = data.getExtras();
Bitmap thePic = extras.getParcelable("data");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
thePic.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
//SharePreference to store image
PrefManager.putString(Constant.IMAGE_DATA, encodedImage);
//set gallery image
setChatBackground();
} catch (NullPointerException e) {
Log.d(TAG, e.getLocalizedMessage());
}
}
});
}
break;
}
case SELECT_PICTURE: {
if (resultCode == RESULT_OK && null != data) {
mHandler.post(new Runnable() {
@Override
public void run() {
Uri selectedImageUri = data.getData();
InputStream imageStream;
Bitmap selectedImage;
try {
cropCapturedImage(selectedImageUri);
} catch (ActivityNotFoundException aNFE) {
//display an error message if user device doesn't support
showToast(getString(R.string.error_crop_not_supported));
try {
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImageUri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
imageStream = getContentResolver().openInputStream(selectedImageUri);
selectedImage = BitmapFactory.decodeStream(imageStream);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
selectedImage.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
//SharePreference to store image
PrefManager.putString(Constant.IMAGE_DATA, encodedImage);
cursor.close();
//set gallery image
setChatBackground();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
});
}
break;
}
}
}
private void init() {
ButterKnife.bind(this);
realm = Realm.getDefaultInstance();
fab_scrollToEnd = (FloatingActionButton) findViewById(R.id.btnScrollToEnd);
registerReceiver(networkStateReceiver, new IntentFilter(android.net.ConnectivityManager.CONNECTIVITY_ACTION));
networkStateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
new computeThread().start();
}
};
Log.d(TAG, "init");
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle("");
getSupportActionBar().setIcon(R.drawable.susi);
nonDeliveredMessages.clear();
RealmResults<ChatMessage> nonDelivered = realm.where(ChatMessage.class).equalTo("isDelivered", false).findAll().sort("id");
for (ChatMessage each : nonDelivered) {
Log.d(TAG, each.getContent());
nonDeliveredMessages.add(new Pair(each.getContent(), each.getId()));
}
checkEnterKeyPref();
setupAdapter();
rvChatFeed.setOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
LinearLayoutManager linearLayoutManager = (LinearLayoutManager) rvChatFeed.getLayoutManager();
if (linearLayoutManager.findLastCompletelyVisibleItemPosition() < rvChatFeed.getAdapter().getItemCount() - 5) {
fab_scrollToEnd.setEnabled(true);
fab_scrollToEnd.setVisibility(View.VISIBLE);
} else {
fab_scrollToEnd.setEnabled(false);
fab_scrollToEnd.setVisibility(View.GONE);
}
}
});
ChatMessage.addTextChangedListener(watch);
ChatMessage.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
boolean handled = false;
if (actionId == EditorInfo.IME_ACTION_SEND) {
String message = ChatMessage.getText().toString();
message = message.trim();
if (!TextUtils.isEmpty(message)) {
sendMessage(message);
ChatMessage.setText("");
}
handled = true;
}
return handled;
}
});
setChatBackground();
}
public void getLocationFromIP() {
final LocationService locationService =
LocationClient.getClient().create(LocationService.class);
Call<LocationResponse> call = locationService.getLocationUsingIP();
call.enqueue(new Callback<LocationResponse>() {
@Override
public void onResponse(Call<LocationResponse> call, Response<LocationResponse> response) {
String loc = response.body().getLoc();
String s[] = loc.split(",");
Float f = new Float(0);
PrefManager.putFloat(Constant.LATITUDE, f.parseFloat(s[0]));
PrefManager.putFloat(Constant.LONGITUDE, f.parseFloat(s[1]));
PrefManager.putString(Constant.GEO_SOURCE, "ip");
}
@Override
public void onFailure(Call<LocationResponse> call, Throwable t) {
// Log error here since request failed
Log.e(TAG, t.toString());
}
});
}
public void getLocationFromLocationService() {
LocationHelper locationHelper = new LocationHelper(MainActivity.this);
if (locationHelper.canGetLocation()) {
float latitude = locationHelper.getLatitude();
float longitude = locationHelper.getLongitude();
String source = locationHelper.getSource();
PrefManager.putFloat(Constant.LATITUDE, latitude);
PrefManager.putFloat(Constant.LONGITUDE, longitude);
PrefManager.putString(Constant.GEO_SOURCE, source);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
LocationHelper locationHelper = new LocationHelper(MainActivity.this);
if (locationHelper.canGetLocation()) {
float latitude = locationHelper.getLatitude();
float longitude = locationHelper.getLongitude();
String source = locationHelper.getSource();
PrefManager.putFloat(Constant.LATITUDE, latitude);
PrefManager.putFloat(Constant.LONGITUDE, longitude);
PrefManager.putString(Constant.GEO_SOURCE, source);
}
}
break;
}
}
}
private void voiceReply(final String reply, final boolean isMap) {
if ((checkSpeechOutputPref() && check) || checkSpeechAlwaysPref()) {
final AudioManager audiofocus = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
Handler handler = new Handler();
handler.post(new Runnable() {
@Override
public void run() {
int result = audiofocus.requestAudioFocus(afChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
textToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
Locale locale = textToSpeech.getLanguage();
textToSpeech.setLanguage(locale);
String spokenReply = reply;
if (isMap) {
spokenReply = reply.substring(0, reply.indexOf("http"));
}
textToSpeech.speak(spokenReply, TextToSpeech.QUEUE_FLUSH, null);
audiofocus.abandonAudioFocus(afChangeListener);
}
}
});
}
}
});
}
}
protected void chatBackgroundActivity() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(R.string.dialog_action_complete);
builder.setItems(R.array.dialog_complete_action_items,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, SELECT_PICTURE);
break;
case 1:
PrefManager.putString(Constant.IMAGE_DATA,
getString(R.string.background_no_wall));
setChatBackground();
break;
}
}
});
builder.create().show();
}
public void cropCapturedImage(Uri picUri) {
Intent cropIntent = new Intent("com.android.camera.action.CROP");
|
package com.censoredsoftware.demigods.player;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.OfflinePlayer;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
import org.bukkit.conversations.Conversation;
import org.bukkit.conversations.ConversationContext;
import org.bukkit.entity.Player;
import org.bukkit.potion.PotionEffect;
import org.bukkit.scheduler.BukkitRunnable;
import com.censoredsoftware.demigods.Demigods;
import com.censoredsoftware.demigods.battle.Battle;
import com.censoredsoftware.demigods.conversation.ChatRecorder;
import com.censoredsoftware.demigods.conversation.Prayer;
import com.censoredsoftware.demigods.data.DataManager;
import com.censoredsoftware.demigods.helper.ColoredStringBuilder;
import com.censoredsoftware.demigods.helper.ConfigFile;
import com.censoredsoftware.demigods.language.Translation;
import com.censoredsoftware.demigods.location.Region;
import com.censoredsoftware.demigods.structure.Structure;
import com.censoredsoftware.demigods.util.Structures;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import com.google.common.collect.Sets;
public class DPlayer implements ConfigurationSerializable
{
private String player;
private boolean canPvp;
private long lastLoginTime, lastLogoutTime;
private String currentDeityName;
private UUID current;
private UUID previous;
private static ChatRecorder chatRecording;
public DPlayer()
{}
public DPlayer(String player, ConfigurationSection conf)
{
this.player = player;
canPvp = conf.getBoolean("canPvp");
if(conf.isLong("lastLoginTime")) lastLoginTime = conf.getLong("lastLoginTime");
else lastLoginTime = -1;
if(conf.isLong("lastLogoutTime")) lastLogoutTime = conf.getLong("lastLogoutTime");
else lastLogoutTime = -1;
if(conf.getString("currentDeityName") != null) currentDeityName = conf.getString("currentDeityName");
if(conf.getString("current") != null) current = UUID.fromString(conf.getString("current"));
if(conf.getString("previous") != null) previous = UUID.fromString(conf.getString("previous"));
}
@Override
public Map<String, Object> serialize()
{
Map<String, Object> map = new HashMap<String, Object>();
map.put("canPvp", canPvp);
map.put("lastLoginTime", lastLoginTime);
map.put("lastLogoutTime", lastLogoutTime);
if(currentDeityName != null) map.put("currentDeityName", currentDeityName);
if(current != null) map.put("current", current.toString());
if(previous != null) map.put("previous", previous.toString());
return map;
}
void setPlayer(String player)
{
this.player = player;
}
public void resetCurrent()
{
this.current = null;
this.currentDeityName = null;
if(getOfflinePlayer().isOnline())
{
getOfflinePlayer().getPlayer().setDisplayName(getOfflinePlayer().getName());
getOfflinePlayer().getPlayer().setPlayerListName(getOfflinePlayer().getName());
getOfflinePlayer().getPlayer().setMaxHealth(20.0);
}
}
public void setCanPvp(boolean pvp)
{
this.canPvp = pvp;
Util.save(this);
}
public void updateCanPvp()
{
if(!getOfflinePlayer().isOnline()) return;
// Define variables
final Player player = getOfflinePlayer().getPlayer();
final boolean inNoPvpZone = Structures.isInRadiusWithFlag(player.getLocation(), Structure.Flag.NO_PVP);
if(!canPvp() && !inNoPvpZone)
{
setCanPvp(true);
player.sendMessage(ChatColor.GRAY + Demigods.language.getText(Translation.Text.UNSAFE_FROM_PVP));
}
else if(!inNoPvpZone)
{
setCanPvp(true);
DataManager.removeTimed(player.getName(), "pvp_cooldown");
}
else if(canPvp() && !DataManager.hasTimed(player.getName(), "pvp_cooldown"))
{
if(getCurrent() != null && Battle.Util.isInBattle(getCurrent())) return;
int delay = Demigods.config.getSettingInt("zones.pvp_area_delay_time");
DataManager.saveTimed(player.getName(), "pvp_cooldown", true, delay);
Bukkit.getScheduler().scheduleSyncDelayedTask(Demigods.plugin, new BukkitRunnable()
{
@Override
public void run()
{
if(Structures.isInRadiusWithFlag(player.getLocation(), Structure.Flag.NO_PVP))
{
setCanPvp(false);
player.sendMessage(ChatColor.GRAY + Demigods.language.getText(Translation.Text.SAFE_FROM_PVP));
}
}
}, (delay * 20));
}
}
public OfflinePlayer getOfflinePlayer()
{
return Bukkit.getOfflinePlayer(this.player);
}
public void setLastLoginTime(Long time)
{
this.lastLoginTime = time;
Util.save(this);
}
public Long getLastLoginTime()
{
if(lastLoginTime != -1) return this.lastLoginTime;
return null;
}
public void setLastLogoutTime(Long time)
{
this.lastLogoutTime = time;
Util.save(this);
}
public Long getLastLogoutTime()
{
if(lastLogoutTime != -1) return this.lastLogoutTime;
return null;
}
public void switchCharacter(DCharacter newChar)
{
Player player = getOfflinePlayer().getPlayer();
if(!newChar.getPlayer().equals(this.player))
{
player.sendMessage(ChatColor.RED + "You can't do that.");
return;
}
// Update the current character
DCharacter currChar = getCurrent();
if(currChar != null)
{
// Set to inactive and update previous
currChar.setActive(false);
this.previous = currChar.getId();
// Set the values
// TODO: Confirm that this covers all of the bases.
currChar.setMaxHealth(player.getMaxHealth());
currChar.setHealth(player.getHealth());
currChar.setHunger(player.getFoodLevel());
currChar.setLevel(player.getLevel());
currChar.setExperience(player.getExp());
currChar.setLocation(player.getLocation());
currChar.setPotionEffects(player.getActivePotionEffects());
currChar.saveInventory();
// Disown pets
Pet.Util.disownPets(currChar.getName());
// Save it
DCharacter.Util.save(currChar);
}
// Set new character to active
newChar.setActive(true);
this.current = newChar.getId();
// Set new deity
currentDeityName = newChar.getDeity().getName();
// Update their inventory
if(getCharacters().size() == 1) newChar.saveInventory();
newChar.getInventory().setToPlayer(player);
// Update health, experience, and name
// TODO: Confirm that this covers all of the bases too.
player.setDisplayName(newChar.getDeity().getColor() + newChar.getName());
try
{
player.setPlayerListName(newChar.getDeity().getColor() + newChar.getName());
}
catch(Exception e)
{
Demigods.message.warning("Character name too long.");
}
player.setMaxHealth(newChar.getMaxHealth());
player.setHealth(newChar.getHealth());
player.setFoodLevel(newChar.getHunger());
player.setExp(newChar.getExperience());
player.setLevel(newChar.getLevel());
for(PotionEffect potion : player.getActivePotionEffects())
player.removePotionEffect(potion.getType());
player.addPotionEffects(newChar.getPotionEffects());
// Re-own pets
Pet.Util.reownPets(player, newChar);
// Teleport them
try
{
player.teleport(newChar.getLocation());
}
catch(Exception e)
{
Demigods.message.severe("There was a problem while teleporting a player to their character.");
}
// Save instances
Util.save(this);
DCharacter.Util.save(newChar);
}
public boolean canPvp()
{
return this.canPvp;
}
public String getPlayerName()
{
return player;
}
public boolean hasCurrent()
{
return getCurrent() != null;
}
public Region getRegion()
{
if(getOfflinePlayer().isOnline()) return Region.Util.getRegion(getOfflinePlayer().getPlayer().getLocation());
return Region.Util.getRegion(getCurrent().getLocation());
}
public DCharacter getCurrent()
{
if(this.current == null) return null;
DCharacter character = DCharacter.Util.load(this.current);
if(character != null && character.isUsable()) return character;
return null;
}
public DCharacter getPrevious()
{
if(this.previous == null) return null;
return DCharacter.Util.load(this.previous);
}
public String getCurrentDeityName()
{
return currentDeityName;
}
public Set<DCharacter> getCharacters()
{
return Sets.newHashSet(Collections2.filter(DCharacter.Util.loadAll(), new Predicate<DCharacter>()
{
@Override
public boolean apply(DCharacter character)
{
return character != null && character.getPlayer().equals(player) && character.isUsable();
}
}));
}
public boolean canUseCurrent()
{
if(getCurrent() == null || !getCurrent().isUsable())
{
getOfflinePlayer().getPlayer().sendMessage(ChatColor.RED + "Your current character was unable to load!");
getOfflinePlayer().getPlayer().sendMessage(ChatColor.RED + "Please contact the server administrator immediately.");
return false;
}
else return getOfflinePlayer().isOnline();
}
public static class File extends ConfigFile
{
private static String SAVE_PATH;
private static final String SAVE_FILE = "players.yml";
public File()
{
super(Demigods.plugin);
SAVE_PATH = Demigods.plugin.getDataFolder() + "/data/";
}
@Override
public ConcurrentHashMap<String, DPlayer> loadFromFile()
{
final FileConfiguration data = getData(SAVE_PATH, SAVE_FILE);
ConcurrentHashMap<String, DPlayer> map = new ConcurrentHashMap<String, DPlayer>();
for(String stringId : data.getKeys(false))
map.put(stringId, new DPlayer(stringId, data.getConfigurationSection(stringId)));
return map;
}
@Override
public boolean saveToFile()
{
FileConfiguration saveFile = getData(SAVE_PATH, SAVE_FILE);
Map<String, DPlayer> currentFile = loadFromFile();
for(String id : DataManager.players.keySet())
if(!currentFile.keySet().contains(id) || !currentFile.get(id).equals(DataManager.players.get(id))) saveFile.createSection(id, Util.getPlayer(id).serialize());
for(String id : currentFile.keySet())
if(!DataManager.players.keySet().contains(id)) saveFile.set(id, null);
return saveFile(SAVE_PATH, SAVE_FILE, saveFile);
}
}
public static class Util
{
public static DPlayer create(OfflinePlayer player)
{
DPlayer trackedPlayer = new DPlayer();
trackedPlayer.setPlayer(player.getName());
trackedPlayer.setLastLoginTime(player.getLastPlayed());
trackedPlayer.setCanPvp(true);
Util.save(trackedPlayer);
return trackedPlayer;
}
public static void save(DPlayer player)
{
DataManager.players.put(player.getPlayerName(), player);
}
public static DPlayer getPlayer(OfflinePlayer player)
{
DPlayer found = getPlayer(player.getName());
if(found == null) return create(player);
return found;
}
public static DPlayer getPlayer(String player)
{
if(DataManager.players.containsKey(player)) return DataManager.players.get(player);
return null;
}
/**
* Returns true if the <code>player</code> is currently immortal.
*
* @param player the player to check.
* @return boolean
*/
public static boolean isImmortal(OfflinePlayer player)
{
DCharacter character = getPlayer(player).getCurrent();
return character != null;
}
/**
* Returns true if <code>player</code> has a character with the name <code>charName</code>.
*
* @param player the player to check.
* @param charName the charName to check with.
* @return boolean
*/
public static boolean hasCharName(OfflinePlayer player, String charName)
{
for(DCharacter character : getPlayer(player).getCharacters())
if(character.getName().equalsIgnoreCase(charName)) return true;
return false;
}
/**
* Returns true if the <code>player</code> is currently praying.
*
* @param player the player to check.
* @return boolean
*/
public static boolean isPraying(Player player)
{
try
{
return DataManager.hasKeyTemp(player.getName(), "prayer_conversation");
}
catch(Exception ignored)
{}
return false;
}
/**
* Removes all temp data related to prayer for the <code>player</code>.
*
* @param player the player to clean.
*/
public static void clearPrayerSession(Player player)
{
DataManager.removeTemp(player.getName(), "prayer_conversation");
DataManager.removeTemp(player.getName(), "prayer_context");
DataManager.removeTemp(player.getName(), "prayer_location");
}
/**
* Returns the context for the <code>player</code>'s prayer converstion.
*
* @param player the player whose context to return.
* @return ConversationContext
*/
public static ConversationContext getPrayerContext(Player player)
{
if(!isPraying(player)) return null;
return (ConversationContext) DataManager.getValueTemp(player.getName(), "prayer_context");
}
/**
* Changes prayer status for <code>player</code> to <code>option</code> and tells them.
*
* @param player the player the manipulate.
* @param option the boolean to set to.
*/
public static void togglePraying(Player player, boolean option)
{
if(option)
{
// Toggle on
togglePrayingSilent(player, true, false);
// Record chat
startRecording(player);
}
else
{
// Toggle off
togglePrayingSilent(player, false, false);
// Message them
Demigods.message.clearChat(player);
for(String message : Demigods.language.getTextBlock(Translation.Text.PRAYER_ENDED))
player.sendMessage(message);
// Handle recorded chat
stopRecording(player);
}
}
/**
* Changes prayer status for <code>player</code> to <code>option</code> silently.
*
* @param player the player the manipulate.
* @param option the boolean to set to.
* @param recordChat whether or not the chat should be recorded.
*/
public static void togglePrayingSilent(Player player, boolean option, boolean recordChat)
{
if(option)
{
// Create the conversation and save it
Conversation prayer = Prayer.startPrayer(player);
DataManager.saveTemp(player.getName(), "prayer_conversation", prayer);
DataManager.saveTemp(player.getName(), "prayer_location", player.getLocation());
player.setSneaking(true);
// Record chat if enabled
if(recordChat) startRecording(player);
}
else
{
// Save context and abandon the conversation
if(DataManager.hasKeyTemp(player.getName(), "prayer_conversation"))
{
Conversation prayer = (Conversation) DataManager.getValueTemp(player.getName(), "prayer_conversation");
DataManager.saveTemp(player.getName(), "prayer_context", prayer.getContext());
prayer.abandon();
}
// Remove the data
DataManager.removeTemp(player.getName(), "prayer_conversation");
DataManager.removeTemp(player.getName(), "prayer_location");
player.setSneaking(false);
// Handle recorded chat
stopRecording(player);
}
}
/**
* Starts recording recording the <code>player</code>'s chat.
*
* @param player the player to stop recording for.
*/
public static void startRecording(Player player)
{
chatRecording = ChatRecorder.Util.startRecording(player);
}
/**
* Stops recording and sends all messages that have been recorded thus far to the player.
*
* @param player the player to stop recording for.
*/
public static List<String> stopRecording(Player player)
{
// Handle recorded chat
if(chatRecording != null && chatRecording.isRecording())
{
// Send held back chat
List<String> messages = chatRecording.stop();
if(messages.size() > 0)
{
player.sendMessage(" ");
player.sendMessage(new ColoredStringBuilder().italic().gray(Demigods.language.getText(Translation.Text.HELD_BACK_CHAT).replace("{size}", "" + messages.size())).build());
for(String message : messages)
player.sendMessage(message);
}
return messages;
}
return null;
}
/**
* Updates favor for all online players.
*
* @param multiplier the favor multiplier.
*/
public static void updateFavor(double multiplier)
{
for(Player player : Bukkit.getOnlinePlayers())
{
DCharacter character = DPlayer.Util.getPlayer(player).getCurrent();
if(character == null) continue;
int regenRate = (int) Math.ceil(multiplier * character.getMeta().getAscensions());
if(regenRate < 30) regenRate = 30;
character.getMeta().addFavor(regenRate);
}
}
}
}
|
package eu.monnetproject.lemon.impl;
import eu.monnetproject.lemon.ElementVisitor;
import eu.monnetproject.lemon.LemonModel;
import eu.monnetproject.lemon.LinguisticOntology;
import eu.monnetproject.lemon.URIElement;
import eu.monnetproject.lemon.impl.io.ReaderAccepter;
import eu.monnetproject.lemon.impl.io.UnactualizedAccepter;
import eu.monnetproject.lemon.model.LemonElement;
import eu.monnetproject.lemon.model.LemonPredicate;
import eu.monnetproject.lemon.model.Property;
import eu.monnetproject.lemon.model.PropertyValue;
import eu.monnetproject.lemon.model.Text;
import java.io.Serializable;
import java.net.URI;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* Base class for element implementations
*
* @author John McCrae
*/
public abstract class LemonElementImpl<Elem extends LemonElement> extends URIElement implements LemonElement, ReaderAccepter, IntrospectableElement, Serializable {
public static final URI RDF_TYPE = URI.create("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
private final Map<LemonPredicate, Collection<LemonElement>> predElems =
Collections.synchronizedMap(new HashMap<LemonPredicate, Collection<LemonElement>>());
private final Map<String, Collection<LemonElement>> strElems =
Collections.synchronizedMap(new HashMap<String, Collection<LemonElement>>());
private final Map<String, LemonElement> strElem =
Collections.synchronizedMap(new HashMap<String, LemonElement>());
private final Map<String, Text> strText =
Collections.synchronizedMap(new HashMap<String, Text>());
private HashSet<URI> types = new HashSet<URI>();
protected List<LemonElementImpl<?>> referencers = new LinkedList<LemonElementImpl<?>>();
private final HashMap<URI, Collection<Object>> annotations = new HashMap<URI, Collection<Object>>();
private final String modelName;
protected final LemonModelImpl model;
protected boolean checkRemote;
protected LemonElementImpl(URI uri, String type, LemonModelImpl model) {
super(uri);
types.add(URI.create(LemonModel.LEMON_URI + type));
modelName = type;
this.model = model;
this.checkRemote = model.allowRemote();
}
protected LemonElementImpl(String id, String type, LemonModelImpl model) {
super(id);
types.add(URI.create(LemonModel.LEMON_URI + type));
modelName = type;
this.model = model;
this.checkRemote = model.allowRemote();
}
@Override
@SuppressWarnings("unchecked")
public Map<Property, Collection<PropertyValue>> getPropertys() {
if (checkRemote) {
resolveRemote();
}
return (Map) getPredElems(Property.class);
}
@Override
@SuppressWarnings("unchecked")
public Collection<PropertyValue> getProperty(final Property property) {
if (checkRemote) {
resolveRemote();
}
return (Collection) getPredElem(property);
}
@Override
public boolean addProperty(final Property property, final PropertyValue propertyVal) {
checkRemote = false;
return addPredElem(property, propertyVal);
}
@Override
public boolean removeProperty(final Property property, final PropertyValue propertyVal) {
checkRemote = false;
return removePredElem(property, propertyVal);
}
@Override
public Collection<URI> getTypes() {
if (checkRemote) {
resolveRemote();
}
return Collections.unmodifiableSet(types);
}
@Override
public void addType(URI uri) {
checkRemote = false;
if (model.allowUpdate()) {
if (getURI() != null) {
model.updater().add(getURI(), RDF_TYPE, uri);
}
}
addTypeDirect(uri);
}
protected boolean addStrElemDirect(String p, LemonElement e) {
checkRemote = false;
if (!strElems.containsKey(p)) {
strElems.put(p, new HashSet<LemonElement>());
}
return strElems.get(p).add(e);
}
protected void addTypeDirect(URI uri) {
checkRemote = false;
types.add(uri);
}
@Override
public void removeType(URI uri) {
checkRemote = false;
types.add(uri);
}
@Override
public Map<URI, Collection<Object>> getAnnotations() {
if (checkRemote) {
resolveRemote();
}
return annotations;
}
@Override
@SuppressWarnings("unchecked")
public Collection<Object> getAnnotations(URI uri) {
if (checkRemote) {
resolveRemote();
}
final Collection<Object> annos = annotations.get(uri);
return annos == null ? Collections.EMPTY_LIST : annos;
}
@Override
public boolean addAnnotation(URI uri, Object o) {
checkRemote = false;
if (o instanceof URI || o instanceof String || o instanceof Text || o instanceof Boolean || o instanceof Integer || o instanceof Double) {
if (!annotations.containsKey(uri)) {
annotations.put(uri, new LinkedList<Object>());
}
return annotations.get(uri).add(o);
} else {
throw new IllegalArgumentException();
}
}
@Override
public boolean removeAnnotation(URI uri, Object o) {
checkRemote = false;
if (o instanceof URI || o instanceof String || o instanceof Text || o instanceof Boolean || o instanceof Integer || o instanceof Double) {
if (!annotations.containsKey(uri)) {
annotations.put(uri, new LinkedList<Object>());
}
final boolean rval = annotations.get(uri).remove(o);
if (annotations.get(uri).isEmpty()) {
annotations.remove(uri);
}
return rval;
} else {
throw new IllegalArgumentException();
}
}
// General functions
protected LemonElement getStrElem(String name) {
if (checkRemote) {
resolveRemote();
}
return strElem.get(name);
}
protected void setStrElemDirect(String name, LemonElement elem) {
checkRemote = false;
if (elem != null && elem instanceof LemonElementImpl) {
((LemonElementImpl<?>) elem).addReference(this);
}
if (elem != null) {
strElem.put(name, elem);
} else {
strElem.remove(name);
}
}
protected void setStrElem(String name, LemonElement elem) {
checkRemote = false;
if (strElem.containsKey(name)) {
if (strElem.get(name) instanceof LemonElementImpl) {
((LemonElementImpl<?>) strElem.get(name)).removeReference(this);
}
}
if (model.allowUpdate()) {
if (getURI() != null) {
if (strElem.containsKey(name)) {
if (strElem.get(name).getURI() != null) {
model.updater().remove(getURI(), URI.create(LemonModel.LEMON_URI + name), strElem.get(name).getURI());
} else {
model.updater().remove(getURI(), URI.create(LemonModel.LEMON_URI + name), strElem.get(name).getID());
}
}
if (elem != null && elem.getURI() != null) {
model.updater().add(getURI(), URI.create(LemonModel.LEMON_URI + name), elem.getURI());
} else if (elem != null) {
model.updater().add(getURI(), URI.create(LemonModel.LEMON_URI + name), elem.getID());
}
} else {
if (strElem.containsKey(name)) {
if (strElem.get(name).getURI() != null) {
model.updater().remove(getID(), URI.create(LemonModel.LEMON_URI + name), strElem.get(name).getURI());
} else {
model.updater().remove(getID(), URI.create(LemonModel.LEMON_URI + name), strElem.get(name).getID());
}
}
if (elem != null && elem.getURI() != null) {
model.updater().add(getID(), URI.create(LemonModel.LEMON_URI + name), elem.getURI());
} else if (elem != null) {
model.updater().add(getID(), URI.create(LemonModel.LEMON_URI + name), elem.getID());
}
}
}
setStrElemDirect(name, elem);
}
protected Text getStrText(String name) {
if (checkRemote) {
resolveRemote();
}
return strText.get(name);
}
protected void setStrText(String name, Text txt) {
checkRemote = false;
if (model.allowUpdate()) {
if (strText.containsKey(name)) {
if (getURI() != null) {
model.updater().remove(getURI(), URI.create(LemonModel.LEMON_URI + name), strText.get(name).value, strText.get(name).language);
} else {
model.updater().remove(getID(), URI.create(LemonModel.LEMON_URI + name), strText.get(name).value, strText.get(name).language);
}
}
if (txt != null) {
if (getURI() != null) {
model.updater().add(getURI(), URI.create(LemonModel.LEMON_URI + name), txt.value, txt.language);
} else {
model.updater().add(getID(), URI.create(LemonModel.LEMON_URI + name), txt.value, txt.language);
}
}
}
setStrTextDirect(name, txt);
}
protected void setStrTextDirect(String name, Text txt) {
checkRemote = false;
if (txt != null) {
strText.put(name, txt);
} else {
strText.remove(name);
}
}
@SuppressWarnings("unchecked")
protected <Pred extends LemonPredicate> Map<Pred, Collection<LemonElement>> getPredElems(Class<Pred> clazz) {
if (checkRemote) {
resolveRemote();
}
Map<Pred, Collection<LemonElement>> rval = new HashMap<Pred, Collection<LemonElement>>();
for (LemonPredicate p : predElems.keySet()) {
if (clazz.isInstance(p)) {
rval.put((Pred) p, predElems.get(p));
}
}
return Collections.unmodifiableMap(rval);
}
@SuppressWarnings("unchecked")
protected Collection<LemonElement> getPredElem(LemonPredicate p) {
if (checkRemote) {
resolveRemote();
}
if (predElems.containsKey(p)) {
return Collections.unmodifiableCollection(new LinkedList<LemonElement>(predElems.get(p)));
} else {
return Collections.EMPTY_LIST;
}
}
protected boolean addPredElem(LemonPredicate p, LemonElement e) {
checkRemote = false;
updateAddPredElem(e, p);
return addPredElemDirect(p, e);
}
protected boolean addPredElemDirect(LemonPredicate p, LemonElement e) {
checkRemote = false;
if (e instanceof LemonElementImpl) {
((LemonElementImpl<?>) e).addReference(this);
}
if (!predElems.containsKey(p)) {
predElems.put(p, new HashSet<LemonElement>());
}
return predElems.get(p).add(e);
}
protected void updateAddPredElem(LemonElement e, LemonPredicate p) {
if (model.allowUpdate()) {
if (getURI() != null) {
if (e.getURI() != null) {
model.updater().add(getURI(), p.getURI(), e.getURI());
} else {
model.updater().add(getURI(), p.getURI(), e.getID());
}
} else {
if (e.getURI() != null) {
model.updater().add(getID(), p.getURI(), e.getURI());
} else {
model.updater().add(getID(), p.getURI(), e.getID());
}
}
}
}
protected boolean removePredElem(LemonPredicate p, LemonElement e) {
checkRemote = false;
updateRemovePredElem(e, p);
if (e instanceof LemonElementImpl) {
((LemonElementImpl<?>) e).removeReference(this);
}
if (predElems.containsKey(p)) {
return predElems.get(p).remove(e);
} else {
return false;
}
}
private void updateRemovePredElem(LemonElement e, LemonPredicate p) {
if (model.allowUpdate()) {
if (getURI() != null) {
if (e.getURI() != null) {
model.updater().remove(getURI(), p.getURI(), e.getURI());
} else {
model.updater().remove(getURI(), p.getURI(), e.getID());
}
} else {
if (e.getURI() != null) {
model.updater().remove(getID(), p.getURI(), e.getURI());
} else {
model.updater().remove(getID(), p.getURI(), e.getID());
}
}
}
}
@SuppressWarnings("unchecked")
protected Collection<LemonElement> getStrElems(String name) {
if (checkRemote) {
resolveRemote();
}
if (strElems.containsKey(name)) {
return Collections.unmodifiableCollection(new LinkedList<LemonElement>(strElems.get(name)));
} else {
return Collections.EMPTY_LIST;
}
}
protected boolean addStrElem(String p, LemonElement e) {
checkRemote = false;
if (e instanceof LemonElementImpl) {
((LemonElementImpl<?>) e).addReference(this);
}
if (model.allowUpdate()) {
if (getURI() != null) {
if (e.getURI() != null) {
model.updater().add(getURI(), URI.create(LemonModel.LEMON_URI + p), e.getURI());
} else {
model.updater().add(getURI(), URI.create(LemonModel.LEMON_URI + p), e.getID());
}
} else {
if (e.getURI() != null) {
model.updater().add(getID(), URI.create(LemonModel.LEMON_URI + p), e.getURI());
} else {
model.updater().add(getID(), URI.create(LemonModel.LEMON_URI + p), e.getID());
}
}
}
return addStrElemDirect(p, e);
}
protected boolean removeStrElem(String p, LemonElement e) {
checkRemote = false;
if (e instanceof LemonElementImpl) {
((LemonElementImpl<?>) e).removeReference(this);
}
if (model.allowUpdate()) {
if (getURI() != null) {
if (e.getURI() != null) {
model.updater().remove(getURI(), URI.create(LemonModel.LEMON_URI + p), e.getURI());
} else {
model.updater().remove(getURI(), URI.create(LemonModel.LEMON_URI + p), e.getID());
}
} else {
if (e.getURI() != null) {
model.updater().remove(getID(), URI.create(LemonModel.LEMON_URI + p), e.getURI());
} else {
model.updater().remove(getID(), URI.create(LemonModel.LEMON_URI + p), e.getID());
}
}
}
if (strElems.containsKey(p)) {
return strElems.get(p).remove(e);
} else {
return false;
}
}
// Merge support
protected void addReference(LemonElementImpl<?> element) {
referencers.add(element);
}
protected void removeReference(LemonElementImpl<?> element) {
referencers.remove(element);
}
protected void updateReference(LemonElement from, LemonElement to) {
for (LemonPredicate pred : predElems.keySet()) {
if (predElems.get(pred).contains(from)) {
predElems.get(pred).remove(from);
predElems.get(pred).add(to);
}
}
for (String pred : strElems.keySet()) {
if (strElems.get(pred).contains(from)) {
strElems.get(pred).remove(from);
strElems.get(pred).add(to);
}
}
List<String> preds = new LinkedList<String>();
for (String pred : strElem.keySet()) {
if (strElem.get(pred).equals(from)) {
// Avoid concurrent modification
preds.add(pred);
}
}
for (String pred : preds) {
strElem.put(pred, to);
}
}
protected void mergeIn(Elem elem) {
if (!(elem instanceof LemonElementImpl)) {
throw new IllegalArgumentException("Cannot merge non-simple lemon element into simple store");
}
LemonElementImpl<?> lesp = (LemonElementImpl<?>) elem;
predElems.putAll(lesp.predElems);
strElems.putAll(lesp.strElems);
strElem.putAll(lesp.strElem);
strText.putAll(lesp.strText);
types.addAll(lesp.types);
for (Iterator<LemonElementImpl<?>> it = lesp.referencers.iterator(); it.hasNext();) {
LemonElementImpl<?> rlesp = it.next();
rlesp.updateReference(elem, this);
}
}
// Serialization related
protected boolean refers() {
return !(predElems.isEmpty() && strElems.isEmpty() && strElem.isEmpty()
&& strText.isEmpty() && types.isEmpty());
}
public void visit(java.io.PrintWriter stream, SerializationState state) {
boolean refers = refers();
// If the object is referenced at mutliple points we only put its ID
if (referencers.size() > 1) {
if (this.getURI() != null) {
printURI(this.getURI(), stream);
} else {
stream.print("_:" + this.getID());
}
} else {
if (this.getURI() != null) {
printURI(this.getURI(), stream);
} else if (!refers || state.serialized.contains(this)) {
stream.print("_:" + this.getID());
} else {
stream.print("[ ");
printAsBlankNode(stream, state);
stream.print(" ]");
}
}
}
private static String LS = System.getProperty("line.separator");
protected void printAsBlankNode(java.io.PrintWriter stream, SerializationState state) {
state.serialized.add(this);
boolean first = true;
for (LemonPredicate pred : predElems.keySet()) {
if (!first) {
stream.println(" ;");
}
boolean first2 = true;
printURI(pred.getURI(), stream);
for (LemonElement elem : predElems.get(pred)) {
if (!first2) {
stream.println(" ,");
} else {
stream.print(" ");
}
if (elem instanceof LemonElementImpl) {
((LemonElementImpl) elem).visit(stream, state);
if (((LemonElementImpl) elem).isMultiReferenced() && elem.getURI() != null) {
state.postponed.add(elem);
}
first2 = false;
} else {
if (elem.getURI() != null) {
stream.print(" ");
printURI(elem.getURI(), stream);
} else {
throw new RuntimeException("Not an element and blank... can't serialize");
}
first2 = false;
}
}
first = false;
}
for (String pred : strElems.keySet()) {
if (!first) {
stream.println(" ;");
}
boolean first2 = true;
stream.print(" lemon:" + pred + " ");
for (LemonElement elem : strElems.get(pred)) {
if (!first2) {
stream.println(" ,");
}
((LemonElementImpl) elem).visit(stream, state);
if (((LemonElementImpl) elem).isMultiReferenced() && elem.getURI() != null) {
state.postponed.add(elem);
}
first2 = false;
}
first = false;
}
for (String pred : strElem.keySet()) {
if (!first) {
stream.println(" ;");
}
stream.print(" lemon:" + pred + " ");
LemonElement elem = strElem.get(pred);
if (elem instanceof LemonElementImpl) {
((LemonElementImpl) elem).visit(stream, state);
if (((LemonElementImpl) elem).isMultiReferenced() && elem.getURI() != null) {
state.postponed.add(elem);
}
} else {
if(elem.getURI() != null) {
stream.print(" <" + elem.getURI().toString() + "> ");
} else {
stream.print(" _:" + elem.getID() + " ");
}
}
first = false;
}
for (String pred : strText.keySet()) {
if (!first) {
stream.println(" ;");
}
stream.print(" lemon:" + pred + " ");
Text txt = strText.get(pred);
if (txt.language != null) {
stream.print("\"" + txt.value + "\"@" + txt.language);
} else {
stream.print("\"" + txt.value + "\"");
}
first = false;
}
boolean first2 = true;
for (URI typeURI : types) {
if (first) {
stream.print(" a ");
} else if (first2) {
stream.print(" ;"+LS+" a ");
} else {
stream.println(" ,");
}
printURI(typeURI, stream);
first2 = false;
first = false;
}
printAsBlankNode(stream, state, first);
}
protected void printURI(URI uri, java.io.PrintWriter stream) {
if (uri.toString().startsWith(LemonModel.LEMON_URI)) {
stream.print("lemon:" + uri.toString().substring(LemonModel.LEMON_URI.length()));
} else {
stream.print("<" + uri + ">");
}
}
protected void printAsBlankNode(java.io.PrintWriter stream, SerializationState state, boolean first) {
}
public void write(java.io.PrintWriter stream, SerializationState state) {
if (!refers() || (referencers.size() == 1 && getURI() == null)) {
return;
}
if (this.getURI() != null) {
printURI(this.getURI(), stream);
} else {
stream.print("_:" + getID() + " ");
}
printAsBlankNode(stream, state);
stream.println(" ."+LS);
}
protected boolean follow(LemonPredicate predicate) {
return true;
}
protected boolean follow(String predName) {
return true;
}
protected void doAccept(ElementVisitor visitor) {
}
@SuppressWarnings("unchecked")
public final void accept(ElementVisitor visitor) {
if (visitor.hasVisited((Elem) this)) {
return;
}
if (visitor.visitFirst()) {
visitor.visit((Elem) this);
}
for (Map.Entry<String, Collection<LemonElement>> elemsES : strElems.entrySet()) {
final String pred = elemsES.getKey();
final Collection<LemonElement> elems = elemsES.getValue();
for (LemonElement elem : elems) {
if (elem instanceof LemonElementImpl) {
if (!visitor.follow(URI.create(LemonModel.LEMON_URI + pred)) || follow(pred)) {
((LemonElementImpl) elem).accept(visitor);
}
} else {
//log.info("Could not visit " + elem);
}
}
}
for (Map.Entry<LemonPredicate, Collection<LemonElement>> elemsES : predElems.entrySet()) {
final LemonPredicate pred = elemsES.getKey();
final Collection<LemonElement> elems = elemsES.getValue();
for (LemonElement elem : elems) {
if (elem instanceof LemonElementImpl) {
if (!visitor.follow(pred) || follow(pred)) {
((LemonElementImpl) elem).accept(visitor);
}
} else {
//log.info("Could not visit " + elem);
}
}
}
for (Map.Entry<String, LemonElement> es : strElem.entrySet()) {
final String pred = es.getKey();
final LemonElement elem = es.getValue();
if (elem instanceof LemonElementImpl) {
if (visitor.follow(URI.create(LemonModel.LEMON_URI + pred)) || follow(pred)) {
((LemonElementImpl) elem).accept(visitor);
}
} else {
//log.info("Could not visit " + elem);
}
}
doAccept(visitor);
if (!visitor.visitFirst()) {
visitor.visit(this);
}
}
public void clearAll() {
for (Collection<LemonElement> elems : predElems.values()) {
for (LemonElement lemonElement : elems) {
if (lemonElement instanceof LemonElementImpl) {
((LemonElementImpl) lemonElement).referencers.remove(this);
}
}
}
for (Collection<LemonElement> elems : strElems.values()) {
for (LemonElement lemonElement : elems) {
if (lemonElement instanceof LemonElementImpl) {
((LemonElementImpl) lemonElement).referencers.remove(this);
}
}
}
for (LemonElement lemonElement : strElem.values()) {
if (lemonElement instanceof LemonElementImpl) {
((LemonElementImpl) lemonElement).referencers.remove(this);
}
}
predElems.clear();
strElem.clear();
strElems.clear();
strText.clear();
}
protected ReaderAccepter defaultAccept(URI pred, URI value, LinguisticOntology lingOnto) {
if (pred.equals(RDF_TYPE)) {
if (!value.toString().startsWith(LemonModel.LEMON_URI)) {
addTypeDirect(value);
return null;
} else {
return null;
}
}
if (!acceptProperties(pred, value, lingOnto)) {
addAnnotation(pred, value);
}
return null;
}
protected ReaderAccepter defaultAccept(URI pred, String value) {
addAnnotation(pred, value);
return null;
}
protected void defaultAccept(URI pred, String val, String lang) {
addAnnotation(pred, new Text(val, lang));
}
protected <X, Y> void merge(Map<X, Collection<Y>> map1, Map<X, Collection<Y>> map2) {
for (X x : map2.keySet()) {
if (!map1.containsKey(x)) {
map1.put(x, map2.get(x));
} else {
for (Y y : map2.get(x)) {
if (!map1.get(x).contains(y)) {
map1.get(x).add(y);
}
}
}
}
}
protected <X> void merge(Collection<X> list1, Collection<X> list2) {
for (X x : list2) {
if (!list1.contains(x)) {
list1.add(x);
}
}
}
protected void defaultMerge(ReaderAccepter accepter, LinguisticOntology lingOnto, AccepterFactory factory) {
if (this == accepter) {
return;
}
if (accepter instanceof LemonElementImpl) {
final LemonElementImpl<?> sle = (LemonElementImpl<?>) accepter;
merge(this.annotations, sle.annotations);
merge(this.predElems, sle.predElems);
merge(this.referencers, sle.referencers);
this.strElem.putAll(sle.strElem);
merge(this.strElems, sle.strElems);
this.strText.putAll(sle.strText);
merge(this.types, sle.types);
} else if (accepter instanceof UnactualizedAccepter) {
((UnactualizedAccepter) accepter).actualizedAs(this, lingOnto, factory);
}
}
protected boolean acceptProperties(URI pred, URI value, LinguisticOntology lingOnto) {
try {
if (pred.getFragment() != null && lingOnto.getProperty(pred.getFragment()) != null
&& value.getFragment() != null && lingOnto.getPropertyValue(value.getFragment()) != null) {
addPredElemDirect(lingOnto.getProperty(pred.getFragment()), lingOnto.getPropertyValue(value.getFragment()));
return true;
}
} catch (Exception x) {
}
return false;
}
@Override
@SuppressWarnings("unchecked")
public Map<URI, Collection<Object>> getElements() {
Map<URI, Collection<Object>> rval = new HashMap<URI, Collection<Object>>();
for (Map.Entry<LemonPredicate, Collection<LemonElement>> entry : predElems.entrySet()) {
rval.put(entry.getKey().getURI(), (Collection) entry.getValue());
}
for (Map.Entry<String, LemonElement> entry : strElem.entrySet()) {
URI uri = URI.create(LemonModel.LEMON_URI + entry.getKey());
if (!rval.containsKey(uri)) {
rval.put(uri, new LinkedList<Object>());
}
rval.get(uri).add(entry.getValue());
}
for (Map.Entry<String, Collection<LemonElement>> entry : strElems.entrySet()) {
URI uri = URI.create(LemonModel.LEMON_URI + entry.getKey());
if (!rval.containsKey(uri)) {
rval.put(uri, new LinkedList<Object>());
}
rval.get(uri).addAll(entry.getValue());
}
for (Map.Entry<String, Text> entry : strText.entrySet()) {
URI uri = URI.create(LemonModel.LEMON_URI + entry.getKey());
if (!rval.containsKey(uri)) {
rval.put(uri, new LinkedList<Object>());
}
rval.get(uri).add(entry.getValue());
}
if (!rval.containsKey(RDF_TYPE) && !types.isEmpty()) {
rval.put(RDF_TYPE, new LinkedList<Object>());
}
for (URI type : types) {
rval.get(RDF_TYPE).add(type);
}
rval.putAll(annotations);
return rval;
}
@Override
public String getModelName() {
return modelName;
}
public boolean isMultiReferenced() {
return referencers.size() > 1;
}
protected void resolveRemote() {
checkRemote = false;
model.resolver().resolveRemote(model, this, 1);
}
}
|
package uk.org.ponder.rsf.template;
import java.util.HashMap;
import uk.org.ponder.arrayutil.ArrayUtil;
/**
* A primitive "lump" of an XML document, representing a "significant"
* character span. The basic function is to hold indexes start, length into
* the character array for the document, as well as various housekeeping
* information to aid navigation and debugging.
*
* @author Antranig Basman (antranig@caret.cam.ac.uk)
*/
public class XMLLump {
/** This string is used as separator between transition entries in forwardmap,
* of the form "old-id-suffix new-id-suffix" */
public static final String TRANSITION_SEPARATOR = " ";
public int lumpindex;
public int line, column;
public int nestingdepth;
public XMLViewTemplate parent;
public int start, length;
public String rsfID;
public XMLLump open_end = null; // lump containing " >"
public XMLLump close_tag = null; // lump containing "</close">
public XMLLump uplump = null;
// open and close will be the same for empty tag case " />"
// headlump has standard text of |<tagname | to allow easy identification.
public XMLLumpMMap downmap = null;
// map from attribute name to lump where value occurs.
// this may be reformed to map to text if we collapse attribute lumps?
public HashMap attributemap = null;
// the (XHTML) attribute appearing in the template file designating a
// template component.
public static final String ID_ATTRIBUTE = "rsf:id";
// A value for the rsf:id attribute representing a component that needs
// URL rewriting (issued URLs beginning with root /). NEVER issue a component
// with this ID!
public static final String SCR_PREFIX = "scr=";
// Value for rsf:id that represents a CollectingSCR
public static final String SCR_CONTRIBUTE_PREFIX = "scr=contribute-";
public static final String URL_REWRITE = "rewrite-url";
// A value for the rsf:id attribute indicating that the actual (leaf) component
// to be targetted by component rendering is somewhere inside the component
// holding the ID. NEVER issue a component with this ID! In this case, the
// component holding the ID will be either a div or a span.
public static final String PAYLOAD_COMPONENT = "payload-component";
// this occurs in the SAME CONTAINER scope as the target???
public static final String FORID_PREFIX = "message-for";// + SplitID.SEPARATOR;
public static final String FORID_SUFFIX = ":*";
public XMLLump() {}
public XMLLump(int lumpindex, int nestingdepth) {
this.lumpindex = lumpindex;
this.nestingdepth = nestingdepth;
}
public boolean textEquals(String tocheck) {
return ArrayUtil.equals(tocheck, parent.buffer, start, length);
}
public static String tagToText(String tagname) {
return "<" + tagname + " ";
}
public static String textToTag(String text) {
return text.substring(1, text.length() - 1);
}
public String getTag() {
return new String(parent.buffer, start + 1, length - 2);
}
public String toDebugString() {
return "lump index " + lumpindex + " line " + line + " column " + column;
}
public String toString() {
return new String(parent.buffer, start, length) + " at " + toDebugString()
+ (parent.fullpath == null? "" : " in file " + parent.fullpath);
}
}
|
package org.openlmis.core.view.activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.inject.Inject;
import org.openlmis.core.R;
import org.openlmis.core.manager.SharedPreferenceMgr;
import org.openlmis.core.model.repository.MMIARepository;
import org.openlmis.core.model.repository.VIARepository;
import org.openlmis.core.service.SyncManager;
import org.openlmis.core.utils.Constants;
import org.openlmis.core.utils.DateUtil;
import org.openlmis.core.utils.ToastUtil;
import java.util.Date;
import roboguice.inject.ContentView;
import roboguice.inject.InjectResource;
import roboguice.inject.InjectView;
@ContentView(R.layout.activity_main_page)
public class HomeActivity extends BaseActivity {
@InjectView(R.id.btn_stock_card)
Button btnStockCard;
@InjectView(R.id.btn_inventory)
Button btnInventory;
@InjectView(R.id.btn_mmia)
Button btnMMIA;
@InjectView(R.id.btn_requisition)
Button btnRequisition;
@InjectView(R.id.btn_sync_data)
Button btnSyncData;
@InjectView(R.id.tx_last_synced_rnrform)
TextView txLastSyncedRnrForm;
@InjectView(R.id.tx_last_synced_stockcard)
TextView txLastSyncedStockCard;
@InjectView(R.id.btn_mmia_list)
Button btnMMIAList;
@InjectView(R.id.btn_via_list)
Button btnVIAList;
@InjectResource(R.integer.back_twice_interval)
int BACK_TWICE_INTERVAL;
@Inject
SyncManager syncManager;
private boolean exitPressedOnce = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
}
setSyncedTime();
IntentFilter filter = new IntentFilter();
filter.addAction(Constants.INTENT_FILTER_SET_SYNCED_TIME);
registerReceiver(syncedTimeReceiver, filter);
}
BroadcastReceiver syncedTimeReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
setSyncedTime();
}
};
@Override
protected void onDestroy() {
unregisterReceiver(syncedTimeReceiver);
super.onDestroy();
}
public void onClickStockCard(View view) {
startActivity(StockCardListActivity.class, false);
}
public void onClickInventory(View view) {
Intent intent = new Intent(HomeActivity.this, InventoryActivity.class);
intent.putExtra(Constants.PARAM_IS_PHYSICAL_INVENTORY, true);
startActivity(intent);
}
public void onClickMMIA(View view) {
startActivity(MMIARequisitionActivity.class, false);
}
public void onClickRequisition(View view) {
startActivity(VIARequisitionActivity.class, false);
}
public void onClickSyncData(View view) {
syncManager.requestSyncImmediately();
}
public void onClickMMIAHistory(View view) {
Intent intent = new Intent(this, RnRFormListActivity.class);
intent.putExtra(Constants.PARAM_PROGRAM_CODE, MMIARepository.MMIA_PROGRAM_CODE);
startActivity(intent);
}
public void onClickVIAHistory(View view) {
Intent intent = new Intent(this, RnRFormListActivity.class);
intent.putExtra(Constants.PARAM_PROGRAM_CODE, VIARepository.VIA_PROGRAM_CODE);
startActivity(intent);
}
@Override
protected void onResume() {
super.onResume();
setSyncedTime();
}
protected void setSyncedTime() {
showRnrFormLastSyncedTime();
showStockCardLastSyncedTime();
}
private void showRnrFormLastSyncedTime() {
long lastSyncedTimestamp = getPreferences().getLong(SharedPreferenceMgr.KEY_LAST_SYNCED_TIME_RNR_FORM, 0);
if (lastSyncedTimestamp == 0) {
return;
}
long currentTimestamp = new Date().getTime();
long diff = currentTimestamp - lastSyncedTimestamp;
if (diff < DateUtil.MILLISECONDS_HOUR) {
txLastSyncedRnrForm.setText(getResources().getString(R.string.label_rnr_form_last_synced_mins_ago, (diff / DateUtil.MILLISECONDS_MINUTE)));
} else if (diff < DateUtil.MILLISECONDS_DAY) {
txLastSyncedRnrForm.setText(getResources().getString(R.string.label_rnr_form_last_synced_hours_ago, (diff / DateUtil.MILLISECONDS_HOUR)));
} else {
txLastSyncedRnrForm.setText(getResources().getString(R.string.label_rnr_form_last_synced_days_ago, (diff / DateUtil.MILLISECONDS_DAY)));
}
}
private void showStockCardLastSyncedTime() {
long lastSyncedTimestamp = getPreferences().getLong(SharedPreferenceMgr.KEY_LAST_SYNCED_TIME_STOCKCARD, 0);
if (lastSyncedTimestamp == 0) {
return;
}
long currentTimestamp = new Date().getTime();
long diff = currentTimestamp - lastSyncedTimestamp;
if (diff < DateUtil.MILLISECONDS_HOUR) {
txLastSyncedStockCard.setText(getResources().getString(R.string.label_stock_card_last_synced_mins_ago, (diff / DateUtil.MILLISECONDS_MINUTE)));
} else if (diff < DateUtil.MILLISECONDS_DAY) {
txLastSyncedStockCard.setText(getResources().getString(R.string.label_stock_card_last_synced_hours_ago, (diff / DateUtil.MILLISECONDS_HOUR)));
} else {
txLastSyncedStockCard.setText(getResources().getString(R.string.label_stock_card_last_synced_days_ago, (diff / DateUtil.MILLISECONDS_DAY)));
}
}
@Override
public void onBackPressed() {
if (exitPressedOnce) {
moveTaskToBack(true);
} else {
ToastUtil.show(R.string.msg_back_twice_to_exit);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
exitPressedOnce = false;
}
}, BACK_TWICE_INTERVAL);
}
exitPressedOnce = !exitPressedOnce;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_home, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_sign_out) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
public static Intent getIntentToMe(Context context) {
Intent intent = new Intent(context, HomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
return intent;
}
}
|
package cx2x.translator.language;
import cx2x.translator.language.helper.accelerator.AcceleratorDirective;
import cx2x.xcodeml.exception.IllegalDirectiveException;
import cx2x.xcodeml.language.AnalyzedPragma;
import cx2x.xcodeml.xelement.Xpragma;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.BailErrorStrategy;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.misc.ParseCancellationException;
import java.util.List;
/**
* ClawLanguage class represent an analyzed pragma statement.
*
* @author clementval
*/
public class ClawLanguage extends AnalyzedPragma {
private static final String PREFIX_CLAW = "claw";
private AcceleratorDirective _target;
private ClawDirective _directive;
// Clauses values
private String _accClausesValue;
private String _arrayName;
private int _collapseClauseValue;
private List<String> _dataValues;
private String _groupClauseValue;
private List<String> _fctCallParameters;
private String _fctName;
private List<String> _hoistInductionValues;
private List<String> _indexesValues;
private List<String> _inductionClauseValues;
private List<ClawMapping> _mappingValues;
private List<Integer> _offsetValues;
private ClawRange _rangeValue;
private List<ClawReshapeInfo> _reshapeInfos;
// Clauses flags
private boolean _hasAccClause, _hasCollapseClause, _hasDataClause;
private boolean _hasFusionClause, _hasGroupClause, _hasIndexesValue;
private boolean _hasInductionClause, _hasInitClause, _hasInterchangeClause;
private boolean _hasParallelClause, _hasPrivateClause, _hasReshapeClause;
/**
* Constructs an empty ClawLanguage section.
* WARNING: This ctor should only be used by the parser.
*/
protected ClawLanguage(){
resetVariables();
}
/**
* Constructs an empty ClawLanguage object with an attached pragma. Used only
* for transformation that are not CLAW related.
* @param pragma The pragma that is attached to the ClawLanguage object.
*/
public ClawLanguage(Xpragma pragma){
super(pragma);
resetVariables();
}
private void resetVariables(){
// Clauses values members
_accClausesValue = null;
_arrayName = null;
_collapseClauseValue = 0;
_dataValues = null;
_fctCallParameters = null;
_fctName = null;
_groupClauseValue = null;
_hoistInductionValues = null;
_indexesValues = null;
_inductionClauseValues = null;
_mappingValues = null;
_offsetValues = null;
_rangeValue = null;
_reshapeInfos = null;
// Clauses flags members
_hasAccClause = false;
_hasCollapseClause = false;
_hasFusionClause = false;
_hasGroupClause = false;
_hasIndexesValue = false;
_hasInductionClause = false;
_hasInitClause = false;
_hasInterchangeClause = false;
_hasParallelClause = false;
_hasPrivateClause = false;
_hasReshapeClause = false;
// General members
_directive = null;
_target = AcceleratorDirective.NONE;
// super class members
_pragma = null;
}
/**
* Check if the pragma statement starts with the claw keyword.
* @param pragma The Xpragma object to check.
* @return True if the statement starts with claw keyword. False otherwise.
*/
public static boolean startsWithClaw(Xpragma pragma) {
return !(pragma == null || pragma.getValue() == null)
&& pragma.getValue().startsWith(PREFIX_CLAW);
}
public static ClawLanguage analyze(Xpragma pragma,
AcceleratorDirective target)
throws IllegalDirectiveException
{
/*
* OMNI compiler keeps the claw prefix when a pragma is defined on several
* lines using the continuation symbol '&'. In order to have a simpler
* grammar, these multiple occurences of the prefix are not taken into
* account. Therefore, this method remove all the prefix and keeps only the
* first one.
*/
String nakedPragma = pragma.getValue().toLowerCase().replaceAll(PREFIX_CLAW, "");
nakedPragma = PREFIX_CLAW + " " + nakedPragma;
// Instantiate the lexer with the raw string input
ClawLexer lexer = new ClawLexer(new ANTLRInputStream(nakedPragma));
// Get a list of matched tokens
CommonTokenStream tokens = new CommonTokenStream(lexer);
// Pass the tokens to the parser
ClawParser parser = new ClawParser(tokens);
parser.setErrorHandler(new BailErrorStrategy());
parser.removeErrorListeners();
ClawErrorListener cel = new ClawErrorListener();
parser.addErrorListener(cel);
try {
// Start the parser analysis from the "analyze" entry point
ClawParser.AnalyzeContext ctx = parser.analyze();
// Get the ClawLanguage object return by the parser after analysis.
ctx.l.attachPragma(pragma);
ctx.l.setAcceleratorDirective(target);
return ctx.l;
} catch(ParseCancellationException pcex){
IllegalDirectiveException ex = cel.getLastError();
if(ex != null){
throw ex;
} else {
throw new IllegalDirectiveException("", "", 0, 0); // TODO
}
}
}
/**
* Check whether a group clause was specified.
* @return True if group clause was specified.
*/
public boolean hasGroupClause(){
return _hasGroupClause;
}
/**
* Set the group name and hasGroupClause to true
* @param groupName The group name defined in the group clause.
*/
void setGroupClause(String groupName){
if(groupName != null) {
_hasGroupClause = true;
_groupClauseValue = groupName;
}
}
/**
* Get the group name defined in the group clause.
* @return The group name as a String value.
*/
public String getGroupValue(){
return _groupClauseValue;
}
/**
* Check whether the collapse clause is used.
* @return True if the collapse clause if used.
*/
public boolean hasCollapseClause(){
return _hasCollapseClause;
}
/**
* Set the collapse number and boolean flag.
* @param n Number of loop to be collapsed. Will be converted to integer.
*/
void setCollapseClause(String n){
_hasCollapseClause = true;
_collapseClauseValue = Integer.parseInt(n);
}
/**
* Set the collapse number and boolean flag. Flag is enable if n is greater
* than 1. Otherwise, collapse clause has no impact.
* @param n Number of loops to be collapsed.
*/
void setCollapseClause(int n){
if(n > 1) {
_hasCollapseClause = true;
_collapseClauseValue = n;
}
}
/**
* Get the collapse clause extracted value.
* @return An interger value.
*/
public int getCollapseValue(){
return _collapseClauseValue;
}
// Loop interchange specific methods
/**
* Set the list of interhcnage indexes.
* @param indexes List of indexes as string.
*/
void setIndexes(List<String> indexes){
_hasIndexesValue = true;
_indexesValues = indexes;
}
/**
* Get the loop index list
* @return List of loop index
*/
public List<String> getIndexes(){
return _indexesValues;
}
/**
* Check whether the interchange directive has indexes values.
* @return True if the directive has interchange value.
*/
public boolean hasIndexes(){
return _hasIndexesValue;
}
// Loop extract specific methods
/**
* Set the range value.
* @param range A ClawRange object.
*/
protected void setRange(ClawRange range){
_rangeValue = range;
}
/**
* Get the range extracted value.
* @return A ClawRange object.
*/
public ClawRange getRange(){
return _rangeValue;
}
/**
* Set the ClawMapping list
* @param mappings A list of ClawMapping objects.
*/
void setMappings(List<ClawMapping> mappings){
_mappingValues = mappings;
}
/**
* Get the list of extracted ClawMapping objects.
* @return List of ClawMapping objects.
*/
public List<ClawMapping> getMappings(){
return _mappingValues;
}
/**
* Enable the fusion clause for the current directive.
*/
void setFusionClause(){
_hasFusionClause = true;
}
/**
* Check whether the current directive has the fusion clause enabled.
* @return True if the fusion clause is enabled.
*/
public boolean hasFusionClause(){
return _hasFusionClause;
}
/**
* Enable the parallel clause for the current directive.
*/
void setParallelClause(){
_hasParallelClause = true;
}
/**
* Check whether the current directive has the parallel clause enabled.
* @return True if the parallel clause is enabled.
*/
public boolean hasParallelClause(){
return _hasParallelClause;
}
/**
* Enable the accelerator clause for the current directive and set the
* extracted clauses.
* @param clauses Accelerator clauses extracted from the accelerator clause.
*/
void setAcceleratorClauses(String clauses){
_hasAccClause = true;
_accClausesValue = clauses;
}
/**
* Check whether the current directive has the accelerator clause enabled.
* @return True if the accelerator clause is enabled.
*/
public boolean hasAcceleratorClause(){
return _hasAccClause;
}
/**
* Get the accelerator clauses extracted from the accelerator clause.
* @return Accelerator clauses as a String.
*/
public String getAcceleratorClauses(){
return _accClausesValue;
}
/**
* Set the offsets list extracted from the kcache directive.
* @param offsets A list of offsets.
*/
void setOffsets(List<Integer> offsets){
_offsetValues = offsets;
}
/**
* Get the list of offsets.
* @return List of offsets.
*/
public List<Integer> getOffsets(){
return _offsetValues;
}
// loop hoist clauses
/**
* Check whether the interchange clause is used.
* @return True if the interchange clause if used.
*/
public boolean hasInterchangeClause(){
return _hasInterchangeClause;
}
/**
* Set the interchange clause as used.
*/
void setInterchangeClause(){
_hasInterchangeClause = true;
}
/**
* Set the list of induction variables used in the loop-hoist directive.
* @param vars List of induction variable.
*/
void setHoistInductionVars(List<String> vars){
_hoistInductionValues = vars;
}
/**
* Get the list of induction variables used in the hoist directive.
* @return A list of induction variable.
*/
public List<String> getHoistInductionVars(){
return _hoistInductionValues;
}
// Directive generic method
/**
* Define the current directive of the language section.
* @param directive A value of the ClawDirective enumeration.
*/
public void setDirective(ClawDirective directive){
_directive = directive;
}
/**
* Get the current directive of the language section.
* @return Value of the current directive.
*/
public ClawDirective getDirective(){
return _directive;
}
/**
* Enable the induction clause for the current directive and set the extracted
* name value.
* @param names List of induction name extracted from the clause.
*/
void setInductionClause(List<String> names){
_hasInductionClause = true;
_inductionClauseValues = names;
}
/**
* Check whether the current directive has the induction clause enabled.
* @return True if the induction clause is enabled.
*/
public boolean hasInductionClause(){
return _hasInductionClause;
}
/**
* Get the name value extracted from the induction clause.
* @return Induction name as a String.
*/
public List<String> getInductionValues(){
return _inductionClauseValues;
}
/**
* Enable the data clause for the current directive and set the extracted
* identifiers value.
* @param data List of identifiers extracted from the clause.
*/
void setDataClause(List<String> data){
_hasDataClause = true;
_dataValues = data;
}
/**
* Check whether the current directive has the induction clause enabled.
* @return True if the induction clause is enabled.
*/
public boolean hasDataClause(){
return _hasDataClause;
}
/**
* Get the identifier values extracted from the data clause.
* @return Identifier as a String.
*/
public List<String> getDataClauseValues(){
return _dataValues;
}
/**
* Check whether the init clause is used.
* @return True if the init clause is used.
*/
public boolean hasInitClause(){
return _hasInitClause;
}
/**
* Set the init clause flag.
*/
void setInitClause(){
_hasInitClause = true;
}
/**
* Check whether the private clause is used.
* @return True if the private clause is used.
*/
public boolean hasPrivateClause(){
return _hasPrivateClause;
}
/**
* Set the private clause flag.
*/
void setPrivateClause(){
_hasPrivateClause = true;
}
/**
* Set the list of parameters for the fct call of the "call" directive
* @param data List of identifiers extracted from the clause.
*/
void setFctParams(List<String> data){
_fctCallParameters = data;
}
/**
* Get the list of parameters extracted from the call directive.
* @return List of parameters identifier as String value.
*/
public List<String> getFctParams(){
return _fctCallParameters;
}
/**
* Set the array name value.
* @param value String value for the array name.
*/
void setArrayName(String value){
_arrayName = value;
}
/**
* Get the array name extracted from the call directive.
* @return Array name from the call directive.
*/
public String getArrayName(){
return _arrayName;
}
/**
* Set the function name value.
* @param value String value for the function name.
*/
void setFctName(String value){
_fctName = value;
}
/**
* Get the fct name extracted from the call directive.
* @return Fct name from the call directive.
*/
public String getFctName(){
return _fctName;
}
/**
* Set the reshape clause extracted information.
* @param infos List of ClawReshapeInfo objects containing the extracted
* information from the reshape clause.
*/
void setReshapeClauseValues(List<ClawReshapeInfo> infos){
_hasReshapeClause = true;
_reshapeInfos = infos;
}
/**
* Get the reshape extracted information.
* @return List of ClawReshapeInfo objects containing the extracted
* information from the reshape clause.
*/
public List<ClawReshapeInfo> getReshapeClauseValues(){
return _reshapeInfos;
}
/**
* Check whether the reshape clause is used.
* @return True if the reshape clause is used.
*/
public boolean hasReshapeClause(){
return _hasReshapeClause;
}
/**
* Attach the pragma related to this CLAW language analysis.
* @param pragma Xpragma object.
*/
private void attachPragma(Xpragma pragma){
_pragma = pragma;
}
/**
* Set the accelerator target for pragma generation
* @param target Accelerator directive value.
*/
private void setAcceleratorDirective(AcceleratorDirective target){
_target = target;
}
/**
* Get the accelerator directive language associated with
* @return Associated accelerator directive.
*/
public AcceleratorDirective getAcceleratorDirective(){
return _target;
}
/**
* Create an instance of ClawLanguage that correspond to a loop-fusion
* directive. Used for dynamically created transformation.
* @param master Base object which initiate the creation of this instance.
* @return An instance of ClawLanguage describing a loop-fusion with the
* group, collapse clauses and the pragma from the master object.
*/
public static ClawLanguage createLoopFusionLanguage(ClawLanguage master){
ClawLanguage l = new ClawLanguage();
l.setDirective(ClawDirective.LOOP_FUSION);
l.setGroupClause(master.getGroupValue());
l.setCollapseClause(master.getCollapseValue());
l.attachPragma(master.getPragma());
return l;
}
/**
* Create an instance of ClawLanguage that correspond to a loop-fusion
* directive. Used for dynamically created transformation.
* @param base Pragma that triggered the transformation.
* @param group Group clause value.
* @param collapse Collapse clause value.
* @return An instance of ClawLanguage describing a loop-fusion with the
* group, collapse clauses and the pragma from the master object.
*/
public static ClawLanguage createLoopFusionLanguage(Xpragma base,
String group,
int collapse)
{
ClawLanguage l = new ClawLanguage();
l.setDirective(ClawDirective.LOOP_FUSION);
l.setGroupClause(group);
l.setCollapseClause(collapse);
l.attachPragma(base);
return l;
}
/**
* Create an instance of ClawLanguage that correspond to a loop-interchange
* directive. Used for dynamically created transformation.
* @param master Base object which initiate the creation of this instance.
* @param pragma Pragma statement located just before the first do stmt.
* @return An instance of ClawLanguage describing a loop-interchange with the
* indexes from the master object.
*/
public static ClawLanguage createLoopInterchangeLanguage(ClawLanguage master,
Xpragma pragma)
{
ClawLanguage l = new ClawLanguage();
l.setDirective(ClawDirective.LOOP_INTERCHANGE);
l.setIndexes(master.getIndexes());
l.attachPragma(pragma);
return l;
}
}
|
package guitests.guihandles;
import guitests.GuiRobot;
import javafx.scene.Node;
import javafx.stage.Stage;
import seedu.task.model.task.ReadOnlyTask;
/**
* Provides a handle to a task card in the task list panel.
*/
public class TaskCardHandle extends GuiHandle {
private static final String NAME_FIELD_ID = "#name";
private static final String OPEN_TIME_FIELD_ID = "#openTime";
private static final String CLOSE_TIME_FIELD_ID = "#closeTime";
private Node node;
public TaskCardHandle(GuiRobot guiRobot, Stage primaryStage, Node node){
super(guiRobot, primaryStage, null);
this.node = node;
}
protected String getTextFromLabel(String fieldId) {
return getTextFromLabel(fieldId, node);
}
protected String getTextFromText(String fieldId) {
return getTextFromText(fieldId, node);
}
public String getTaskName() {
return getTextFromText(NAME_FIELD_ID);
}
public String getOpenTime() {
return getTextFromLabel(OPEN_TIME_FIELD_ID);
}
public String getCloseTime() {
return getTextFromLabel(CLOSE_TIME_FIELD_ID);
}
public boolean isDetailsShown() {
Node openTimeNode = getNode(OPEN_TIME_FIELD_ID, node);
Node closeTimeNode = getNode(CLOSE_TIME_FIELD_ID, node);
return openTimeNode.isVisible() && openTimeNode.isManaged() && closeTimeNode.isVisible() && closeTimeNode.isManaged();
}
public boolean isSameTask(ReadOnlyTask task){
return getTaskName().equals(task.getName().taskName)
&& getOpenTime().equals(task.getOpenTime())
&& getCloseTime().equals(task.getCloseTime());
}
@Override
public boolean equals(Object obj) {
if(obj instanceof TaskCardHandle) {
TaskCardHandle handle = (TaskCardHandle) obj;
return getTaskName().equals(handle.getTaskName())
&& getOpenTime().equals(handle.getOpenTime())
&& getCloseTime().equals(handle.getCloseTime());
}
return super.equals(obj);
}
@Override
public String toString() {
return getTaskName() + " " + getOpenTime() + " " + getCloseTime();
}
}
|
package com.contentful.java.cma.gson;
import com.contentful.java.cma.model.CMAAsset;
import com.contentful.java.cma.model.CMAEntry;
import com.contentful.java.cma.model.CMAResource;
import com.contentful.java.cma.model.CMASystem;
import com.contentful.java.cma.model.CMAType;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import java.lang.reflect.Type;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static com.contentful.java.cma.model.CMAType.Link;
/**
* Serialize an entry from Contentful
*/
public class EntrySerializer implements JsonSerializer<CMAEntry> {
/**
* Make sure all fields are mapped in the locale - value way.
*
* @param src the source to be edited.
* @param type the type to be used.
* @param context the json context to be changed.
* @return a created json element.
*/
@Override
public JsonElement serialize(CMAEntry src, Type type, JsonSerializationContext context) {
JsonObject fields = new JsonObject();
for (Map.Entry<String, LinkedHashMap<String, Object>> field : src.getFields().entrySet()) {
LinkedHashMap<String, Object> value = field.getValue();
if (value == null) {
continue;
}
String fieldId = field.getKey();
JsonObject jsonField = serializeField(context, field.getValue());
if (jsonField != null) {
fields.add(fieldId, jsonField);
}
}
JsonObject result = new JsonObject();
result.add("fields", fields);
final CMASystem sys = src.getSystem();
if (sys != null) {
result.add("sys", context.serialize(sys));
}
return result;
}
private JsonObject serializeField(JsonSerializationContext context,
LinkedHashMap<String, Object> values) {
JsonObject field = new JsonObject();
for (String locale : values.keySet()) {
Object localized = values.get(locale);
if (localized instanceof CMAResource) {
field.add(locale, toLink(context, (CMAResource) localized));
} else if (localized instanceof List) {
field.add(locale, serializeList(context, (List) localized));
} else if (localized != null) {
field.add(locale, context.serialize(localized));
}
}
if (field.entrySet().size() > 0) {
return field;
}
return null;
}
private JsonArray serializeList(JsonSerializationContext context, List list) {
JsonArray array = new JsonArray();
for (Object item : list) {
if (item instanceof CMAResource) {
array.add(toLink(context, (CMAResource) item));
} else {
array.add(context.serialize(item));
}
}
return array;
}
private JsonObject toLink(JsonSerializationContext context, CMAResource resource) {
final String id = resource.getId();
if (id == null || id.isEmpty()) {
throw new IllegalArgumentException("Entry contains link to draft resource (has no ID).");
}
CMAType type = resource.getSystem().getType();
if (type == null) {
if (resource instanceof CMAAsset) {
type = CMAType.Asset;
} else if (resource instanceof CMAEntry) {
type = CMAType.Entry;
}
}
JsonObject sys = new JsonObject();
sys.addProperty("type", Link.toString());
sys.addProperty("linkType", type.toString());
sys.addProperty("id", id);
JsonObject result = new JsonObject();
result.add("sys", context.serialize(sys));
return result;
}
}
|
package com.exedio.cope.pattern;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import com.exedio.cope.Attribute;
import com.exedio.cope.FunctionAttribute;
import com.exedio.cope.Item;
import com.exedio.cope.ItemAttribute;
import com.exedio.cope.Pattern;
import com.exedio.cope.SetValue;
import com.exedio.cope.Type;
import com.exedio.cope.UniqueConstraint;
public final class Qualifier extends Pattern
{
private final ItemAttribute<Item> parent;
private final FunctionAttribute[] keys;
private final List<FunctionAttribute> keyList;
private final UniqueConstraint uniqueConstraint;
public Qualifier(final UniqueConstraint uniqueConstraint)
{
if(uniqueConstraint==null)
throw new RuntimeException(
"argument of qualifier constructor is null, " +
"may happen due to bad class initialization order.");
final List<FunctionAttribute<?>> uniqueAttributes = uniqueConstraint.getUniqueAttributes();
if(uniqueAttributes.size()<2)
throw new RuntimeException(uniqueAttributes.toString());
this.parent = castItemAttribute(uniqueAttributes.get(0));
this.keys = new FunctionAttribute[uniqueAttributes.size()-1];
for(int i = 0; i<this.keys.length; i++)
this.keys[i] = uniqueAttributes.get(i+1);
this.keyList = Collections.unmodifiableList(Arrays.asList(this.keys));
this.uniqueConstraint = uniqueConstraint;
for(final FunctionAttribute uniqueAttribute : uniqueAttributes)
registerSource(uniqueAttribute);
}
@SuppressWarnings("unchecked") // OK: UniqueConstraint looses type information
private static final ItemAttribute<Item> castItemAttribute(final Attribute a)
{
return (ItemAttribute<Item>)a;
}
// TODO SOON implicit external source: new Qualifier(QualifiedStringQualifier.key))
// TODO SOON internal source: new Qualifier(stringAttribute(OPTIONAL))
// TODO SOON use registerPattern on sources
public ItemAttribute<Item> getParent()
{
return parent;
}
public List<FunctionAttribute> getKeys()
{
return keyList;
}
public UniqueConstraint getUniqueConstraint()
{
return uniqueConstraint;
}
private List<Attribute> attributes;
public List<Attribute> getAttributes()
{
if(this.attributes==null)
{
final List<Attribute> typeAttributes = getType().getAttributes();
final ArrayList<Attribute> attributesModifiyable = new ArrayList<Attribute>(typeAttributes.size());
for(final Attribute attribute : typeAttributes)
{
if(attribute!=parent && !keyList.contains(attribute))
attributesModifiyable.add(attribute);
}
this.attributes = Collections.unmodifiableList(attributesModifiyable);
}
return attributes;
}
public Item getQualifier(final Object[] values)
{
return uniqueConstraint.searchUnique(values);
}
public Object get(final Object[] values, final FunctionAttribute attribute)
{
final Item item = uniqueConstraint.searchUnique(values);
if(item!=null)
return attribute.get(item);
else
return null;
}
public Item getForSet(final Object[] keys)
{
Item item = uniqueConstraint.searchUnique(keys);
if(item==null)
{
final SetValue[] keySetValues = new SetValue[keys.length];
int j = 0;
for(final FunctionAttribute uniqueAttribute : uniqueConstraint.getUniqueAttributes())
keySetValues[j] = new SetValue(uniqueAttribute, keys[j++]);
item = uniqueConstraint.getType().newItem(keySetValues);
}
return item;
}
public Item set(final Object[] keys, final SetValue[] values)
{
Item item = uniqueConstraint.searchUnique(keys);
if(item==null)
{
final SetValue[] keyValues = new SetValue[values.length + keys.length];
System.arraycopy(values, 0, keyValues, 0, values.length);
int j = 0;
for(final FunctionAttribute uniqueAttribute : uniqueConstraint.getUniqueAttributes())
keyValues[j + values.length] = new SetValue(uniqueAttribute, keys[j++]);
item = uniqueConstraint.getType().newItem(keyValues);
}
else
{
item.set(values);
}
return item;
}
private static final HashMap<Type<?>, List<Qualifier>> qualifiers = new HashMap<Type<?>, List<Qualifier>>();
/**
* Returns all qualifiers where <tt>type</tt> is
* the parent type {@link #getParent()()}.{@link ItemAttribute#getValueType() getValueType()}.
*
* @see Relation#getRelations(Type)
*/
public static final List<Qualifier> getQualifiers(final Type<?> type)
{
synchronized(qualifiers)
{
{
final List<Qualifier> cachedResult = qualifiers.get(type);
if(cachedResult!=null)
return cachedResult;
}
final ArrayList<Qualifier> resultModifiable = new ArrayList<Qualifier>();
for(final ItemAttribute<?> ia : type.getReferences())
for(final Pattern pattern : ia.getPatterns())
{
if(pattern instanceof Qualifier)
{
final Qualifier qualifier = (Qualifier)pattern;
if(ia==qualifier.getParent())
resultModifiable.add(qualifier);
}
}
resultModifiable.trimToSize();
final List<Qualifier> result =
!resultModifiable.isEmpty()
? Collections.unmodifiableList(resultModifiable)
: Collections.<Qualifier>emptyList();
qualifiers.put(type, result);
return result;
}
}
}
|
package i5.las2peer.p2p;
import i5.las2peer.security.UserAgent;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
import org.junit.Test;
public class PastryNodeImplTest {
public final int NODE_COUNT = 5;
public final int AGENTS_PER_NODE_COUNT = 5;
public final int PORT = 30200;
PastryNodeImpl[] node = new PastryNodeImpl[NODE_COUNT];
UserAgent[] agents = new UserAgent[NODE_COUNT * AGENTS_PER_NODE_COUNT];
/**
* gets a non-loopback address to connect to this pc
*
* more a hack than clean code, i couldn't find another way to do this...
*
* @return
* @throws SocketException
* @throws UnknownHostException
*/
private static String getIp() throws SocketException, UnknownHostException {
Enumeration<NetworkInterface> n = NetworkInterface.getNetworkInterfaces();
for (; n.hasMoreElements();) {
NetworkInterface e = n.nextElement();
Enumeration<InetAddress> a = e.getInetAddresses();
while (a.hasMoreElements()) {
InetAddress addr = a.nextElement();
String ip = addr.getHostAddress();
if (!addr.isLoopbackAddress() && !addr.isLinkLocalAddress() && !addr.isAnyLocalAddress())
return ip;
}
}
return Inet4Address.getLocalHost().getHostAddress();
}
@Test
public void doNothing() {
}
/*
@Before
public void setUp() throws NodeException, CryptoException, L2pSecurityException, AgentException,
UnknownHostException, SocketException, InterruptedException {
int port = PORT;
String ip = getIp();
// launch first node
node[0] = new PastryNodeImpl(port, null, STORAGE_MODE.memory, false, null, null);
node[0].launch();
port++;
// launch other nodes
for (int i = 1; i < NODE_COUNT; i++) {
node[i] = new PastryNodeImpl(port, ip + ":" + PORT, STORAGE_MODE.memory, false, null, null);
node[i].launch();
port++;
}
Thread.sleep(1000);
// register agents
for (int nodeId = 0; nodeId < NODE_COUNT; nodeId++) {
for (int agentId = 0; agentId < AGENTS_PER_NODE_COUNT; agentId++) {
UserAgent a = UserAgent.createUserAgent("passphrase");
a.unlockPrivateKey("passphrase");
node[nodeId].storeAgent(a);
node[nodeId].getOrRegisterLocalMediator(a);
agents[nodeId * AGENTS_PER_NODE_COUNT + agentId] = a;
}
}
Thread.sleep(1000);
}
@After
public void shutDown() {
for (int i = 0; i < NODE_COUNT; i++) {
node[i].shutDown();
}
}
@Test
public void testTopics() throws AgentNotKnownException, AgentAlreadyRegisteredException, L2pSecurityException,
AgentException, EncodingFailedException, SerializationException, InterruptedException, NodeException {
// register
node[0].registerReceiverToTopic(node[0].getOrRegisterLocalMediator(agents[1]), 123);
node[0].registerReceiverToTopic(node[0].getOrRegisterLocalMediator(agents[2]), 123);
node[1].registerReceiverToTopic(node[1].getOrRegisterLocalMediator(agents[5]), 123);
node[1].registerReceiverToTopic(node[1].getOrRegisterLocalMediator(agents[6]), 123);
node[2].registerReceiverToTopic(node[2].getOrRegisterLocalMediator(agents[10]), 123);
node[2].registerReceiverToTopic(node[2].getOrRegisterLocalMediator(agents[11]), 123);
// send
Message msg = new Message(agents[0], 123, "topic");
node[0].sendMessage(msg, null);
Thread.sleep(5000);
assertTrue(node[0].getOrRegisterLocalMediator(agents[1]).getNextMessage().getContent().equals("topic"));
assertTrue(node[0].getOrRegisterLocalMediator(agents[2]).getNextMessage().getContent().equals("topic"));
assertTrue(node[1].getOrRegisterLocalMediator(agents[5]).getNextMessage().getContent().equals("topic"));
assertTrue(node[1].getOrRegisterLocalMediator(agents[6]).getNextMessage().getContent().equals("topic"));
assertTrue(node[2].getOrRegisterLocalMediator(agents[10]).getNextMessage().getContent().equals("topic"));
assertTrue(node[2].getOrRegisterLocalMediator(agents[11]).getNextMessage().getContent().equals("topic"));
// unregister
node[1].unregisterReceiverFromTopic(node[1].getOrRegisterLocalMediator(agents[6]), 123);
node[2].unregisterReceiverFromTopic(node[2].getOrRegisterLocalMediator(agents[10]), 123);
node[2].unregisterReceiverFromTopic(node[2].getOrRegisterLocalMediator(agents[11]), 123);
// send
Message msg2 = new Message(agents[0], 123, "topic");
node[0].sendMessage(msg2, null);
Thread.sleep(5000);
assertTrue(node[0].getOrRegisterLocalMediator(agents[1]).getNextMessage().getContent().equals("topic"));
assertTrue(node[0].getOrRegisterLocalMediator(agents[2]).getNextMessage().getContent().equals("topic"));
assertTrue(node[1].getOrRegisterLocalMediator(agents[5]).getNextMessage().getContent().equals("topic"));
assertFalse(node[1].getOrRegisterLocalMediator(agents[6]).hasMessages());
assertFalse(node[2].getOrRegisterLocalMediator(agents[10]).hasMessages());
assertFalse(node[2].getOrRegisterLocalMediator(agents[11]).hasMessages());
}*/
// TODO add more pastry node tests
}
|
package com.conveyal.gtfs.validator;
import com.conveyal.gtfs.error.NewGTFSError;
import com.conveyal.gtfs.error.NewGTFSErrorType;
import com.conveyal.gtfs.error.SQLErrorStorage;
import com.conveyal.gtfs.loader.DateField;
import com.conveyal.gtfs.loader.Feed;
import com.conveyal.gtfs.loader.JdbcGtfsLoader;
import com.conveyal.gtfs.loader.Table;
import com.conveyal.gtfs.model.Calendar;
import com.conveyal.gtfs.model.CalendarDate;
import com.conveyal.gtfs.model.Entity;
import com.conveyal.gtfs.model.Route;
import com.conveyal.gtfs.model.Stop;
import com.conveyal.gtfs.model.StopTime;
import com.conveyal.gtfs.model.Trip;
import com.conveyal.gtfs.storage.StorageException;
import gnu.trove.map.hash.TIntIntHashMap;
import org.apache.commons.dbutils.DbUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* This will validate that service date information is coherent, and attempt to deduce or validate the range of dates
* covered by a GTFS feed.
*
* It turns the GTFS system of repeating weekly calendars and exceptions (calendar dates) into a single large table
* listing which services run on which days. This in turn allows us to build a histogram of service duration on each
* day.
*
* As an intermediate result it builds a table of service duration by service ID and mode of transport.
*
* Makes one object representing each service ID.
* That object will contain a calendar (for repeating service on specific days of the week)
* and potentially multiple CalendarDates defining exceptions to the base calendar.
* TODO build histogram of stop times, check against calendar and declared feed validity dates
*/
public class ServiceValidator extends TripValidator {
private static final Logger LOG = LoggerFactory.getLogger(ServiceValidator.class);
private Map<String, ServiceInfo> serviceInfoForServiceId = new HashMap<>();
private Map<LocalDate, DateInfo> dateInfoForDate = new HashMap<>();
public ServiceValidator(Feed feed, SQLErrorStorage errorStorage) {
super(feed, errorStorage);
}
@Override
public void validateTrip(Trip trip, Route route, List<StopTime> stopTimes, List<Stop> stops) {
int firstStopDeparture = stopTimes.get(0).departure_time;
int lastStopArrival = stopTimes.get(stopTimes.size() - 1).arrival_time;
if (firstStopDeparture == Entity.INT_MISSING || lastStopArrival == Entity.INT_MISSING) {
// ERR
return;
}
int tripDurationSeconds = lastStopArrival - firstStopDeparture;
if (tripDurationSeconds <= 0) {
// ERR
return;
}
// Get the map from modes to service durations in seconds for this trip's service ID.
// Create a new empty map if it doesn't yet exist.
ServiceInfo serviceInfo = serviceInfoForServiceId.computeIfAbsent(trip.service_id, ServiceInfo::new);
if (route != null) {
// Increment the service duration for this trip's transport mode and service ID.
serviceInfo.durationByRouteType.adjustOrPutValue(route.route_type, tripDurationSeconds, tripDurationSeconds);
}
// Record which trips occur on each service_id.
serviceInfo.tripIds.add(trip.trip_id);
// TODO validate mode codes
}
/**
* You'd think we'd want to do this during the loading phase. But during the loading phase we don't have a reading
* connection to the entity tables in the database. Rather than make the Feed object read-write, we want to leave
* it completely read-only.
*
* @param validationResult can be written into
*/
@Override
public void complete(ValidationResult validationResult) {
LOG.info("Merging calendars and calendar_dates...");
// First handle the calendar entries, which define repeating weekly schedules.
for (Calendar calendar : feed.calendars) {
try {
LocalDate endDate = calendar.end_date;
// Loop over all days in this calendar entry, recording on which ones it is active.
for (LocalDate date = calendar.start_date; date.isBefore(endDate) || date.isEqual(endDate); date = date.plusDays(1)) {
DayOfWeek dayOfWeek = date.getDayOfWeek();
if ( (dayOfWeek == DayOfWeek.MONDAY && calendar.monday > 0) ||
(dayOfWeek == DayOfWeek.TUESDAY && calendar.tuesday > 0) ||
(dayOfWeek == DayOfWeek.WEDNESDAY && calendar.wednesday > 0) ||
(dayOfWeek == DayOfWeek.THURSDAY && calendar.thursday > 0) ||
(dayOfWeek == DayOfWeek.FRIDAY && calendar.friday > 0) ||
(dayOfWeek == DayOfWeek.SATURDAY && calendar.saturday > 0) ||
(dayOfWeek == DayOfWeek.SUNDAY && calendar.sunday > 0)) {
// Service is active on this date.
serviceInfoForServiceId.computeIfAbsent(calendar.service_id, ServiceInfo::new).datesActive.add(date);
}
}
} catch (Exception ex) {
LOG.error(ex.getMessage());
ex.printStackTrace();
// Continue on to next calendar entry.
}
}
// Next handle the calendar_dates, which specify exceptions to the repeating weekly schedules.
for (CalendarDate calendarDate : feed.calendarDates) {
ServiceInfo serviceInfo = serviceInfoForServiceId.computeIfAbsent(calendarDate.service_id, ServiceInfo::new);
if (calendarDate.exception_type == 1) {
// Service added, add to set for this date.
serviceInfo.datesActive.add(calendarDate.date);
} else if (calendarDate.exception_type == 2) {
// Service removed, remove from Set for this date.
serviceInfo.datesActive.remove(calendarDate.date);
}
// Otherwise exception_type is out of range. This should already have been caught during the loading phase.
}
/*
A view that is similar to ServiceInfo class, but doesn't deal well with missing IDs in either subquery:
select durations.service_id, duration_seconds, days_active from (
(select service_id, sum(duration_seconds) as duration_seconds
from elwp_qhqsgzufnpvwnxtdbwcthn.service_durations group by service_id) as durations
join
(select service_id, count(service_date) as days_active
from elwp_qhqsgzufnpvwnxtdbwcthn.service_dates group by service_id) as days
on durations.service_id = days.service_id
);
*/
// Check for incoherent or erroneous services.
for (ServiceInfo serviceInfo : serviceInfoForServiceId.values()) {
if (serviceInfo.datesActive.isEmpty()) {
// This service must have been referenced by trips but is never active on any day.
registerError(NewGTFSError.forFeed(NewGTFSErrorType.SERVICE_NEVER_ACTIVE, serviceInfo.serviceId));
for (String tripId : serviceInfo.tripIds) {
registerError(
NewGTFSError.forTable(Table.TRIPS, NewGTFSErrorType.TRIP_NEVER_ACTIVE)
.setEntityId(tripId)
.setBadValue(tripId));
}
}
if (serviceInfo.tripIds.isEmpty()) {
registerError(NewGTFSError.forFeed(NewGTFSErrorType.SERVICE_UNUSED, serviceInfo.serviceId));
}
}
// Accumulate info about services into each date that they are active.
for (ServiceInfo serviceInfo : serviceInfoForServiceId.values()) {
for (LocalDate date : serviceInfo.datesActive) {
dateInfoForDate.computeIfAbsent(date, DateInfo::new).add(serviceInfo);
}
}
// Check for dates that have no service within full range of dates with defined service.
// Sum up service duration by mode for each day within that range.
if (dateInfoForDate.isEmpty()) {
registerError(NewGTFSError.forFeed(NewGTFSErrorType.NO_SERVICE, null));
} else {
LocalDate firstDate = LocalDate.MAX;
LocalDate lastDate = LocalDate.MIN;
for (LocalDate date : dateInfoForDate.keySet()) {
if (date.isBefore(firstDate)) firstDate = date;
if (date.isAfter(lastDate)) lastDate = date;
}
// Copy some useful information into the ValidationResult object to return to the caller.
validationResult.firstCalendarDate = firstDate;
validationResult.lastCalendarDate = lastDate;
// Is this any different? firstDate.until(lastDate, ChronoUnit.DAYS);
int nDays = (int) ChronoUnit.DAYS.between(firstDate, lastDate) + 1;
validationResult.dailyBusSeconds = new int[nDays];
validationResult.dailyTramSeconds = new int[nDays];
validationResult.dailyMetroSeconds = new int[nDays];
validationResult.dailyRailSeconds = new int[nDays];
validationResult.dailyTotalSeconds = new int[nDays];
validationResult.dailyTripCounts = new int[nDays];
for (int d = 0; d < nDays; d++) {
LocalDate date = firstDate.plusDays(d); // current date being processed
// Add one value per day. Trove map returns zero for missing keys.
DateInfo dateInfo = dateInfoForDate.get(date);
if (dateInfo == null) {
dateInfo = new DateInfo(date); // new empty object to get empty durations map.
}
validationResult.dailyBusSeconds[d] = dateInfo.durationByRouteType.get(3);
validationResult.dailyTramSeconds[d] = dateInfo.durationByRouteType.get(0);
validationResult.dailyMetroSeconds[d] = dateInfo.durationByRouteType.get(1);
validationResult.dailyRailSeconds[d] = dateInfo.durationByRouteType.get(2);
validationResult.dailyTotalSeconds[d] = dateInfo.getTotalServiceDurationSeconds();
validationResult.dailyTripCounts[d] = dateInfo.tripCount;
if (dateInfo.getTotalServiceDurationSeconds() <= 0) {
// Check for low or zero service, which seems to happen even when services are defined.
// This will also catch cases where dateInfo was null and the new instance contains no service.
registerError(NewGTFSError.forFeed(NewGTFSErrorType.DATE_NO_SERVICE,
DateField.GTFS_DATE_FORMATTER.format(date)));
}
}
}
// Now write all these calendar-date relations out to the database.
Connection connection = null;
try {
connection = feed.getConnection();
Statement statement = connection.createStatement();
// Create a table summarizing all known service IDs.
// This is almost just a view joining two sub-selects:
// select * from
// (select service_id, count(service_date) from x.service_dates group by service_id) as days
// join
// (select service_id, sum(duration_seconds) from x.service_durations group by service_id) as durations
// on days.service_id = durations.service_id;
// Except that some service IDs may have no trips on them, or may not be referenced in any calendar or
// calendar exception, which would keep them from appearing in either of those tables. So we just create
// this somewhat redundant materialized view to serve as a master list of all services.
String servicesTableName = feed.tablePrefix + "services";
String sql = String.format("create table %s (service_id varchar, n_days_active integer, duration_seconds integer, n_trips integer)", servicesTableName);
statement.execute(sql);
sql = String.format("insert into %s values (?, ?, ?, ?)", servicesTableName);
PreparedStatement serviceStatement = connection.prepareStatement(sql);
final BatchTracker serviceTracker = new BatchTracker(serviceStatement);
for (ServiceInfo serviceInfo : serviceInfoForServiceId.values()) {
serviceStatement.setString(1, serviceInfo.serviceId);
serviceStatement.setInt(2, serviceInfo.datesActive.size());
serviceStatement.setInt(3, serviceInfo.getTotalServiceDurationSeconds());
serviceStatement.setInt(4, serviceInfo.tripIds.size());
serviceTracker.addBatch();
}
serviceTracker.executeRemaining();
// Create a table that shows on which dates each service is active.
String serviceDatesTableName = feed.tablePrefix + "service_dates";
sql = String.format("create table %s (service_date varchar, service_id varchar)", serviceDatesTableName);
statement.execute(sql);
sql = String.format("insert into %s values (?, ?)", serviceDatesTableName);
PreparedStatement serviceDateStatement = connection.prepareStatement(sql);
final BatchTracker serviceDateTracker = new BatchTracker(serviceDateStatement);
for (ServiceInfo serviceInfo : serviceInfoForServiceId.values()) {
for (LocalDate date : serviceInfo.datesActive) {
if (date == null) continue; // TODO ERR? Can happen with bad data (unparseable dates).
try {
serviceDateStatement.setString(1, date.format(DateField.GTFS_DATE_FORMATTER));
serviceDateStatement.setString(2, serviceInfo.serviceId);
serviceDateTracker.addBatch();
} catch (SQLException ex) {
throw new StorageException(ex);
}
}
}
serviceDateTracker.executeRemaining();
LOG.info("Indexing...");
statement.execute(String.format("create index service_dates_service_date on %s (service_date)", serviceDatesTableName));
statement.execute(String.format("create index service_dates_service_id on %s (service_id)", serviceDatesTableName));
// Create a table containing the total trip durations per service_id and per transit mode.
// Using this table you can get total service duration by mode (route_type) per day, joining tables:
// select service_date, route_type, sum(duration_seconds)
// from x.service_dates as dates, x.service_durations as durations
// where dates.service_id = durations.service_id
// group by service_date, route_type order by service_date, route_type;
String serviceDurationsTableName = feed.tablePrefix + "service_durations";
sql = String.format("create table %s (service_id varchar, route_type integer, " +
"duration_seconds integer, primary key (service_id, route_type))", serviceDurationsTableName);
statement.execute(sql);
sql = String.format("insert into %s values (?, ?, ?)", serviceDurationsTableName);
PreparedStatement serviceDurationStatement = connection.prepareStatement(sql);
final BatchTracker serviceDurationTracker = new BatchTracker(serviceDurationStatement);
for (ServiceInfo serviceInfo : serviceInfoForServiceId.values()) {
serviceInfo.durationByRouteType.forEachEntry((routeType, serviceDurationSeconds) -> {
try {
serviceDurationStatement.setString(1, serviceInfo.serviceId);
serviceDurationStatement.setInt(2, routeType);
serviceDurationStatement.setInt(3, serviceDurationSeconds);
serviceDurationTracker.addBatch();
} catch (SQLException ex) {
throw new StorageException(ex);
}
return true; // Iteration continues
});
}
serviceDurationTracker.executeRemaining();
// No need to build indexes because (service_id, route_type) is already the primary key of this table.
connection.commit();
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
DbUtils.closeQuietly(connection);
}
LOG.info("Done.");
}
private static class ServiceInfo {
final String serviceId;
TIntIntHashMap durationByRouteType = new TIntIntHashMap();
Set<LocalDate> datesActive = new HashSet<>();
Set<String> tripIds = new HashSet<>();
public ServiceInfo(String serviceId) {
this.serviceId = serviceId;
}
public int getTotalServiceDurationSeconds() {
return Arrays.stream(durationByRouteType.values()).sum();
}
}
private static class DateInfo {
final LocalDate date;
TIntIntHashMap durationByRouteType = new TIntIntHashMap();
int tripCount = 0; // Trip count could also in theory be broken down by route type.
Set<String> servicesActive = new HashSet<>();
public DateInfo(LocalDate date) {
this.date = date;
}
public int getTotalServiceDurationSeconds() {
return Arrays.stream(durationByRouteType.values()).sum();
}
public void add (ServiceInfo serviceInfo) {
servicesActive.add(serviceInfo.serviceId);
serviceInfo.durationByRouteType.forEachEntry((routeType, serviceDurationSeconds) -> {
durationByRouteType.adjustOrPutValue(routeType, serviceDurationSeconds, serviceDurationSeconds);
return true; // Continue iteration.
});
tripCount += serviceInfo.tripIds.size();
}
}
/**
* Avoid Java's "effectively final" nonsense when using prepared statements in foreach loops.
* Automatically push execute batches of prepared statements before the batch gets too big.
* TODO there's probably something like this in an Apache Commons util library
*/
public static class BatchTracker {
private PreparedStatement preparedStatement;
private int currentBatchSize = 0;
public BatchTracker(PreparedStatement preparedStatement) {
this.preparedStatement = preparedStatement;
}
public void addBatch() throws SQLException {
preparedStatement.addBatch();
currentBatchSize += 1;
if (currentBatchSize > JdbcGtfsLoader.INSERT_BATCH_SIZE) {
preparedStatement.executeBatch();
currentBatchSize = 0;
}
}
public void executeRemaining() throws SQLException {
if (currentBatchSize > 0) {
preparedStatement.executeBatch();
currentBatchSize = 0;
}
// Avoid reuse, signal that this was cleanly closed.
preparedStatement = null;
}
public void finalize () {
if (preparedStatement != null || currentBatchSize > 0) {
throw new RuntimeException("BUG: It looks like someone did not call executeRemaining on a BatchTracker.");
}
}
}
}
|
package com.echsylon.atlantis;
import android.content.Context;
import android.os.AsyncTask;
import com.echsylon.atlantis.internal.UrlUtils;
import com.echsylon.atlantis.internal.Utils;
import com.echsylon.atlantis.internal.json.JsonParser;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Locale;
import java.util.Map;
import java.util.Stack;
import java.util.concurrent.Callable;
import fi.iki.elonen.NanoHTTPD;
/**
* This is the local web server that will serve the template responses. This web server will only
* handle requests issued targeting "localhost", "192.168.0.1" or "127.0.0.1".
*/
public class Atlantis {
private static final String HOSTNAME = "localhost";
private static final int PORT = 8080;
/**
* This is a converter class, representing an HTTP status as the NanoHTTPD class knows it.
* Atlantis only works with integers and strings when it comes to HTTP status code, hence the
* need for this class.
*/
private static final class NanoStatus implements NanoHTTPD.Response.IStatus {
private final int code;
private final String name;
private NanoStatus(int code, String name) {
this.code = code;
this.name = name;
}
@Override
public String getDescription() {
return String.format(Locale.ENGLISH, "%d %s", code, name);
}
@Override
public int getRequestStatus() {
return code;
}
}
/**
* This is a callback interface through which any asynchronous success states are notified.
*/
public interface OnSuccessListener {
/**
* Delivers a success notification.
*/
void onSuccess();
}
/**
* THis is a callback interface through which any asynchronous exceptions are notified.
*/
public interface OnErrorListener {
/**
* Delivers an error result.
*
* @param cause The cause of the error.
*/
void onError(Throwable cause);
}
/**
* Starts the local Atlantis server. The caller must manually set a configuration (either by
* pointing to a JSON asset or by injecting programmatically defined requests). The success
* callback is called once the server is fully operational. Note that the configuration can be
* injected regardless of the current start-up state of the local server.
*
* @param successListener The success state callback implementation.
* @param errorListener The error callback implementation.
* @return An Atlantis object instance.
*/
public static Atlantis start(OnSuccessListener successListener, OnErrorListener errorListener) {
Atlantis atlantis = new Atlantis();
atlantis.enqueueTask(() -> {
atlantis.nanoHTTPD.start();
return null;
}, successListener, errorListener);
return atlantis;
}
/**
* Starts the local Atlantis server and automatically loads a configuration from a JSON asset.
*
* @param context The context to use while loading assets.
* @param configAssetName The name of the configuration asset to load.
* @param successListener The success state callback implementation.
* @param errorListener The error callback implementation.
* @return An Atlantis object instance.
*/
public static Atlantis start(Context context, String configAssetName, OnSuccessListener successListener, OnErrorListener errorListener) {
Atlantis atlantis = new Atlantis();
atlantis.enqueueTask(() -> {
atlantis.nanoHTTPD.start();
return null;
},
() -> atlantis.setConfiguration(context, configAssetName, successListener, errorListener),
errorListener);
return atlantis;
}
/**
* Starts the local Atlantis server and automatically sets a built configuration.
*
* @param context The context to use while loading any response assets.
* @param configuration The built configuration object.
* @param successListener The success state callback implementation.
* @param errorListener The error callback implementation.
* @return An Atlantis object instance.
*/
public static Atlantis start(Context context, Configuration configuration, OnSuccessListener successListener, OnErrorListener errorListener) {
Atlantis atlantis = new Atlantis();
atlantis.enqueueTask(() -> {
atlantis.nanoHTTPD.start();
return null;
},
() -> {
atlantis.setConfiguration(context, configuration);
successListener.onSuccess();
},
errorListener);
return atlantis;
}
private Context context;
private Configuration configuration;
private NanoHTTPD nanoHTTPD;
private boolean isCapturing;
private final Object captureLock;
private volatile Stack<Request> captured;
// Intentionally hidden constructor.
private Atlantis() {
this.isCapturing = false;
this.captureLock = new Object();
this.captured = new Stack<>();
this.nanoHTTPD = new NanoHTTPD(HOSTNAME, PORT) {
@Override
public Response serve(IHTTPSession session) {
// Early bail-out.
if (configuration == null)
return super.serve(session);
// Get a response to deliver.
com.echsylon.atlantis.Response response = getMockedResponse(
session.getUri(),
session.getMethod().name(),
session.getHeaders());
// No response found, try to fall back to the real world.
if (response == null)
if (configuration.hasAlternativeRoute())
response = getRealResponse(configuration.fallbackBaseUrl(),
session.getUri(),
session.getMethod().name(),
session.getHeaders());
// Nope, the real world isn't any better. Bail out and serve default response.
if (response == null)
return super.serve(session);
// We have a response. Maybe delay before actually delivering it.
long delay = response.delay();
if (delay > 0L)
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
// For some reason we weren't allowed to sleep as long as we wanted.
}
// Now, finally, deliver.
try {
NanoStatus status = new NanoStatus(response.statusCode(), response.statusName());
String mime = response.mimeType();
byte[] bytes = response.hasAsset() ?
response.asset(Atlantis.this.context) :
response.content().getBytes();
return newFixedLengthResponse(status, mime, new ByteArrayInputStream(bytes), bytes.length);
} catch (Exception e) {
return newFixedLengthResponse(
Response.Status.INTERNAL_ERROR,
NanoHTTPD.MIME_PLAINTEXT,
"SERVER INTERNAL ERROR: Exception: " + e.getMessage());
}
}
};
}
/**
* Stops the local web server.
*/
public void stop() {
configuration = null;
nanoHTTPD.closeAllConnections();
nanoHTTPD.stop();
nanoHTTPD = null;
isCapturing = false;
}
/**
* Reconfigures Atlantis by setting the new set of requests to respond to.
*
* @param context The context to use when reading assets.
* @param configuration The new configuration.
*/
public void setConfiguration(Context context, Configuration configuration) {
this.context = context;
this.configuration = configuration;
}
/**
* Reconfigures Atlantis from a configuration JSON asset. The asset is read read from disk on a
* worker thread. Any results are notified through the given callbacks, if given.
*
* @param context The context to use when reading assets.
* @param configAssetName The name of the configuration asset (relative to the apps 'assets'
* folder).
* @param successListener The success callback.
* @param errorListener The error callback.
*/
public void setConfiguration(final Context context, final String configAssetName, OnSuccessListener successListener, OnErrorListener errorListener) {
enqueueTask(() -> {
byte[] bytes = Utils.readAsset(context, configAssetName);
String json = new String(bytes);
this.configuration = new JsonParser().fromJson(json, Configuration.class);
this.context = context;
return null;
}, successListener, errorListener);
}
/**
* Tells the local web server to start capturing a copy of any served requests. This method will
* start a new capture session by clearing the capture history stack.
*/
public void startCapturing() {
clearCapturedRequests();
isCapturing = true;
}
/**
* Tells the local web server to stop capturing any served requests. This method leaves the
* capture history stack intact.
*/
public void stopCapturing() {
isCapturing = false;
}
/**
* Returns a snapshot of the capture history stack as it looks right this moment. This method
* leaves the actual stack intact, but new requests may be added to it at any time. These new
* additions won't be reflected in the output of this method though.
*
* @return A snapshot of the captured history stack.
*/
public Stack<Request> getCapturedRequests() {
Stack<Request> result = new Stack<>();
synchronized (captureLock) {
result.addAll(captured);
}
return result;
}
/**
* Clears any captured requests in the history stack. This method will not affect the capturing
* state.
*/
public void clearCapturedRequests() {
synchronized (captureLock) {
captured.clear();
}
}
// Creates a new AsyncTask instance and executes a callable from it. AsyncTasks will by default
// be queued up in a serial executor, which ensures they are operated on in the very same order
// they were once enqueued.
private void enqueueTask(final Callable<Void> callable, final OnSuccessListener successListener, final OnErrorListener errorListener) {
new AsyncTask<Void, Void, Throwable>() {
@Override
protected Throwable doInBackground(Void... params) {
try {
callable.call();
return null;
} catch (Exception e) {
return e;
}
}
@Override
protected void onPostExecute(Throwable throwable) {
if (throwable == null) {
if (successListener != null)
successListener.onSuccess();
} else {
if (errorListener != null)
errorListener.onError(throwable);
}
}
}.execute();
}
// Tries to find a response configuration that matches the given request parameters. Also
// captures the request if in such a mode.
private Response getMockedResponse(String url, String method, Map<String, String> headers) {
Request request = configuration.findRequest(url, method, headers);
if (isCapturing)
synchronized (captureLock) {
captured.push(request != null ?
request :
new Request.Builder()
.withUrl(url)
.withMethod(method)
.withHeaders(headers));
}
return request != null ?
request.response() :
null;
}
// Synchronously makes a real network request and returns the response as an Atlantis response
// or null, would anything go wrong. This request is completely anonymous from the local web
// servers (currently NanoHTTPD) point of view, as in the internal state won't be updated with
// these real world parameters. Would the real world request fail, then the local web server
private Response getRealResponse(String realBaseUrl, String requestUrl, String method, Map<String, String> headers) {
HttpURLConnection connection = null;
String realUrl = String.format("%s%s%s%s", realBaseUrl,
UrlUtils.getPath(requestUrl),
UrlUtils.getQuery(requestUrl),
UrlUtils.getFragment(requestUrl));
try {
// Initiate the real world request.
URL url = new URL(realUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(method);
connection.getRequestProperties();
// Some headers we don't want to leak to the real world at all.
headers.remove("host");
headers.remove("remote-addr");
headers.remove("http-client-ip");
// But the rest we might want to expose, still making sure we don't overwrite stuff.
if (!headers.isEmpty())
for (Map.Entry<String, String> entry : headers.entrySet())
if (connection.getRequestProperty(entry.getKey()) == null)
connection.setRequestProperty(entry.getKey(), entry.getValue());
// And so build an Atlantis response from the real world response.
return new com.echsylon.atlantis.Response.Builder()
.withStatus(UrlUtils.getResponseCode(connection), UrlUtils.getResponseMessage(connection))
.withMimeType(UrlUtils.getResponseMimeType(connection))
.withHeaders(UrlUtils.getResponseHeaders(connection))
.withAsset(UrlUtils.getResponseBody(connection));
} catch (IOException e) {
return null;
} finally {
UrlUtils.closeSilently(connection);
}
}
}
|
import in.zapr.druid.druidry.Interval;
import org.joda.time.DateTime;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.HashSet;
import java.util.Set;
public class IntervalTest {
@Test(expectedExceptions = NullPointerException.class)
public void testMissingStartField() {
DateTime startTime = new DateTime();
Interval interval = new Interval(startTime, null);
}
@Test(expectedExceptions = NullPointerException.class)
public void testMissingEndField() {
DateTime endTime = new DateTime();
Interval interval = new Interval(null, endTime);
}
@Test
public void intervalEqualityTest() {
DateTime startTime = new DateTime();
DateTime endTime = startTime.plusDays(1);
Interval interval1 = new Interval(startTime, endTime);
Interval interval2 = new Interval(startTime, endTime);
Assert.assertEquals(interval1, interval2);
Interval interval3 = new Interval(startTime, endTime.plusDays(1));
Assert.assertNotEquals(interval1, interval3);
DateTime otherStartTime = new DateTime(startTime);
DateTime otherEndTime = new DateTime(endTime);
Interval interval4 = new Interval(otherStartTime, otherEndTime);
Assert.assertEquals(interval1, interval4);
}
}
|
package com.creatubbles.ctbmod.client.gui;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;
import lombok.SneakyThrows;
import lombok.Synchronized;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.ResourceLocation;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import com.creatubbles.api.core.Creation;
import com.creatubbles.api.core.Creator;
import com.creatubbles.api.core.User;
import com.creatubbles.api.request.auth.SignInRequest;
import com.creatubbles.api.request.creation.GetCreationsRequest;
import com.creatubbles.api.request.creator.UsersCreatorsRequest;
import com.creatubbles.api.request.user.UserProfileRequest;
import com.creatubbles.api.response.creation.GetCreationsResponse;
import com.creatubbles.ctbmod.CTBMod;
import com.creatubbles.ctbmod.common.creator.ContainerCreator;
import com.creatubbles.ctbmod.common.creator.TileCreator;
import com.creatubbles.ctbmod.common.http.DownloadableImage;
import com.creatubbles.ctbmod.common.http.DownloadableImage.ImageType;
import com.creatubbles.ctbmod.common.network.MessageCreate;
import com.creatubbles.ctbmod.common.network.PacketHandler;
import com.creatubbles.repack.endercore.client.gui.GuiContainerBase;
import com.creatubbles.repack.endercore.client.gui.button.IconButton;
import com.creatubbles.repack.endercore.client.gui.button.MultiIconButton;
import com.creatubbles.repack.endercore.client.gui.widget.GuiToolTip;
import com.creatubbles.repack.endercore.client.gui.widget.TextFieldEnder;
import com.creatubbles.repack.endercore.client.gui.widget.VScrollbar;
import com.creatubbles.repack.endercore.client.render.EnderWidget;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.MultimapBuilder;
public class GuiCreator extends GuiContainerBase implements ISelectionCallback {
private class PasswordTextField extends TextFieldEnder {
public PasswordTextField(FontRenderer fnt, int x, int y, int width, int height) {
super(fnt, x, y, width, height);
}
@Override
public void setFocused(boolean state) {
super.setFocused(state);
GuiCreator.this.tfActualPassword.setFocused(state);
}
private String transformText(String text) {
if (!"_".equals(text)) {
text = text.replaceAll(".", "\u2022");
}
return text;
}
@Override
public void setText(String text) {
GuiCreator.this.tfActualPassword.setText(text);
super.setText(transformText(text));
}
@Override
public void writeText(String text) {
GuiCreator.this.tfActualPassword.writeText(text);
super.writeText(transformText(text));
}
@Override
public void deleteWords(int cursor) {
GuiCreator.this.tfActualPassword.deleteWords(cursor);
super.deleteWords(cursor);
}
@Override
public void deleteFromCursor(int cursor) {
GuiCreator.this.tfActualPassword.deleteFromCursor(cursor);
super.deleteFromCursor(cursor);
}
}
private class LoginRunnable implements Runnable {
@Override
public void run() {
try {
checkCancel();
if (getUser() == null) {
setState(State.LOGGING_IN, true);
loginReq = new SignInRequest(tfEmail.getText(), tfActualPassword.getText());
loginReq.execute();
}
checkCancel();
if (loginReq != null && !loginReq.wasSuccessful()) {
header = EnumChatFormatting.YELLOW.toString().concat(loginReq.getResponse().message);
loginReq = null;
logout();
} else {
if (getUser() == null) {
userReq = new UserProfileRequest("me", loginReq.getResponse().access_token);
userReq.execute();
CTBMod.cache.activateUser(userReq.getResponse().user);
CTBMod.cache.getActiveUser().access_token = loginReq.getResponse().access_token;
CTBMod.cache.save();
}
checkCancel();
if (getCreator() == null) {
setState(State.LOGGING_IN, true);
UsersCreatorsRequest creatorsReq = new UsersCreatorsRequest(Integer.toString(getUser().id));
creatorsReq.execute();
CTBMod.cache.setCreators(creatorsReq.getResponse().creators.toArray(new Creator[0]));
}
checkCancel();
Creation[] creations = creationList.getCreations();
if (creations == null) {
setState(State.LOGGING_IN, true);
for (Creator c : CTBMod.cache.getCreators()) {
int page = 1;
GetCreationsRequest creationsReq = new GetCreationsRequest(c.id);
creationsReq.execute();
GetCreationsResponse resp = creationsReq.getResponse();
creations = ArrayUtils.addAll(creations, resp.creations);
while (resp.page < resp.total_pages) {
creationsReq = new GetCreationsRequest(c.id, ++page);
creationsReq.execute();
resp = creationsReq.getResponse();
creations = ArrayUtils.addAll(creations, resp.creations);
}
}
creationList.setCreations(creations);
CTBMod.cache.setCreationCache(creations);
}
checkCancel();
// Once we have all creation data, we can say we are "logged in" while the images download
setState(State.LOGGED_IN, true);
for (Creation c : creations) {
DownloadableImage img = new DownloadableImage(c.image, c);
images.put(c, img);
img.download(ImageType.LIST_VIEW);
checkCancel();
}
}
} catch (InterruptedException e) {
CTBMod.logger.info("Logging in canceled!");
// Clear the cache
logout();
} catch (Exception e) {
CTBMod.logger.error("Logging in uncountered an unknown error.", e);
logout();
} finally {
// Thread cleanup, erase all evidence we were here
// This assures a fresh start if a new login is attempted
loginReq = null;
userReq = null;
thread = null;
cancelButton.enabled = true;
}
}
private void checkCancel() throws InterruptedException {
if (thread.isInterrupted()) {
throw new InterruptedException();
}
}
}
public enum State {
LOGGED_OUT,
USER_SELECT,
LOGGING_IN,
LOGGED_IN;
}
private static final int XSIZE_DEFAULT = 176, XSIZE_SIDEBAR = 270;
private static final int ID_LOGIN = 0, ID_USER = 1, ID_CANCEL = 2, ID_LOGOUT = 3, ID_CREATE = 4;
private static final int ID_H_PLUS = 5, ID_H_MINUS = 6, ID_W_PLUS = 7, ID_W_MINUS = 8;
private static final ResourceLocation BG_TEX = new ResourceLocation(CTBMod.DOMAIN, "textures/gui/creator.png");
private static final String DEFAULT_HEADER = "Please log in to Creatubbles:";
static final ResourceLocation OVERLAY_TEX = new ResourceLocation(CTBMod.DOMAIN, "textures/gui/creator_overlays.png");
static final User DUMMY_USER = new User();
static {
DUMMY_USER.username = "No Users";
}
private Multimap<IHideable, State> visibleMap = MultimapBuilder.hashKeys().enumSetValues(State.class).build();
Map<Creation, DownloadableImage> images = Maps.newHashMap();
private TextFieldEnder tfEmail, tfActualPassword;
private VScrollbar scrollbar;
private PasswordTextField tfVisualPassword;
private GuiButtonHideable loginButton, userButton, cancelButton;
private IconButton logoutButton, createButton;
private MultiIconButton heightUpButton, heightDownButton, widthUpButton, widthDownButton;
private GuiToolTip userInfo;
private OverlayCreationList creationList;
private OverlayUserSelection userSelection;
private OverlaySelectedCreation selectedCreation;
private Creation selected;
private State state;
private Thread thread;
private SignInRequest loginReq;
private UserProfileRequest userReq;
private String header = DEFAULT_HEADER;
private TileCreator te;
public GuiCreator(InventoryPlayer inv, TileCreator creator) {
super(new ContainerCreator(inv, creator));
this.te = creator;
this.mc = Minecraft.getMinecraft();
setState(getUser() == null ? State.LOGGED_OUT : State.LOGGED_IN, false);
// Must be done before getState() is called
userSelection = new OverlayUserSelection(10, 10);
addOverlay(userSelection);
ySize += 44;
xSize = getState() == State.LOGGED_IN ? XSIZE_SIDEBAR : XSIZE_DEFAULT;
tfEmail = new TextFieldEnder(getFontRenderer(), (XSIZE_DEFAULT / 2) - 75, 35, 150, 12);
tfEmail.setFocused(true);
textFields.add(tfEmail);
// This is a dummy to store the uncensored PW
tfActualPassword = new TextFieldEnder(getFontRenderer(), 0, 0, 0, 0);
tfVisualPassword = new PasswordTextField(getFontRenderer(), (XSIZE_DEFAULT / 2) - 75, 65, 150, 12);
textFields.add(tfVisualPassword);
scrollbar = new VScrollbar(this, XSIZE_SIDEBAR - 11, 0, ySize + 1) {
@Override
public int getScrollMax() {
return creationList.getMaxScroll();
}
@Override
public void mouseWheel(int x, int y, int delta) {
if (!isDragActive()) {
scrollBy(-Integer.signum(delta) * 4);
}
}
};
creationList = new OverlayCreationList(XSIZE_DEFAULT, 0);
addOverlay(creationList);
logoutButton = new IconButton(this, ID_LOGOUT, 7, 106, EnderWidget.CROSS);
logoutButton.setToolTip("Log Out");
createButton = new IconButton(this, ID_CREATE, 110, 29, EnderWidget.TICK) {
@Override
public boolean isEnabled() {
return super.isEnabled() && te.getOutput() == null;
}
};
createButton.setToolTip("Create!");
selectedCreation = new OverlaySelectedCreation(10, 10, creationList, createButton);
creationList.addCallback(selectedCreation);
creationList.addCallback(this);
addOverlay(selectedCreation);
userInfo = new GuiToolTip(new java.awt.Rectangle(), Lists.<String> newArrayList()) {
@Override
public java.awt.Rectangle getBounds() {
if (getUser() == null) {
System.out.println("!");
}
FontRenderer fr = getFontRenderer();
return new java.awt.Rectangle(25, 110, fr.getStringWidth(getUser().username), 8);
}
@Override
protected void updateText() {
User u = getUser();
setToolTipText(StringUtils.capitalize(u.role), getCreator().age, u.country);
}
};
addToolTip(userInfo);
int y = 61;
int x = 97;
widthUpButton = MultiIconButton.createAddButton(this, ID_W_PLUS, x, y);
widthDownButton = MultiIconButton.createMinusButton(this, ID_W_MINUS, x, y + 8);
x += 50;
heightUpButton = MultiIconButton.createAddButton(this, ID_H_PLUS, x, y);
heightDownButton = MultiIconButton.createMinusButton(this, ID_H_MINUS, x, y + 8);
}
@Override
@SneakyThrows
public void initGui() {
// logout();
super.initGui();
buttonList.clear();
addButton(loginButton = new GuiButtonHideable(ID_LOGIN, guiLeft + xSize / 2 - 75, guiTop + 90, 75, 20, "Log in"));
addButton(userButton = new GuiButtonHideable(ID_USER, guiLeft + xSize / 2, guiTop + 90, 75, 20, "Saved Users"));
addButton(cancelButton = new GuiButtonHideable(ID_CANCEL, guiLeft + xSize / 2 - 50, guiTop + 90, 100, 20, "Cancel"));
logoutButton.onGuiInit();
createButton.onGuiInit();
heightUpButton.onGuiInit();
heightDownButton.onGuiInit();
widthUpButton.onGuiInit();
widthDownButton.onGuiInit();
addScrollbar(scrollbar);
// Avoids CME when state is set during this method
synchronized (visibleMap) {
visibleMap.put(tfEmail, State.LOGGED_OUT);
visibleMap.put(tfVisualPassword, State.LOGGED_OUT);
visibleMap.put(userSelection, State.USER_SELECT);
visibleMap.put(creationList, State.LOGGED_IN);
visibleMap.put(selectedCreation, State.LOGGED_IN);
visibleMap.put(userInfo, State.LOGGED_IN);
visibleMap.put(loginButton, State.LOGGED_OUT);
visibleMap.put(userButton, State.LOGGED_OUT);
visibleMap.putAll(cancelButton, Lists.newArrayList(State.USER_SELECT, State.LOGGING_IN));
visibleMap.put(logoutButton, State.LOGGED_IN);
visibleMap.put(createButton, State.LOGGED_IN);
visibleMap.put(heightUpButton, State.LOGGED_IN);
visibleMap.put(heightDownButton, State.LOGGED_IN);
visibleMap.put(widthUpButton, State.LOGGED_IN);
visibleMap.put(widthDownButton, State.LOGGED_IN);
visibleMap.put(scrollbar, State.LOGGED_IN);
}
creationList.setCreations(CTBMod.cache.getCreationCache());
// TODO this needs to go
if (thread == null && getUser() != null) {
actionPerformed(loginButton);
}
updateVisibility();
}
@Override
public void callback(Creation selected) {
this.selected = selected;
}
@Override
protected void keyTyped(char c, int key) throws IOException {
if ((c == '\r' || c == '\n') && (tfEmail.isFocused() || tfVisualPassword.isFocused())) {
actionPerformed(loginButton);
}
super.keyTyped(c, key);
}
@Override
@SneakyThrows
public void updateScreen() {
if (CTBMod.cache.isDirty()) {
if (thread != null) {
System.out.println("!");
}
}
if (CTBMod.cache.isDirty() && thread == null) {
actionPerformed(loginButton);
CTBMod.cache.dirty(false);
}
}
@Override
public void onGuiClosed() {
super.onGuiClosed();
if (thread != null) {
thread.interrupt();
}
}
@Override
protected void drawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY) {
GlStateManager.color(1, 1, 1, 1);
GlStateManager.disableLighting();
State state = getState();
mc.getTextureManager().bindTexture(BG_TEX);
int x = guiLeft;
int y = guiTop;
drawTexturedModalRect(x, y, 0, 0, XSIZE_DEFAULT, ySize);
// TODO localize all the things
switch(state) {
case LOGGED_IN:
if (getUser() == null) {
System.out.println("!");
}
creationList.setScroll(scrollbar.getScrollPos());
x += 25;
y += 110;
drawString(getFontRenderer(), getUser().username, x, y, 0xFFFFFF);
x = guiLeft + 90;
y = guiTop + 12;
mc.getTextureManager().bindTexture(OVERLAY_TEX);
drawTexturedModalRect(scrollbar.getX(), scrollbar.getY() + 8, creationList.getWidth() * 2, 8, 11, scrollbar.getWholeArea().height - 16);
x = guiLeft + 70;
y = guiTop + 19;
drawTexturedModalRect(x, y, 94, 54, 36, 36);
x += 74;
y += 9;
drawTexturedModalRect(x, y, 94, 90, 18, 18);
x -= 28;
y -= 6;
if (createButton.enabled) {
// Mojang didn't add an integer color method...
GlStateManager.color(88f / 255f, 196f / 255f, 61f / 255f);
} else {
GlStateManager.color(0.5f, 0.5f, 0.5f);
}
EnderWidget.map.render(EnderWidget.ARROW_RIGHT, x, y, 32, 32, 1, true);
x = guiLeft + 70;
y = guiTop + 65;
drawString(getFontRenderer(), "W: " + te.getWidth(), x, y, 0xFFFFFF);
drawString(getFontRenderer(), "H: " + te.getHeight(), x + 50, y, 0xFFFFFF);
y += 15;
drawString(getFontRenderer(), "Paper: 100", x, y, 0xFFFFFF);
y += 10;
drawString(getFontRenderer(), "Dye: 100", x, y, 0xFFFFFF);
break;
case LOGGED_OUT:
x += xSize / 2;
y += 5;
drawCenteredString(getFontRenderer(), header, x, y, 0xFFFFFF);
x = guiLeft + 13;
y = guiTop + 20;
drawString(getFontRenderer(), "Email/Username:", tfEmail.xPosition, tfEmail.yPosition - 10, 0xFFFFFF);
y += 25;
drawString(getFontRenderer(), "Password:", tfVisualPassword.xPosition, tfVisualPassword.yPosition - 10, 0xFFFFFF);
break;
case USER_SELECT:
break;
case LOGGING_IN:
x += xSize / 2;
y += 25;
String s = thread.isInterrupted() ? "Canceling..." : "Logging in...";
drawCenteredString(getFontRenderer(), s, x, y, 0xFFFFFF);
break;
}
super.drawGuiContainerBackgroundLayer(partialTicks, mouseX, mouseY);
}
private void updateSize() {
int newSize = getState() == State.LOGGED_IN ? XSIZE_SIDEBAR : XSIZE_DEFAULT;
if (xSize != newSize) {
xSize = newSize;
initGui();
}
}
State getState() {
return state;
}
private void setState(State state, boolean update) {
this.state = state;
if (update) {
updateSize();
updateVisibility();
}
}
@Synchronized("visibleMap")
private void updateVisibility() {
for (Entry<IHideable, Collection<State>> e : visibleMap.asMap().entrySet()) {
boolean visible = e.getValue().contains(getState());
e.getKey().setIsVisible(visible);
}
}
private User getUser() {
return CTBMod.cache.getActiveUser();
}
private Creator getCreator() {
return CTBMod.cache.getActiveCreator();
}
@Override
protected void mouseClicked(int x, int y, int button) throws IOException {
super.mouseClicked(x, y, button);
// This works around the fact that changing the visibility in actionPerformed
// will cause buttons that didn't exist when the user clicked to be valid targets
updateVisibility();
}
@Override
protected void actionPerformed(GuiButton button) throws IOException {
switch (button.id) {
case ID_LOGIN:
header = DEFAULT_HEADER;
thread = new Thread(new LoginRunnable());
thread.start();
break;
case ID_USER:
userSelection.clear();
userSelection.addAll(CTBMod.cache.getSavedUsers());
if (userSelection.isEmpty()) {
userSelection.add(DUMMY_USER);
}
setState(State.USER_SELECT, false);
break;
case ID_CANCEL:
if (getState() == State.LOGGING_IN) {
thread.interrupt();
cancelButton.setEnabled(false);
} else {
logout();
}
break;
case ID_LOGOUT:
if (thread != null) {
// Creation/Image data may still be processing, this will potentially save bandwidth
thread.interrupt();
}
logout();
break;
case ID_W_MINUS:
te.setWidth(te.getWidth() - 1);
break;
case ID_W_PLUS:
te.setWidth(te.getWidth() + 1);
break;
case ID_H_MINUS:
te.setHeight(te.getHeight() - 1);
break;
case ID_H_PLUS:
te.setHeight(te.getHeight() + 1);
break;
case ID_CREATE:
PacketHandler.INSTANCE.sendToServer(new MessageCreate(selected, te));
break;
}
widthDownButton.setEnabled(te.getWidth() > te.getMinSize());
widthUpButton.setEnabled(te.getWidth() < te.getMaxSize());
heightDownButton.setEnabled(te.getHeight() > te.getMinSize());
heightUpButton.setEnabled(te.getHeight() < te.getMaxSize());
}
private void logout() {
setState(State.LOGGED_OUT, true);
CTBMod.cache.activateUser(null);
CTBMod.cache.setCreators(null);
CTBMod.cache.setCreationCache(null);
creationList.setCreations(null);
}
}
|
package net.alexanderkiel.junit;
import org.junit.Test;
import static net.alexanderkiel.junit.Assert.assertBasicEqualsAndHashCodeBehavior;
/**
* @author Alexander Kiel
* @version $Id$
*/
public class AssertTest {
@Test
public void testAssertBasicEqualsAndHashCodeBehavior() {
assertBasicEqualsAndHashCodeBehavior("foo", "foo", "bar");
}
@Test(expected = AssertionError.class)
public void testAssertBasicEqualsAndHashCodeBehaviorThrowsAssertionErrorOnEqualsNotTestingNull() {
EqualsNotTestingNull foo1 = new EqualsNotTestingNull(1);
EqualsNotTestingNull foo2 = new EqualsNotTestingNull(1);
EqualsNotTestingNull bar = new EqualsNotTestingNull(2);
assertBasicEqualsAndHashCodeBehavior(foo1, foo2, bar);
}
private static class EqualsNotTestingNull {
private final int value;
private EqualsNotTestingNull(int value) {
this.value = value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (getClass() != o.getClass()) return false;
HashCodeReturnsAlways42 that = (HashCodeReturnsAlways42) o;
return value == that.value;
}
@Override
public int hashCode() {
return value;
}
}
@Test(expected = AssertionError.class)
public void testAssertBasicEqualsAndHashCodeBehaviorThrowsAssertionErrorOnHashCodeReturnsAlways42() {
HashCodeReturnsAlways42 foo1 = new HashCodeReturnsAlways42(1);
HashCodeReturnsAlways42 foo2 = new HashCodeReturnsAlways42(1);
HashCodeReturnsAlways42 bar = new HashCodeReturnsAlways42(2);
assertBasicEqualsAndHashCodeBehavior(foo1, foo2, bar);
}
private static class HashCodeReturnsAlways42 {
private final int value;
private HashCodeReturnsAlways42(int value) {
this.value = value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof HashCodeReturnsAlways42)) return false;
HashCodeReturnsAlways42 that = (HashCodeReturnsAlways42) o;
return value == that.value;
}
@Override
public int hashCode() {
return 42;
}
}
@Test(expected = AssertionError.class)
public void testAssertBasicEqualsAndHashCodeBehaviorThrowsAssertionErrorOnHashCodeReturnsDifferentValuesOnEqualInstances() {
HashCodeReturnsDifferentValuesOnEqualInstances foo1 = new HashCodeReturnsDifferentValuesOnEqualInstances(1, 1);
HashCodeReturnsDifferentValuesOnEqualInstances foo2 = new HashCodeReturnsDifferentValuesOnEqualInstances(1, 2);
HashCodeReturnsDifferentValuesOnEqualInstances bar = new HashCodeReturnsDifferentValuesOnEqualInstances(2, 1);
assertBasicEqualsAndHashCodeBehavior(foo1, foo2, bar);
}
private static class HashCodeReturnsDifferentValuesOnEqualInstances {
private final int value1, value2;
private HashCodeReturnsDifferentValuesOnEqualInstances(int value1, int value2) {
this.value1 = value1;
this.value2 = value2;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof HashCodeReturnsDifferentValuesOnEqualInstances)) return false;
HashCodeReturnsDifferentValuesOnEqualInstances that = (HashCodeReturnsDifferentValuesOnEqualInstances) o;
return value1 == that.value1;
}
@Override
public int hashCode() {
return value2;
}
}
}
|
package com.ezardlabs.dethsquare.multiplayer;
import com.ezardlabs.dethsquare.GameObject;
import com.ezardlabs.dethsquare.Time;
import com.ezardlabs.dethsquare.Vector2;
import com.ezardlabs.dethsquare.multiplayer.Network.NetworkStateChangeListener.State;
import com.ezardlabs.dethsquare.prefabs.PrefabManager;
import com.ezardlabs.dethsquare.util.GameListeners;
import com.ezardlabs.dethsquare.util.GameListeners.UpdateListener;
import org.bitlet.weupnp.GatewayDevice;
import org.bitlet.weupnp.GatewayDiscover;
import org.bitlet.weupnp.PortMappingEntry;
import org.json.JSONArray;
import org.json.JSONObject;
import org.xml.sax.SAXException;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
public class Network {
static {
// Add hook into game loop
// GameListeners.addUpdateListener(Network::update);
}
private static UpdateListener updateListener;
private static NetworkStateChangeListener listener;
private static InetAddress[] addresses;
private static int[] ports;
private static UDPWriter udpOut;
private static UDPReader udpIn;
private static TCPWriter[] tcpOut;
private static ServerSocket tcpIn;
private static int myPort = 2828;
private static int playerId = -1;
private static boolean host;
private static int networkIdCounter = -1;
public static int getPlayerId() {
return playerId;
}
static int getNewNetworkId() {
if (networkIdCounter == -1) throw new Error("Network ID counter has not been setup yet");
return networkIdCounter++;
}
public static boolean isHost() {
return host;
}
private static void configureUPnP() throws ParserConfigurationException, SAXException, IOException {
GatewayDiscover discover = new GatewayDiscover();
System.out.println("Looking for Gateway Devices");
discover.discover();
GatewayDevice d = discover.getValidGateway();
PortMappingEntry pme = new PortMappingEntry();
if (!d.getSpecificPortMappingEntry(myPort, "UDP", pme)) {
System.out.println("UDP mapping does not already exist");
System.out.println("Adding UDP port mapping: " +
d.addPortMapping(myPort, myPort, d.getLocalAddress().getHostAddress(), "UDP",
"Lost Sector UDP"));
} else {
System.out.println("UDP mapping already exists");
}
pme = new PortMappingEntry();
if (!d.getSpecificPortMappingEntry(myPort + 1, "TCP", pme)) {
System.out.println("TCP mapping does not already exist");
System.out.println("Adding TCP port mapping: " +
d.addPortMapping(myPort + 1, myPort + 1, d.getLocalAddress().getHostAddress(),
"TCP", "Lost Sector TCP"));
} else {
System.out.println("TCP mapping already exists");
}
}
public static void findGame(NetworkStateChangeListener listener) {
Network.listener = listener;
new TCPServer().start();
MatchmakingThread mt = new MatchmakingThread();
updateListener = () -> checkIfGameFound(mt);
GameListeners.addUpdateListener(updateListener);
mt.start();
listener.onNetworkStateChanged(State.MATCHMAKING_SEARCHING);
}
private static void checkIfGameFound(MatchmakingThread mt) {
if (mt.data != null) {
listener.onNetworkStateChanged(State.MATCHMAKING_FOUND);
JSONObject data = new JSONObject(mt.data);
playerId = data.getInt("id");
host = data.getBoolean("host");
JSONArray peers = data.getJSONArray("peers");
addresses = new InetAddress[peers.length()];
ports = new int[peers.length()];
tcpOut = new TCPWriter[peers.length()];
listener.onNetworkStateChanged(State.GAME_CONNECTING);
for (int i = 0; i < peers.length(); i++) {
JSONObject player = peers.getJSONObject(i);
try {
addresses[i] = InetAddress.getByName(player.getString("address"));
} catch (UnknownHostException e) {
e.printStackTrace();
}
ports[i] = player.getInt("port");
try {
tcpOut[i] = new TCPWriter(new Socket(addresses[i], ports[i] + 1));
tcpOut[i].start();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
DatagramSocket socket = new DatagramSocket(myPort);
udpOut = new UDPWriter(socket);
udpOut.start();
udpIn = new UDPReader(socket);
udpIn.start();
} catch (SocketException e) {
e.printStackTrace();
}
networkIdCounter = playerId * (Integer.MAX_VALUE / 4) + 1;
listener.onNetworkStateChanged(State.GAME_CONNECTED);
GameListeners.removeUpdateListener(updateListener);
GameListeners.addUpdateListener(Network::update);
}
}
private static void update() {
if (Time.frameCount % 2 == 0) {
ByteBuffer data = ByteBuffer.allocate(NetworkBehaviour.totalSize + (NetworkBehaviour
.myNetworkBehaviours.size() * 8));
for (NetworkBehaviour nb : NetworkBehaviour.myNetworkBehaviours.values()) {
data.putInt(nb.getNetworkId());
data.putInt(nb.getSize());
data.put(nb.onSend());
}
udpOut.sendMessage(data.array());
}
synchronized (udpIn.udpMessages) {
while (udpIn.udpMessages.size() > 0) {
int count = 0;
ByteBuffer data = ByteBuffer.wrap(udpIn.udpMessages.remove(0));
NetworkBehaviour nb;
while (count < data.capacity()) {
data.position(count);
int networkId = data.getInt(count);
if (networkId == 0) break;
int size = data.getInt(count + 4);
nb = NetworkBehaviour.otherNetworkBehaviours.get(networkId);
if (nb != null) {
nb.onReceive(data, count + 8);
}
count += size + 8;
}
}
}
}
private static class MatchmakingThread extends Thread {
private String data;
MatchmakingThread() {
super("MatchmakingThread");
}
@Override
public void run() {
byte[] buffer = String.valueOf(myPort).getBytes();
try (DatagramSocket s = new DatagramSocket(myPort)) {
s.send(new DatagramPacket(buffer, buffer.length,
InetAddress.getByName("8bitwarframe.com"), 3000));
DatagramPacket p = new DatagramPacket(new byte[1024], 1024);
s.receive(p);
data = new String(p.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static class UDPReader extends Thread {
private final DatagramSocket socket;
final ArrayList<byte[]> udpMessages = new ArrayList<>();
UDPReader(DatagramSocket socket) {
super("UDPReader");
this.socket = socket;
}
@Override
public void run() {
try {
DatagramPacket packet = new DatagramPacket(new byte[4096], 4096);
while (true) {
socket.receive(packet);
synchronized (udpMessages) {
udpMessages.add(packet.getData());
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static class UDPWriter extends Thread {
private final DatagramSocket socket;
private final ArrayList<byte[]> messages = new ArrayList<>();
private final DatagramPacket[] packets = new DatagramPacket[addresses.length];
UDPWriter(DatagramSocket socket) {
super("UDPWriter");
this.socket = socket;
for (int i = 0; i < packets.length; i++) {
packets[i] = new DatagramPacket(new byte[0], 0, addresses[i], ports[i]);
}
}
@Override
public void run() {
try {
while (true) {
synchronized (messages) {
messages.wait();
while (messages.size() > 0) {
byte[] message = messages.remove(0);
for (int i = 0; i < addresses.length; i++) {
packets[i].setData(message);
socket.send(packets[i]);
}
}
}
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
void sendMessage(byte[] message) {
synchronized (messages) {
messages.add(message);
messages.notify();
}
}
}
private static class TCPServer extends Thread {
TCPServer() {
super("TCPServer");
}
@Override
public void run() {
try (ServerSocket ss = new ServerSocket(myPort + 1)) {
while (true) {
new TCPReader(ss.accept()).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static class TCPReader extends Thread {
private final Socket socket;
TCPReader(Socket socket) {
super("TCPReader");
this.socket = socket;
}
@Override
public void run() {
try (BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()))) {
socket.setKeepAlive(true);
while (socket.isConnected()) {
String command = in.readLine();
if (command != null) {
if (command.equals("instantiate")) {
processInstantiation(in);
} else {
System.out.println("Unknown command:" + command);
}
}
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static class TCPWriter extends Thread {
private final Socket socket;
private final ArrayList<String> messages = new ArrayList<>();
TCPWriter(Socket socket) {
super("TCPWriter");
this.socket = socket;
}
@Override
public void run() {
try (BufferedWriter out = new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream()))) {
while (true) {
synchronized (messages) {
messages.wait();
while (messages.size() > 0) {
String s = messages.remove(0);
out.write(s);
out.flush();
}
}
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
void sendMessage(String message) {
synchronized (messages) {
messages.add(message);
messages.notify();
}
}
}
public static GameObject instantiate(String prefabName, Vector2 position) {
GameObject gameObject = PrefabManager.loadPrefab(prefabName);
if (tcpOut != null) {
List<NetworkBehaviour> networkBehaviours = gameObject.getComponentsOfType(NetworkBehaviour.class);
HashMap<String, Integer> networkIds = new HashMap<>();
for (NetworkBehaviour nb : networkBehaviours) {
networkIds.put(nb.getClass().getCanonicalName(), nb.getNetworkId());
}
StringBuilder sb = new StringBuilder();
sb.append("instantiate").append(System.lineSeparator());
if (PrefabManager.prefabExists(prefabName + "_other")) {
sb.append(prefabName).append("_other").append(System.lineSeparator());
} else {
sb.append(prefabName).append(System.lineSeparator());
}
sb.append(position.x).append(System.lineSeparator());
sb.append(position.y).append(System.lineSeparator());
sb.append(playerId).append(System.lineSeparator());
for (String key : networkIds.keySet()) {
sb.append(key).append(System.lineSeparator()).append(networkIds.get(key)).append(System.lineSeparator());
}
String message = sb.toString();
for (TCPWriter writer : tcpOut) {
writer.sendMessage(message);
}
}
// for (int i = 0; i < tcp.length; i++) {
// try (BufferedWriter out = new BufferedWriter(
// new OutputStreamWriter(tcp[i].getOutputStream()))) {
// out.write("instantiate");
// out.newLine();
// if (PrefabManager.prefabExists(prefabName + "_other")) {
// out.write(prefabName + "_other");
// } else {
// out.write(prefabName);
// out.newLine();
// out.write(String.valueOf(position.x));
// out.newLine();
// out.write(String.valueOf(position.y));
// out.newLine();
// out.write(String.valueOf(playerId));
// out.newLine();
// for (String key : networkIds.keySet()) {
// out.write(key);
// out.newLine();
// out.write(networkIds.get(key));
// out.newLine();
// } catch (IOException e) {
// e.printStackTrace();
return GameObject.instantiate(gameObject, position);
}
private static void processInstantiation(BufferedReader in) throws IOException {
String name = in.readLine();
GameObject gameObject = PrefabManager.loadPrefab(name);
Vector2 position = new Vector2(Float.parseFloat(in.readLine()),
Float.parseFloat(in.readLine()));
int playerId = Integer.parseInt(in.readLine());
List<NetworkBehaviour> networkBehaviours = gameObject
.getComponentsOfType(NetworkBehaviour.class);
HashMap<String, Integer> networkIds = new HashMap<>();
for (int i = 0; i < networkBehaviours.size(); i++) {
networkIds.put(in.readLine(), Integer.parseInt(in.readLine()));
}
for (NetworkBehaviour nb : networkBehaviours) {
nb.setPlayerId(playerId);
nb.setNetworkId(networkIds.get(nb.getClass().getCanonicalName()));
}
GameObject.instantiate(gameObject, position);
}
public interface NetworkStateChangeListener {
enum State {
MATCHMAKING_SEARCHING,
MATCHMAKING_FOUND,
GAME_CONNECTING,
GAME_CONNECTED
}
void onNetworkStateChanged(State state);
}
}
|
package com.falcon.suitagent.util;
import lombok.extern.slf4j.Slf4j;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.StringTokenizer;
import java.util.concurrent.*;
/*
* :
* guqiu@yiji.com 2016-06-22 17:48
*/
/**
*
* @author guqiu@yiji.com
*/
@Slf4j
public class CommandUtilForUnix {
public static class ExecuteResult{
public boolean isSuccess = false;
/**
*
* false
*/
public boolean isNormalExit = false;
public String msg = "";
public ExecuteResult(boolean isSuccess, boolean isNormalExit, String msg) {
this.isSuccess = isSuccess;
this.isNormalExit = isNormalExit;
this.msg = msg;
}
@Override
public String toString() {
return "ExecuteResult{" +
"isSuccess=" + isSuccess +
", isNormalExit=" + isNormalExit +
", msg='" + msg + '\'' +
'}';
}
}
/**
*
* @param pid
* @return
* @throws IOException
*/
public static String getCmdDirByPid(int pid) throws IOException {
String cmd = "ls -al /proc/" + pid;
CommandUtilForUnix.ExecuteResult executeResult = CommandUtilForUnix.execWithReadTimeLimit(cmd,false,7);
String msg = executeResult.msg;
String[] ss = msg.split("\n");
for (String s : ss) {
if(s.toLowerCase().contains("cwd")){
String[] split = s.split("\\s+");
return split[split.length - 1];
}
}
return null;
}
/**
* ,()2
* @param execTarget
* @param cmd
* @param cmdSep
* cmd
* @param maxReadTime
* @return
* @throws IOException
*/
public static ExecuteResult execWithReadTimeLimit(String execTarget,String cmd,boolean cmdSep, long maxReadTime){
final List<Process> resultList = new ArrayList<>();
final BlockingQueue<Object> blockingQueue = new ArrayBlockingQueue<>(1);
StringBuilder resultMsg = new StringBuilder();
ExecuteThreadUtil.execute(() -> {
Process process = null;
try {
process = exec(resultMsg,execTarget,cmd,cmdSep,maxReadTime, TimeUnit.SECONDS);
} catch (IOException e) {
log.error("Command '{}' execute exception",cmd,e);
}
resultList.add(process);
if (!blockingQueue.offer(resultList.get(0)))
log.error("");
});
try {
Object result = blockingQueue.take();
if (result instanceof Process){
Process process = (Process) result;
if(process.isAlive()){
log.debug("process destroyForcibly");
process.destroyForcibly();
}
boolean exeSuccess = process.exitValue() == 0;
if(!exeSuccess){
log.debug(" {} {}",cmd,resultMsg.toString());
}
return new ExecuteResult(resultMsg.length() > 0 ,exeSuccess,String.valueOf(resultMsg.toString()));
}else{
log.error("Unknown Result Type Mapper",result);
return new ExecuteResult(resultMsg.length() > 0,false,resultMsg.toString());
}
} catch (InterruptedException e) {
log.warn("Command '{}' execute exception",cmd,e);
return new ExecuteResult(resultMsg.length() > 0,false,resultMsg.toString());
}
}
/**
* ,
* @param cmd
* @param cmdSep
* cmd
* @param maxReadTime
* @return
* @throws IOException
*/
public static ExecuteResult execWithReadTimeLimit(String cmd,boolean cmdSep, long maxReadTime) throws IOException {
return execWithReadTimeLimit(null,cmd,cmdSep,maxReadTime);
}
/**
*
* @param result
*
* @param execTarget
*
* /bin/sh
* @param cmd
*
* @param cmdSep
* cmd
* @return
* @throws IOException
*/
private static Process exec(StringBuilder result,String execTarget,String cmd,boolean cmdSep,long timeout,TimeUnit timeUnit) throws IOException {
List<String> shList = new ArrayList<>();
if(execTarget == null){
execTarget = "/bin/sh";
shList.add(execTarget);
shList.add("-c");
log.debug(" : {} -c \"{}\"",execTarget,cmd);
}else{
shList.add(execTarget);
log.debug(" : {} {}",execTarget,cmd);
}
if(cmdSep){
Collections.addAll(shList, cmd.split("\\s"));
}else{
shList.add(cmd);
}
ProcessBuilder pb = new ProcessBuilder(shList);
Process process = pb.start();
try(ByteArrayOutputStream resultOutStream = new ByteArrayOutputStream();
InputStream errorInStream = new BufferedInputStream(process.getErrorStream());
InputStream processInStream = new BufferedInputStream(process.getInputStream())){
Callable readTask1 = (Callable<String>) () -> {
readFromStream(result,errorInStream,resultOutStream);
return "";
};
Callable readTask2 = (Callable<String>) () -> {
readFromStream(result,processInStream,resultOutStream);
return "";
};
Future readFuture1 = ExecuteThreadUtil.execute(readTask1);
Future readFuture2 = ExecuteThreadUtil.execute(readTask2);
try {
readFuture1.get(timeout,timeUnit);
readFuture2.get(timeout,timeUnit);
} catch (Exception e) {
log.info("Command '{}' read timeout {} {}",cmd,timeout,timeUnit.name());
}finally {
process.destroy();
try {
process.waitFor();
} catch (InterruptedException e) {
log.error("",e);
}
}
}
return process;
}
private static void readFromStream(StringBuilder result,InputStream inputStream,ByteArrayOutputStream resultOutStream) throws IOException {
int num;
byte[] bs = new byte[1024];
while ((num = inputStream.read(bs)) != -1) {
resultOutStream.write(bs, 0, num);
result.append(new String(resultOutStream.toByteArray(),"utf-8"));
resultOutStream.reset();
}
}
/**
* Ping
* @param address
* Ping
* @param count
* Ping
* @return
* Ping
* -1 Ping
* -2
*/
public static PingResult ping(String address,int count) throws IOException {
PingResult pingResult = new PingResult();
String commend = String.format("ping -c %d %s",count,address);
CommandUtilForUnix.ExecuteResult executeResult = CommandUtilForUnix.execWithReadTimeLimit(commend,false,30);
if(executeResult.isNormalExit){
List<Float> times = new ArrayList<>();
String msg = executeResult.msg;
for (String line : msg.split("\n")) {
for (String ele : line.split(" ")) {
if(ele.toLowerCase().contains("time=")){
float time = Float.parseFloat(ele.replace("time=",""));
times.add(time);
}
}
}
if(times.isEmpty()){
log.warn(String.format("ping %s ",address));
pingResult.resultCode = -1;
}else{
float sum = 0;
for (Float time : times) {
sum += time;
}
pingResult.resultCode = 1;
pingResult.avgTime = Maths.div(sum,times.size(),3);
pingResult.successCount = times.size();
}
}else{
log.error("{}",commend);
pingResult.resultCode = -2;
}
return pingResult;
}
/**
* /etc/profile JAVA_HOME
* @return
* null :
* @throws IOException
*/
public static String getJavaHomeFromEtcProfile() throws IOException {
ExecuteResult executeResult = execWithReadTimeLimit("cat /etc/profile",false,7);
if(!executeResult.isSuccess){
return null;
}
String msg = executeResult.msg;
StringTokenizer st = new StringTokenizer(msg,"\n",false);
while( st.hasMoreElements() ){
String split = st.nextToken().trim();
if(!StringUtils.isEmpty(split)){
if(split.contains("JAVA_HOME=")){
String[] ss = split.split("=");
List<String> list = new ArrayList<>();
for (String s : ss) {
if(!StringUtils.isEmpty(s)){
list.add(s);
}
}
return list.get(list.size() - 1);
}
}
}
return null;
}
public static class PingResult{
/**
*
* 1
* -1 Ping
* -2
*/
public int resultCode;
/**
* ping
*/
public int successCount;
/**
* ping
*/
public double avgTime;
@Override
public String toString() {
return "PingResult{" +
"resultCode=" + resultCode +
", successCount=" + successCount +
", avgTime=" + avgTime +
'}';
}
}
}
|
package org.dstadler.github;
import static org.junit.Assert.*;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.junit.Assume;
import org.junit.Test;
import org.kohsuke.github.GitHub;
import com.google.common.collect.Multimap;
public class BaseSearchTest {
@Test
public void testConnect() throws Exception {
final GitHub connect;
try {
connect = BaseSearch.connect();
} catch (FileNotFoundException e) {
Assume.assumeTrue("Ignore missing credentials", false);
return;
} catch (IOException e) {
Assume.assumeTrue("Ignore missing credentials", e.getMessage().contains("Failed to resolve credentials"));
throw e;
}
assertNotNull(connect);
}
@Test
public void testGetRepository() throws Exception {
assertNull(BaseSearch.getRepository(""));
assertNull(BaseSearch.getRepository("some url"));
assertEquals("user/repo", BaseSearch.getRepository("https://github.com/user/repo/blob/some_file"));
}
@Test
public void testGetNonForkRepository() throws Exception {
BaseSearch search = new BaseSearch() {
@Override
void search(GitHub github, Multimap<String, String> versions) {
}
@Override
String getExcludeRegex() {
return null;
}
@Override
void parseVersion(Multimap<String, String> versions, String htmlUrl, String repo, String str) {
}
};
try {
assertNull(search.getNonForkRepository(BaseSearch.connect(), ""));
} catch (FileNotFoundException e) {
Assume.assumeTrue("Ignore missing credentials", false);
} catch (IOException e) {
Assume.assumeTrue("Ignore missing credentials", e.getMessage().contains("Failed to resolve credentials"));
throw e;
}
assertNotNull(search.getNonForkRepository(BaseSearch.connect(),
"https://github.com/centic9/jgit-cookbook/blob/README.md"));
assertNull(search.getNonForkRepository(BaseSearch.connect(),
"https://github.com/a0xec0/Spoon-Knife/blob/README.md"));
}
}
|
package com.gamingmesh.jobs.Placeholders;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.bukkit.entity.Player;
import com.gamingmesh.jobs.Jobs;
import com.gamingmesh.jobs.container.CurrencyType;
import com.gamingmesh.jobs.container.Job;
import com.gamingmesh.jobs.container.JobProgression;
import com.gamingmesh.jobs.container.JobsPlayer;
import com.gamingmesh.jobs.stuff.TimeManage;
public class Placeholder {
private Jobs plugin;
Pattern placeholderPatern = Pattern.compile("(%)([^\"^%]*)(%)");
public Placeholder(Jobs plugin) {
this.plugin = plugin;
}
static String pref = "jobsr";
private static ChatFilterRule numericalRule = new ChatFilterRule().setPattern("(\\$\\d)");
public enum JobsPlaceHolders {
user_id,
user_bstandcount,
user_maxbstandcount,
user_furncount,
user_maxfurncount,
user_doneq,
user_dailyquests_pending,
user_dailyquests_completed,
user_dailyquests_total,
user_seen,
user_totallevels,
user_issaved,
user_displayhonorific,
user_joinedjobcount,
user_points,
user_points_fixed,
user_total_points,
user_archived_jobs,
user_jobs,
user_boost_$1_$2("jname/number", "money/exp/points"),
user_isin_$1("jname/number"),
user_canjoin_$1("jname/number"),
user_jlevel_$1("jname/number"),
user_jexp_$1("jname/number"),
user_jmaxexp_$1("jname/number"),
user_jexpunf_$1("jname/number"),
user_jmaxexpunf_$1("jname/number"),
user_jmaxlvl_$1("jname/number"),
user_job_$1("jname/number"),
maxjobs,
limit_$1("money/exp/points"),
plimit_$1("money/exp/points"),
plimit_tleft_$1("money/exp/points"),
total_workers,
name_$1("jname/number"),
shortname_$1("jname/number"),
chatcolor_$1("jname/number"),
description_$1("jname/number"),
maxdailyq_$1("jname/number"),
maxlvl_$1("jname/number"),
maxviplvl_$1("jname/number"),
totalplayers_$1("jname/number"),
maxslots_$1("jname/number"),
bonus_$1("jname/number");
private String[] vars;
private List<Integer> groups = new ArrayList<>();
private ChatFilterRule rule = null;
private boolean hidden = false;
JobsPlaceHolders(String... vars) {
Matcher matcher = numericalRule.getMatcher(this.toString());
if (matcher != null) {
rule = new ChatFilterRule();
List<String> ls = new ArrayList<>();
ls.add("(%" + pref + "_)" + this.toString().replaceAll("\\$\\d", "([^\"^%]*)") + "(%)");
// For MVdWPlaceholderAPI
// ls.add("(\\{" + pref + this.toString().replaceAll("\\$\\d", "([^\"^%]*)" + "(\\})"));
rule.setPattern(ls);
while (matcher.find()) {
try {
int id = Integer.parseInt(matcher.group(1).substring(1));
groups.add(id);
} catch (Exception e) {
e.printStackTrace();
}
}
}
this.vars = vars;
this.hidden = false;
}
public static JobsPlaceHolders getByName(String name) {
String original = name;
for (JobsPlaceHolders one : JobsPlaceHolders.values()) {
if (one.isComplex())
continue;
if (one.toString().equalsIgnoreCase(name))
return one;
}
for (JobsPlaceHolders one : JobsPlaceHolders.values()) {
if (one.isComplex())
continue;
if (one.getName().equalsIgnoreCase(name))
return one;
}
name = pref + name;
for (JobsPlaceHolders one : JobsPlaceHolders.values()) {
if (one.isComplex())
continue;
if (one.getName().equalsIgnoreCase(name))
return one;
}
name = "%" + pref + "_" + original + "%";
for (JobsPlaceHolders one : JobsPlaceHolders.values()) {
if (!one.isComplex())
continue;
if (!one.getComplexRegexMatchers(name).isEmpty())
return one;
}
// For MVdWPlaceholderAPI
// if (Jobs.getInstance().isMVdWPlaceholderAPIEnabled() && original.startsWith(pref+"_")) {
// String t = "{" + original + "}";
// for (JobsPlaceHolders one : JobsPlaceHolders.values()) {
// if (!one.isComplex())
// continue;
// if (!one.getComplexRegexMatchers(t).isEmpty()) {
// return one;
return null;
}
public static JobsPlaceHolders getByNameExact(String name) {
name = name.toLowerCase();
for (JobsPlaceHolders one : JobsPlaceHolders.values()) {
if (one.isComplex()) {
if (!one.getComplexRegexMatchers("%" + name + "%").isEmpty()) {
return one;
}
} else {
String n = one.getName();
if (n.equals(name))
return one;
}
}
return null;
}
public String getName() {
return pref + "_" + this.name();
}
public String getFull() {
if (this.isComplex()) {
String name = this.getName();
int i = 0;
for (String one : this.getName().split("_")) {
if (!one.startsWith("$"))
continue;
if (vars.length >= i - 1)
name = name.replace(one, "[" + vars[i] + "]");
i++;
}
return "%" + name + "%";
}
return "%" + this.getName() + "%";
}
public String getMVdW() {
if (this.isComplex()) {
String name = this.getName();
int i = 0;
for (String one : this.getName().split("_")) {
if (!one.startsWith("$"))
continue;
if (vars.length >= i - 1)
name = name.replace(one, "*");
i++;
}
return name;
}
return this.getName();
}
public List<String> getComplexRegexMatchers(String text) {
List<String> lsInLs = new ArrayList<>();
if (!this.isComplex())
return lsInLs;
Matcher matcher = this.getRule().getMatcher(text);
if (matcher == null)
return lsInLs;
while (matcher.find()) {
lsInLs.add(matcher.group());
}
return lsInLs;
}
public List<String> getComplexValues(String text) {
List<String> lsInLs = new ArrayList<>();
if (!this.isComplex() || text == null)
return lsInLs;
Matcher matcher = this.getRule().getMatcher(text);
if (matcher == null)
return lsInLs;
while (matcher.find()) {
try {
for (Integer oneG : groups) {
lsInLs.add(matcher.group(oneG + 1));
}
} catch (Exception e) {
}
break;
}
return lsInLs;
}
public boolean isComplex() {
return rule != null;
}
public ChatFilterRule getRule() {
return rule;
}
public void setRule(ChatFilterRule rule) {
this.rule = rule;
}
public boolean isHidden() {
return hidden;
}
}
public List<String> updatePlaceHolders(Player player, List<String> messages) {
List<String> ms = new ArrayList<>(messages);
for (int i = 0, l = messages.size(); i < l; ++i) {
ms.set(i, updatePlaceHolders(player, messages.get(i)));
}
return ms;
}
public enum JobsPlaceholderType {
Jobs, PAPI, MVdW;
}
public JobsPlaceholderType getPlaceHolderType(Player player, String placeholder) {
if (placeholder == null)
return null;
if (placeholder.contains("%")) {
if (!placeholder.equals(translateOwnPlaceHolder(player, placeholder)))
return JobsPlaceholderType.Jobs;
}
if (plugin.isPlaceholderAPIEnabled()) {
if (placeholder.contains("%")) {
if (!placeholder.equals(me.clip.placeholderapi.PlaceholderAPI.setPlaceholders(player, placeholder)))
return JobsPlaceholderType.PAPI;
}
}
// For MVdWPlaceholderAPI
// if (plugin.isMVdWPlaceholderAPIEnabled()) {
// if (placeholder.contains("{"))
// if (!placeholder.equals(be.maximvdw.placeholderapi.PlaceholderAPI.replacePlaceholders(player, placeholder)))
// return CMIPlaceholderType.MVdW;
return null;
}
public String updatePlaceHolders(Player player, String message) {
if (message == null)
return null;
if (message.contains("%"))
message = translateOwnPlaceHolder(player, message);
if (plugin.isPlaceholderAPIEnabled()) {
if (message.contains("%"))
message = me.clip.placeholderapi.PlaceholderAPI.setPlaceholders(player, message);
}
// For MVdWPlaceholderAPI
// if (plugin.isMVdWPlaceholderAPIEnabled()) {
// if (message.contains("{"))
// message = be.maximvdw.placeholderapi.PlaceholderAPI.replacePlaceholders(player, message);
return message;
}
private String translateOwnPlaceHolder(Player player, String message) {
if (message == null)
return null;
if (message.contains("%")) {
Matcher match = placeholderPatern.matcher(message);
while (match.find()) {
try {
String cmd = match.group(2);
if (!message.contains("%"))
break;
JobsPlaceHolders place = JobsPlaceHolders.getByNameExact(cmd);
if (place == null)
continue;
String group = match.group();
String with = this.getValue(player, place, group);
if (with == null)
with = "";
if (with.startsWith("$"))
with = "\\" + with;
message = message.replaceFirst(group, with);
} catch (Exception e) {
e.printStackTrace();
}
}
}
return message;
}
public String getValue(Player player, JobsPlaceHolders placeHolder) {
return getValue(player, placeHolder, null);
}
public String getValue(Player player, JobsPlaceHolders placeHolder, String value) {
return getValue(player != null ? player.getUniqueId() : null, placeHolder, value);
}
private static JobProgression getProgFromValue(JobsPlayer user, String value) {
JobProgression j = null;
try {
int id = Integer.parseInt(value);
if (id > 0)
j = user.getJobProgression().get(id - 1);
} catch (Exception e) {
Job job = Jobs.getJob(value);
if (job != null)
j = user.getJobProgression(job);
}
return j;
}
private static Job getJobFromValue(String value) {
Job j = null;
try {
int id = Integer.parseInt(value);
if (id > 0)
j = Jobs.getJobs().get(id - 1);
} catch (Exception e) {
j = Jobs.getJob(value);
}
return j;
}
private static String simplifyDouble(double value) {
return String.valueOf((int) (value * 100) / 100D);
}
public String getValue(UUID uuid, JobsPlaceHolders placeHolder, String value) {
if (placeHolder == null)
return null;
JobsPlayer user = uuid == null ? null : Jobs.getPlayerManager().getJobsPlayer(uuid);
// Placeholders by JobsPlayer object
if (user != null) {
NumberFormat format = NumberFormat.getInstance(Locale.ENGLISH);
switch (placeHolder) {
case user_dailyquests_pending:
Integer pendingQuests = (int) user.getQuestProgressions().stream().filter(q -> !q.isCompleted()).count();
return Integer.toString(pendingQuests);
case user_dailyquests_completed:
Integer completedQuests = (int) user.getQuestProgressions().stream().filter(q -> q.isCompleted()).count();
return Integer.toString(completedQuests);
case user_dailyquests_total:
Integer dailyquests = user.getQuestProgressions().size();
return Integer.toString(dailyquests);
case user_id:
return Integer.toString(user.getUserId());
case user_bstandcount:
return Integer.toString(user.getBrewingStandCount());
case user_maxbstandcount:
return Integer.toString(user.getMaxBrewingStandsAllowed());
case user_furncount:
return Integer.toString(user.getFurnaceCount());
case user_maxfurncount:
return Integer.toString(user.getMaxFurnacesAllowed());
case user_doneq:
return Integer.toString(user.getDoneQuests());
case user_seen:
return TimeManage.to24hourShort(System.currentTimeMillis() - user.getSeen());
case user_totallevels:
return Integer.toString(user.getTotalLevels());
case user_points:
DecimalFormat dec = new DecimalFormat("00.0");
return dec.format(user.getPointsData().getCurrentPoints());
case user_points_fixed:
return Integer.toString((int) user.getPointsData().getCurrentPoints());
case user_total_points:
format = NumberFormat.getInstance(Locale.ENGLISH);
return format.format(user.getPointsData().getTotalPoints());
case user_issaved:
return convert(user.isSaved());
case user_displayhonorific:
return user.getDisplayHonorific();
case user_joinedjobcount:
return Integer.toString(user.getJobProgression().size());
case user_archived_jobs:
return Integer.toString(user.getArchivedJobs().getArchivedJobs().size());
case user_jobs:
List<JobProgression> l = user.getJobProgression();
if (l.isEmpty()) {
return "";
}
JobProgression prog = l.get(ThreadLocalRandom.current().nextInt(l.size()));
return prog.getJob().getName();
default:
break;
}
if (placeHolder.isComplex()) {
List<String> vals = placeHolder.getComplexValues(value);
if (vals.isEmpty())
return "";
JobProgression j = getProgFromValue(user, vals.get(0));
switch (placeHolder) {
case limit_$1:
CurrencyType t = CurrencyType.getByName(vals.get(0));
return Integer.toString(user.getLimit(t));
case plimit_$1:
t = CurrencyType.getByName(vals.get(0));
return Double.toString(user.getPaymentLimit().GetAmount(t));
case plimit_tleft_$1:
t = CurrencyType.getByName(vals.get(0));
return TimeManage.to24hourShort(user.getPaymentLimit().GetLeftTime(t));
case user_jlevel_$1:
return j == null ? "0" : Integer.toString(j.getLevel());
case user_jexp_$1:
format = NumberFormat.getInstance(Locale.ENGLISH);
return j == null ? "0" : format.format(j.getExperience());
case user_jmaxexp_$1:
format = NumberFormat.getInstance(Locale.ENGLISH);
return j == null ? "0" : format.format(j.getMaxExperience());
case user_jexpunf_$1:
return j == null ? "0" : Double.toString(j.getExperience());
case user_jmaxexpunf_$1:
return j == null ? "0" : Integer.toString(j.getMaxExperience());
case user_jmaxlvl_$1:
return j == null ? "0" : Integer.toString(j.getJob().getMaxLevel(user));
case user_boost_$1_$2:
if (vals.size() < 2)
return "";
return j == null ? "" : simplifyDouble(user.getBoost(j.getJob().getName(), CurrencyType.getByName(vals.get(1))));
case user_isin_$1:
vals = placeHolder.getComplexValues(value);
if (vals.isEmpty())
return "";
Job jobs = getJobFromValue(vals.get(0));
return jobs == null ? "no" : convert(user.isInJob(jobs));
case user_job_$1:
return j == null ? "" : j.getJob().getName();
case maxjobs:
Double max = Jobs.getPermissionManager().getMaxPermission(user, "jobs.max");
max = max == null ? Jobs.getGCManager().getMaxJobs() : max;
return Double.toString(max);
default:
break;
}
}
// Placeholders by player object
if (user.isOnline()) {
Player player = user.getPlayer();
if (player != null) {
List<String> values;
switch (placeHolder) {
case user_canjoin_$1:
values = placeHolder.getComplexValues(value);
if (values.isEmpty())
return "";
Job job = getJobFromValue(values.get(0));
if (job == null)
return "";
if (!Jobs.getCommandManager().hasJobPermission(player, job))
return convert(false);
if (user.isInJob(job))
return convert(false);
if (job.getMaxSlots() != null && Jobs.getUsedSlots(job) >= job.getMaxSlots())
return convert(false);
int confMaxJobs = Jobs.getGCManager().getMaxJobs();
short PlayerMaxJobs = (short) user.getJobProgression().size();
if (confMaxJobs > 0 && PlayerMaxJobs >= confMaxJobs && !Jobs.getPlayerManager().getJobsLimit(user, PlayerMaxJobs))
return convert(false);
return convert(true);
default:
break;
}
}
}
}
if (placeHolder.isComplex()) {
List<String> values = placeHolder.getComplexValues(value);
if (values.isEmpty())
return "";
Job jo = getJobFromValue(values.get(0));
if (jo == null)
return "";
// Global placeholders by jobname
switch (placeHolder) {
case name_$1:
return jo.getName();
case shortname_$1:
return jo.getShortName();
case chatcolor_$1:
return jo.getChatColor().toString();
case description_$1:
return jo.getDescription();
case maxdailyq_$1:
return Integer.toString(jo.getMaxDailyQuests());
case maxlvl_$1:
return Integer.toString(jo.getMaxLevel());
case maxviplvl_$1:
return Integer.toString(jo.getVipMaxLevel());
case bonus_$1:
return Double.toString(jo.getBonus());
case totalplayers_$1:
return Integer.toString(jo.getTotalPlayers());
case maxslots_$1:
return Integer.toString(jo.getMaxSlots());
default:
break;
}
}
// Global placeholders
switch (placeHolder) {
case maxjobs:
return Integer.toString(Jobs.getGCManager().getMaxJobs());
case total_workers:
return Integer.toString(Jobs.getJobsDAO().getTotalPlayers());
default:
break;
}
return null;
}
private String convert(boolean state) {
return state ? Jobs.getLanguage().getMessage("general.info.true") : Jobs.getLanguage().getMessage("general.info.false");
}
}
|
package org.gitlab4j.api;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeTrue;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.List;
import org.gitlab4j.api.models.Branch;
import org.gitlab4j.api.models.Commit;
import org.gitlab4j.api.models.CompareResults;
import org.gitlab4j.api.models.Project;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
/**
* In order for these tests to run you must set the following properties in test-gitlab4j.properties
*
* TEST_NAMESPACE
* TEST_PROJECT_NAME
* TEST_HOST_URL
* TEST_PRIVATE_TOKEN
*
* If any of the above are NULL, all tests in this class will be skipped.
*
* NOTE: &FixMethodOrder(MethodSorters.NAME_ASCENDING) is very important to insure that testCreate() is executed first.
*/
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class TestRepositoryApi {
// The following needs to be set to your test repository
private static final String TEST_PROJECT_NAME;
private static final String TEST_NAMESPACE;
private static final String TEST_HOST_URL;
private static final String TEST_PRIVATE_TOKEN;
static {
TEST_NAMESPACE = TestUtils.getProperty("TEST_NAMESPACE");
TEST_PROJECT_NAME = TestUtils.getProperty("TEST_PROJECT_NAME");
TEST_HOST_URL = TestUtils.getProperty("TEST_HOST_URL");
TEST_PRIVATE_TOKEN = TestUtils.getProperty("TEST_PRIVATE_TOKEN");
}
private static final String TEST_BRANCH_NAME = "feature/test_branch";
private static final String TEST_PROTECT_BRANCH_NAME = "feature/protect_branch";
private static GitLabApi gitLabApi;
public TestRepositoryApi() {
super();
}
@BeforeClass
public static void setup() {
String problems = "";
if (TEST_NAMESPACE == null || TEST_NAMESPACE.trim().isEmpty()) {
problems += "TEST_NAMESPACE cannot be empty\n";
}
if (TEST_PROJECT_NAME == null || TEST_PROJECT_NAME.trim().isEmpty()) {
problems += "TEST_PROJECT_NAME cannot be empty\n";
}
if (TEST_HOST_URL == null || TEST_HOST_URL.trim().isEmpty()) {
problems += "TEST_HOST_URL cannot be empty\n";
}
if (TEST_PRIVATE_TOKEN == null || TEST_PRIVATE_TOKEN.trim().isEmpty()) {
problems += "TEST_PRIVATE_TOKEN cannot be empty\n";
}
if (problems.isEmpty()) {
gitLabApi = new GitLabApi(TEST_HOST_URL, TEST_PRIVATE_TOKEN);
teardown();
} else {
System.err.print(problems);
}
}
@AfterClass
public static void teardown() {
if (gitLabApi != null) {
try {
Project project = gitLabApi.getProjectApi().getProject(TEST_NAMESPACE, TEST_PROJECT_NAME);
try {
gitLabApi.getRepositoryApi().deleteBranch(project.getId(), TEST_BRANCH_NAME);
} catch (GitLabApiException ignore) {
}
gitLabApi.getRepositoryApi().deleteBranch(project.getId(), TEST_PROTECT_BRANCH_NAME);
} catch (GitLabApiException ignore) {
}
}
}
@Before
public void beforeMethod() {
assumeTrue(gitLabApi != null);
}
@Test
public void testCreateBranch() throws GitLabApiException {
Project project = gitLabApi.getProjectApi().getProject(TEST_NAMESPACE, TEST_PROJECT_NAME);
assertNotNull(project);
Branch branch = gitLabApi.getRepositoryApi().createBranch(project.getId(), TEST_BRANCH_NAME, "master");
assertNotNull(branch);
Branch fetchedBranch = gitLabApi.getRepositoryApi().getBranch(project.getId(), TEST_BRANCH_NAME);
assertNotNull(fetchedBranch);
assertEquals(branch.getName(), fetchedBranch.getName());
}
@Test
public void testDeleteBranch() throws GitLabApiException {
Project project = gitLabApi.getProjectApi().getProject(TEST_NAMESPACE, TEST_PROJECT_NAME);
assertNotNull(project);
gitLabApi.getRepositoryApi().deleteBranch(project.getId(), TEST_BRANCH_NAME);
}
@Test
public void testRepositoryArchiveViaInputStream() throws GitLabApiException, IOException {
Project project = gitLabApi.getProjectApi().getProject(TEST_NAMESPACE, TEST_PROJECT_NAME);
assertNotNull(project);
InputStream in = gitLabApi.getRepositoryApi().getRepositoryArchive(project.getId(), "master");
Path target = Files.createTempFile(TEST_PROJECT_NAME + "-", ".tar.gz");
Files.copy(in, target, StandardCopyOption.REPLACE_EXISTING);
assertTrue(target.toFile().length() > 0);
Files.delete(target);
}
@Test
public void testRepositoryArchiveViaFile() throws GitLabApiException, IOException {
Project project = gitLabApi.getProjectApi().getProject(TEST_NAMESPACE, TEST_PROJECT_NAME);
assertNotNull(project);
File file = gitLabApi.getRepositoryApi().getRepositoryArchive(project.getId(), "master", (File)null);
assertTrue(file.length() > 0);
file.delete();
file = gitLabApi.getRepositoryApi().getRepositoryArchive(project.getId(), "master", new File("."));
assertTrue(file.length() > 0);
file.delete();
}
@Test
public void testCompare() throws GitLabApiException {
Project project = gitLabApi.getProjectApi().getProject(TEST_NAMESPACE, TEST_PROJECT_NAME);
assertNotNull(project);
List<Commit> commits = gitLabApi.getCommitsApi().getCommits(project.getId());
assertNotNull(commits);
assertTrue(commits.size() > 1);
int numCommits = commits.size();
CompareResults compareResults = gitLabApi.getRepositoryApi().compare(project.getId(), commits.get(numCommits - 1).getId(), commits.get(numCommits - 2).getId());
assertNotNull(compareResults);
compareResults = gitLabApi.getRepositoryApi().compare(TEST_NAMESPACE + "/" + TEST_PROJECT_NAME, commits.get(numCommits - 1).getId(), commits.get(numCommits - 2).getId());
assertNotNull(compareResults);
}
@Test
public void testProtectBranch() throws GitLabApiException {
Project project = gitLabApi.getProjectApi().getProject(TEST_NAMESPACE, TEST_PROJECT_NAME);
assertNotNull(project);
Branch branch = gitLabApi.getRepositoryApi().createBranch(project.getId(), TEST_PROTECT_BRANCH_NAME, "master");
assertNotNull(branch);
Branch protectedBranch = gitLabApi.getRepositoryApi().protectBranch(project.getId(), TEST_PROTECT_BRANCH_NAME);
assertNotNull(protectedBranch);
assertTrue(protectedBranch.getProtected());
Branch unprotectedBranch = gitLabApi.getRepositoryApi().unprotectBranch(project.getId(), TEST_PROTECT_BRANCH_NAME);
assertNotNull(unprotectedBranch);
assertFalse(unprotectedBranch.getProtected());
}
}
|
package com.gamingmesh.jobs.Placeholders;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import com.gamingmesh.jobs.Jobs;
import com.gamingmesh.jobs.commands.JobsCommands;
import com.gamingmesh.jobs.container.CurrencyType;
import com.gamingmesh.jobs.container.Job;
import com.gamingmesh.jobs.container.JobProgression;
import com.gamingmesh.jobs.container.JobsPlayer;
import com.gamingmesh.jobs.container.Quest;
import com.gamingmesh.jobs.container.QuestProgression;
import com.gamingmesh.jobs.container.Title;
import com.gamingmesh.jobs.container.TopList;
import com.gamingmesh.jobs.container.blockOwnerShip.BlockOwnerShip;
import com.gamingmesh.jobs.container.blockOwnerShip.BlockTypes;
import com.gamingmesh.jobs.stuff.TimeManage;
public class Placeholder {
private Jobs plugin;
private final AtomicInteger jobLevel = new AtomicInteger();
private final Pattern placeholderPatern = Pattern.compile("(%)([^\"^%]*)(%)");
public Placeholder(Jobs plugin) {
this.plugin = plugin;
}
static String pref = "jobsr";
private static ChatFilterRule numericalRule = new ChatFilterRule().setPattern("(\\$\\d)");
public enum JobsPlaceHolders {
user_id,
user_bstandcount,
user_maxbstandcount,
user_furncount,
user_maxfurncount,
user_smokercount,
user_maxsmokercount,
user_blastcount,
user_maxblastcount,
user_doneq,
user_dailyquests_pending,
user_dailyquests_completed,
user_dailyquests_total,
user_quests,
user_seen,
user_totallevels,
user_issaved,
user_displayhonorific,
user_joinedjobcount,
user_points,
user_points_fixed,
user_total_points,
user_archived_jobs,
user_jobs,
user_boost_$1_$2("jname/number", "money/exp/points"),
user_jtoplvl_$1_$2("jname/number", "number"),
user_isin_$1("jname/number"),
user_canjoin_$1("jname/number"),
user_jlevel_$1("jname/number"),
user_jexp_$1("jname/number"),
user_jmexp_$1("jname/number"),
user_jprogress_$1("jname/number"),
user_jexp_rounded_$1("jname/number"),
user_jmaxexp_$1("jname/number"),
user_jexpunf_$1("jname/number"),
user_jmaxexpunf_$1("jname/number"),
user_jmaxlvl_$1("jname/number"),
user_job_$1("jname/number"),
user_title_$1("jname/number"),
user_archived_jobs_level_$1("jname/number"),
user_archived_jobs_exp_$1("jname/number"),
maxjobs,
total_workers,
limit_$1("money/exp/points"),
plimit_$1("money/exp/points"),
plimit_tleft_$1("money/exp/points"),
name_$1("jname/number"),
shortname_$1("jname/number"),
chatcolor_$1("jname/number"),
description_$1("jname/number"),
maxdailyq_$1("jname/number"),
maxlvl_$1("jname/number"),
maxviplvl_$1("jname/number"),
totalplayers_$1("jname/number"),
maxslots_$1("jname/number"),
bonus_$1("jname/number");
private String[] vars;
private List<Integer> groups = new ArrayList<>();
private ChatFilterRule rule;
JobsPlaceHolders(String... vars) {
Matcher matcher = numericalRule.getMatcher(toString());
if (matcher != null) {
rule = new ChatFilterRule();
List<String> ls = new ArrayList<>();
ls.add("(%" + pref + "_)" + toString().replaceAll("\\$\\d", "([^\"^%]*)") + "(%)");
// For MVdWPlaceholderAPI
// ls.add("(\\{" + pref + toString().replaceAll("\\$\\d", "([^\"^%]*)" + "(\\})"));
rule.setPattern(ls);
while (matcher.find()) {
groups.add(Integer.parseInt(matcher.group(1).substring(1)));
}
}
this.vars = vars;
}
public static JobsPlaceHolders getByName(String name) {
String original = name;
for (JobsPlaceHolders one : JobsPlaceHolders.values()) {
if (!one.isComplex() && one.toString().equalsIgnoreCase(name))
return one;
}
for (JobsPlaceHolders one : JobsPlaceHolders.values()) {
if (!one.isComplex() && one.getName().equalsIgnoreCase(name))
return one;
}
name = pref + name;
for (JobsPlaceHolders one : JobsPlaceHolders.values()) {
if (!one.isComplex() && one.getName().equalsIgnoreCase(name))
return one;
}
JobsPlaceHolders bestMatch = null;
name = "%" + pref + "_" + original + "%";
for (JobsPlaceHolders one : JobsPlaceHolders.values()) {
if (one.isComplex() && !one.getComplexRegexMatchers(name).isEmpty())
bestMatch = one;
}
// For MVdWPlaceholderAPI
// if (Jobs.getInstance().isMVdWPlaceholderAPIEnabled() && original.startsWith(pref+"_")) {
// String t = "{" + original + "}";
// for (JobsPlaceHolders one : JobsPlaceHolders.values()) {
// if (!one.isComplex())
// continue;
// if (!one.getComplexRegexMatchers(t).isEmpty()) {
// return one;
return bestMatch;
}
public static JobsPlaceHolders getByNameExact(String name) {
name = name.toLowerCase();
// Should iterate over all placeholders to match the correct one
// for example with %jobsr_plimit_tleft_money%
JobsPlaceHolders bestMatch = null;
for (JobsPlaceHolders one : JobsPlaceHolders.values()) {
if (one.isComplex()) {
if (!one.getComplexRegexMatchers("%" + name + "%").isEmpty()) {
bestMatch = one;
}
} else if (one.getName().equals(name)) {
bestMatch = one;
}
}
return bestMatch;
}
public String getName() {
return pref + "_" + name();
}
public String getFull() {
if (isComplex()) {
String name = getName();
int i = 0;
for (String one : name.split("_")) {
if (!one.startsWith("$"))
continue;
if (vars.length >= i - 1)
name = name.replace(one, "[" + vars[i] + "]");
i++;
}
return "%" + name + "%";
}
return "%" + getName() + "%";
}
/*public String getMVdW() {
if (this.isComplex()) {
String name = this.getName();
int i = 0;
for (String one : this.getName().split("_")) {
if (!one.startsWith("$"))
continue;
if (vars.length >= i - 1)
name = name.replace(one, "*");
i++;
}
return name;
}
return this.getName();
}*/
public List<String> getComplexRegexMatchers(String text) {
List<String> lsInLs = new ArrayList<>();
if (!isComplex())
return lsInLs;
Matcher matcher = rule.getMatcher(text);
if (matcher == null)
return lsInLs;
while (matcher.find()) {
lsInLs.add(matcher.group());
}
return lsInLs;
}
public List<String> getComplexValues(String text) {
List<String> lsInLs = new ArrayList<>();
if (text == null || !isComplex())
return lsInLs;
Matcher matcher = rule.getMatcher(text);
if (matcher != null && matcher.find()) {
try {
for (Integer oneG : groups) {
lsInLs.add(matcher.group(oneG + 1));
}
} catch (Exception e) {
}
}
return lsInLs;
}
public boolean isComplex() {
return rule != null;
}
public ChatFilterRule getRule() {
return rule;
}
public void setRule(ChatFilterRule rule) {
this.rule = rule;
}
}
public List<String> updatePlaceHolders(Player player, List<String> messages) {
List<String> ms = new ArrayList<>(messages);
for (int i = 0, l = messages.size(); i < l; ++i) {
ms.set(i, updatePlaceHolders(player, messages.get(i)));
}
return ms;
}
public enum JobsPlaceholderType {
JOBS, PAPI, MVDW;
}
public JobsPlaceholderType getPlaceHolderType(Player player, String placeholder) {
if (placeholder == null)
return null;
if (placeholder.contains("%") && !placeholder.equals(translateOwnPlaceHolder(player, placeholder))) {
return JobsPlaceholderType.JOBS;
}
if (plugin.isPlaceholderAPIEnabled() && placeholder.contains("%")
&& !placeholder.equals(me.clip.placeholderapi.PlaceholderAPI.setPlaceholders((OfflinePlayer) player, placeholder))) {
return JobsPlaceholderType.PAPI;
}
// For MVdWPlaceholderAPI
// if (plugin.isMVdWPlaceholderAPIEnabled()) {
// if (placeholder.contains("{"))
// if (!placeholder.equals(be.maximvdw.placeholderapi.PlaceholderAPI.replacePlaceholders(player, placeholder)))
// return CMIPlaceholderType.MVDW;
return null;
}
public String updatePlaceHolders(Player player, String message) {
if (message == null)
return null;
if (message.contains("%")) {
message = translateOwnPlaceHolder(player, message);
if (plugin.isPlaceholderAPIEnabled()) {
message = me.clip.placeholderapi.PlaceholderAPI.setPlaceholders((OfflinePlayer) player, message);
}
}
// For MVdWPlaceholderAPI
// if (plugin.isMVdWPlaceholderAPIEnabled()) {
// if (message.contains("{"))
// message = be.maximvdw.placeholderapi.PlaceholderAPI.replacePlaceholders(player, message);
return message;
}
private String translateOwnPlaceHolder(Player player, String message) {
if (message == null)
return null;
if (message.contains("%")) {
Matcher match = placeholderPatern.matcher(message);
while (match.find()) {
if (!message.contains("%"))
break;
JobsPlaceHolders place = JobsPlaceHolders.getByNameExact(match.group(2));
if (place == null)
continue;
String group = match.group();
String with = getValue(player, place, group);
if (with == null)
with = "";
if (with.startsWith("$"))
with = "\\" + with;
message = message.replaceFirst(group, with);
}
}
return message;
}
public String getValue(Player player, JobsPlaceHolders placeHolder) {
return getValue(player, placeHolder, null);
}
public String getValue(Player player, JobsPlaceHolders placeHolder, String value) {
return getValue(player != null ? player.getUniqueId() : null, placeHolder, value);
}
private static JobProgression getProgFromValue(JobsPlayer user, String value) {
try {
int id = Integer.parseInt(value);
if (id > 0)
return user.progression.get(id - 1);
} catch (IndexOutOfBoundsException | NumberFormatException e) {
Job job = Jobs.getJob(value);
if (job != null)
return user.getJobProgression(job);
}
return null;
}
private static Job getJobFromValue(String value) {
try {
int id = Integer.parseInt(value);
if (id > 0)
return Jobs.getJobs().get(id - 1);
} catch (IndexOutOfBoundsException | NumberFormatException e) {
return Jobs.getJob(value);
}
return null;
}
private String simplifyDouble(double value) {
return String.valueOf((int) (value * 100) / 100D);
}
public String getValue(UUID uuid, JobsPlaceHolders placeHolder, String value) {
if (placeHolder == null)
return null;
JobsPlayer user = uuid == null ? null : Jobs.getPlayerManager().getJobsPlayer(uuid);
// Placeholders by JobsPlayer object
if (user != null) {
NumberFormat format = NumberFormat.getInstance(Locale.ENGLISH);
switch (placeHolder) {
case user_dailyquests_pending:
Integer pendingQuests = (int) user.getQuestProgressions().stream().filter(q -> !q.isCompleted()).count();
return Integer.toString(pendingQuests);
case user_dailyquests_completed:
Integer completedQuests = (int) user.getQuestProgressions().stream().filter(q -> q.isCompleted()).count();
return Integer.toString(completedQuests);
case user_dailyquests_total:
return Integer.toString(user.getQuestProgressions().size());
case user_id:
return Integer.toString(user.getUserId());
case user_bstandcount:
return Integer.toString(user.getBrewingStandCount());
case user_maxbstandcount:
return Integer.toString(user.getMaxOwnerShipAllowed(BlockTypes.BREWING_STAND));
case user_furncount:
return Integer.toString(user.getFurnaceCount());
case user_maxfurncount:
return Integer.toString(user.getMaxOwnerShipAllowed(BlockTypes.FURNACE));
case user_smokercount:
Optional<BlockOwnerShip> blastSmoker = plugin.getBlockOwnerShip(BlockTypes.SMOKER);
return !blastSmoker.isPresent() ? "0" : Integer.toString(blastSmoker.get().getTotal(uuid));
case user_maxsmokercount:
return Integer.toString(user.getMaxOwnerShipAllowed(BlockTypes.SMOKER));
case user_blastcount:
Optional<BlockOwnerShip> blastShip = plugin.getBlockOwnerShip(BlockTypes.BLAST_FURNACE);
return !blastShip.isPresent() ? "0" : Integer.toString(blastShip.get().getTotal(uuid));
case user_maxblastcount:
return Integer.toString(user.getMaxOwnerShipAllowed(BlockTypes.BLAST_FURNACE));
case user_doneq:
return Integer.toString(user.getDoneQuests());
case user_seen:
return TimeManage.to24hourShort(System.currentTimeMillis() - user.getSeen());
case user_totallevels:
return Integer.toString(user.getTotalLevels());
case user_points:
return new DecimalFormat("00.0").format(user.getPointsData().getCurrentPoints());
case user_points_fixed:
return Integer.toString((int) user.getPointsData().getCurrentPoints());
case user_total_points:
return format.format(user.getPointsData().getTotalPoints());
case user_issaved:
return convert(user.isSaved());
case user_displayhonorific:
return user.getDisplayHonorific();
case user_joinedjobcount:
return Integer.toString(user.progression.size());
case user_archived_jobs:
return Integer.toString(user.getArchivedJobs().getArchivedJobs().size());
case user_jobs:
String jobNames = "";
for (JobProgression prog : user.progression) {
if (!jobNames.isEmpty()) {
jobNames += ", ";
}
jobNames += prog.getJob().getName();
}
return jobNames;
case user_quests:
String q = "";
for (QuestProgression questProg : user.getQuestProgressions()) {
Quest quest = questProg.getQuest();
if (quest == null || quest.isStopped()) {
continue;
}
if (!q.isEmpty()) {
q += ", ";
}
q += quest.getQuestName();
}
return q;
default:
break;
}
if (placeHolder.isComplex()) {
List<String> vals = placeHolder.getComplexValues(value);
if (vals.isEmpty())
return "";
String keyValue = vals.get(0);
JobProgression j = getProgFromValue(user, keyValue);
Job job = getJobFromValue(keyValue);
switch (placeHolder) {
case limit_$1:
return Integer.toString(user.getLimit(CurrencyType.getByName(keyValue)));
case plimit_$1:
return Double.toString(user.getPaymentLimit().getAmount(CurrencyType.getByName(keyValue)));
case plimit_tleft_$1:
return TimeManage.to24hourShort(user.getPaymentLimit().getLeftTime(CurrencyType.getByName(keyValue)));
case user_jlevel_$1:
return j == null ? "0" : j.getLevelFormatted();
case user_jexp_$1:
return j == null ? "0" : format.format(j.getExperience());
case user_jmexp_$1:
return j == null ? "0" : format.format(j.getMaxExperience() - j.getExperience());
case user_jprogress_$1:
return j == null ? "" : Jobs.getCommandManager().jobProgressMessage(j.getMaxExperience(), j.getExperience());
case user_jexp_rounded_$1:
return j == null ? "0" : new DecimalFormat("
case user_jmaxexp_$1:
return j == null ? "0" : format.format(j.getMaxExperience());
case user_jexpunf_$1:
return j == null ? "0" : Double.toString(j.getExperience());
case user_jmaxexpunf_$1:
return j == null ? "0" : Integer.toString(j.getMaxExperience());
case user_jmaxlvl_$1:
return j == null ? "0" : Integer.toString(j.getJob().getMaxLevel(user));
case user_boost_$1_$2:
return (vals.size() < 2 || j == null) ? "" : simplifyDouble(user.getBoost(j.getJob().getName(),
CurrencyType.getByName(vals.get(1))));
case user_jtoplvl_$1_$2:
if (vals.size() < 2 || job == null)
return "";
try {
jobLevel.set(Integer.parseInt(vals.get(1)));
} catch (NumberFormatException e) {
return "";
}
return CompletableFuture.supplyAsync(() -> {
for (TopList l : Jobs.getJobsDAO().getGlobalTopList(jobLevel.get())) {
if (l.getPlayerInfo().getName().equals(user.getName())) {
JobProgression prog = l.getPlayerInfo().getJobsPlayer().getJobProgression(job);
return prog == null ? "" : prog.getLevelFormatted();
}
}
return "";
}).join();
case user_isin_$1:
return job == null ? "no" : convert(user.isInJob(job));
case user_job_$1:
return j == null ? "" : j.getJob().getName();
case user_title_$1:
if (j == null)
return "";
Title title = Jobs.getTitleManager().getTitle(j.getLevel(), j.getJob().getName());
return title == null ? "" : title.getChatColor() + title.getName();
case user_archived_jobs_level_$1:
if (job == null) {
return "";
}
JobProgression archivedJobProg = user.getArchivedJobProgression(job);
return archivedJobProg == null ? "" : archivedJobProg.getLevelFormatted();
case user_archived_jobs_exp_$1:
if (job == null)
return "";
JobProgression archivedJobProgression = user.getArchivedJobProgression(job);
return archivedJobProgression == null ? "0" : Double.toString(archivedJobProgression.getExperience());
default:
break;
}
}
// Placeholders by player object
if (user.isOnline()) {
Player player = user.getPlayer();
if (player != null) {
switch (placeHolder) {
case user_canjoin_$1:
List<String> values = placeHolder.getComplexValues(value);
if (values.isEmpty())
return "";
Job job = getJobFromValue(values.get(0));
if (job == null)
return "";
if (!Jobs.getCommandManager().hasJobPermission(player, job) || user.isInJob(job))
return convert(false);
if (job.getMaxSlots() != null && Jobs.getUsedSlots(job) >= job.getMaxSlots())
return convert(false);
int confMaxJobs = Jobs.getGCManager().getMaxJobs();
short playerMaxJobs = (short) user.progression.size();
return convert(confMaxJobs > 0 && playerMaxJobs >= confMaxJobs
&& !Jobs.getPlayerManager().getJobsLimit(user, playerMaxJobs));
case maxjobs:
return Integer.toString(Jobs.getPlayerManager().getMaxJobs(user));
default:
break;
}
}
}
}
if (placeHolder.isComplex()) {
List<String> values = placeHolder.getComplexValues(value);
if (values.isEmpty())
return "";
Job jo = getJobFromValue(values.get(0));
if (jo == null)
return "";
// Global placeholders by jobname
switch (placeHolder) {
case name_$1:
return jo.getName();
case shortname_$1:
return jo.getShortName();
case chatcolor_$1:
return jo.getChatColor().toString();
case description_$1:
return jo.getDescription();
case maxdailyq_$1:
return Integer.toString(jo.getMaxDailyQuests());
case maxlvl_$1:
return Integer.toString(jo.getMaxLevel());
case maxviplvl_$1:
return Integer.toString(jo.getVipMaxLevel());
case bonus_$1:
return Double.toString(jo.getBonus());
case totalplayers_$1:
return Integer.toString(jo.getTotalPlayers());
case maxslots_$1:
return Integer.toString(jo.getMaxSlots());
default:
break;
}
}
// Global placeholders
switch (placeHolder) {
case maxjobs:
return Integer.toString(Jobs.getPlayerManager().getMaxJobs(user));
case total_workers:
return Integer.toString(Jobs.getJobsDAO().getTotalPlayers());
default:
break;
}
return null;
}
private static String convert(boolean state) {
return Jobs.getLanguage().getMessage("general.info." + (state ? "true" : "false"));
}
}
|
package org.jboss.as.model.test;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ALTERNATIVES;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ATTRIBUTE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ATTRIBUTES;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.COMPOSITE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.FAILED;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.FAILURE_DESCRIPTION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NILLABLE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OPERATIONS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OUTCOME;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.REPLY_PROPERTIES;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.REQUEST_PROPERTIES;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.REQUIRED;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESULT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.STEPS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUCCESS;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.net.URL;
import java.util.ArrayList;
import java.nio.charset.StandardCharsets;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import java.util.TreeSet;
import java.util.regex.Pattern;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.ModelVersion;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.controller.registry.AttributeAccess;
import org.jboss.as.controller.registry.ImmutableManagementResourceRegistration;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.transform.OperationTransformer.TransformedOperation;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
import org.jboss.dmr.Property;
import org.junit.Assert;
import org.w3c.dom.Document;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSInput;
import org.w3c.dom.ls.LSParser;
import org.w3c.dom.ls.LSSerializer;
/**
*
* @author <a href="kabir.khan@jboss.com">Kabir Khan</a>
*/
public class ModelTestUtils {
private static final Pattern EXPRESSION_PATTERN = Pattern.compile(".*\\$\\{.*\\}.*");
/**
* Read the classpath resource with the given name and return its contents as a string. Hook to
* for reading in classpath resources for subsequent parsing. The resource is loaded using similar
* semantics to {@link Class#getResource(String)}
*
* @param name the name of the resource
* @return the contents of the resource as a string
* @throws IOException
*/
public static String readResource(final Class<?> clazz, final String name) throws IOException {
URL configURL = clazz.getResource(name);
Assert.assertNotNull(name + " url is null", configURL);
StringWriter writer = new StringWriter();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(configURL.openStream(), StandardCharsets.UTF_8))){
String line;
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.write("\n");
}
}
return writer.toString();
}
/**
* Checks that the result was successful and gets the real result contents
*
* @param result the result to check
* @return the result contents
*/
public static ModelNode checkResultAndGetContents(ModelNode result) {
checkOutcome(result);
Assert.assertTrue("could not check for result as its missing! look for yourself here [" + result.toString() +
"] and result.hasDefined(RESULT) returns " + result.hasDefined(RESULT)
, result.hasDefined(RESULT));
return result.get(RESULT);
}
/**
* Checks that the result was successful
*
* @param result the result to check
* @return the result contents
*/
public static ModelNode checkOutcome(ModelNode result) {
boolean success = SUCCESS.equals(result.get(OUTCOME).asString());
Assert.assertTrue(result.get(FAILURE_DESCRIPTION).asString(), success);
return result;
}
/**
* Checks that the operation failes
*
* @param result the result to check
* @return the failure desciption contents
*/
public static ModelNode checkFailed(ModelNode result) {
Assert.assertEquals(FAILED, result.get(OUTCOME).asString());
return result.get(FAILURE_DESCRIPTION);
}
public static void validateModelDescriptions(PathAddress address, ImmutableManagementResourceRegistration reg) {
ModelNode description = reg.getModelDescription(PathAddress.EMPTY_ADDRESS).getModelDescription(Locale.getDefault());
ModelNode attributes = description.get(ATTRIBUTES);
Set<String> regAttributeNames = reg.getAttributeNames(PathAddress.EMPTY_ADDRESS);
Set<String> attributeNames = new HashSet<String>();
if (attributes.isDefined()) {
if (attributes.asList().size() != regAttributeNames.size()) {
for (Property p : attributes.asPropertyList()) {
attributeNames.add(p.getName());
}
if (regAttributeNames.size() > attributeNames.size()) {
regAttributeNames.removeAll(attributeNames);
Assert.fail("More attributes defined on resource registration than in description, missing: " + regAttributeNames + " for " + address);
} else if (regAttributeNames.size() < attributeNames.size()) {
attributeNames.removeAll(regAttributeNames);
Assert.fail("More attributes defined in description than on resource registration, missing: " + attributeNames + " for " + address);
}
}
Map<String, ModelNode> attrMap = new LinkedHashMap<>();
for (Property p : attributes.asPropertyList()) {
attrMap.put(p.getName(), p.getValue());
}
attributeNames = attrMap.keySet();
if (!attributeNames.containsAll(regAttributeNames)) {
Set<String> missDesc = new HashSet<String>(attributeNames);
missDesc.removeAll(regAttributeNames);
Set<String> missReg = new HashSet<String>(regAttributeNames);
missReg.removeAll(attributeNames);
if (!missReg.isEmpty()) {
Assert.fail("There are different attributes defined on resource registration than in description, registered only on Resource Reg: " + missReg + " for " + address);
}
if (!missDesc.isEmpty()) {
Assert.fail("There are different attributes defined on resource registration than in description, registered only int description: " + missDesc + " for " + address);
}
}
for (Map.Entry<String, ModelNode> entry : attrMap.entrySet()) {
validateRequiredNillable(ATTRIBUTE + " " + entry.getKey(), entry.getValue());
}
}
if (description.hasDefined(OPERATIONS)) {
ModelNode operations = description.get(OPERATIONS);
// TODO compare operation descriptions to the MRR (e.g. same names)
for (Property property : operations.asPropertyList()) {
ModelNode opDesc = property.getValue();
if (opDesc.hasDefined(REQUEST_PROPERTIES)) {
String prefix = "operation " + property.getName() + " param ";
for (Property param : opDesc.get(REQUEST_PROPERTIES).asPropertyList()) {
validateRequiredNillable(prefix + param.getName(), param.getValue());
}
}
if (opDesc.hasDefined(REPLY_PROPERTIES)) {
String prefix = "operation " + property.getName() + " reply field ";
for (Property field : opDesc.get(REPLY_PROPERTIES).asPropertyList()) {
validateRequiredNillable(prefix + field.getName(), field.getValue());
}
}
}
}
for (PathElement pe : reg.getChildAddresses(PathAddress.EMPTY_ADDRESS)) {
ImmutableManagementResourceRegistration sub = reg.getSubModel(PathAddress.pathAddress(pe));
validateModelDescriptions(address.append(pe), sub);
}
}
private static void validateRequiredNillable(String name, ModelNode desc) {
Assert.assertTrue(name + " does not have 'required' metadata", desc.hasDefined(REQUIRED));
Assert.assertEquals(name + " does not have boolean 'required' metadata", ModelType.BOOLEAN, desc.get(REQUIRED).getType());
Assert.assertTrue(name + " does not have 'nillable' metadata", desc.hasDefined(NILLABLE));
Assert.assertEquals(name + " does not have boolean 'nillable' metadata", ModelType.BOOLEAN, desc.get(NILLABLE).getType());
boolean alternatives = false;
if (desc.hasDefined(ALTERNATIVES)) {
Assert.assertEquals(name + " does not have 'alternatives' metadata in list form", ModelType.LIST, desc.get(ALTERNATIVES).getType());
alternatives = desc.get(ALTERNATIVES).asInt() > 0;
}
boolean required = desc.get(REQUIRED).asBoolean();
Assert.assertEquals(name + " does not have correct 'nillable' metadata. required: " + required + " -- alternatives: " + desc.get(ALTERNATIVES),
!required || alternatives, desc.get("nillable").asBoolean());
}
/**
* Compares two models to make sure that they are the same
*
* @param node1 the first model
* @param node2 the second model
*/
public static void compare(ModelNode node1, ModelNode node2) {
compare(node1, node2, false);
}
/**
* Resolve two models and compare them to make sure that they have same
content after expression resolution
*
* @param node1 the first model
* @param node2 the second model
*/
public static void resolveAndCompareModels(ModelNode node1, ModelNode node2) {
compare(node1.resolve(), node2.resolve(), false, true, new Stack<String>());
}
/**
* Compares two models to make sure that they are the same
*
* @param node1 the first model
* @param node2 the second model
* @param ignoreUndefined {@code true} if keys containing undefined nodes should be ignored
*/
public static void compare(ModelNode node1, ModelNode node2, boolean ignoreUndefined) {
compare(node1, node2, ignoreUndefined, false, new Stack<String>());
}
/**
* Normalize and pretty-print XML so that it can be compared using string
* compare. The following code does the following: - Removes comments -
* Makes sure attributes are ordered consistently - Trims every element -
* Pretty print the document
*
* @param xml The XML to be normalized
* @return The equivalent XML, but now normalized
*/
public static String normalizeXML(String xml) throws Exception {
// Remove all white space adjoining tags ("trim all elements")
xml = xml.replaceAll("\\s*<", "<");
xml = xml.replaceAll(">\\s*", ">");
DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
DOMImplementationLS domLS = (DOMImplementationLS) registry.getDOMImplementation("LS");
LSParser lsParser = domLS.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);
LSInput input = domLS.createLSInput();
input.setStringData(xml);
Document document = lsParser.parse(input);
LSSerializer lsSerializer = domLS.createLSSerializer();
lsSerializer.getDomConfig().setParameter("comments", Boolean.FALSE);
lsSerializer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
return lsSerializer.writeToString(document);
}
/**
* Validate the marshalled xml without adjusting the namespaces for the original and marshalled xml.
*
* @param original the original subsystem xml
* @param marshalled the marshalled subsystem xml
* @throws Exception
*/
public static void compareXml(final String original, final String marshalled) throws Exception {
compareXml(original, marshalled, false);
}
/**
* Validate the marshalled xml without adjusting the namespaces for the original and marshalled xml.
*
* @param original the original subsystem xml
* @param marshalled the marshalled subsystem xml
* @param ignoreNamespace if {@code true} the subsystem's namespace is ignored, otherwise it is taken into account when comparing the normalized xml.
* @throws Exception
*/
public static void compareXml(final String original, final String marshalled, final boolean ignoreNamespace) throws Exception {
final String xmlOriginal;
final String xmlMarshalled;
if (ignoreNamespace) {
xmlOriginal = removeNamespace(original);
xmlMarshalled = removeNamespace(marshalled);
} else {
xmlOriginal = original;
xmlMarshalled = marshalled;
}
Assert.assertEquals(normalizeXML(xmlOriginal), normalizeXML(xmlMarshalled));
}
public static ModelNode getSubModel(ModelNode model, PathElement pathElement) {
return model.get(pathElement.getKey(), pathElement.getValue());
}
public static ModelNode getSubModel(ModelNode model, PathAddress pathAddress) {
for (PathElement pathElement : pathAddress) {
model = getSubModel(model, pathElement);
}
return model;
}
/**
* Scans for entries of type STRING containing expression formatted strings. This is to trap where parsers
* call ModelNode.set("${A}") when ModelNode.setExpression("${A}) should have been used
*
* @param model the model to check
*/
public static void scanForExpressionFormattedStrings(ModelNode model) {
if (model.getType().equals(ModelType.STRING)) {
if (EXPRESSION_PATTERN.matcher(model.asString()).matches()) {
Assert.fail("ModelNode with type==STRING contains an expression formatted string: " + model.asString());
}
} else if (model.getType() == ModelType.OBJECT) {
for (String key : model.keys()) {
final ModelNode child = model.get(key);
scanForExpressionFormattedStrings(child);
}
} else if (model.getType() == ModelType.LIST) {
List<ModelNode> list = model.asList();
for (ModelNode entry : list) {
scanForExpressionFormattedStrings(entry);
}
} else if (model.getType() == ModelType.PROPERTY) {
Property prop = model.asProperty();
scanForExpressionFormattedStrings(prop.getValue());
}
}
private static String removeNamespace(String xml) {
int start = xml.indexOf(" xmlns=\"");
int end = xml.indexOf('"', start + "xmlns=\"".length() + 1);
if (start != -1) {
StringBuilder sb = new StringBuilder(xml.substring(0, start));
sb.append(xml.substring(end + 1));
return sb.toString();
}
return xml;
}
private static void compare(ModelNode node1, ModelNode node2, boolean ignoreUndefined, boolean ignoreType, Stack<String> stack) {
if (! ignoreType) {
Assert.assertEquals(getCompareStackAsString(stack) + " types", node1.getType(), node2.getType());
}
if (node1.getType() == ModelType.OBJECT) {
ModelNode model1 = ignoreUndefined ? trimUndefinedChildren(node1) : node1;
ModelNode model2 = ignoreUndefined ? trimUndefinedChildren(node2) : node2;
final Set<String> keys1 = new TreeSet<String>(model1.keys());
final Set<String> keys2 = new TreeSet<String>(model2.keys());
// compare string representations of the keys to help see the difference
if (!keys1.toString().equals(keys2.toString())){
//Just to make debugging easier
System.out.print("");
}
Assert.assertEquals(getCompareStackAsString(stack) + ": " + node1 + "\n" + node2, keys1.toString(), keys2.toString());
Assert.assertTrue(keys1.containsAll(keys2));
for (String key : keys1) {
final ModelNode child1 = model1.get(key);
Assert.assertTrue("Missing: " + key + "\n" + node1 + "\n" + node2, model2.has(key));
final ModelNode child2 = model2.get(key);
if (child1.isDefined()) {
if (!ignoreUndefined) {
Assert.assertTrue(getCompareStackAsString(stack) + " key=" + key + "\n with child1 \n" + child1.toString() + "\n has child2 not defined\n node2 is:\n" + node2.toString(), child2.isDefined());
}
stack.push(key + "/");
compare(child1, child2, ignoreUndefined, ignoreType, stack);
stack.pop();
} else if (!ignoreUndefined) {
Assert.assertFalse(getCompareStackAsString(stack) + " key=" + key + "\n with child1 undefined has child2 \n" + child2.asString(), child2.isDefined());
}
}
} else if (node1.getType() == ModelType.LIST) {
List<ModelNode> list1 = node1.asList();
List<ModelNode> list2 = node2.asList();
Assert.assertEquals(list1 + "\n" + list2, list1.size(), list2.size());
for (int i = 0; i < list1.size(); i++) {
stack.push(i + "/");
compare(list1.get(i), list2.get(i), ignoreUndefined, ignoreType, stack);
stack.pop();
}
} else if (node1.getType() == ModelType.PROPERTY) {
Property prop1 = node1.asProperty();
Property prop2 = node2.asProperty();
Assert.assertEquals(prop1 + "\n" + prop2, prop1.getName(), prop2.getName());
stack.push(prop1.getName() + "/");
compare(prop1.getValue(), prop2.getValue(), ignoreUndefined, ignoreType, stack);
stack.pop();
} else {
Assert.assertEquals(getCompareStackAsString(stack) +
"\n\"" + node1.asString() + "\"\n\"" + node2.asString() + "\"\n
}
}
private static ModelNode trimUndefinedChildren(ModelNode model) {
ModelNode copy = model.clone();
for (String key : new HashSet<String>(copy.keys())) {
if (!copy.hasDefined(key)) {
copy.remove(key);
} else if (copy.get(key).getType() == ModelType.OBJECT) {
boolean undefined = true;
for (ModelNode mn : model.get(key).asList()) {
Property p = mn.asProperty();
if (p.getValue().getType() != ModelType.OBJECT) { continue; }
for (String subKey : new HashSet<String>(p.getValue().keys())) {
if (copy.get(key, p.getName()).hasDefined(subKey)) {
undefined = false;
break;
} else {
copy.get(key, p.getName()).remove(subKey);
}
}
if (undefined) {
copy.get(key).remove(p.getName());
if (!copy.hasDefined(key)) {
copy.remove(key);
} else if (copy.get(key).getType() == ModelType.OBJECT) { //this is stupid workaround
if (copy.get(key).keys().size() == 0) {
copy.remove(key);
}
}
}
}
}
}
return copy;
}
private static String getCompareStackAsString(Stack<String> stack) {
StringBuilder buf = new StringBuilder();
for (String element : stack) {
buf.append(element);
}
return buf.toString();
}
public static void checkModelAgainstDefinition(final ModelNode model, ManagementResourceRegistration rr) {
checkModelAgainstDefinition(model, rr, new Stack<PathElement>());
}
private static void checkModelAgainstDefinition(final ModelNode model, ManagementResourceRegistration rr, Stack<PathElement> stack) {
final Set<String> children = rr.getChildNames(PathAddress.EMPTY_ADDRESS);
final Set<String> attributeNames = rr.getAttributeNames(PathAddress.EMPTY_ADDRESS);
for (ModelNode el : model.asList()) {
String name = el.asProperty().getName();
ModelNode value = el.asProperty().getValue();
if (attributeNames.contains(name)) {
AttributeAccess aa = rr.getAttributeAccess(PathAddress.EMPTY_ADDRESS, name);
Assert.assertNotNull(getComparePathAsString(stack) + " Attribute " + name + " is not known", aa);
AttributeDefinition ad = aa.getAttributeDefinition();
if (!value.isDefined()) {
// check if the attribute definition allows null *or* if its default value is null
Assert.assertTrue(getComparePathAsString(stack) + " Attribute " + name + " does not allow null", (!ad.isRequired() || ad.getDefaultValue() == null));
} else {
// Assert.assertEquals("Attribute '" + name + "' type mismatch", value.getType(), ad.getType()); //todo re-enable this check
}
try {
if (ad.isRequired() && value.isDefined()){
ad.getValidator().validateParameter(name, value);
}
} catch (OperationFailedException e) {
Assert.fail(getComparePathAsString(stack) + " validation for attribute '" + name + "' failed, " + e.getFailureDescription().asString());
}
} else if (!children.contains(name)) {
Assert.fail(getComparePathAsString(stack) + " Element '" + name + "' is not known in target definition");
}
}
for (PathElement pe : rr.getChildAddresses(PathAddress.EMPTY_ADDRESS)) {
if (pe.isWildcard()) {
if (children.contains(pe.getKey()) && model.hasDefined(pe.getKey())) {
for (ModelNode v : model.get(pe.getKey()).asList()) {
String name = v.asProperty().getName();
ModelNode value = v.asProperty().getValue();
ManagementResourceRegistration sub = rr.getSubModel(PathAddress.pathAddress(pe));
Assert.assertNotNull(getComparePathAsString(stack) + " Child with name '" + name + "' not found", sub);
if (value.isDefined()) {
stack.push(pe);
checkModelAgainstDefinition(value, sub, stack);
stack.pop();
}
}
}
} else {
if (children.contains(pe.getKey()) && model.hasDefined(pe.getKey()) && model.get(pe.getKey()).hasDefined(pe.getValue())) {
String name = pe.getValue();
ModelNode value = model.get(pe.getKeyValuePair());
ManagementResourceRegistration sub = rr.getSubModel(PathAddress.pathAddress(pe));
Assert.assertNotNull(getComparePathAsString(stack) + " Child with name '" + name + "' not found", sub);
if (value.isDefined()) {
stack.push(pe);
checkModelAgainstDefinition(value, sub, stack);
stack.pop();
}
}
}
}
}
private static String getComparePathAsString(Stack<PathElement> stack) {
PathAddress pa = PathAddress.EMPTY_ADDRESS;
for (PathElement element : stack) {
pa = pa.append(element);
}
return pa.toModelNode().asString();
}
/**
* <P>A standard test for transformers where things should be rejected.
* Takes the operations and installs them in the main controller.
* </P>
* <P>
* It then attempts to transform the same operations for the legacy controller, validating that expected
* failures take place.
* It then attempts to fix the operations so they can be executed in the legacy controller, since if an 'add' fails,
* there could be adds for children later in the list.
* </P>
* <P>
* Internally the operations (both for the main and legacy controllers) are added to a composite so that we have
* everything we need if any versions of the subsystem use capabilities and requirements. Normally this composite
* will contain the original operations that have been fixed by the {@code config}. This composite is then transformed
* before executing it in the legacy controller. However, in some extreme cases the one-shot transformation of the
* composite intended for the legacy controller may not be possible. For these cases you can call
* {@link FailedOperationTransformationConfig#setDontTransformComposite()} and the individually transformed operations
* get added to the composite, which is then used as-is (without any transformation).
* </P>
* <P>
* To configure a callback that gets executed before the composite is transformed for the legacy controller,
* and executed there, you can call
* {@link FailedOperationTransformationConfig#setCallback(FailedOperationTransformationConfig.BeforeExecuteCompositeCallback)}.
* </P>
*
* @param mainServices The main controller services
* @param modelVersion The version of the legacy controller
* @param operations the operations
* @param config the config
*/
public static void checkFailedTransformedBootOperations(ModelTestKernelServices<?> mainServices,
ModelVersion modelVersion, List<ModelNode> operations,
FailedOperationTransformationConfig config) throws OperationFailedException {
//Create a composite to execute all the boot operations in the main controller.
//We execute the operations in the main controller to make sure it is a valid config in the main controller
//The reason this needs to be a composite is that an add operation for a resource might have a reference on
//a capability introduced by a later add operation, and the controller has already started
final ModelNode mainComposite = Util.createEmptyOperation(COMPOSITE, PathAddress.EMPTY_ADDRESS);
final ModelNode mainSteps = mainComposite.get(STEPS).setEmptyList();
for (ModelNode op : operations) {
mainSteps.add(op.clone());
}
Assert.assertEquals(operations, mainSteps.asList());
ModelTestUtils.checkOutcome(mainServices.executeOperation(mainComposite));
//Next check the transformations of the operations for the legacy controller, fixing them up from the config when
//they are rejected.
//We gather all the transformed operations into a composite which we then execute in the legacy controller. The
//reason this is a composite is the same as for the main controller.
final ModelNode legacyComposite = Util.createEmptyOperation(COMPOSITE, PathAddress.EMPTY_ADDRESS);
final ModelNode legacySteps = legacyComposite.get(STEPS).setEmptyList();
//We also check all the attributes by executing write operations after we have created the legacy composite.
//Let's gather these while checking rejections of the ops, and creating the legacy composite.
final List<ModelNode> writeOps = new ArrayList<>();
for (ModelNode op : operations) {
writeOps.addAll(config.createWriteAttributeOperations(op));
checkFailedTransformedAddOperation(mainServices, modelVersion, op, config, legacySteps);
}
config.invokeCallback();
if (config.isTransformComposite()) {
//Transform and execute the composite
TransformedOperation transformedComposite = mainServices.transformOperation(modelVersion, legacyComposite);
if (transformedComposite.rejectOperation(successResult())) {
Assert.fail(transformedComposite.getFailureDescription());
}
ModelTestUtils.checkOutcome(mainServices.executeOperation(modelVersion, transformedComposite));
} else {
//The composite already contains the transformed operations
ModelTestKernelServices<?> legacyServices = mainServices.getLegacyServices(modelVersion);
ModelTestUtils.checkOutcome(legacyServices.executeOperation(legacyComposite));
}
//Check all the write ops
for (ModelNode writeOp : writeOps) {
checkFailedTransformedWriteAttributeOperation(mainServices, modelVersion, writeOp, config);
}
}
private static void checkFailedTransformedAddOperation(
ModelTestKernelServices<?> mainServices, ModelVersion modelVersion,
ModelNode operation, FailedOperationTransformationConfig config, ModelNode legacySteps) throws OperationFailedException {
TransformedOperation transformedOperation = mainServices.transformOperation(modelVersion, operation.clone());
if (config.expectFailed(operation)) {
Assert.assertTrue("Expected transformation to get rejected " + operation + " for version " + modelVersion, transformedOperation.rejectOperation(successResult()));
Assert.assertNotNull("Expected transformation to get rejected " + operation + " for version " + modelVersion , transformedOperation.getFailureDescription());
if (config.canCorrectMore(operation)) {
checkFailedTransformedAddOperation(mainServices, modelVersion, config.correctOperation(operation), config, legacySteps);
}
} else if (config.expectDiscarded(operation)) {
Assert.assertNull("Expected null transformed operation for discarded " + operation, transformedOperation.getTransformedOperation());
Assert.assertFalse("Expected transformation to not be rejected for discarded " + operation, transformedOperation.rejectOperation(successResult()));
} else {
if (transformedOperation.rejectOperation(successResult())) {
Assert.fail(operation + " should not have been rejected " + transformedOperation.getFailureDescription());
}
Assert.assertFalse(config.canCorrectMore(operation));
config.operationDone(operation);
if (config.isTransformComposite()) {
//Add the original operation here since the legacy composite as a whole
// will be transformed by checkFailedTransformedBootOperations()
legacySteps.add(operation);
} else {
ModelNode transformed = transformedOperation.getTransformedOperation();
if (transformed != null) {
legacySteps.add(transformed);
}
}
}
}
private static void checkFailedTransformedWriteAttributeOperation(ModelTestKernelServices<?> mainServices, ModelVersion modelVersion, ModelNode operation, FailedOperationTransformationConfig config) throws OperationFailedException {
TransformedOperation transformedOperation = mainServices.transformOperation(modelVersion, operation.clone());
if (config.expectFailedWriteAttributeOperation(operation)) {
Assert.assertNotNull("Expected transformation to get rejected " + operation, transformedOperation.getFailureDescription());
//For write-attribute we currently only correct once, all in one go
checkFailedTransformedWriteAttributeOperation(mainServices, modelVersion, config.correctWriteAttributeOperation(operation), config);
} else {
ModelNode result = mainServices.executeOperation(modelVersion, transformedOperation);
Assert.assertEquals("Failed: " + operation + "\n: " + result, SUCCESS, result.get(OUTCOME).asString());
}
}
private static ModelNode successResult() {
final ModelNode result = new ModelNode();
result.get(ModelDescriptionConstants.OUTCOME).set(ModelDescriptionConstants.SUCCESS);
result.get(ModelDescriptionConstants.RESULT);
return result;
}
}
|
package org.owasp.esapi.reference;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import javax.servlet.http.HttpSession;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.owasp.esapi.Authenticator;
import org.owasp.esapi.ESAPI;
import org.owasp.esapi.User;
import org.owasp.esapi.errors.AuthenticationException;
import org.owasp.esapi.errors.EncryptionException;
import org.owasp.esapi.http.MockHttpServletRequest;
import org.owasp.esapi.http.MockHttpServletResponse;
import org.owasp.esapi.http.MockHttpSession;
/**
* The Class UserTest.
*
* @author Jeff Williams (jeff.williams@aspectsecurity.com)
*/
public class UserTest extends TestCase {
/**
* Suite.
*
* @return the test
*/
public static Test suite() {
TestSuite suite = new TestSuite(UserTest.class);
return suite;
}
/**
* Instantiates a new user test.
*
* @param testName
* the test name
*/
public UserTest(String testName) {
super(testName);
}
/**
* Creates the test user.
*
* @param password
* the password
*
* @return the user
*
* @throws AuthenticationException
* the authentication exception
*/
private DefaultUser createTestUser(String password) throws AuthenticationException {
String username = ESAPI.randomizer().getRandomString(8, DefaultEncoder.CHAR_ALPHANUMERICS);
Exception e = new Exception();
System.out.println("Creating user " + username + " for " + e.getStackTrace()[1].getMethodName());
DefaultUser user = (DefaultUser) ESAPI.authenticator().createUser(username, password, password);
return user;
}
/**
* {@inheritDoc}
*
* @throws Exception
*/
protected void setUp() throws Exception {
// none
}
/**
* {@inheritDoc}
*
* @throws Exception
*/
protected void tearDown() throws Exception {
// none
}
/**
* Test of testAddRole method, of class org.owasp.esapi.User.
*
* @exception Exception
* any Exception thrown by testing addRole()
*/
public void testAddRole() throws Exception {
System.out.println("addRole");
Authenticator instance = ESAPI.authenticator();
String accountName = ESAPI.randomizer().getRandomString(8, DefaultEncoder.CHAR_ALPHANUMERICS);
String password = ESAPI.authenticator().generateStrongPassword();
String role = ESAPI.randomizer().getRandomString(8, DefaultEncoder.CHAR_LOWERS);
User user = instance.createUser(accountName, password, password);
user.addRole(role);
assertTrue(user.isInRole(role));
assertFalse(user.isInRole("ridiculous"));
}
/**
* Test of addRoles method, of class org.owasp.esapi.User.
*
* @throws AuthenticationException
* the authentication exception
*/
public void testAddRoles() throws AuthenticationException {
System.out.println("addRoles");
Authenticator instance = ESAPI.authenticator();
String oldPassword = instance.generateStrongPassword();
DefaultUser user = createTestUser(oldPassword);
Set set = new HashSet();
set.add("rolea");
set.add("roleb");
user.addRoles(set);
assertTrue(user.isInRole("rolea"));
assertTrue(user.isInRole("roleb"));
assertFalse(user.isInRole("ridiculous"));
}
/**
* Test of changePassword method, of class org.owasp.esapi.User.
*
* @throws Exception
* the exception
*/
public void testChangePassword() throws Exception {
System.out.println("changePassword");
Authenticator instance = ESAPI.authenticator();
String oldPassword = "Password12!@";
DefaultUser user = createTestUser(oldPassword);
System.out.println("Hash of " + oldPassword + " = " + ((FileBasedAuthenticator)instance).getHashedPassword(user));
String password1 = "SomethingElse34
user.changePassword(oldPassword, password1, password1);
System.out.println("Hash of " + password1 + " = " + ((FileBasedAuthenticator)instance).getHashedPassword(user));
assertTrue(user.verifyPassword(password1));
String password2 = "YetAnother56%^";
user.changePassword(password1, password2, password2);
System.out.println("Hash of " + password2 + " = " + ((FileBasedAuthenticator)instance).getHashedPassword(user));
try {
user.changePassword(password2, password1, password1);
fail("Shouldn't be able to reuse a password");
} catch( AuthenticationException e ) {
// expected
}
assertTrue(user.verifyPassword(password2));
assertFalse(user.verifyPassword("badpass"));
}
/**
* Test of disable method, of class org.owasp.esapi.User.
*
* @throws AuthenticationException
* the authentication exception
*/
public void testDisable() throws AuthenticationException {
System.out.println("disable");
Authenticator instance = ESAPI.authenticator();
String oldPassword = instance.generateStrongPassword();
DefaultUser user = createTestUser(oldPassword);
user.enable();
assertTrue(user.isEnabled());
user.disable();
assertFalse(user.isEnabled());
}
/**
* Test of enable method, of class org.owasp.esapi.User.
*
* @throws AuthenticationException
* the authentication exception
*/
public void testEnable() throws AuthenticationException {
System.out.println("enable");
Authenticator instance = ESAPI.authenticator();
String oldPassword = instance.generateStrongPassword();
DefaultUser user = createTestUser(oldPassword);
user.enable();
assertTrue(user.isEnabled());
user.disable();
assertFalse(user.isEnabled());
}
/**
* Test of failedLoginCount lockout, of class org.owasp.esapi.User.
*
* @throws AuthenticationException
* the authentication exception
* @throws EncryptionException
* any EncryptionExceptions thrown by testing failedLoginLockout()
*/
public void testFailedLoginLockout() throws AuthenticationException, EncryptionException {
System.out.println("failedLoginLockout");
DefaultUser user = createTestUser("failedLoginLockout");
user.enable();
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
ESAPI.httpUtilities().setCurrentHTTP(request, response);
user.loginWithPassword("failedLoginLockout");
try {
user.loginWithPassword("ridiculous");
} catch( AuthenticationException e ) {
// expected
}
System.out.println("FAILED: " + user.getFailedLoginCount());
assertFalse(user.isLocked());
try {
user.loginWithPassword("ridiculous");
} catch( AuthenticationException e ) {
// expected
}
System.out.println("FAILED: " + user.getFailedLoginCount());
assertFalse(user.isLocked());
try {
user.loginWithPassword("ridiculous");
} catch( AuthenticationException e ) {
// expected
}
System.out.println("FAILED: " + user.getFailedLoginCount());
assertTrue(user.isLocked());
}
/**
* Test of getAccountName method, of class org.owasp.esapi.User.
*
* @throws AuthenticationException
* the authentication exception
*/
public void testGetAccountName() throws AuthenticationException {
System.out.println("getAccountName");
DefaultUser user = createTestUser("getAccountName");
String accountName = ESAPI.randomizer().getRandomString(7, DefaultEncoder.CHAR_ALPHANUMERICS);
user.setAccountName(accountName);
assertEquals(accountName.toLowerCase(), user.getAccountName());
assertFalse("ridiculous".equals(user.getAccountName()));
}
/**
* Test get last failed login time.
*
* @throws Exception
* the exception
*/
public void testGetLastFailedLoginTime() throws Exception {
System.out.println("getLastLoginTime");
Authenticator instance = ESAPI.authenticator();
String oldPassword = instance.generateStrongPassword();
DefaultUser user = createTestUser(oldPassword);
try {
user.loginWithPassword("ridiculous");
} catch( AuthenticationException e ) {
// expected
}
Date llt1 = user.getLastFailedLoginTime();
Thread.sleep(100); // need a short delay to separate attempts
try {
user.loginWithPassword("ridiculous");
} catch( AuthenticationException e ) {
// expected
}
Date llt2 = user.getLastFailedLoginTime();
assertTrue(llt1.before(llt2));
}
/**
* Test get last login time.
*
* @throws Exception
* the exception
*/
public void testGetLastLoginTime() throws Exception {
System.out.println("getLastLoginTime");
Authenticator instance = ESAPI.authenticator();
String oldPassword = instance.generateStrongPassword();
DefaultUser user = createTestUser(oldPassword);
user.verifyPassword(oldPassword);
Date llt1 = user.getLastLoginTime();
Thread.sleep(10); // need a short delay to separate attempts
user.verifyPassword(oldPassword);
Date llt2 = user.getLastLoginTime();
assertTrue(llt1.before(llt2));
}
/**
* Test getLastPasswordChangeTime method, of class org.owasp.esapi.User.
*
* @throws Exception
* the exception
*/
public void testGetLastPasswordChangeTime() throws Exception {
System.out.println("getLastPasswordChangeTime");
DefaultUser user = createTestUser("getLastPasswordChangeTime");
Date t1 = user.getLastPasswordChangeTime();
Thread.sleep(10); // need a short delay to separate attempts
String newPassword = ESAPI.authenticator().generateStrongPassword(user, "getLastPasswordChangeTime");
user.changePassword("getLastPasswordChangeTime", newPassword, newPassword);
Date t2 = user.getLastPasswordChangeTime();
assertTrue(t2.after(t1));
}
/**
* Test of getRoles method, of class org.owasp.esapi.User.
*
* @throws Exception
*/
public void testGetRoles() throws Exception {
System.out.println("getRoles");
Authenticator instance = ESAPI.authenticator();
String accountName = ESAPI.randomizer().getRandomString(8, DefaultEncoder.CHAR_ALPHANUMERICS);
String password = ESAPI.authenticator().generateStrongPassword();
String role = ESAPI.randomizer().getRandomString(8, DefaultEncoder.CHAR_LOWERS);
User user = instance.createUser(accountName, password, password);
user.addRole(role);
Set roles = user.getRoles();
assertTrue(roles.size() > 0);
}
/**
* Test of getScreenName method, of class org.owasp.esapi.User.
*
* @throws AuthenticationException
* the authentication exception
*/
public void testGetScreenName() throws AuthenticationException {
System.out.println("getScreenName");
DefaultUser user = createTestUser("getScreenName");
String screenName = ESAPI.randomizer().getRandomString(7, DefaultEncoder.CHAR_ALPHANUMERICS);
user.setScreenName(screenName);
assertEquals(screenName, user.getScreenName());
assertFalse("ridiculous".equals(user.getScreenName()));
}
/**
*
* @throws org.owasp.esapi.errors.AuthenticationException
*/
public void testGetSessions() throws AuthenticationException {
System.out.println("getSessions");
Authenticator instance = ESAPI.authenticator();
String accountName = ESAPI.randomizer().getRandomString(8, DefaultEncoder.CHAR_ALPHANUMERICS);
String password = ESAPI.authenticator().generateStrongPassword();
User user = instance.createUser(accountName, password, password);
HttpSession session1 = new MockHttpSession();
user.addSession( session1 );
HttpSession session2 = new MockHttpSession();
user.addSession( session2 );
HttpSession session3 = new MockHttpSession();
user.addSession( session3 );
Set sessions = user.getSessions();
Iterator i = sessions.iterator();
while ( i.hasNext() ) {
HttpSession s = (HttpSession)i.next();
System.out.println( ">>>" + s.getId() );
}
assertTrue(sessions.size() == 3);
}
public void testAddSession() {
// TODO
}
public void testRemoveSession() {
// TODO
}
/**
* Test of incrementFailedLoginCount method, of class org.owasp.esapi.User.
*
* @throws AuthenticationException
* the authentication exception
*/
public void testIncrementFailedLoginCount() throws AuthenticationException {
System.out.println("incrementFailedLoginCount");
DefaultUser user = createTestUser("incrementFailedLoginCount");
user.enable();
assertEquals(0, user.getFailedLoginCount());
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
ESAPI.httpUtilities().setCurrentHTTP(request, response);
try {
user.loginWithPassword("ridiculous");
} catch (AuthenticationException e) {
// expected
}
assertEquals(1, user.getFailedLoginCount());
try {
user.loginWithPassword("ridiculous");
} catch (AuthenticationException e) {
// expected
}
assertEquals(2, user.getFailedLoginCount());
try {
user.loginWithPassword("ridiculous");
} catch (AuthenticationException e) {
// expected
}
assertEquals(3, user.getFailedLoginCount());
try {
user.loginWithPassword("ridiculous");
} catch (AuthenticationException e) {
// expected
}
assertTrue(user.isLocked());
}
/**
* Test of isEnabled method, of class org.owasp.esapi.User.
*
* @throws AuthenticationException
* the authentication exception
*/
public void testIsEnabled() throws AuthenticationException {
System.out.println("isEnabled");
DefaultUser user = createTestUser("isEnabled");
user.disable();
assertFalse(user.isEnabled());
user.enable();
assertTrue(user.isEnabled());
}
/**
* Test of isInRole method, of class org.owasp.esapi.User.
*
* @throws AuthenticationException
* the authentication exception
*/
public void testIsInRole() throws AuthenticationException {
System.out.println("isInRole");
DefaultUser user = createTestUser("isInRole");
String role = "TestRole";
assertFalse(user.isInRole(role));
user.addRole(role);
assertTrue(user.isInRole(role));
assertFalse(user.isInRole("Ridiculous"));
}
/**
* Test of isLocked method, of class org.owasp.esapi.User.
*
* @throws AuthenticationException
* the authentication exception
*/
public void testIsLocked() throws AuthenticationException {
System.out.println("isLocked");
DefaultUser user = createTestUser("isLocked");
user.lock();
assertTrue(user.isLocked());
user.unlock();
assertFalse(user.isLocked());
}
/**
* Test of isSessionAbsoluteTimeout method, of class
* org.owasp.esapi.IntrusionDetector.
*
* @throws AuthenticationException
* the authentication exception
*/
public void testIsSessionAbsoluteTimeout() throws AuthenticationException {
System.out.println("isSessionAbsoluteTimeout");
Authenticator instance = ESAPI.authenticator();
String oldPassword = instance.generateStrongPassword();
DefaultUser user = createTestUser(oldPassword);
long now = System.currentTimeMillis();
// setup request and response
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
ESAPI.httpUtilities().setCurrentHTTP(request, response);
MockHttpSession session = (MockHttpSession)request.getSession();
// set session creation -3 hours (default is 2 hour timeout)
session.setCreationTime( now - (1000 * 60 * 60 * 3) );
assertTrue(user.isSessionAbsoluteTimeout());
// set session creation -1 hour (default is 2 hour timeout)
session.setCreationTime( now - (1000 * 60 * 60 * 1) );
assertFalse(user.isSessionAbsoluteTimeout());
}
/**
* Test of isSessionTimeout method, of class
* org.owasp.esapi.IntrusionDetector.
*
* @throws AuthenticationException
* the authentication exception
*/
public void testIsSessionTimeout() throws AuthenticationException {
System.out.println("isSessionTimeout");
Authenticator instance = ESAPI.authenticator();
String oldPassword = instance.generateStrongPassword();
DefaultUser user = createTestUser(oldPassword);
long now = System.currentTimeMillis();
// setup request and response
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
ESAPI.httpUtilities().setCurrentHTTP(request, response);
MockHttpSession session = (MockHttpSession)request.getSession();
// set creation -30 mins (default is 20 min timeout)
session.setAccessedTime( now - 1000 * 60 * 30 );
assertTrue(user.isSessionTimeout());
// set creation -1 hour (default is 20 min timeout)
session.setAccessedTime( now - 1000 * 60 * 10 );
assertFalse(user.isSessionTimeout());
}
/**
* Test of lockAccount method, of class org.owasp.esapi.User.
*
* @throws AuthenticationException
* the authentication exception
*/
public void testLock() throws AuthenticationException {
System.out.println("lock");
Authenticator instance = ESAPI.authenticator();
String oldPassword = instance.generateStrongPassword();
DefaultUser user = createTestUser(oldPassword);
user.lock();
assertTrue(user.isLocked());
user.unlock();
assertFalse(user.isLocked());
}
/**
* Test of loginWithPassword method, of class org.owasp.esapi.User.
*
* @throws AuthenticationException
* the authentication exception
*/
public void testLoginWithPassword() throws AuthenticationException {
System.out.println("loginWithPassword");
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpSession session = (MockHttpSession) request.getSession();
assertFalse(session.getInvalidated());
DefaultUser user = createTestUser("loginWithPassword");
user.enable();
user.loginWithPassword("loginWithPassword");
assertTrue(user.isLoggedIn());
user.logout();
assertFalse(user.isLoggedIn());
assertFalse(user.isLocked());
try {
user.loginWithPassword("ridiculous");
} catch (AuthenticationException e) {
// expected
}
assertFalse(user.isLoggedIn());
try {
user.loginWithPassword("ridiculous");
} catch (AuthenticationException e) {
// expected
}
try {
user.loginWithPassword("ridiculous");
} catch (AuthenticationException e) {
// expected
}
assertTrue(user.isLocked());
user.unlock();
assertTrue(user.getFailedLoginCount() == 0 );
}
/**
* Test of logout method, of class org.owasp.esapi.User.
*
* @throws AuthenticationException
* the authentication exception
*/
public void testLogout() throws AuthenticationException {
System.out.println("logout");
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
MockHttpSession session = (MockHttpSession) request.getSession();
assertFalse(session.getInvalidated());
Authenticator instance = ESAPI.authenticator();
ESAPI.httpUtilities().setCurrentHTTP(request, response);
String oldPassword = instance.generateStrongPassword();
DefaultUser user = createTestUser(oldPassword);
user.enable();
System.out.println(user.getLastLoginTime());
user.loginWithPassword(oldPassword);
assertTrue(user.isLoggedIn());
// get new session after user logs in
session = (MockHttpSession) request.getSession();
assertFalse(session.getInvalidated());
user.logout();
assertFalse(user.isLoggedIn());
assertTrue(session.getInvalidated());
}
/**
* Test of testRemoveRole method, of class org.owasp.esapi.User.
*
* @throws AuthenticationException
* the authentication exception
*/
public void testRemoveRole() throws AuthenticationException {
System.out.println("removeRole");
String role = ESAPI.randomizer().getRandomString(8, DefaultEncoder.CHAR_LOWERS);
DefaultUser user = createTestUser("removeRole");
user.addRole(role);
assertTrue(user.isInRole(role));
user.removeRole(role);
assertFalse(user.isInRole(role));
}
/**
* Test of testResetCSRFToken method, of class org.owasp.esapi.User.
*
* @throws AuthenticationException
* the authentication exception
*/
public void testResetCSRFToken() throws AuthenticationException {
System.out.println("resetCSRFToken");
DefaultUser user = createTestUser("resetCSRFToken");
String token1 = user.resetCSRFToken();
String token2 = user.resetCSRFToken();
assertFalse( token1.equals( token2 ) );
}
/**
* Test of setAccountName method, of class org.owasp.esapi.User.
*
* @throws AuthenticationException
*/
public void testSetAccountName() throws AuthenticationException {
System.out.println("setAccountName");
DefaultUser user = createTestUser("setAccountName");
String accountName = ESAPI.randomizer().getRandomString(7, DefaultEncoder.CHAR_ALPHANUMERICS);
user.setAccountName(accountName);
assertEquals(accountName.toLowerCase(), user.getAccountName());
assertFalse("ridiculous".equals(user.getAccountName()));
}
/**
* Test of setExpirationTime method, of class org.owasp.esapi.User.
*
* @throws Exception
*/
public void testSetExpirationTime() throws Exception {
Date longAgo = new Date(0);
Date now = new Date();
assertTrue("new Date(0) returned " + longAgo + " which is considered before new Date() " + now + ". Please report this output to the email list or as a issue", longAgo.before(now));
String password=ESAPI.randomizer().getRandomString(8, DefaultEncoder.CHAR_ALPHANUMERICS);
DefaultUser user = createTestUser(password);
user.setExpirationTime(longAgo);
assertTrue( user.isExpired() );
}
/**
* Test of setRoles method, of class org.owasp.esapi.User.
*
* @throws AuthenticationException
* the authentication exception
*/
public void testSetRoles() throws AuthenticationException {
System.out.println("setRoles");
DefaultUser user = createTestUser("setRoles");
user.addRole("user");
assertTrue(user.isInRole("user"));
Set set = new HashSet();
set.add("rolea");
set.add("roleb");
user.setRoles(set);
assertFalse(user.isInRole("user"));
assertTrue(user.isInRole("rolea"));
assertTrue(user.isInRole("roleb"));
assertFalse(user.isInRole("ridiculous"));
}
/**
* Test of setScreenName method, of class org.owasp.esapi.User.
*
* @throws AuthenticationException
* the authentication exception
*/
public void testSetScreenName() throws AuthenticationException {
System.out.println("setScreenName");
DefaultUser user = createTestUser("setScreenName");
String screenName = ESAPI.randomizer().getRandomString(7, DefaultEncoder.CHAR_ALPHANUMERICS);
user.setScreenName(screenName);
assertEquals(screenName, user.getScreenName());
assertFalse("ridiculous".equals(user.getScreenName()));
}
/**
* Test of unlockAccount method, of class org.owasp.esapi.User.
*
* @throws AuthenticationException
* the authentication exception
*/
public void testUnlock() throws AuthenticationException {
System.out.println("unlockAccount");
Authenticator instance = ESAPI.authenticator();
String oldPassword = instance.generateStrongPassword();
DefaultUser user = createTestUser(oldPassword);
user.lock();
assertTrue(user.isLocked());
user.unlock();
assertFalse(user.isLocked());
}
}
|
package ru.stqa.pft.homework;
import org.testng.Assert;
import org.testng.annotations.Test;
public class PointTest {
@Test
public void testDistance(){
Point p1 = new Point(2.0, 1.0);
Point p2 = new Point(6.0, 4.0);
Assert.assertEquals(p1.distance(p2), 5.0);
Point p3 = new Point(-2.0, -1.0);
Point p4 = new Point(-6.0, -4.0);
Assert.assertEquals(p3.distance(p4), 5.0);
Point p5 = new Point(0, 0);
Point p6 = new Point(0, 0);
Assert.assertEquals(p5.distance(p6), 0.0);
}
}
|
package com.github.abilityapi.trigger;
import com.github.abilityapi.Ability;
import com.github.abilityapi.AbilityManager;
import com.github.abilityapi.AbilityProvider;
import com.github.abilityapi.AbilityRegistry;
import com.github.abilityapi.listener.AbilityListener;
import com.github.abilityapi.trigger.sequence.Sequence;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerEvent;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
public class TriggerManager {
private final JavaPlugin plugin;
private final AbilityRegistry registry;
private final AbilityManager abilityManager;
private final Map<AbilityProvider, Sequence> abilityPotentials = new ConcurrentHashMap<>();
private final Map<AbilityListener, Sequence> listenerPotentials = new ConcurrentHashMap<>();
private final Map<Player, Ability> abilities;
public TriggerManager(JavaPlugin plugin, AbilityRegistry registry, AbilityManager abilityManager) {
this.plugin = plugin;
this.registry = registry;
this.abilityManager = abilityManager;
this.abilities = abilityManager.getExecuting();
}
public <T extends PlayerEvent> void handle(T event, ActionType type) {
Player player = event.getPlayer();
{
// handle current potentials for ability listeners
Iterator<Map.Entry<AbilityListener, Sequence>> it = listenerPotentials.entrySet().iterator();
handleCurrent(player, type, it).forEach(AbilityListener::execute);
}
{
// handle current potentials for abilities
Iterator<Map.Entry<AbilityProvider, Sequence>> it = abilityPotentials.entrySet().iterator();
handleCurrent(player, type, it).forEach(provider -> abilityManager.execute(player, provider));
}
{
// handle new potential triggers for ability listeners
Iterator<Map.Entry<AbilityListener, Sequence>> it = abilities.values().stream()
.flatMap(ability -> ability.getListeners().stream())
.collect(Collectors.toMap(listener -> listener, listener -> listener.getTrigger().createSequence()))
.entrySet()
.iterator();
handleNew(player, type, it, listenerPotentials)
.forEach(AbilityListener::execute);
}
{
// handle new potential triggers for abilities
Iterator<Map.Entry<AbilityProvider, Sequence>> it = registry.getProviders().stream()
.collect(Collectors.toMap(provider -> provider, provider -> provider.getTrigger().createSequence()))
.entrySet()
.iterator();
handleNew(player, type, it, abilityPotentials)
.forEach(provider -> abilityManager.execute(player, provider));
}
}
public void checkExpire() {
{
Iterator<Sequence> it = abilityPotentials.values().iterator();
while (it.hasNext()) {
Sequence sequence = it.next();
if (sequence.isCancelled() || sequence.hasExpired()) {
it.remove();
}
}
}
{
Iterator<Map.Entry<AbilityListener, Sequence>> it = listenerPotentials.entrySet().iterator();
while (it.hasNext()) {
Ability ability = it.next().getKey().getAbility();
if (!abilities.containsValue(ability)) {
it.remove();
}
}
}
}
private <T> List<T> handleCurrent(Player player, ActionType type, Iterator<Map.Entry<T, Sequence>> it) {
List<T> finished = new ArrayList<>();
while (it.hasNext()) {
Map.Entry<T, Sequence> entry = it.next();
T key = entry.getKey();
Sequence sequence = entry.getValue();
if (sequence.isCancelled() || sequence.hasExpired()) {
it.remove();
continue;
}
if (sequence.next(player, type) && sequence.hasFinished()) {
finished.add(key);
it.remove();
}
}
return finished;
}
private <T> List<T> handleNew(Player player, ActionType type, Iterator<Map.Entry<T, Sequence>> it,
Map<T, Sequence> potentials) {
List<T> finished = new ArrayList<>();
while (it.hasNext()) {
Map.Entry<T, Sequence> entry = it.next();
T key = entry.getKey();
Sequence sequence = entry.getValue();
if (sequence.next(player, type)) {
if (sequence.hasFinished()) {
finished.add(key);
continue;
}
potentials.put(key, sequence);
}
}
return finished;
}
}
|
package seedu.todo.commons;
import org.junit.*;
import static org.junit.Assert.*;
import seedu.todo.models.CalendarItem;
import seedu.todo.models.Event;
import seedu.todo.models.Task;
public class EphemeralDBTest {
@Test
public void check_singleton() {
EphemeralDB one = EphemeralDB.getInstance();
EphemeralDB two = EphemeralDB.getInstance();
assertEquals(one, two);
}
@Test
public void test_calendar_items() {
CalendarItem task = new Task();
CalendarItem event = new Event();
EphemeralDB db = EphemeralDB.getInstance();
db.addToDisplayedCalendarItems(task);
db.addToDisplayedCalendarItems(event);
assertEquals(db.getCalendarItemsByDisplayedId(1), task);
assertEquals(db.getCalendarItemsByDisplayedId(2), event);
}
@Test
public void test_missing_calendar_item() {
EphemeralDB db = EphemeralDB.getInstance();
assertEquals(db.getCalendarItemsByDisplayedId(0), null);
assertEquals(db.getCalendarItemsByDisplayedId(3), null);
}
}
|
package com.github.blindpirate.gogradle;
import com.github.blindpirate.gogradle.build.Configuration;
import com.github.blindpirate.gogradle.core.GolangConfigurationContainer;
import com.github.blindpirate.gogradle.core.dependency.GolangDependencyHandler;
import com.github.blindpirate.gogradle.core.dependency.parse.DefaultNotationParser;
import com.github.blindpirate.gogradle.task.GolangTaskContainer;
import com.google.inject.Guice;
import com.google.inject.Injector;
import org.gradle.api.Action;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.Task;
import org.gradle.api.artifacts.ConfigurationContainer;
import org.gradle.api.plugins.ExtensionAware;
import org.gradle.api.tasks.TaskContainer;
import org.gradle.internal.reflect.Instantiator;
import javax.inject.Inject;
import java.util.stream.Stream;
import static com.github.blindpirate.gogradle.task.GolangTaskContainer.TASKS;
public class GolangPlugin implements Plugin<Project> {
// injected by gradle
private final Instantiator instantiator;
private Injector injector;
private GolangPluginSetting settings;
private GolangTaskContainer golangTaskContainer;
private Project project;
private Action<? super Task> dependencyInjectionAction = new Action<Task>() {
@Override
public void execute(Task task) {
injector.injectMembers(task);
}
};
// This is invoked by gradle, not our Guice.
@Inject
public GolangPlugin(Instantiator instantiator) {
this.instantiator = instantiator;
}
private Injector initGuice() {
return Guice.createInjector(new GogradleModule(project, instantiator));
}
@Override
public void apply(Project project) {
init(project);
customizeProjectInternalServices(project);
configureSettings(project);
configureConfigurations(project);
configureTasks(project);
configureGlobalInjector();
}
private void init(Project project) {
this.project = project;
this.injector = initGuice();
this.settings = injector.getInstance(GolangPluginSetting.class);
this.golangTaskContainer = injector.getInstance(GolangTaskContainer.class);
}
private void configureGlobalInjector() {
GogradleGlobal.INSTANCE.setInjector(injector);
}
private void configureTasks(Project project) {
TaskContainer taskContainer = project.getTasks();
TASKS.entrySet().forEach(entry -> {
Task task = taskContainer.create(entry.getKey(), entry.getValue(), dependencyInjectionAction);
golangTaskContainer.put((Class) entry.getValue(), task);
});
}
/**
* Here we cannot use Guice since we need GroovyObject to be mixed in
* See {@link org.gradle.api.internal.AbstractClassGenerator}
*/
private void customizeProjectInternalServices(Project project) {
DefaultNotationParser parser = injector.getInstance(DefaultNotationParser.class);
GolangConfigurationContainer configurationContainer =
instantiator.newInstance(GolangConfigurationContainer.class,
instantiator);
project.setProperty("configurationContainer", configurationContainer);
project.setProperty("dependencyHandler",
instantiator.newInstance(GolangDependencyHandler.class,
configurationContainer,
parser));
overwriteRepositoryHandler(project);
}
private void overwriteRepositoryHandler(Project project) {
GitRepositoryHandler repositoryHandler = injector.getInstance(GitRepositoryHandler.class);
ExtensionAware.class.cast(project.getRepositories()).getExtensions().add("git", repositoryHandler);
}
private void configureConfigurations(Project project) {
ConfigurationContainer configurations = project.getConfigurations();
Stream.of(Configuration.values()).map(Configuration::getName).forEach(configurations::create);
}
private void configureSettings(Project project) {
project.getExtensions().add("golang", settings);
}
}
|
package systems.crigges.jmpq3test;
import com.esotericsoftware.minlog.Log;
import org.testng.Assert;
import org.testng.annotations.Test;
import systems.crigges.jmpq3.HashTable;
import systems.crigges.jmpq3.JMpqEditor;
import systems.crigges.jmpq3.MPQOpenOption;
import systems.crigges.jmpq3.security.MPQEncryption;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.NonWritableChannelException;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.Scanner;
public class MpqTests {
private static File[] getMpqs() {
return new File(MpqTests.class.getClassLoader().getResource("./mpqs/").getFile()).listFiles((dir, name) -> name.endsWith(".w3x"));
}
private static File getFile(String name) {
return new File(MpqTests.class.getClassLoader().getResource(name).getFile());
}
@Test
public void cryptoTest() throws IOException {
byte[] bytes = "Hello World!".getBytes();
final ByteBuffer workBuffer = ByteBuffer.allocate(bytes.length);
final MPQEncryption encryptor = new MPQEncryption(-1011927184, false);
encryptor.processFinal(ByteBuffer.wrap(bytes), workBuffer);
workBuffer.flip();
encryptor.changeKey(-1011927184, true);
encryptor.processSingle(workBuffer);
workBuffer.flip();
//Assert.assertTrue(Arrays.equals(new byte[]{-96, -93, 89, -50, 43, -60, 18, -33, -31, -71, -81, 86}, a));
//Assert.assertTrue(Arrays.equals(new byte[]{2, -106, -97, 38, 5, -82, -88, -91, -6, 63, 114, -31}, b));
Assert.assertTrue(Arrays.equals(bytes, workBuffer.array()));
}
@Test
public void hashTableTest() throws IOException {
// get real example file paths
final InputStream listFileFile = getClass().getClassLoader().getResourceAsStream("DefaultListfile.txt");
final Scanner listFile = new Scanner(listFileFile);
final String fp1 = listFile.nextLine();
final String fp2 = listFile.nextLine();
// small test hash table
final HashTable ht = new HashTable(8);
final short defaultLocale = HashTable.DEFAULT_LOCALE;
final short germanLocale = 0x407;
final short frenchLocale = 0x40c;
final short russianLocale = 0x419;
// assignment test
ht.setFileBlockIndex(fp1, defaultLocale, 0);
ht.setFileBlockIndex(fp2, defaultLocale, 1);
Assert.assertEquals(ht.getFileBlockIndex(fp1, defaultLocale), 0);
Assert.assertEquals(ht.getFileBlockIndex(fp2, defaultLocale), 1);
// deletion test
ht.removeFile(fp2, defaultLocale);
Assert.assertEquals(ht.getFileBlockIndex(fp1, defaultLocale), 0);
Assert.assertFalse(ht.hasFile(fp2));
// locale test
ht.setFileBlockIndex(fp1, germanLocale, 2);
ht.setFileBlockIndex(fp1, frenchLocale, 3);
Assert.assertEquals(ht.getFileBlockIndex(fp1, defaultLocale), 0);
Assert.assertEquals(ht.getFileBlockIndex(fp1, germanLocale), 2);
Assert.assertEquals(ht.getFileBlockIndex(fp1, frenchLocale), 3);
Assert.assertEquals(ht.getFileBlockIndex(fp1, russianLocale), 0);
// file path deletion test
ht.setFileBlockIndex(fp2, defaultLocale, 1);
ht.removeFileAll(fp1);
Assert.assertFalse(ht.hasFile(fp1));
Assert.assertEquals(ht.getFileBlockIndex(fp2, defaultLocale), 1);
// clean up
listFile.close();
}
@Test
public void testRebuild() throws IOException {
File[] mpqs = getMpqs();
for (File mpq : mpqs) {
Log.info(mpq.getName());
JMpqEditor mpqEditor = new JMpqEditor(mpq, MPQOpenOption.FORCE_V0);
mpqEditor.close();
}
}
@Test
public void testRecompressBuild() throws IOException {
File[] mpqs = getMpqs();
for (File mpq : mpqs) {
Log.info(mpq.getName());
JMpqEditor mpqEditor = new JMpqEditor(mpq, MPQOpenOption.FORCE_V0);
long length = mpq.length();
mpqEditor.close(true, true, true);
long newlength = mpq.length();
System.out.println("Size win: " + (length - newlength));
}
}
@Test
public void testExtractAll() throws IOException {
File[] mpqs = getMpqs();
for (File mpq : mpqs) {
JMpqEditor mpqEditor = new JMpqEditor(mpq, MPQOpenOption.READ_ONLY, MPQOpenOption.FORCE_V0);
File file = new File("out/");
file.mkdirs();
mpqEditor.extractAllFiles(file);
mpqEditor.close();
}
}
@Test
public void testExtractScriptFile() throws IOException {
File[] mpqs = getMpqs();
for (File mpq : mpqs) {
Log.info("test extract script: " + mpq.getName());
JMpqEditor mpqEditor = new JMpqEditor(mpq, MPQOpenOption.READ_ONLY, MPQOpenOption.FORCE_V0);
File temp = File.createTempFile("war3mapj", "extracted", JMpqEditor.tempDir);
temp.deleteOnExit();
if (mpqEditor.hasFile("war3map.j")) {
String extractedFile = mpqEditor.extractFileAsString("war3map.j").replaceAll("\\r\\n", "\n").replaceAll("\\r", "\n");
String existingFile = new String(Files.readAllBytes(getFile("war3map.j").toPath())).replaceAll("\\r\\n", "\n").replaceAll("\\r", "\n");
Assert.assertTrue(extractedFile.equalsIgnoreCase(existingFile));
}
mpqEditor.close();
}
}
@Test
public void testInsertDeleteRegularFile() throws IOException {
File[] mpqs = getMpqs();
for (File mpq : mpqs) {
insertAndDelete(mpq, "Example.txt");
}
}
@Test
public void testInsertDeleteZeroLengthFile() throws IOException {
File[] mpqs = getMpqs();
for (File mpq : mpqs) {
insertAndDelete(mpq, "0ByteExample.txt");
}
}
@Test
public void testMultipleInstances() throws IOException {
File[] mpqs = getMpqs();
for (File mpq : mpqs) {
JMpqEditor mpqEditors[] = new JMpqEditor[]{new JMpqEditor(mpq, MPQOpenOption.READ_ONLY, MPQOpenOption.FORCE_V0),
new JMpqEditor(mpq, MPQOpenOption.READ_ONLY, MPQOpenOption.FORCE_V0),
new JMpqEditor(mpq, MPQOpenOption.READ_ONLY, MPQOpenOption.FORCE_V0)};
for (int i = 0; i < mpqEditors.length; i++) {
mpqEditors[i].extractAllFiles(JMpqEditor.tempDir);
}
for (int i = 0; i < mpqEditors.length; i++) {
mpqEditors[i].close();
}
}
}
@Test
public void testIncompressibleFile() throws IOException {
File[] mpqs = getMpqs();
for (File mpq : mpqs) {
insertAndVerify(mpq, "incompressible.w3u");
}
}
private void insertAndVerify(File mpq, String filename) throws IOException {
JMpqEditor mpqEditor = new JMpqEditor(mpq, MPQOpenOption.FORCE_V0);
try {
File file = getFile(filename);
String hashBefore = TestHelper.md5(mpq);
byte[] bytes = Files.readAllBytes(file.toPath());
mpqEditor.insertFile(filename, getFile(filename), false);
mpqEditor.close();
String hashAfter = TestHelper.md5(mpq);
// If this fails, the mpq is not changed by the insert file command and something went wrong
Assert.assertNotEquals(hashBefore, hashAfter);
mpqEditor = new JMpqEditor(mpq, MPQOpenOption.FORCE_V0);
Assert.assertTrue(mpqEditor.hasFile(filename));
byte[] bytes2 = mpqEditor.extractFileAsBytes(filename);
Assert.assertEquals(bytes, bytes2);
mpqEditor.deleteFile(filename);
mpqEditor.close();
mpqEditor = new JMpqEditor(mpq, MPQOpenOption.READ_ONLY, MPQOpenOption.FORCE_V0);
Assert.assertFalse(mpqEditor.hasFile(filename));
} catch (NonWritableChannelException ignored) {
}
}
private void insertAndDelete(File mpq, String filename) throws IOException {
JMpqEditor mpqEditor = new JMpqEditor(mpq, MPQOpenOption.FORCE_V0);
Assert.assertFalse(mpqEditor.hasFile(filename));
try {
String hashBefore = TestHelper.md5(mpq);
mpqEditor.insertFile(filename, getFile(filename), true);
mpqEditor.deleteFile(filename);
mpqEditor.insertFile(filename, getFile(filename), false);
mpqEditor.close();
String hashAfter = TestHelper.md5(mpq);
// If this fails, the mpq is not changed by the insert file command and something went wrong
Assert.assertNotEquals(hashBefore, hashAfter);
mpqEditor = new JMpqEditor(mpq, MPQOpenOption.FORCE_V0);
Assert.assertTrue(mpqEditor.hasFile(filename));
mpqEditor.deleteFile(filename);
mpqEditor.close();
mpqEditor = new JMpqEditor(mpq, MPQOpenOption.READ_ONLY, MPQOpenOption.FORCE_V0);
Assert.assertFalse(mpqEditor.hasFile(filename));
mpqEditor.close();
} catch (NonWritableChannelException ignored) {
}
}
@Test(enabled = false)
public void testRemoveHeaderoffset() throws IOException {
File[] mpqs = getMpqs();
File mpq = null;
for (File mpq1 : mpqs) {
if (mpq1.getName().startsWith("normal")) {
mpq = mpq1;
break;
}
}
Assert.assertNotNull(mpq);
Log.info(mpq.getName());
JMpqEditor mpqEditor = new JMpqEditor(mpq, MPQOpenOption.FORCE_V0);
mpqEditor.setKeepHeaderOffset(false);
mpqEditor.close();
byte[] bytes = new byte[4];
new FileInputStream(mpq).read(bytes);
ByteBuffer order = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN);
Assert.assertEquals(order.getInt(), JMpqEditor.ARCHIVE_HEADER_MAGIC);
mpqEditor = new JMpqEditor(mpq, MPQOpenOption.FORCE_V0);
Assert.assertTrue(mpqEditor.isCanWrite());
mpqEditor.close();
}
}
|
package org.apache.commons.lang;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import junit.textui.TestRunner;
import org.apache.commons.lang.time.DateUtils;
/**
* Unit tests {@link org.apache.commons.lang.ObjectUtils}.
*
* @author <a href="mailto:jmcnally@collab.net">John McNally</a>
* @author <a href="mailto:scolebourne@joda.org">Stephen Colebourne</a>
* @author <a href="mailto:ridesmet@users.sourceforge.net">Ringo De Smet</a>
* @author <a href="mailto:ggregory@seagullsw.com">Gary Gregory</a>
* @version $Id: ObjectUtilsTest.java,v 1.10 2004/02/16 23:39:03 ggregory Exp $
*/
public class ObjectUtilsTest extends TestCase {
private static final String FOO = "foo";
private static final String BAR = "bar";
public ObjectUtilsTest(String name) {
super(name);
}
public static void main(String[] args) {
TestRunner.run(suite());
}
public static Test suite() {
TestSuite suite = new TestSuite(ObjectUtilsTest.class);
suite.setName("ObjectUtils Tests");
return suite;
}
protected void setUp() throws Exception {
super.setUp();
}
protected void tearDown() throws Exception {
super.tearDown();
}
public void testConstructor() {
assertNotNull(new ObjectUtils());
Constructor[] cons = ObjectUtils.class.getDeclaredConstructors();
assertEquals(1, cons.length);
assertEquals(true, Modifier.isPublic(cons[0].getModifiers()));
assertEquals(true, Modifier.isPublic(ObjectUtils.class.getModifiers()));
assertEquals(false, Modifier.isFinal(ObjectUtils.class.getModifiers()));
}
public void testIsNull() {
Object o = FOO;
Object dflt = BAR;
assertSame("dflt was not returned when o was null", dflt, ObjectUtils.defaultIfNull(null, dflt));
assertSame("dflt was returned when o was not null", o, ObjectUtils.defaultIfNull(o, dflt));
}
public void testEquals() {
assertTrue("ObjectUtils.equals(null, null) returned false", ObjectUtils.equals(null, null));
assertTrue("ObjectUtils.equals(\"foo\", null) returned true", !ObjectUtils.equals(FOO, null));
assertTrue("ObjectUtils.equals(null, \"bar\") returned true", !ObjectUtils.equals(null, BAR));
assertTrue("ObjectUtils.equals(\"foo\", \"bar\") returned true", !ObjectUtils.equals(FOO, BAR));
assertTrue("ObjectUtils.equals(\"foo\", \"foo\") returned false", ObjectUtils.equals(FOO, FOO));
}
/**
* Show that java.util.Date and java.sql.Timestamp are apples and oranges.
* Prompted by an email discussion.
*/
public void testDateEquals() {
long now = 1076957313284L; // Feb 16, 2004 10:49... PST
java.util.Date date = new java.util.Date(now);
java.util.Date timestamp = new java.sql.Timestamp(now);
// sanity check:
assertFalse(date.getTime() == timestamp.getTime());
assertFalse(timestamp.equals(date));
// real test:
assertFalse(ObjectUtils.equals(date, timestamp));
}
public void testIdentityToString() {
assertEquals(null, ObjectUtils.identityToString(null));
assertEquals(
"java.lang.String@" + Integer.toHexString(System.identityHashCode(FOO)),
ObjectUtils.identityToString(FOO));
Integer i = new Integer(90);
assertEquals(
"java.lang.Integer@" + Integer.toHexString(System.identityHashCode(i)),
ObjectUtils.identityToString(i));
}
public void testAppendIdentityToString() {
assertEquals(null, ObjectUtils.appendIdentityToString(null, null));
assertEquals(null, ObjectUtils.appendIdentityToString(new StringBuffer(), null));
assertEquals(
"java.lang.String@" + Integer.toHexString(System.identityHashCode(FOO)),
ObjectUtils.appendIdentityToString(null, FOO).toString());
assertEquals(
"java.lang.String@" + Integer.toHexString(System.identityHashCode(FOO)),
ObjectUtils.appendIdentityToString(new StringBuffer(), FOO).toString());
Integer val = new Integer(90);
assertEquals(
"java.lang.Integer@" + Integer.toHexString(System.identityHashCode(val)),
ObjectUtils.appendIdentityToString(null, val).toString());
assertEquals(
"java.lang.Integer@" + Integer.toHexString(System.identityHashCode(val)),
ObjectUtils.appendIdentityToString(new StringBuffer(), val).toString());
}
public void testToString_Object() {
assertEquals("", ObjectUtils.toString((Object) null) );
assertEquals(Boolean.TRUE.toString(), ObjectUtils.toString(Boolean.TRUE) );
}
public void testToString_ObjectString() {
assertEquals(BAR, ObjectUtils.toString((Object) null, BAR) );
assertEquals(Boolean.TRUE.toString(), ObjectUtils.toString(Boolean.TRUE, BAR) );
}
public void testNull() {
assertTrue(ObjectUtils.NULL != null);
assertTrue(ObjectUtils.NULL instanceof ObjectUtils.Null);
assertSame(ObjectUtils.NULL, SerializationUtils.clone(ObjectUtils.NULL));
}
}
|
package com.github.tonivade.resp.protocol;
import static com.github.tonivade.resp.protocol.SafeString.safeString;
import static java.util.Arrays.asList;
import static java.util.Collections.unmodifiableList;
import static java.util.Objects.requireNonNull;
import static tonivade.equalizer.Equalizer.equalizer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
public abstract class RedisToken {
private static final String SEPARATOR = "=>";
private final RedisTokenType type;
private final Object value;
private RedisToken(RedisTokenType type, Object value) {
this.type = requireNonNull(type);
this.value = value;
}
public RedisTokenType getType() {
return type;
}
@SuppressWarnings("unchecked")
public <T> T getValue() {
return (T) value;
}
@Override
public int hashCode() {
return Objects.hashCode(value);
}
@Override
public boolean equals(Object obj) {
return equalizer(this).append((one, other) -> Objects.equals(one.value, other.value)).applyTo(obj);
}
@Override
public String toString() {
return type + SEPARATOR + value;
}
public static RedisToken nullString() {
return new StringRedisToken(null);
}
public static RedisToken string(SafeString str) {
return new StringRedisToken(str);
}
public static RedisToken string(String str) {
return new StringRedisToken(safeString(str));
}
public static RedisToken status(String str) {
return new StatusRedisToken(safeString(str));
}
public static RedisToken integer(boolean b) {
return new IntegerRedisToken(b ? 1 : 0);
}
public static RedisToken integer(int i) {
return new IntegerRedisToken(i);
}
public static RedisToken error(String str) {
return new ErrorRedisToken(safeString(str));
}
public static RedisToken array(RedisToken... redisTokens) {
return new ArrayRedisToken(asList(redisTokens));
}
public static RedisToken array(Collection<RedisToken> redisTokens) {
return new ArrayRedisToken(redisTokens);
}
static class UnknownRedisToken extends RedisToken {
public UnknownRedisToken(SafeString value) {
super(RedisTokenType.UNKNOWN, value);
}
}
static class StringRedisToken extends RedisToken {
public StringRedisToken(SafeString value) {
super(RedisTokenType.STRING, value);
}
}
static class StatusRedisToken extends RedisToken {
public StatusRedisToken(SafeString value) {
super(RedisTokenType.STATUS, value);
}
}
static class ErrorRedisToken extends RedisToken {
public ErrorRedisToken(SafeString value) {
super(RedisTokenType.ERROR, value);
}
}
static class IntegerRedisToken extends RedisToken {
public IntegerRedisToken(Integer value) {
super(RedisTokenType.INTEGER, value);
}
}
static class ArrayRedisToken extends RedisToken {
public ArrayRedisToken(Collection<RedisToken> value) {
super(RedisTokenType.ARRAY, unmodifiableList(new ArrayList<>(value)));
}
public int size() {
return this.<List<RedisToken>>getValue().size();
}
}
}
|
package tk.wurst_client.features.mods;
import tk.wurst_client.events.listeners.DeathListener;
@Mod.Info(description = "Automatically respawns you whenever you die.",
name = "AutoRespawn",
tags = "auto respawn",
help = "Mods/AutoRespawn")
@Mod.Bypasses
public class AutoRespawnMod extends Mod implements DeathListener
{
@Override
public void onEnable()
{
wurst.events.add(DeathListener.class, this);
}
@Override
public void onDisable()
{
wurst.events.remove(DeathListener.class, this);
}
@Override
public void onDeath()
{
mc.player.respawnPlayer();
mc.displayGuiScreen(null);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.