answer
stringlengths 17
10.2M
|
|---|
package Engine;
public class Casino {
private double blackjackPayoutMultiple;
private int numberOfDecks;
private boolean hitOnSoft17s, doubleAfterSplit, resplitAfterAce;
private String name;
public Casino(String name, double blackjackPayoutMultiple, int numberOfDecks, boolean hitOnSoft17s, boolean doubleAfterSplit, boolean resplitAfterAce) {
this.name = name;
this.numberOfDecks = numberOfDecks;
this.hitOnSoft17s = hitOnSoft17s;
this.doubleAfterSplit = doubleAfterSplit;
this.resplitAfterAce = resplitAfterAce;
this.blackjackPayoutMultiple = blackjackPayoutMultiple;
}
public String getName() {
return name;
}
public int getNumberOfDecks() {
return numberOfDecks;
}
public boolean isHitOnSoft17s() {
return hitOnSoft17s;
}
public boolean isDoubleAfterSplit() {
return doubleAfterSplit;
}
public boolean isResplitAfterAce() {
return resplitAfterAce;
}
public double getBlackjackPayoutMultiple() {
return blackjackPayoutMultiple;
}
}
|
package com.fsck.k9.mail.store;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CodingErrorAction;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import java.security.Security;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.StringTokenizer;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.TrustManager;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.PowerManager;
import android.text.TextUtils;
import android.util.Log;
import com.beetstra.jutf7.CharsetProvider;
import com.fsck.k9.Account;
import com.fsck.k9.K9;
import com.fsck.k9.R;
import com.fsck.k9.controller.MessageRetrievalListener;
import com.fsck.k9.helper.Utility;
import com.fsck.k9.helper.power.TracingPowerManager;
import com.fsck.k9.helper.power.TracingPowerManager.TracingWakeLock;
import com.fsck.k9.mail.Authentication;
import com.fsck.k9.mail.AuthenticationFailedException;
import com.fsck.k9.mail.Body;
import com.fsck.k9.mail.CertificateValidationException;
import com.fsck.k9.mail.FetchProfile;
import com.fsck.k9.mail.Flag;
import com.fsck.k9.mail.Folder;
import com.fsck.k9.mail.Message;
import com.fsck.k9.mail.MessagingException;
import com.fsck.k9.mail.Part;
import com.fsck.k9.mail.PushReceiver;
import com.fsck.k9.mail.Pusher;
import com.fsck.k9.mail.Store;
import com.fsck.k9.mail.filter.EOLConvertingOutputStream;
import com.fsck.k9.mail.filter.FixedLengthInputStream;
import com.fsck.k9.mail.filter.PeekableInputStream;
import com.fsck.k9.mail.internet.MimeBodyPart;
import com.fsck.k9.mail.internet.MimeHeader;
import com.fsck.k9.mail.internet.MimeMessage;
import com.fsck.k9.mail.internet.MimeMultipart;
import com.fsck.k9.mail.internet.MimeUtility;
import com.fsck.k9.mail.store.ImapResponseParser.ImapList;
import com.fsck.k9.mail.store.ImapResponseParser.ImapResponse;
import com.fsck.k9.mail.transport.imap.ImapSettings;
import com.jcraft.jzlib.JZlib;
import com.jcraft.jzlib.ZOutputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
/**
* <pre>
* TODO Need to start keeping track of UIDVALIDITY
* TODO Need a default response handler for things like folder updates
* </pre>
*/
public class ImapStore extends Store {
public static final int CONNECTION_SECURITY_NONE = 0;
public static final int CONNECTION_SECURITY_TLS_OPTIONAL = 1;
public static final int CONNECTION_SECURITY_TLS_REQUIRED = 2;
public static final int CONNECTION_SECURITY_SSL_REQUIRED = 3;
public static final int CONNECTION_SECURITY_SSL_OPTIONAL = 4;
public enum AuthType { PLAIN, CRAM_MD5 }
private static final int IDLE_READ_TIMEOUT_INCREMENT = 5 * 60 * 1000;
private static final int IDLE_FAILURE_COUNT_LIMIT = 10;
private static int MAX_DELAY_TIME = 5 * 60 * 1000; // 5 minutes
private static int NORMAL_DELAY_TIME = 5000;
private static int FETCH_WINDOW_SIZE = 100;
private static final Flag[] PERMANENT_FLAGS = { Flag.DELETED, Flag.SEEN };
private static final String CAPABILITY_IDLE = "IDLE";
private static final String COMMAND_IDLE = "IDLE";
private static final String CAPABILITY_NAMESPACE = "NAMESPACE";
private static final String COMMAND_NAMESPACE = "NAMESPACE";
private static final String CAPABILITY_CAPABILITY = "CAPABILITY";
private static final String COMMAND_CAPABILITY = "CAPABILITY";
private static final String CAPABILITY_COMPRESS_DEFLATE = "COMPRESS=DEFLATE";
private static final String COMMAND_COMPRESS_DEFLATE = "COMPRESS DEFLATE";
private static final Message[] EMPTY_MESSAGE_ARRAY = new Message[0];
private static final String[] EMPTY_STRING_ARRAY = new String[0];
private String mHost;
private int mPort;
private String mUsername;
private String mPassword;
private int mConnectionSecurity;
private AuthType mAuthType;
private volatile String mPathPrefix;
private volatile String mCombinedPrefix = null;
private volatile String mPathDelimeter = null;
public class StoreImapSettings implements ImapSettings {
@Override
public String getHost() {
return mHost;
}
@Override
public int getPort() {
return mPort;
}
@Override
public int getConnectionSecurity() {
return mConnectionSecurity;
}
@Override
public AuthType getAuthType() {
return mAuthType;
}
@Override
public String getUsername() {
return mUsername;
}
@Override
public String getPassword() {
return mPassword;
}
@Override
public boolean useCompression(final int type) {
return mAccount.useCompression(type);
}
@Override
public String getPathPrefix() {
return mPathPrefix;
}
@Override
public void setPathPrefix(String prefix) {
mPathPrefix = prefix;
}
@Override
public String getPathDelimeter() {
return mPathDelimeter;
}
@Override
public void setPathDelimeter(String delimeter) {
mPathDelimeter = delimeter;
}
@Override
public String getCombinedPrefix() {
return mCombinedPrefix;
}
@Override
public void setCombinedPrefix(String prefix) {
mCombinedPrefix = prefix;
}
}
private static final SimpleDateFormat RFC3501_DATE = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
private LinkedList<ImapConnection> mConnections =
new LinkedList<ImapConnection>();
/**
* Charset used for converting folder names to and from UTF-7 as defined by RFC 3501.
*/
private Charset mModifiedUtf7Charset;
/**
* Cache of ImapFolder objects. ImapFolders are attached to a given folder on the server
* and as long as their associated connection remains open they are reusable between
* requests. This cache lets us make sure we always reuse, if possible, for a given
* folder name.
*/
private HashMap<String, ImapFolder> mFolderCache = new HashMap<String, ImapFolder>();
/**
* imap://auth:user:password@server:port CONNECTION_SECURITY_NONE
* imap+tls://auth:user:password@server:port CONNECTION_SECURITY_TLS_OPTIONAL
* imap+tls+://auth:user:password@server:port CONNECTION_SECURITY_TLS_REQUIRED
* imap+ssl+://auth:user:password@server:port CONNECTION_SECURITY_SSL_REQUIRED
* imap+ssl://auth:user:password@server:port CONNECTION_SECURITY_SSL_OPTIONAL
*
* @param _uri
*/
public ImapStore(Account account) throws MessagingException {
super(account);
URI uri;
try {
uri = new URI(mAccount.getStoreUri());
} catch (URISyntaxException use) {
throw new MessagingException("Invalid ImapStore URI", use);
}
String scheme = uri.getScheme();
if (scheme.equals("imap")) {
mConnectionSecurity = CONNECTION_SECURITY_NONE;
mPort = 143;
} else if (scheme.equals("imap+tls")) {
mConnectionSecurity = CONNECTION_SECURITY_TLS_OPTIONAL;
mPort = 143;
} else if (scheme.equals("imap+tls+")) {
mConnectionSecurity = CONNECTION_SECURITY_TLS_REQUIRED;
mPort = 143;
} else if (scheme.equals("imap+ssl+")) {
mConnectionSecurity = CONNECTION_SECURITY_SSL_REQUIRED;
mPort = 993;
} else if (scheme.equals("imap+ssl")) {
mConnectionSecurity = CONNECTION_SECURITY_SSL_OPTIONAL;
mPort = 993;
} else {
throw new MessagingException("Unsupported protocol");
}
mHost = uri.getHost();
if (uri.getPort() != -1) {
mPort = uri.getPort();
}
if (uri.getUserInfo() != null) {
try {
String[] userInfoParts = uri.getUserInfo().split(":");
if (userInfoParts.length == 2) {
mAuthType = AuthType.PLAIN;
mUsername = URLDecoder.decode(userInfoParts[0], "UTF-8");
mPassword = URLDecoder.decode(userInfoParts[1], "UTF-8");
} else {
mAuthType = AuthType.valueOf(userInfoParts[0]);
mUsername = URLDecoder.decode(userInfoParts[1], "UTF-8");
mPassword = URLDecoder.decode(userInfoParts[2], "UTF-8");
}
} catch (UnsupportedEncodingException enc) {
// This shouldn't happen since the encoding is hardcoded to UTF-8
Log.e(K9.LOG_TAG, "Couldn't urldecode username or password.", enc);
}
}
if ((uri.getPath() != null) && (uri.getPath().length() > 0)) {
mPathPrefix = uri.getPath().substring(1);
if (mPathPrefix != null && mPathPrefix.trim().length() == 0) {
mPathPrefix = null;
}
}
mModifiedUtf7Charset = new CharsetProvider().charsetForName("X-RFC-3501");
}
@Override
public Folder getFolder(String name) {
ImapFolder folder;
synchronized (mFolderCache) {
folder = mFolderCache.get(name);
if (folder == null) {
folder = new ImapFolder(this, name);
mFolderCache.put(name, folder);
}
}
return folder;
}
private String getCombinedPrefix() {
if (mCombinedPrefix == null) {
if (mPathPrefix != null) {
String tmpPrefix = mPathPrefix.trim();
String tmpDelim = (mPathDelimeter != null ? mPathDelimeter.trim() : "");
if (tmpPrefix.endsWith(tmpDelim)) {
mCombinedPrefix = tmpPrefix;
} else if (tmpPrefix.length() > 0) {
mCombinedPrefix = tmpPrefix + tmpDelim;
} else {
mCombinedPrefix = "";
}
} else {
mCombinedPrefix = "";
}
}
return mCombinedPrefix;
}
@Override
public List <? extends Folder > getPersonalNamespaces(boolean forceListAll) throws MessagingException {
ImapConnection connection = getConnection();
try {
List <? extends Folder > allFolders = listFolders(connection, false);
if (forceListAll || !mAccount.subscribedFoldersOnly()) {
return allFolders;
} else {
List<Folder> resultFolders = new LinkedList<Folder>();
HashSet<String> subscribedFolderNames = new HashSet<String>();
List <? extends Folder > subscribedFolders = listFolders(connection, true);
for (Folder subscribedFolder : subscribedFolders) {
subscribedFolderNames.add(subscribedFolder.getName());
}
for (Folder folder : allFolders) {
if (subscribedFolderNames.contains(folder.getName())) {
resultFolders.add(folder);
}
}
return resultFolders;
}
} catch (IOException ioe) {
connection.close();
throw new MessagingException("Unable to get folder list.", ioe);
} catch (MessagingException me) {
connection.close();
throw new MessagingException("Unable to get folder list.", me);
} finally {
releaseConnection(connection);
}
}
private List <? extends Folder > listFolders(ImapConnection connection, boolean LSUB) throws IOException, MessagingException {
String commandResponse = LSUB ? "LSUB" : "LIST";
LinkedList<Folder> folders = new LinkedList<Folder>();
List<ImapResponse> responses =
connection.executeSimpleCommand(String.format(commandResponse + " \"\" %s",
encodeString(getCombinedPrefix() + "*")));
for (ImapResponse response : responses) {
if (ImapResponseParser.equalsIgnoreCase(response.get(0), commandResponse)) {
boolean includeFolder = true;
String decodedFolderName;
try {
decodedFolderName = decodeFolderName(response.getString(3));
} catch (CharacterCodingException e) {
Log.w(K9.LOG_TAG, "Folder name not correctly encoded with the UTF-7 variant " +
"as defined by RFC 3501: " + response.getString(3), e);
//TODO: Use the raw name returned by the server for all commands that require
// a folder name. Use the decoded name only for showing it to the user.
// We currently just skip folders with malformed names.
continue;
}
String folder = decodedFolderName;
if (mPathDelimeter == null) {
mPathDelimeter = response.getString(2);
mCombinedPrefix = null;
}
if (folder.equalsIgnoreCase(mAccount.getInboxFolderName())) {
continue;
} else if (folder.equals(mAccount.getOutboxFolderName())) {
/*
* There is a folder on the server with the same name as our local
* outbox. Until we have a good plan to deal with this situation
* we simply ignore the folder on the server.
*/
continue;
} else {
int prefixLength = getCombinedPrefix().length();
if (prefixLength > 0) {
// Strip prefix from the folder name
if (folder.length() >= prefixLength) {
folder = folder.substring(prefixLength);
}
if (!decodedFolderName.equalsIgnoreCase(getCombinedPrefix() + folder)) {
includeFolder = false;
}
}
}
ImapList attributes = response.getList(1);
for (int i = 0, count = attributes.size(); i < count; i++) {
String attribute = attributes.getString(i);
if (attribute.equalsIgnoreCase("\\NoSelect")) {
includeFolder = false;
}
}
if (includeFolder) {
folders.add(getFolder(folder));
}
}
}
folders.add(getFolder(mAccount.getInboxFolderName()));
return folders;
}
@Override
public void checkSettings() throws MessagingException {
try {
ImapConnection connection = new ImapConnection(new StoreImapSettings());
connection.open();
connection.close();
} catch (IOException ioe) {
throw new MessagingException(K9.app.getString(R.string.error_unable_to_connect), ioe);
}
}
/**
* Gets a connection if one is available for reuse, or creates a new one if not.
* @return
*/
private ImapConnection getConnection() throws MessagingException {
synchronized (mConnections) {
ImapConnection connection = null;
while ((connection = mConnections.poll()) != null) {
try {
connection.executeSimpleCommand("NOOP");
break;
} catch (IOException ioe) {
connection.close();
}
}
if (connection == null) {
connection = new ImapConnection(new StoreImapSettings());
}
return connection;
}
}
private void releaseConnection(ImapConnection connection) {
if (connection != null && connection.isOpen()) {
synchronized (mConnections) {
mConnections.offer(connection);
}
}
}
/**
* Encode a string to be able to use it in an IMAP command.
*
* "A quoted string is a sequence of zero or more 7-bit characters,
* excluding CR and LF, with double quote (<">) characters at each
* end." - Section 4.3, RFC 3501
*
* Double quotes and backslash are escaped by prepending a backslash.
*
* @param str
* The input string (only 7-bit characters allowed).
* @return
* The string encoded as quoted (IMAP) string.
*/
private static String encodeString(String str) {
return "\"" + str.replace("\\", "\\\\").replace("\"", "\\\"") + "\"";
}
private String encodeFolderName(String name) {
try {
ByteBuffer bb = mModifiedUtf7Charset.encode(name);
byte[] b = new byte[bb.limit()];
bb.get(b);
return new String(b, "US-ASCII");
} catch (UnsupportedEncodingException uee) {
/*
* The only thing that can throw this is getBytes("US-ASCII") and if US-ASCII doesn't
* exist we're totally screwed.
*/
throw new RuntimeException("Unable to encode folder name: " + name, uee);
}
}
private String decodeFolderName(String name) throws CharacterCodingException {
/*
* Convert the encoded name to US-ASCII, then pass it through the modified UTF-7
* decoder and return the Unicode String.
*/
try {
// Make sure the decoder throws an exception if it encounters an invalid encoding.
CharsetDecoder decoder = mModifiedUtf7Charset.newDecoder().onMalformedInput(CodingErrorAction.REPORT);
CharBuffer cb = decoder.decode(ByteBuffer.wrap(name.getBytes("US-ASCII")));
return cb.toString();
} catch (UnsupportedEncodingException uee) {
/*
* The only thing that can throw this is getBytes("US-ASCII") and if US-ASCII doesn't
* exist we're totally screwed.
*/
throw new RuntimeException("Unable to decode folder name: " + name, uee);
}
}
@Override
public boolean isMoveCapable() {
return true;
}
@Override
public boolean isCopyCapable() {
return true;
}
@Override
public boolean isPushCapable() {
return true;
}
@Override
public boolean isExpungeCapable() {
return true;
}
class ImapFolder extends Folder {
private String mName;
protected volatile int mMessageCount = -1;
protected volatile int uidNext = -1;
protected volatile ImapConnection mConnection;
private OpenMode mMode;
private volatile boolean mExists;
private ImapStore store = null;
Map<Integer, String> msgSeqUidMap = new ConcurrentHashMap<Integer, String>();
public ImapFolder(ImapStore nStore, String name) {
super(nStore.getAccount());
store = nStore;
this.mName = name;
}
public String getPrefixedName() throws MessagingException {
String prefixedName = "";
if (!mAccount.getInboxFolderName().equalsIgnoreCase(mName)) {
ImapConnection connection = null;
synchronized (this) {
if (mConnection == null) {
connection = getConnection();
} else {
connection = mConnection;
}
}
try {
connection.open();
} catch (IOException ioe) {
throw new MessagingException("Unable to get IMAP prefix", ioe);
} finally {
if (mConnection == null) {
releaseConnection(connection);
}
}
prefixedName = getCombinedPrefix();
}
prefixedName += mName;
return prefixedName;
}
protected List<ImapResponse> executeSimpleCommand(String command) throws MessagingException, IOException {
return handleUntaggedResponses(mConnection.executeSimpleCommand(command));
}
protected List<ImapResponse> executeSimpleCommand(String command, boolean sensitve, UntaggedHandler untaggedHandler) throws MessagingException, IOException {
return handleUntaggedResponses(mConnection.executeSimpleCommand(command, sensitve, untaggedHandler));
}
@Override
public void open(OpenMode mode) throws MessagingException {
internalOpen(mode);
if (mMessageCount == -1) {
throw new MessagingException(
"Did not find message count during open");
}
}
public List<ImapResponse> internalOpen(OpenMode mode) throws MessagingException {
if (isOpen() && mMode == mode) {
// Make sure the connection is valid. If it's not we'll close it down and continue
// on to get a new one.
try {
List<ImapResponse> responses = executeSimpleCommand("NOOP");
return responses;
} catch (IOException ioe) {
ioExceptionHandler(mConnection, ioe);
}
}
releaseConnection(mConnection);
synchronized (this) {
mConnection = getConnection();
}
// * FLAGS (\Answered \Flagged \Deleted \Seen \Draft NonJunk
// $MDNSent)
// * OK [PERMANENTFLAGS (\Answered \Flagged \Deleted \Seen \Draft
// NonJunk $MDNSent \*)] Flags permitted.
// * 23 EXISTS
// * 0 RECENT
// * OK [UIDVALIDITY 1125022061] UIDs valid
// * OK [UIDNEXT 57576] Predicted next UID
// 2 OK [READ-WRITE] Select completed.
try {
msgSeqUidMap.clear();
String command = String.format((mode == OpenMode.READ_WRITE ? "SELECT" : "EXAMINE") + " %s",
encodeString(encodeFolderName(getPrefixedName())));
List<ImapResponse> responses = executeSimpleCommand(command);
/*
* If the command succeeds we expect the folder has been opened read-write
* unless we are notified otherwise in the responses.
*/
mMode = mode;
for (ImapResponse response : responses) {
if (response.mTag != null && response.size() >= 2) {
Object bracketedObj = response.get(1);
if (bracketedObj instanceof ImapList) {
ImapList bracketed = (ImapList)bracketedObj;
if (bracketed.size() > 0) {
Object keyObj = bracketed.get(0);
if (keyObj instanceof String) {
String key = (String)keyObj;
if ("READ-ONLY".equalsIgnoreCase(key)) {
mMode = OpenMode.READ_ONLY;
} else if ("READ-WRITE".equalsIgnoreCase(key)) {
mMode = OpenMode.READ_WRITE;
}
}
}
}
}
}
mExists = true;
return responses;
} catch (IOException ioe) {
throw ioExceptionHandler(mConnection, ioe);
} catch (MessagingException me) {
Log.e(K9.LOG_TAG, "Unable to open connection for " + getLogId(), me);
throw me;
}
}
@Override
public boolean isOpen() {
return mConnection != null;
}
@Override
public OpenMode getMode() {
return mMode;
}
@Override
public void close() {
if (mMessageCount != -1) {
mMessageCount = -1;
}
if (!isOpen()) {
return;
}
synchronized (this) {
releaseConnection(mConnection);
mConnection = null;
}
}
@Override
public String getName() {
return mName;
}
/**
* Check if a given folder exists on the server.
*
* @param folderName
* The name of the folder encoded as quoted string.
* See {@link ImapStore#encodeString}
*
* @return
* {@code True}, if the folder exists. {@code False}, otherwise.
*/
private boolean exists(String folderName) throws MessagingException {
try {
// Since we don't care about RECENT, we'll use that for the check, because we're checking
// a folder other than ourself, and don't want any untagged responses to cause a change
// in our own fields
mConnection.executeSimpleCommand(String.format("STATUS %s (RECENT)", folderName));
return true;
} catch (IOException ioe) {
throw ioExceptionHandler(mConnection, ioe);
} catch (MessagingException me) {
return false;
}
}
@Override
public boolean exists() throws MessagingException {
if (mExists) {
return true;
}
/*
* This method needs to operate in the unselected mode as well as the selected mode
* so we must get the connection ourselves if it's not there. We are specifically
* not calling checkOpen() since we don't care if the folder is open.
*/
ImapConnection connection = null;
synchronized (this) {
if (mConnection == null) {
connection = getConnection();
} else {
connection = mConnection;
}
}
try {
connection.executeSimpleCommand(String.format("STATUS %s (UIDVALIDITY)",
encodeString(encodeFolderName(getPrefixedName()))));
mExists = true;
return true;
} catch (MessagingException me) {
return false;
} catch (IOException ioe) {
throw ioExceptionHandler(connection, ioe);
} finally {
if (mConnection == null) {
releaseConnection(connection);
}
}
}
@Override
public boolean create(FolderType type) throws MessagingException {
/*
* This method needs to operate in the unselected mode as well as the selected mode
* so we must get the connection ourselves if it's not there. We are specifically
* not calling checkOpen() since we don't care if the folder is open.
*/
ImapConnection connection = null;
synchronized (this) {
if (mConnection == null) {
connection = getConnection();
} else {
connection = mConnection;
}
}
try {
connection.executeSimpleCommand(String.format("CREATE %s",
encodeString(encodeFolderName(getPrefixedName()))));
return true;
} catch (MessagingException me) {
return false;
} catch (IOException ioe) {
throw ioExceptionHandler(mConnection, ioe);
} finally {
if (mConnection == null) {
releaseConnection(connection);
}
}
}
@Override
public void copyMessages(Message[] messages, Folder folder) throws MessagingException {
if (!(folder instanceof ImapFolder)) {
throw new MessagingException("ImapFolder.copyMessages passed non-ImapFolder");
}
if (messages.length == 0)
return;
ImapFolder iFolder = (ImapFolder)folder;
checkOpen();
SortedSet<Message> messageSet = new TreeSet<Message>(new Comparator<Message>() {
public int compare(Message m1, Message m2) {
int uid1 = Integer.parseInt(m1.getUid()), uid2 = Integer.parseInt(m2.getUid());
if (uid1 < uid2) {
return -1;
} else if (uid1 == uid2) {
return 0;
} else {
return 1;
}
}
});
String[] uids = new String[messages.length];
for (int i = 0, count = messages.length; i < count; i++) {
messageSet.add(messages[i]);
// Not bothering to sort the UIDs in ascending order while sending the command for convenience, and because it does not make a difference.
uids[i] = messages[i].getUid();
}
try {
String remoteDestName = encodeString(encodeFolderName(iFolder.getPrefixedName()));
if (!exists(remoteDestName)) {
/*
* If the remote trash folder doesn't exist we try to create it.
*/
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "IMAPMessage.copyMessages: attempting to create remote '" + remoteDestName + "' folder for " + getLogId());
iFolder.create(FolderType.HOLDS_MESSAGES);
}
mConnection.sendCommand(String.format("UID COPY %s %s",
Utility.combine(uids, ','),
remoteDestName), false);
ImapResponse response;
do {
response = mConnection.readResponse();
handleUntaggedResponse(response);
if (response.mCommandContinuationRequested) {
EOLConvertingOutputStream eolOut = new EOLConvertingOutputStream(mConnection.mOut);
eolOut.write('\r');
eolOut.write('\n');
eolOut.flush();
}
while (response.more());
} while (response.mTag == null);
/*
* If the server supports UIDPLUS, then along with the COPY response it will return an COPYUID response code.
* e.g. 24 OK [COPYUID 38505 304,319:320 3956:3958] Success
*
* COPYUID is followed by UIDVALIDITY, set of UIDs of copied messages from the source folder and set of corresponding UIDs assigned to them in the destination folder.
*
* We can use the new UIDs included in this response to update our records.
*/
Object responseList = response.get(1);
if (responseList instanceof ImapList) {
final ImapList copyList = (ImapList) responseList;
if ((copyList.size() >= 4) && copyList.getString(0).equals("COPYUID")) {
List<String> oldUids = parseSequenceSet(copyList.getString(2));
List<String> newUids = parseSequenceSet(copyList.getString(3));
if (oldUids.size() == newUids.size()) {
Iterator<Message> messageIterator = messageSet.iterator();
for (int i = 0; i < messages.length && messageIterator.hasNext(); i++) {
Message nextMessage = messageIterator.next();
if (oldUids.get(i).equals(nextMessage.getUid())) {
/*
* Here, we need to *create* new messages in the localstore, same as the older messages, the only changes are that old UIDs need to be swapped with new UIDs,
* and old folder swapped with new folder.
*/
// nextMessage.setUid(newUids.get(i));
}
}
}
}
}
} catch (IOException ioe) {
throw ioExceptionHandler(mConnection, ioe);
}
}
private List<String> parseSequenceSet(String set) {
int index = 0;
List<String> sequenceList = new ArrayList<String>();
String element = "";
while (index < set.length()) {
if (set.charAt(index) == ':') {
String upperBound = "";
index++;
while (index < set.length()) {
if (!(set.charAt(index) == ',')) {
upperBound += set.charAt(index);
index++;
} else {
break;
}
}
int lower = Integer.parseInt(element);
int upper = Integer.parseInt(upperBound);
if (lower < upper) {
for (int i = lower; i <= upper; i++) {
sequenceList.add(String.valueOf(i));
}
} else {
for (int i = upper; i <= lower; i++) {
sequenceList.add(String.valueOf(i));
}
}
element = "";
} else if (set.charAt(index) == ',') {
sequenceList.add(element);
element = "";
} else {
element += set.charAt(index);
}
index++;
}
if (!element.equals("")) {
sequenceList.add(element);
}
return sequenceList;
}
@Override
public void moveMessages(Message[] messages, Folder folder) throws MessagingException {
if (messages.length == 0)
return;
copyMessages(messages, folder);
setFlags(messages, new Flag[] { Flag.DELETED }, true);
}
@Override
public void delete(Message[] messages, String trashFolderName) throws MessagingException {
if (messages.length == 0)
return;
if (trashFolderName == null || getName().equalsIgnoreCase(trashFolderName)) {
setFlags(messages, new Flag[] { Flag.DELETED }, true);
} else {
ImapFolder remoteTrashFolder = (ImapFolder)getStore().getFolder(trashFolderName);
String remoteTrashName = encodeString(encodeFolderName(remoteTrashFolder.getPrefixedName()));
if (!exists(remoteTrashName)) {
/*
* If the remote trash folder doesn't exist we try to create it.
*/
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "IMAPMessage.delete: attempting to create remote '" + trashFolderName + "' folder for " + getLogId());
remoteTrashFolder.create(FolderType.HOLDS_MESSAGES);
}
if (exists(remoteTrashName)) {
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "IMAPMessage.delete: copying remote " + messages.length + " messages to '" + trashFolderName + "' for " + getLogId());
moveMessages(messages, remoteTrashFolder);
} else {
throw new MessagingException("IMAPMessage.delete: remote Trash folder " + trashFolderName + " does not exist and could not be created for " + getLogId()
, true);
}
}
}
@Override
public int getMessageCount() {
return mMessageCount;
}
private int getRemoteMessageCount(String criteria) throws MessagingException {
checkOpen();
try {
int count = 0;
int start = 1;
List<ImapResponse> responses = executeSimpleCommand(String.format("SEARCH %d:* " + criteria, start));
for (ImapResponse response : responses) {
if (ImapResponseParser.equalsIgnoreCase(response.get(0), "SEARCH")) {
count += response.size() - 1;
}
}
return count;
} catch (IOException ioe) {
throw ioExceptionHandler(mConnection, ioe);
}
}
@Override
public int getUnreadMessageCount() throws MessagingException {
return getRemoteMessageCount("UNSEEN NOT DELETED");
}
@Override
public int getFlaggedMessageCount() throws MessagingException {
return getRemoteMessageCount("FLAGGED NOT DELETED");
}
protected int getHighestUid() {
try {
ImapSearcher searcher = new ImapSearcher() {
public List<ImapResponse> search() throws IOException, MessagingException {
return executeSimpleCommand("UID SEARCH *:*");
}
};
Message[] messages = search(searcher, null);
if (messages.length > 0) {
return Integer.parseInt(messages[0].getUid());
}
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Unable to find highest UID in folder " + getName(), e);
}
return -1;
}
@Override
public void delete(boolean recurse) throws MessagingException {
throw new Error("ImapStore.delete() not yet implemented");
}
@Override
public Message getMessage(String uid) throws MessagingException {
return new ImapMessage(uid, this);
}
@Override
public Message[] getMessages(int start, int end, Date earliestDate, MessageRetrievalListener listener)
throws MessagingException {
return getMessages(start, end, earliestDate, false, listener);
}
protected Message[] getMessages(final int start, final int end, Date earliestDate, final boolean includeDeleted, final MessageRetrievalListener listener)
throws MessagingException {
if (start < 1 || end < 1 || end < start) {
throw new MessagingException(
String.format("Invalid message set %d %d",
start, end));
}
final StringBuilder dateSearchString = new StringBuilder();
if (earliestDate != null) {
dateSearchString.append(" SINCE ");
synchronized (RFC3501_DATE) {
dateSearchString.append(RFC3501_DATE.format(earliestDate));
}
}
ImapSearcher searcher = new ImapSearcher() {
public List<ImapResponse> search() throws IOException, MessagingException {
return executeSimpleCommand(String.format("UID SEARCH %d:%d%s" + (includeDeleted ? "" : " NOT DELETED"), start, end, dateSearchString));
}
};
return search(searcher, listener);
}
protected Message[] getMessages(final List<Integer> mesgSeqs, final boolean includeDeleted, final MessageRetrievalListener listener)
throws MessagingException {
ImapSearcher searcher = new ImapSearcher() {
public List<ImapResponse> search() throws IOException, MessagingException {
return executeSimpleCommand(String.format("UID SEARCH %s" + (includeDeleted ? "" : " NOT DELETED"), Utility.combine(mesgSeqs.toArray(), ',')));
}
};
return search(searcher, listener);
}
protected Message[] getMessagesFromUids(final List<String> mesgUids, final boolean includeDeleted, final MessageRetrievalListener listener)
throws MessagingException {
ImapSearcher searcher = new ImapSearcher() {
public List<ImapResponse> search() throws IOException, MessagingException {
return executeSimpleCommand(String.format("UID SEARCH UID %s" + (includeDeleted ? "" : " NOT DELETED"), Utility.combine(mesgUids.toArray(), ',')));
}
};
return search(searcher, listener);
}
private Message[] search(ImapSearcher searcher, MessageRetrievalListener listener) throws MessagingException {
checkOpen();
ArrayList<Message> messages = new ArrayList<Message>();
try {
ArrayList<Integer> uids = new ArrayList<Integer>();
List<ImapResponse> responses = searcher.search();
for (ImapResponse response : responses) {
if (response.mTag == null) {
if (ImapResponseParser.equalsIgnoreCase(response.get(0), "SEARCH")) {
for (int i = 1, count = response.size(); i < count; i++) {
uids.add(Integer.parseInt(response.getString(i)));
}
}
}
}
// Sort the uids in numerically ascending order
Collections.sort(uids);
for (int i = 0, count = uids.size(); i < count; i++) {
if (listener != null) {
listener.messageStarted("" + uids.get(i), i, count);
}
ImapMessage message = new ImapMessage("" + uids.get(i), this);
messages.add(message);
if (listener != null) {
listener.messageFinished(message, i, count);
}
}
} catch (IOException ioe) {
throw ioExceptionHandler(mConnection, ioe);
}
return messages.toArray(EMPTY_MESSAGE_ARRAY);
}
@Override
public Message[] getMessages(MessageRetrievalListener listener) throws MessagingException {
return getMessages(null, listener);
}
@Override
public Message[] getMessages(String[] uids, MessageRetrievalListener listener)
throws MessagingException {
checkOpen();
ArrayList<Message> messages = new ArrayList<Message>();
try {
if (uids == null) {
List<ImapResponse> responses = executeSimpleCommand("UID SEARCH 1:* NOT DELETED");
ArrayList<String> tempUids = new ArrayList<String>();
for (ImapResponse response : responses) {
if (ImapResponseParser.equalsIgnoreCase(response.get(0), "SEARCH")) {
for (int i = 1, count = response.size(); i < count; i++) {
tempUids.add(response.getString(i));
}
}
}
uids = tempUids.toArray(EMPTY_STRING_ARRAY);
}
for (int i = 0, count = uids.length; i < count; i++) {
if (listener != null) {
listener.messageStarted(uids[i], i, count);
}
ImapMessage message = new ImapMessage(uids[i], this);
messages.add(message);
if (listener != null) {
listener.messageFinished(message, i, count);
}
}
} catch (IOException ioe) {
throw ioExceptionHandler(mConnection, ioe);
}
return messages.toArray(EMPTY_MESSAGE_ARRAY);
}
@Override
public void fetch(Message[] messages, FetchProfile fp, MessageRetrievalListener listener)
throws MessagingException {
if (messages == null || messages.length == 0) {
return;
}
checkOpen();
List<String> uids = new ArrayList<String>(messages.length);
HashMap<String, Message> messageMap = new HashMap<String, Message>();
for (int i = 0, count = messages.length; i < count; i++) {
String uid = messages[i].getUid();
uids.add(uid);
messageMap.put(uid, messages[i]);
}
/*
* Figure out what command we are going to run:
* Flags - UID FETCH (FLAGS)
* Envelope - UID FETCH ([FLAGS] INTERNALDATE UID RFC822.SIZE FLAGS BODY.PEEK[HEADER.FIELDS (date subject from content-type to cc)])
*
*/
LinkedHashSet<String> fetchFields = new LinkedHashSet<String>();
fetchFields.add("UID");
if (fp.contains(FetchProfile.Item.FLAGS)) {
fetchFields.add("FLAGS");
}
if (fp.contains(FetchProfile.Item.ENVELOPE)) {
fetchFields.add("INTERNALDATE");
fetchFields.add("RFC822.SIZE");
fetchFields.add("BODY.PEEK[HEADER.FIELDS (date subject from content-type to cc reply-to "
+ K9.IDENTITY_HEADER + ")]");
}
if (fp.contains(FetchProfile.Item.STRUCTURE)) {
fetchFields.add("BODYSTRUCTURE");
}
if (fp.contains(FetchProfile.Item.BODY_SANE)) {
fetchFields.add(String.format("BODY.PEEK[]<0.%d>", mAccount.getMaximumAutoDownloadMessageSize()));
}
if (fp.contains(FetchProfile.Item.BODY)) {
fetchFields.add("BODY.PEEK[]");
}
for (int windowStart = 0; windowStart < messages.length; windowStart += (FETCH_WINDOW_SIZE)) {
List<String> uidWindow = uids.subList(windowStart, Math.min((windowStart + FETCH_WINDOW_SIZE), messages.length));
try {
mConnection.sendCommand(String.format("UID FETCH %s (%s)",
Utility.combine(uidWindow.toArray(new String[uidWindow.size()]), ','),
Utility.combine(fetchFields.toArray(new String[fetchFields.size()]), ' ')
), false);
ImapResponse response;
int messageNumber = 0;
ImapResponseParser.IImapResponseCallback callback = null;
if (fp.contains(FetchProfile.Item.BODY) || fp.contains(FetchProfile.Item.BODY_SANE)) {
callback = new FetchBodyCallback(messageMap);
}
do {
response = mConnection.readResponse(callback);
if (response.mTag == null && ImapResponseParser.equalsIgnoreCase(response.get(1), "FETCH")) {
ImapList fetchList = (ImapList)response.getKeyedValue("FETCH");
String uid = fetchList.getKeyedString("UID");
int msgSeq = response.getNumber(0);
if (uid != null) {
try {
msgSeqUidMap.put(msgSeq, uid);
if (K9.DEBUG) {
Log.v(K9.LOG_TAG, "Stored uid '" + uid + "' for msgSeq " + msgSeq + " into map " /*+ msgSeqUidMap.toString() */);
}
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Unable to store uid '" + uid + "' for msgSeq " + msgSeq);
}
}
Message message = messageMap.get(uid);
if (message == null) {
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Do not have message in messageMap for UID " + uid + " for " + getLogId());
handleUntaggedResponse(response);
continue;
}
if (listener != null) {
listener.messageStarted(uid, messageNumber++, messageMap.size());
}
ImapMessage imapMessage = (ImapMessage) message;
Object literal = handleFetchResponse(imapMessage, fetchList);
if (literal != null) {
if (literal instanceof String) {
String bodyString = (String)literal;
InputStream bodyStream = new ByteArrayInputStream(bodyString.getBytes());
imapMessage.parse(bodyStream);
} else if (literal instanceof Integer) {
// All the work was done in FetchBodyCallback.foundLiteral()
} else {
// This shouldn't happen
throw new MessagingException("Got FETCH response with bogus parameters");
}
}
if (listener != null) {
listener.messageFinished(message, messageNumber, messageMap.size());
}
} else {
handleUntaggedResponse(response);
}
while (response.more());
} while (response.mTag == null);
} catch (IOException ioe) {
throw ioExceptionHandler(mConnection, ioe);
}
}
}
@Override
public void fetchPart(Message message, Part part, MessageRetrievalListener listener)
throws MessagingException {
checkOpen();
String[] parts = part.getHeader(MimeHeader.HEADER_ANDROID_ATTACHMENT_STORE_DATA);
if (parts == null) {
return;
}
String fetch;
String partId = parts[0];
if ("TEXT".equalsIgnoreCase(partId)) {
fetch = String.format("BODY.PEEK[TEXT]<0.%d>", mAccount.getMaximumAutoDownloadMessageSize());
} else {
fetch = String.format("BODY.PEEK[%s]", partId);
}
try {
mConnection.sendCommand(
String.format("UID FETCH %s (UID %s)", message.getUid(), fetch),
false);
ImapResponse response;
int messageNumber = 0;
ImapResponseParser.IImapResponseCallback callback = new FetchPartCallback(part);
do {
response = mConnection.readResponse(callback);
if ((response.mTag == null) &&
(ImapResponseParser.equalsIgnoreCase(response.get(1), "FETCH"))) {
ImapList fetchList = (ImapList)response.getKeyedValue("FETCH");
String uid = fetchList.getKeyedString("UID");
if (!message.getUid().equals(uid)) {
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Did not ask for UID " + uid + " for " + getLogId());
handleUntaggedResponse(response);
continue;
}
if (listener != null) {
listener.messageStarted(uid, messageNumber++, 1);
}
ImapMessage imapMessage = (ImapMessage) message;
Object literal = handleFetchResponse(imapMessage, fetchList);
if (literal != null) {
if (literal instanceof Body) {
// Most of the work was done in FetchAttchmentCallback.foundLiteral()
part.setBody((Body)literal);
} else if (literal instanceof String) {
String bodyString = (String)literal;
InputStream bodyStream = new ByteArrayInputStream(bodyString.getBytes());
String contentTransferEncoding = part.getHeader(
MimeHeader.HEADER_CONTENT_TRANSFER_ENCODING)[0];
part.setBody(MimeUtility.decodeBody(bodyStream, contentTransferEncoding));
} else {
// This shouldn't happen
throw new MessagingException("Got FETCH response with bogus parameters");
}
}
if (listener != null) {
listener.messageFinished(message, messageNumber, 1);
}
} else {
handleUntaggedResponse(response);
}
while (response.more());
} while (response.mTag == null);
} catch (IOException ioe) {
throw ioExceptionHandler(mConnection, ioe);
}
}
// Returns value of body field
private Object handleFetchResponse(ImapMessage message, ImapList fetchList) throws MessagingException {
Object result = null;
if (fetchList.containsKey("FLAGS")) {
ImapList flags = fetchList.getKeyedList("FLAGS");
if (flags != null) {
for (int i = 0, count = flags.size(); i < count; i++) {
String flag = flags.getString(i);
if (flag.equalsIgnoreCase("\\Deleted")) {
message.setFlagInternal(Flag.DELETED, true);
} else if (flag.equalsIgnoreCase("\\Answered")) {
message.setFlagInternal(Flag.ANSWERED, true);
} else if (flag.equalsIgnoreCase("\\Seen")) {
message.setFlagInternal(Flag.SEEN, true);
} else if (flag.equalsIgnoreCase("\\Flagged")) {
message.setFlagInternal(Flag.FLAGGED, true);
}
}
}
}
if (fetchList.containsKey("INTERNALDATE")) {
Date internalDate = fetchList.getKeyedDate("INTERNALDATE");
message.setInternalDate(internalDate);
}
if (fetchList.containsKey("RFC822.SIZE")) {
int size = fetchList.getKeyedNumber("RFC822.SIZE");
message.setSize(size);
}
if (fetchList.containsKey("BODYSTRUCTURE")) {
ImapList bs = fetchList.getKeyedList("BODYSTRUCTURE");
if (bs != null) {
try {
parseBodyStructure(bs, message, "TEXT");
} catch (MessagingException e) {
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Error handling message for " + getLogId(), e);
message.setBody(null);
}
}
}
if (fetchList.containsKey("BODY")) {
int index = fetchList.getKeyIndex("BODY") + 2;
result = fetchList.getObject(index);
// Check if there's an origin octet
if (result instanceof String) {
String originOctet = (String)result;
if (originOctet.startsWith("<")) {
result = fetchList.getObject(index + 1);
}
}
}
return result;
}
@Override
public Flag[] getPermanentFlags() {
return PERMANENT_FLAGS;
}
/**
* Handle any untagged responses that the caller doesn't care to handle themselves.
* @param responses
*/
protected List<ImapResponse> handleUntaggedResponses(List<ImapResponse> responses) {
for (ImapResponse response : responses) {
handleUntaggedResponse(response);
}
return responses;
}
protected void handlePossibleUidNext(ImapResponse response) {
if (ImapResponseParser.equalsIgnoreCase(response.get(0), "OK") && response.size() > 1) {
Object bracketedObj = response.get(1);
if (bracketedObj instanceof ImapList) {
ImapList bracketed = (ImapList)bracketedObj;
if (bracketed.size() > 1) {
Object keyObj = bracketed.get(0);
if (keyObj instanceof String) {
String key = (String)keyObj;
if ("UIDNEXT".equalsIgnoreCase(key)) {
uidNext = bracketed.getNumber(1);
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Got UidNext = " + uidNext + " for " + getLogId());
}
}
}
}
}
}
/**
* Handle an untagged response that the caller doesn't care to handle themselves.
* @param response
*/
protected void handleUntaggedResponse(ImapResponse response) {
if (response.mTag == null && response.size() > 1) {
if (ImapResponseParser.equalsIgnoreCase(response.get(1), "EXISTS")) {
mMessageCount = response.getNumber(0);
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Got untagged EXISTS with value " + mMessageCount + " for " + getLogId());
}
handlePossibleUidNext(response);
if (ImapResponseParser.equalsIgnoreCase(response.get(1), "EXPUNGE") && mMessageCount > 0) {
mMessageCount
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Got untagged EXPUNGE with mMessageCount " + mMessageCount + " for " + getLogId());
}
// if (response.size() > 1) {
// Object bracketedObj = response.get(1);
// if (bracketedObj instanceof ImapList)
// ImapList bracketed = (ImapList)bracketedObj;
// if (bracketed.size() > 0)
// Object keyObj = bracketed.get(0);
// if (keyObj instanceof String)
// String key = (String)keyObj;
// if ("ALERT".equalsIgnoreCase(key))
// StringBuffer sb = new StringBuffer();
// for (int i = 2, count = response.size(); i < count; i++) {
// sb.append(response.get(i).toString());
// sb.append(' ');
// Log.w(K9.LOG_TAG, "ALERT: " + sb.toString() + " for " + getLogId());
}
//Log.i(K9.LOG_TAG, "mMessageCount = " + mMessageCount + " for " + getLogId());
}
private void parseBodyStructure(ImapList bs, Part part, String id)
throws MessagingException {
if (bs.get(0) instanceof ImapList) {
* This is a multipart/*
*/
MimeMultipart mp = new MimeMultipart();
for (int i = 0, count = bs.size(); i < count; i++) {
if (bs.get(i) instanceof ImapList) {
/*
* For each part in the message we're going to add a new BodyPart and parse
* into it.
*/
ImapBodyPart bp = new ImapBodyPart();
if (id.equalsIgnoreCase("TEXT")) {
parseBodyStructure(bs.getList(i), bp, Integer.toString(i + 1));
} else {
parseBodyStructure(bs.getList(i), bp, id + "." + (i + 1));
}
mp.addBodyPart(bp);
} else {
/*
* We've got to the end of the children of the part, so now we can find out
* what type it is and bail out.
*/
String subType = bs.getString(i);
mp.setSubType(subType.toLowerCase());
break;
}
}
part.setBody(mp);
} else {
/*
* This is a body. We need to add as much information as we can find out about
* it to the Part.
*/
/*
* 0| 0 body type
* 1| 1 body subtype
* 2| 2 body parameter parenthesized list
* 3| 3 body id (unused)
* 4| 4 body description (unused)
* 5| 5 body encoding
* 6| 6 body size
* -| 7 text lines (only for type TEXT, unused)
* Extensions (optional):
* 7| 8 body MD5 (unused)
* 8| 9 body disposition
* 9|10 body language (unused)
* 10|11 body location (unused)
*/
String type = bs.getString(0);
String subType = bs.getString(1);
String mimeType = (type + "/" + subType).toLowerCase();
ImapList bodyParams = null;
if (bs.get(2) instanceof ImapList) {
bodyParams = bs.getList(2);
}
String encoding = bs.getString(5);
int size = bs.getNumber(6);
if (MimeUtility.mimeTypeMatches(mimeType, "message/rfc822")) {
// A body type of type MESSAGE and subtype RFC822
// contains, immediately after the basic fields, the
// envelope structure, body structure, and size in
// text lines of the encapsulated message.
// [MESSAGE, RFC822, [NAME, Fwd: [#HTR-517941]: update plans at 1am Friday - Memory allocation - displayware.eml], NIL, NIL, 7BIT, 5974, NIL, [INLINE, [FILENAME*0, Fwd: [#HTR-517941]: update plans at 1am Friday - Memory all, FILENAME*1, ocation - displayware.eml]], NIL]
/*
* This will be caught by fetch and handled appropriately.
*/
throw new MessagingException("BODYSTRUCTURE message/rfc822 not yet supported.");
}
/*
* Set the content type with as much information as we know right now.
*/
String contentType = String.format("%s", mimeType);
if (bodyParams != null) {
/*
* If there are body params we might be able to get some more information out
* of them.
*/
for (int i = 0, count = bodyParams.size(); i < count; i += 2) {
contentType += String.format(";\n %s=\"%s\"",
bodyParams.getString(i),
bodyParams.getString(i + 1));
}
}
part.setHeader(MimeHeader.HEADER_CONTENT_TYPE, contentType);
// Extension items
ImapList bodyDisposition = null;
if (("text".equalsIgnoreCase(type))
&& (bs.size() > 9)
&& (bs.get(9) instanceof ImapList)) {
bodyDisposition = bs.getList(9);
} else if (!("text".equalsIgnoreCase(type))
&& (bs.size() > 8)
&& (bs.get(8) instanceof ImapList)) {
bodyDisposition = bs.getList(8);
}
String contentDisposition = "";
if (bodyDisposition != null && bodyDisposition.size() > 0) {
if (!"NIL".equalsIgnoreCase(bodyDisposition.getString(0))) {
contentDisposition = bodyDisposition.getString(0).toLowerCase();
}
if ((bodyDisposition.size() > 1)
&& (bodyDisposition.get(1) instanceof ImapList)) {
ImapList bodyDispositionParams = bodyDisposition.getList(1);
/*
* If there is body disposition information we can pull some more information
* about the attachment out.
*/
for (int i = 0, count = bodyDispositionParams.size(); i < count; i += 2) {
contentDisposition += String.format(";\n %s=\"%s\"",
bodyDispositionParams.getString(i).toLowerCase(),
bodyDispositionParams.getString(i + 1));
}
}
}
if (MimeUtility.getHeaderParameter(contentDisposition, "size") == null) {
contentDisposition += String.format(";\n size=%d", size);
}
/*
* Set the content disposition containing at least the size. Attachment
* handling code will use this down the road.
*/
part.setHeader(MimeHeader.HEADER_CONTENT_DISPOSITION, contentDisposition);
/*
* Set the Content-Transfer-Encoding header. Attachment code will use this
* to parse the body.
*/
part.setHeader(MimeHeader.HEADER_CONTENT_TRANSFER_ENCODING, encoding);
if (part instanceof ImapMessage) {
((ImapMessage) part).setSize(size);
} else if (part instanceof ImapBodyPart) {
((ImapBodyPart) part).setSize(size);
} else {
throw new MessagingException("Unknown part type " + part.toString());
}
part.setHeader(MimeHeader.HEADER_ANDROID_ATTACHMENT_STORE_DATA, id);
}
}
/**
* Appends the given messages to the selected folder. This implementation also determines
* the new UID of the given message on the IMAP server and sets the Message's UID to the
* new server UID.
*/
@Override
public void appendMessages(Message[] messages) throws MessagingException {
checkOpen();
try {
for (Message message : messages) {
mConnection.sendCommand(
String.format("APPEND %s (%s) {%d}",
encodeString(encodeFolderName(getPrefixedName())),
combineFlags(message.getFlags()),
message.calculateSize()), false);
ImapResponse response;
do {
response = mConnection.readResponse();
handleUntaggedResponse(response);
if (response.mCommandContinuationRequested) {
EOLConvertingOutputStream eolOut = new EOLConvertingOutputStream(mConnection.mOut);
message.writeTo(eolOut);
eolOut.write('\r');
eolOut.write('\n');
eolOut.flush();
}
while (response.more());
} while (response.mTag == null);
/*
* If the server supports UIDPLUS, then along with the APPEND response it will return an APPENDUID response code.
* e.g. 11 OK [APPENDUID 2 238268] APPEND completed
*
* We can use the UID included in this response to update our records.
*
* Code imported from AOSP Email as of git rev a5c3744a247e432acf9f571a9dfb55321c4baa1a
*/
Object responseList = response.get(1);
if (responseList instanceof ImapList) {
final ImapList appendList = (ImapList) responseList;
if ((appendList.size() >= 3) && appendList.getString(0).equals("APPENDUID")) {
String serverUid = appendList.getString(2);
if (!TextUtils.isEmpty(serverUid)) {
message.setUid(serverUid);
continue;
}
}
}
/*
* This part is executed in case the server does not support UIDPLUS or does not implement the APPENDUID response code.
*/
String newUid = getUidFromMessageId(message);
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Got UID " + newUid + " for message for " + getLogId());
if (newUid != null) {
message.setUid(newUid);
}
}
} catch (IOException ioe) {
throw ioExceptionHandler(mConnection, ioe);
}
}
@Override
public String getUidFromMessageId(Message message) throws MessagingException {
try {
/*
* Try to find the UID of the message we just appended using the
* Message-ID header.
*/
String[] messageIdHeader = message.getHeader("Message-ID");
if (messageIdHeader == null || messageIdHeader.length == 0) {
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Did not get a message-id in order to search for UID for " + getLogId());
return null;
}
String messageId = messageIdHeader[0];
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Looking for UID for message with message-id " + messageId + " for " + getLogId());
List<ImapResponse> responses =
executeSimpleCommand(
String.format("UID SEARCH HEADER MESSAGE-ID %s", messageId));
for (ImapResponse response1 : responses) {
if (response1.mTag == null && ImapResponseParser.equalsIgnoreCase(response1.get(0), "SEARCH")
&& response1.size() > 1) {
return response1.getString(1);
}
}
return null;
} catch (IOException ioe) {
throw new MessagingException("Could not find UID for message based on Message-ID", ioe);
}
}
@Override
public void expunge() throws MessagingException {
checkOpen();
try {
executeSimpleCommand("EXPUNGE");
} catch (IOException ioe) {
throw ioExceptionHandler(mConnection, ioe);
}
}
private String combineFlags(Flag[] flags) {
ArrayList<String> flagNames = new ArrayList<String>();
for (Flag flag : flags) {
if (flag == Flag.SEEN) {
flagNames.add("\\Seen");
} else if (flag == Flag.DELETED) {
flagNames.add("\\Deleted");
} else if (flag == Flag.ANSWERED) {
flagNames.add("\\Answered");
} else if (flag == Flag.FLAGGED) {
flagNames.add("\\Flagged");
}
}
return Utility.combine(flagNames.toArray(new String[flagNames.size()]), ' ');
}
@Override
public void setFlags(Flag[] flags, boolean value)
throws MessagingException {
checkOpen();
try {
executeSimpleCommand(String.format("UID STORE 1:* %sFLAGS.SILENT (%s)",
value ? "+" : "-", combineFlags(flags)));
} catch (IOException ioe) {
throw ioExceptionHandler(mConnection, ioe);
}
}
@Override
public String getNewPushState(String oldPushStateS, Message message) {
try {
String messageUidS = message.getUid();
int messageUid = Integer.parseInt(messageUidS);
ImapPushState oldPushState = ImapPushState.parse(oldPushStateS);
if (messageUid >= oldPushState.uidNext) {
int uidNext = messageUid + 1;
ImapPushState newPushState = new ImapPushState(uidNext);
return newPushState.toString();
} else {
return null;
}
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Exception while updated push state for " + getLogId(), e);
return null;
}
}
@Override
public void setFlags(Message[] messages, Flag[] flags, boolean value)
throws MessagingException {
checkOpen();
String[] uids = new String[messages.length];
for (int i = 0, count = messages.length; i < count; i++) {
uids[i] = messages[i].getUid();
}
ArrayList<String> flagNames = new ArrayList<String>();
for (Flag flag : flags) {
if (flag == Flag.SEEN) {
flagNames.add("\\Seen");
} else if (flag == Flag.DELETED) {
flagNames.add("\\Deleted");
} else if (flag == Flag.ANSWERED) {
flagNames.add("\\Answered");
} else if (flag == Flag.FLAGGED) {
flagNames.add("\\Flagged");
}
}
try {
executeSimpleCommand(String.format("UID STORE %s %sFLAGS.SILENT (%s)",
Utility.combine(uids, ','),
value ? "+" : "-",
Utility.combine(flagNames.toArray(new String[flagNames.size()]), ' ')));
} catch (IOException ioe) {
throw ioExceptionHandler(mConnection, ioe);
}
}
private void checkOpen() throws MessagingException {
if (!isOpen()) {
throw new MessagingException("Folder " + getPrefixedName() + " is not open.");
}
}
private MessagingException ioExceptionHandler(ImapConnection connection, IOException ioe) {
Log.e(K9.LOG_TAG, "IOException for " + getLogId(), ioe);
if (connection != null) {
connection.close();
}
close();
return new MessagingException("IO Error", ioe);
}
@Override
public boolean equals(Object o) {
if (o instanceof ImapFolder) {
return ((ImapFolder)o).getName().equalsIgnoreCase(getName());
}
return super.equals(o);
}
@Override
public int hashCode() {
return getName().hashCode();
}
protected ImapStore getStore() {
return store;
}
protected String getLogId() {
String id = getAccount().getDescription() + ":" + getName() + "/" + Thread.currentThread().getName();
if (mConnection != null) {
id += "/" + mConnection.getLogId();
}
return id;
}
}
/**
* A cacheable class that stores the details for a single IMAP connection.
*/
public static class ImapConnection {
protected Socket mSocket;
protected PeekableInputStream mIn;
protected OutputStream mOut;
protected ImapResponseParser mParser;
protected int mNextCommandTag;
protected Set<String> capabilities = new HashSet<String>();
private ImapSettings mSettings;
public ImapConnection(final ImapSettings settings) {
this.mSettings = settings;
}
protected String getLogId() {
return "conn" + hashCode();
}
private List<ImapResponse> receiveCapabilities(List<ImapResponse> responses) {
for (ImapResponse response : responses) {
ImapList capabilityList = null;
if (response.size() > 0 && ImapResponseParser.equalsIgnoreCase(response.get(0), "OK")) {
for (Object thisPart : response) {
if (thisPart instanceof ImapList) {
ImapList thisList = (ImapList)thisPart;
if (ImapResponseParser.equalsIgnoreCase(thisList.get(0), CAPABILITY_CAPABILITY)) {
capabilityList = thisList;
break;
}
}
}
} else if (response.mTag == null) {
capabilityList = response;
}
if (capabilityList != null) {
if (capabilityList.size() > 0 && ImapResponseParser.equalsIgnoreCase(capabilityList.get(0), CAPABILITY_CAPABILITY)) {
if (K9.DEBUG) {
Log.d(K9.LOG_TAG, "Saving " + capabilityList.size() + " capabilities for " + getLogId());
}
for (Object capability : capabilityList) {
if (capability instanceof String) {
// if (K9.DEBUG)
// Log.v(K9.LOG_TAG, "Saving capability '" + capability + "' for " + getLogId());
capabilities.add(((String)capability).toUpperCase());
}
}
}
}
}
return responses;
}
public void open() throws IOException, MessagingException {
if (isOpen()) {
return;
}
boolean authSuccess = false;
mNextCommandTag = 1;
try {
Security.setProperty("networkaddress.cache.ttl", "0");
} catch (Exception e) {
Log.w(K9.LOG_TAG, "Could not set DNS ttl to 0 for " + getLogId(), e);
}
try {
Security.setProperty("networkaddress.cache.negative.ttl", "0");
} catch (Exception e) {
Log.w(K9.LOG_TAG, "Could not set DNS negative ttl to 0 for " + getLogId(), e);
}
try {
SocketAddress socketAddress = new InetSocketAddress(mSettings.getHost(), mSettings.getPort());
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Connection " + getLogId() + " connecting to " + mSettings.getHost() + " @ IP addr " + socketAddress);
if (mSettings.getConnectionSecurity() == CONNECTION_SECURITY_SSL_REQUIRED ||
mSettings.getConnectionSecurity() == CONNECTION_SECURITY_SSL_OPTIONAL) {
SSLContext sslContext = SSLContext.getInstance("TLS");
final boolean secure = mSettings.getConnectionSecurity() == CONNECTION_SECURITY_SSL_REQUIRED;
sslContext.init(null, new TrustManager[] {
TrustManagerFactory.get(mSettings.getHost(), secure)
}, new SecureRandom());
mSocket = sslContext.getSocketFactory().createSocket();
mSocket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT);
} else {
mSocket = new Socket();
mSocket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT);
}
setReadTimeout(Store.SOCKET_READ_TIMEOUT);
mIn = new PeekableInputStream(new BufferedInputStream(mSocket.getInputStream(),
1024));
mParser = new ImapResponseParser(mIn);
mOut = mSocket.getOutputStream();
capabilities.clear();
ImapResponse nullResponse = mParser.readResponse();
if (K9.DEBUG && K9.DEBUG_PROTOCOL_IMAP)
Log.v(K9.LOG_TAG, getLogId() + "<<<" + nullResponse);
List<ImapResponse> nullResponses = new LinkedList<ImapResponse>();
nullResponses.add(nullResponse);
receiveCapabilities(nullResponses);
if (!hasCapability(CAPABILITY_CAPABILITY)) {
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Did not get capabilities in banner, requesting CAPABILITY for " + getLogId());
List<ImapResponse> responses = receiveCapabilities(executeSimpleCommand(COMMAND_CAPABILITY));
if (responses.size() != 2) {
throw new MessagingException("Invalid CAPABILITY response received");
}
}
if (mSettings.getConnectionSecurity() == CONNECTION_SECURITY_TLS_OPTIONAL
|| mSettings.getConnectionSecurity() == CONNECTION_SECURITY_TLS_REQUIRED) {
if (hasCapability("STARTTLS")) {
// STARTTLS
executeSimpleCommand("STARTTLS");
SSLContext sslContext = SSLContext.getInstance("TLS");
boolean secure = mSettings.getConnectionSecurity() == CONNECTION_SECURITY_TLS_REQUIRED;
sslContext.init(null, new TrustManager[] {
TrustManagerFactory.get(mSettings.getHost(), secure)
}, new SecureRandom());
mSocket = sslContext.getSocketFactory().createSocket(mSocket, mSettings.getHost(), mSettings.getPort(),
true);
mSocket.setSoTimeout(Store.SOCKET_READ_TIMEOUT);
mIn = new PeekableInputStream(new BufferedInputStream(mSocket
.getInputStream(), 1024));
mParser = new ImapResponseParser(mIn);
mOut = mSocket.getOutputStream();
} else if (mSettings.getConnectionSecurity() == CONNECTION_SECURITY_TLS_REQUIRED) {
throw new MessagingException("TLS not supported but required");
}
}
mOut = new BufferedOutputStream(mOut, 1024);
try {
// Yahoo! requires a custom IMAP command to work right over a non-3G network
if (mSettings.getHost().endsWith("yahoo.com")) {
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Found Yahoo! account. Sending proprietary commands.");
executeSimpleCommand("ID (\"GUID\" \"1\")");
}
if (mSettings.getAuthType() == AuthType.CRAM_MD5) {
authCramMD5();
// The authCramMD5 method called on the previous line does not allow for handling updated capabilities
// sent by the server. So, to make sure we update to the post-authentication capability list
// we fetch the capabilities here.
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Updating capabilities after CRAM-MD5 authentication for " + getLogId());
List<ImapResponse> responses = receiveCapabilities(executeSimpleCommand(COMMAND_CAPABILITY));
if (responses.size() != 2) {
throw new MessagingException("Invalid CAPABILITY response received");
}
} else if (mSettings.getAuthType() == AuthType.PLAIN) {
receiveCapabilities(executeSimpleCommand(String.format("LOGIN %s %s", ImapStore.encodeString(mSettings.getUsername()), ImapStore.encodeString(mSettings.getPassword())), true));
}
authSuccess = true;
} catch (ImapException ie) {
throw new AuthenticationFailedException(ie.getAlertText(), ie);
} catch (MessagingException me) {
throw new AuthenticationFailedException(null, me);
}
if (K9.DEBUG) {
Log.d(K9.LOG_TAG, CAPABILITY_COMPRESS_DEFLATE + " = " + hasCapability(CAPABILITY_COMPRESS_DEFLATE));
}
if (hasCapability(CAPABILITY_COMPRESS_DEFLATE)) {
ConnectivityManager connectivityManager = (ConnectivityManager)K9.app.getSystemService(Context.CONNECTIVITY_SERVICE);
boolean useCompression = true;
NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo();
if (netInfo != null) {
int type = netInfo.getType();
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "On network type " + type);
useCompression = mSettings.useCompression(type);
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "useCompression " + useCompression);
if (useCompression) {
try {
executeSimpleCommand(COMMAND_COMPRESS_DEFLATE);
Inflater inf = new Inflater(true);
InflaterInputStream zInputStream = new InflaterInputStream(mSocket.getInputStream(), inf);
mIn = new PeekableInputStream(new BufferedInputStream(zInputStream, 1024));
mParser = new ImapResponseParser(mIn);
ZOutputStream zOutputStream = new ZOutputStream(mSocket.getOutputStream(), JZlib.Z_BEST_SPEED, true);
mOut = new BufferedOutputStream(zOutputStream, 1024);
zOutputStream.setFlushMode(JZlib.Z_PARTIAL_FLUSH);
if (K9.DEBUG) {
Log.i(K9.LOG_TAG, "Compression enabled for " + getLogId());
}
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Unable to negotiate compression", e);
}
}
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "NAMESPACE = " + hasCapability(CAPABILITY_NAMESPACE)
+ ", mPathPrefix = " + mSettings.getPathPrefix());
if (mSettings.getPathPrefix() == null) {
if (hasCapability(CAPABILITY_NAMESPACE)) {
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "mPathPrefix is unset and server has NAMESPACE capability");
List<ImapResponse> namespaceResponses =
executeSimpleCommand(COMMAND_NAMESPACE);
for (ImapResponse response : namespaceResponses) {
if (ImapResponseParser.equalsIgnoreCase(response.get(0), COMMAND_NAMESPACE)) {
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Got NAMESPACE response " + response + " on " + getLogId());
Object personalNamespaces = response.get(1);
if (personalNamespaces != null && personalNamespaces instanceof ImapList) {
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Got personal namespaces: " + personalNamespaces);
ImapList bracketed = (ImapList)personalNamespaces;
Object firstNamespace = bracketed.get(0);
if (firstNamespace != null && firstNamespace instanceof ImapList) {
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Got first personal namespaces: " + firstNamespace);
bracketed = (ImapList)firstNamespace;
mSettings.setPathPrefix(bracketed.getString(0));
mSettings.setPathDelimeter(bracketed.getString(1));
mSettings.setCombinedPrefix(null);
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Got path '" + mSettings.getPathPrefix() + "' and separator '" + mSettings.getPathDelimeter() + "'");
}
}
}
}
} else {
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "mPathPrefix is unset but server does not have NAMESPACE capability");
mSettings.setPathPrefix("");
}
}
if (mSettings.getPathDelimeter() == null) {
try {
List<ImapResponse> nameResponses =
executeSimpleCommand(String.format("LIST \"\" \"\""));
for (ImapResponse response : nameResponses) {
if (ImapResponseParser.equalsIgnoreCase(response.get(0), "LIST")) {
mSettings.setPathDelimeter(response.getString(2));
mSettings.setCombinedPrefix(null);
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Got path delimeter '" + mSettings.getPathDelimeter() + "' for " + getLogId());
}
}
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Unable to get path delimeter using LIST", e);
}
}
} catch (SSLException e) {
throw new CertificateValidationException(e.getMessage(), e);
} catch (GeneralSecurityException gse) {
throw new MessagingException(
"Unable to open connection to IMAP server due to security error.", gse);
} catch (ConnectException ce) {
String ceMess = ce.getMessage();
String[] tokens = ceMess.split("-");
if (tokens != null && tokens.length > 1 && tokens[1] != null) {
Log.e(K9.LOG_TAG, "Stripping host/port from ConnectionException for " + getLogId(), ce);
throw new ConnectException(tokens[1].trim());
} else {
throw ce;
}
} finally {
if (!authSuccess) {
Log.e(K9.LOG_TAG, "Failed to login, closing connection for " + getLogId());
close();
}
}
}
protected void authCramMD5() throws AuthenticationFailedException, MessagingException {
try {
String tag = sendCommand("AUTHENTICATE CRAM-MD5", false);
byte[] buf = new byte[1024];
int b64NonceLen = 0;
for (int i = 0; i < buf.length; i++) {
buf[i] = (byte)mIn.read();
if (buf[i] == 0x0a) {
b64NonceLen = i;
break;
}
}
if (b64NonceLen == 0) {
throw new AuthenticationFailedException("Error negotiating CRAM-MD5: nonce too long.");
}
byte[] b64NonceTrim = new byte[b64NonceLen - 2];
System.arraycopy(buf, 1, b64NonceTrim, 0, b64NonceLen - 2);
byte[] b64CRAM = Authentication.computeCramMd5Bytes(mSettings.getUsername(),
mSettings.getPassword(), b64NonceTrim);
mOut.write(b64CRAM);
mOut.write(new byte[] { 0x0d, 0x0a });
mOut.flush();
int respLen = 0;
for (int i = 0; i < buf.length; i++) {
buf[i] = (byte)mIn.read();
if (buf[i] == 0x0a) {
respLen = i;
break;
}
}
String toMatch = tag + " OK";
String respStr = new String(buf, 0, respLen);
if (!respStr.startsWith(toMatch)) {
throw new AuthenticationFailedException("CRAM-MD5 error: " + respStr);
}
} catch (IOException ioe) {
throw new AuthenticationFailedException("CRAM-MD5 Auth Failed.", ioe);
}
}
protected void setReadTimeout(int millis) throws SocketException {
Socket sock = mSocket;
if (sock != null) {
sock.setSoTimeout(millis);
}
}
protected boolean isIdleCapable() {
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Connection " + getLogId() + " has " + capabilities.size() + " capabilities");
return capabilities.contains(CAPABILITY_IDLE);
}
protected boolean hasCapability(String capability) {
return capabilities.contains(capability.toUpperCase());
}
public boolean isOpen() {
return (mIn != null && mOut != null && mSocket != null && mSocket.isConnected() && !mSocket.isClosed());
}
public void close() {
// if (isOpen()) {
// try {
// executeSimpleCommand("LOGOUT");
// } catch (Exception e) {
try {
mIn.close();
} catch (Exception e) {
}
try {
mOut.close();
} catch (Exception e) {
}
try {
mSocket.close();
} catch (Exception e) {
}
mIn = null;
mOut = null;
mSocket = null;
}
public ImapResponse readResponse() throws IOException, MessagingException {
return readResponse(null);
}
public ImapResponse readResponse(ImapResponseParser.IImapResponseCallback callback) throws IOException {
try {
ImapResponse response = mParser.readResponse(callback);
if (K9.DEBUG && K9.DEBUG_PROTOCOL_IMAP)
Log.v(K9.LOG_TAG, getLogId() + "<<<" + response);
return response;
} catch (IOException ioe) {
close();
throw ioe;
}
}
public void sendContinuation(String continuation) throws IOException {
mOut.write(continuation.getBytes());
mOut.write('\r');
mOut.write('\n');
mOut.flush();
if (K9.DEBUG && K9.DEBUG_PROTOCOL_IMAP)
Log.v(K9.LOG_TAG, getLogId() + ">>> " + continuation);
}
public String sendCommand(String command, boolean sensitive)
throws MessagingException, IOException {
try {
open();
String tag = Integer.toString(mNextCommandTag++);
String commandToSend = tag + " " + command;
mOut.write(commandToSend.getBytes());
mOut.write('\r');
mOut.write('\n');
mOut.flush();
if (K9.DEBUG && K9.DEBUG_PROTOCOL_IMAP) {
if (sensitive && !K9.DEBUG_SENSITIVE) {
Log.v(K9.LOG_TAG, getLogId() + ">>> "
+ "[Command Hidden, Enable Sensitive Debug Logging To Show]");
} else {
Log.v(K9.LOG_TAG, getLogId() + ">>> " + commandToSend);
}
}
return tag;
} catch (IOException ioe) {
close();
throw ioe;
} catch (ImapException ie) {
close();
throw ie;
} catch (MessagingException me) {
close();
throw me;
}
}
public List<ImapResponse> executeSimpleCommand(String command) throws IOException,
ImapException, MessagingException {
return executeSimpleCommand(command, false);
}
public List<ImapResponse> executeSimpleCommand(String command, boolean sensitive) throws IOException,
ImapException, MessagingException {
return executeSimpleCommand(command, sensitive, null);
}
// public void logResponse (ImapList response) {
// for(int i=0;i<response.size();i++) {
// Object o = response.get(i);
// if(o instanceof String){
// Log.w(K9.LOG_TAG+" "+i, (String) o);
// } else if (o instanceof ImapList) {
// logResponse((ImapList)o);
public List<ImapResponse> executeSimpleCommand(String command, boolean sensitive, UntaggedHandler untaggedHandler)
throws IOException, ImapException, MessagingException {
String commandToLog = command;
if (sensitive && !K9.DEBUG_SENSITIVE) {
commandToLog = "*sensitive*";
}
//if (K9.DEBUG)
// Log.v(K9.LOG_TAG, "Sending IMAP command " + commandToLog + " on connection " + getLogId());
String tag = sendCommand(command, sensitive);
//if (K9.DEBUG)
// Log.v(K9.LOG_TAG, "Sent IMAP command " + commandToLog + " with tag " + tag + " for " + getLogId());
ArrayList<ImapResponse> responses = new ArrayList<ImapResponse>();
ImapResponse response;
do {
response = mParser.readResponse();
if (K9.DEBUG && K9.DEBUG_PROTOCOL_IMAP)
Log.v(K9.LOG_TAG, getLogId() + "<<<" + response);
if (response.mTag != null && !response.mTag.equalsIgnoreCase(tag)) {
Log.w(K9.LOG_TAG, "After sending tag " + tag + ", got tag response from previous command " + response + " for " + getLogId());
Iterator<ImapResponse> iter = responses.iterator();
while (iter.hasNext()) {
ImapResponse delResponse = iter.next();
if (delResponse.mTag != null || delResponse.size() < 2
|| (!ImapResponseParser.equalsIgnoreCase(delResponse.get(1), "EXISTS") && !ImapResponseParser.equalsIgnoreCase(delResponse.get(1), "EXPUNGE"))) {
iter.remove();
}
}
response.mTag = null;
continue;
}
if (untaggedHandler != null) {
untaggedHandler.handleAsyncUntaggedResponse(response);
}
responses.add(response);
} while (response.mTag == null);
if (response.size() < 1 || !ImapResponseParser.equalsIgnoreCase(response.get(0), "OK")) {
throw new ImapException("Command: " + commandToLog + "; response: " + response.toString(), response.getAlertText());
}
return responses;
}
}
static class ImapMessage extends MimeMessage {
ImapMessage(String uid, Folder folder) {
this.mUid = uid;
this.mFolder = folder;
}
public void setSize(int size) {
this.mSize = size;
}
@Override
public void parse(InputStream in) throws IOException, MessagingException {
super.parse(in);
}
public void setFlagInternal(Flag flag, boolean set) throws MessagingException {
super.setFlag(flag, set);
}
@Override
public void setFlag(Flag flag, boolean set) throws MessagingException {
super.setFlag(flag, set);
mFolder.setFlags(new Message[] { this }, new Flag[] { flag }, set);
}
@Override
public void delete(String trashFolderName) throws MessagingException {
getFolder().delete(new Message[] { this }, trashFolderName);
}
}
static class ImapBodyPart extends MimeBodyPart {
public ImapBodyPart() throws MessagingException {
super();
}
public void setSize(int size) {
this.mSize = size;
}
}
static class ImapException extends MessagingException {
private static final long serialVersionUID = 3725007182205882394L;
String mAlertText;
public ImapException(String message, String alertText, Throwable throwable) {
super(message, throwable);
this.mAlertText = alertText;
}
public ImapException(String message, String alertText) {
super(message);
this.mAlertText = alertText;
}
public String getAlertText() {
return mAlertText;
}
public void setAlertText(String alertText) {
mAlertText = alertText;
}
}
public class ImapFolderPusher extends ImapFolder implements UntaggedHandler {
final PushReceiver receiver;
Thread listeningThread = null;
final AtomicBoolean stop = new AtomicBoolean(false);
final AtomicBoolean idling = new AtomicBoolean(false);
final AtomicBoolean doneSent = new AtomicBoolean(false);
final AtomicInteger delayTime = new AtomicInteger(NORMAL_DELAY_TIME);
final AtomicInteger idleFailureCount = new AtomicInteger(0);
final AtomicBoolean needsPoll = new AtomicBoolean(false);
List<ImapResponse> storedUntaggedResponses = new ArrayList<ImapResponse>();
TracingWakeLock wakeLock = null;
public ImapFolderPusher(ImapStore store, String name, PushReceiver nReceiver) {
super(store, name);
receiver = nReceiver;
TracingPowerManager pm = TracingPowerManager.getPowerManager(receiver.getContext());
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ImapFolderPusher " + store.getAccount().getDescription() + ":" + getName());
wakeLock.setReferenceCounted(false);
}
public void refresh() throws IOException, MessagingException {
if (idling.get()) {
wakeLock.acquire(K9.PUSH_WAKE_LOCK_TIMEOUT);
sendDone();
}
}
private void sendDone() throws IOException, MessagingException {
if (doneSent.compareAndSet(false, true)) {
ImapConnection conn = mConnection;
if (conn != null) {
conn.setReadTimeout(Store.SOCKET_READ_TIMEOUT);
sendContinuation("DONE");
}
}
}
private void sendContinuation(String continuation)
throws IOException {
ImapConnection conn = mConnection;
if (conn != null) {
conn.sendContinuation(continuation);
}
}
public void start() {
Runnable runner = new Runnable() {
public void run() {
wakeLock.acquire(K9.PUSH_WAKE_LOCK_TIMEOUT);
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Pusher starting for " + getLogId());
while (!stop.get()) {
try {
int oldUidNext = -1;
try {
String pushStateS = receiver.getPushState(getName());
ImapPushState pushState = ImapPushState.parse(pushStateS);
oldUidNext = pushState.uidNext;
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Got oldUidNext " + oldUidNext + " for " + getLogId());
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Unable to get oldUidNext for " + getLogId(), e);
}
ImapConnection oldConnection = mConnection;
internalOpen(OpenMode.READ_ONLY);
ImapConnection conn = mConnection;
if (conn == null) {
receiver.pushError("Could not establish connection for IDLE", null);
throw new MessagingException("Could not establish connection for IDLE");
}
if (!conn.isIdleCapable()) {
stop.set(true);
receiver.pushError("IMAP server is not IDLE capable: " + conn.toString(), null);
throw new MessagingException("IMAP server is not IDLE capable:" + conn.toString());
}
if (!stop.get() && mAccount.isPushPollOnConnect() && (conn != oldConnection || needsPoll.getAndSet(false))) {
List<ImapResponse> untaggedResponses = new ArrayList<ImapResponse>(storedUntaggedResponses);
storedUntaggedResponses.clear();
processUntaggedResponses(untaggedResponses);
if (mMessageCount == -1) {
throw new MessagingException("Message count = -1 for idling");
}
receiver.syncFolder(ImapFolderPusher.this);
}
if (stop.get()) {
continue;
}
int startUid = oldUidNext;
int newUidNext = uidNext;
if (newUidNext == -1) {
if (K9.DEBUG) {
Log.d(K9.LOG_TAG, "uidNext is -1, using search to find highest UID");
}
int highestUid = getHighestUid();
if (highestUid != -1) {
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "highest UID = " + highestUid);
newUidNext = highestUid + 1;
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "highest UID = " + highestUid
+ ", set newUidNext to " + newUidNext);
}
}
if (startUid < newUidNext - mAccount.getDisplayCount()) {
startUid = newUidNext - mAccount.getDisplayCount();
}
if (startUid < 1) {
startUid = 1;
}
if (newUidNext > startUid) {
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Needs sync from uid " + startUid + " to " + newUidNext + " for " + getLogId());
List<Message> messages = new ArrayList<Message>();
for (int uid = startUid; uid < newUidNext; uid++) {
ImapMessage message = new ImapMessage("" + uid, ImapFolderPusher.this);
messages.add(message);
}
if (messages.size() > 0) {
pushMessages(messages, true);
}
} else {
List<ImapResponse> untaggedResponses = null;
while (storedUntaggedResponses.size() > 0) {
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Processing " + storedUntaggedResponses.size() + " untagged responses from previous commands for " + getLogId());
untaggedResponses = new ArrayList<ImapResponse>(storedUntaggedResponses);
storedUntaggedResponses.clear();
processUntaggedResponses(untaggedResponses);
}
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "About to IDLE for " + getLogId());
receiver.setPushActive(getName(), true);
idling.set(true);
doneSent.set(false);
conn.setReadTimeout((getAccount().getIdleRefreshMinutes() * 60 * 1000) + IDLE_READ_TIMEOUT_INCREMENT);
untaggedResponses = executeSimpleCommand(COMMAND_IDLE, false, ImapFolderPusher.this);
idling.set(false);
delayTime.set(NORMAL_DELAY_TIME);
idleFailureCount.set(0);
}
} catch (Exception e) {
wakeLock.acquire(K9.PUSH_WAKE_LOCK_TIMEOUT);
storedUntaggedResponses.clear();
idling.set(false);
receiver.setPushActive(getName(), false);
try {
close();
} catch (Exception me) {
Log.e(K9.LOG_TAG, "Got exception while closing for exception for " + getLogId(), me);
}
if (stop.get()) {
Log.i(K9.LOG_TAG, "Got exception while idling, but stop is set for " + getLogId());
} else {
receiver.pushError("Push error for " + getName(), e);
Log.e(K9.LOG_TAG, "Got exception while idling for " + getLogId(), e);
int delayTimeInt = delayTime.get();
receiver.sleep(wakeLock, delayTimeInt);
delayTimeInt *= 2;
if (delayTimeInt > MAX_DELAY_TIME) {
delayTimeInt = MAX_DELAY_TIME;
}
delayTime.set(delayTimeInt);
if (idleFailureCount.incrementAndGet() > IDLE_FAILURE_COUNT_LIMIT) {
Log.e(K9.LOG_TAG, "Disabling pusher for " + getLogId() + " after " + idleFailureCount.get() + " consecutive errors");
receiver.pushError("Push disabled for " + getName() + " after " + idleFailureCount.get() + " consecutive errors", e);
stop.set(true);
}
}
}
}
receiver.setPushActive(getName(), false);
try {
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Pusher for " + getLogId() + " is exiting");
close();
} catch (Exception me) {
Log.e(K9.LOG_TAG, "Got exception while closing for " + getLogId(), me);
} finally {
wakeLock.release();
}
}
};
listeningThread = new Thread(runner);
listeningThread.start();
}
@Override
protected void handleUntaggedResponse(ImapResponse response) {
if (response.mTag == null && response.size() > 1) {
Object responseType = response.get(1);
if (ImapResponseParser.equalsIgnoreCase(responseType, "FETCH")
|| ImapResponseParser.equalsIgnoreCase(responseType, "EXPUNGE")
|| ImapResponseParser.equalsIgnoreCase(responseType, "EXISTS")) {
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Storing response " + response + " for later processing");
storedUntaggedResponses.add(response);
}
handlePossibleUidNext(response);
}
}
protected void processUntaggedResponses(List<ImapResponse> responses) throws MessagingException {
boolean skipSync = false;
int oldMessageCount = mMessageCount;
if (oldMessageCount == -1) {
skipSync = true;
}
List<Integer> flagSyncMsgSeqs = new ArrayList<Integer>();
List<String> removeMsgUids = new LinkedList<String>();
for (ImapResponse response : responses) {
oldMessageCount += processUntaggedResponse(oldMessageCount, response, flagSyncMsgSeqs, removeMsgUids);
}
if (!skipSync) {
if (oldMessageCount < 0) {
oldMessageCount = 0;
}
if (mMessageCount > oldMessageCount) {
syncMessages(mMessageCount, true);
}
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "UIDs for messages needing flag sync are " + flagSyncMsgSeqs + " for " + getLogId());
if (flagSyncMsgSeqs.size() > 0) {
syncMessages(flagSyncMsgSeqs);
}
if (removeMsgUids.size() > 0) {
removeMessages(removeMsgUids);
}
}
private void syncMessages(int end, boolean newArrivals) throws MessagingException {
int oldUidNext = -1;
try {
String pushStateS = receiver.getPushState(getName());
ImapPushState pushState = ImapPushState.parse(pushStateS);
oldUidNext = pushState.uidNext;
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Got oldUidNext " + oldUidNext + " for " + getLogId());
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Unable to get oldUidNext for " + getLogId(), e);
}
Message[] messageArray = getMessages(end, end, null, true, null);
if (messageArray != null && messageArray.length > 0) {
int newUid = Integer.parseInt(messageArray[0].getUid());
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Got newUid " + newUid + " for message " + end + " on " + getLogId());
int startUid = oldUidNext;
if (startUid < newUid - 10) {
startUid = newUid - 10;
}
if (startUid < 1) {
startUid = 1;
}
if (newUid >= startUid) {
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Needs sync from uid " + startUid + " to " + newUid + " for " + getLogId());
List<Message> messages = new ArrayList<Message>();
for (int uid = startUid; uid <= newUid; uid++) {
ImapMessage message = new ImapMessage("" + uid, ImapFolderPusher.this);
messages.add(message);
}
if (messages.size() > 0) {
pushMessages(messages, true);
}
}
}
}
private void syncMessages(List<Integer> flagSyncMsgSeqs) {
try {
Message[] messageArray = null;
messageArray = getMessages(flagSyncMsgSeqs, true, null);
List<Message> messages = new ArrayList<Message>();
messages.addAll(Arrays.asList(messageArray));
pushMessages(messages, false);
} catch (Exception e) {
receiver.pushError("Exception while processing Push untagged responses", e);
}
}
private void removeMessages(List<String> removeUids) {
List<Message> messages = new ArrayList<Message>(removeUids.size());
try {
Message[] existingMessages = getMessagesFromUids(removeUids, true, null);
for (Message existingMessage : existingMessages) {
needsPoll.set(true);
msgSeqUidMap.clear();
String existingUid = existingMessage.getUid();
Log.w(K9.LOG_TAG, "Message with UID " + existingUid + " still exists on server, not expunging");
removeUids.remove(existingUid);
}
for (String uid : removeUids) {
ImapMessage message = new ImapMessage(uid, this);
try {
message.setFlagInternal(Flag.DELETED, true);
} catch (MessagingException me) {
Log.e(K9.LOG_TAG, "Unable to set DELETED flag on message " + message.getUid());
}
messages.add(message);
}
receiver.messagesRemoved(this, messages);
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Cannot remove EXPUNGEd messages", e);
}
}
protected int processUntaggedResponse(int oldMessageCount, ImapResponse response, List<Integer> flagSyncMsgSeqs, List<String> removeMsgUids) {
super.handleUntaggedResponse(response);
int messageCountDelta = 0;
if (response.mTag == null && response.size() > 1) {
try {
Object responseType = response.get(1);
if (ImapResponseParser.equalsIgnoreCase(responseType, "FETCH")) {
Log.i(K9.LOG_TAG, "Got FETCH " + response);
int msgSeq = response.getNumber(0);
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Got untagged FETCH for msgseq " + msgSeq + " for " + getLogId());
if (!flagSyncMsgSeqs.contains(msgSeq)) {
flagSyncMsgSeqs.add(msgSeq);
}
}
if (ImapResponseParser.equalsIgnoreCase(responseType, "EXPUNGE")) {
int msgSeq = response.getNumber(0);
if (msgSeq <= oldMessageCount) {
messageCountDelta = -1;
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Got untagged EXPUNGE for msgseq " + msgSeq + " for " + getLogId());
List<Integer> newSeqs = new ArrayList<Integer>();
Iterator<Integer> flagIter = flagSyncMsgSeqs.iterator();
while (flagIter.hasNext()) {
Integer flagMsg = flagIter.next();
if (flagMsg >= msgSeq) {
flagIter.remove();
if (flagMsg > msgSeq) {
newSeqs.add(flagMsg
}
}
}
flagSyncMsgSeqs.addAll(newSeqs);
List<Integer> msgSeqs = new ArrayList<Integer>(msgSeqUidMap.keySet());
Collections.sort(msgSeqs); // Have to do comparisons in order because of msgSeq reductions
for (Integer msgSeqNumI : msgSeqs) {
if (K9.DEBUG) {
Log.v(K9.LOG_TAG, "Comparing EXPUNGEd msgSeq " + msgSeq + " to " + msgSeqNumI);
}
int msgSeqNum = msgSeqNumI;
if (msgSeqNum == msgSeq) {
String uid = msgSeqUidMap.get(msgSeqNum);
if (K9.DEBUG) {
Log.d(K9.LOG_TAG, "Scheduling removal of UID " + uid + " because msgSeq " + msgSeqNum + " was expunged");
}
removeMsgUids.add(uid);
msgSeqUidMap.remove(msgSeqNum);
} else if (msgSeqNum > msgSeq) {
String uid = msgSeqUidMap.get(msgSeqNum);
if (K9.DEBUG) {
Log.d(K9.LOG_TAG, "Reducing msgSeq for UID " + uid + " from " + msgSeqNum + " to " + (msgSeqNum - 1));
}
msgSeqUidMap.remove(msgSeqNum);
msgSeqUidMap.put(msgSeqNum - 1, uid);
}
}
}
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Could not handle untagged FETCH for " + getLogId(), e);
}
}
return messageCountDelta;
}
private void pushMessages(List<Message> messages, boolean newArrivals) {
RuntimeException holdException = null;
try {
if (newArrivals) {
receiver.messagesArrived(this, messages);
} else {
receiver.messagesFlagsChanged(this, messages);
}
} catch (RuntimeException e) {
holdException = e;
}
if (holdException != null) {
throw holdException;
}
}
public void stop() {
stop.set(true);
if (listeningThread != null) {
listeningThread.interrupt();
}
ImapConnection conn = mConnection;
if (conn != null) {
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Closing mConnection to stop pushing for " + getLogId());
conn.close();
} else {
Log.w(K9.LOG_TAG, "Attempt to interrupt null mConnection to stop pushing on folderPusher for " + getLogId());
}
}
public void handleAsyncUntaggedResponse(ImapResponse response) {
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Got async response: " + response);
if (stop.get()) {
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Got async untagged response: " + response + ", but stop is set for " + getLogId());
try {
sendDone();
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Exception while sending DONE for " + getLogId(), e);
}
} else {
if (response.mTag == null) {
if (response.size() > 1) {
boolean started = false;
Object responseType = response.get(1);
if (ImapResponseParser.equalsIgnoreCase(responseType, "EXISTS") || ImapResponseParser.equalsIgnoreCase(responseType, "EXPUNGE") ||
ImapResponseParser.equalsIgnoreCase(responseType, "FETCH")) {
if (!started) {
wakeLock.acquire(K9.PUSH_WAKE_LOCK_TIMEOUT);
started = true;
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Got useful async untagged response: " + response + " for " + getLogId());
try {
sendDone();
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Exception while sending DONE for " + getLogId(), e);
}
}
} else if (response.mCommandContinuationRequested) {
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Idling " + getLogId());
wakeLock.release();
}
}
}
}
}
@Override
public Pusher getPusher(PushReceiver receiver) {
return new ImapPusher(this, receiver);
}
public class ImapPusher implements Pusher {
final ImapStore mStore;
final PushReceiver mReceiver;
private long lastRefresh = -1;
HashMap<String, ImapFolderPusher> folderPushers = new HashMap<String, ImapFolderPusher>();
public ImapPusher(ImapStore store, PushReceiver receiver) {
mStore = store;
mReceiver = receiver;
}
public void start(List<String> folderNames) {
stop();
synchronized (folderPushers) {
setLastRefresh(System.currentTimeMillis());
for (String folderName : folderNames) {
ImapFolderPusher pusher = folderPushers.get(folderName);
if (pusher == null) {
pusher = new ImapFolderPusher(mStore, folderName, mReceiver);
folderPushers.put(folderName, pusher);
pusher.start();
}
}
}
}
public void refresh() {
synchronized (folderPushers) {
for (ImapFolderPusher folderPusher : folderPushers.values()) {
try {
folderPusher.refresh();
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Got exception while refreshing for " + folderPusher.getName(), e);
}
}
}
}
public void stop() {
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Requested stop of IMAP pusher");
synchronized (folderPushers) {
for (ImapFolderPusher folderPusher : folderPushers.values()) {
try {
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Requesting stop of IMAP folderPusher " + folderPusher.getName());
folderPusher.stop();
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Got exception while stopping " + folderPusher.getName(), e);
}
}
folderPushers.clear();
}
}
public int getRefreshInterval() {
return (getAccount().getIdleRefreshMinutes() * 60 * 1000);
}
public long getLastRefresh() {
return lastRefresh;
}
public void setLastRefresh(long lastRefresh) {
this.lastRefresh = lastRefresh;
}
}
private interface UntaggedHandler {
void handleAsyncUntaggedResponse(ImapResponse respose);
}
protected static class ImapPushState {
protected int uidNext;
protected ImapPushState(int nUidNext) {
uidNext = nUidNext;
}
protected static ImapPushState parse(String pushState) {
int newUidNext = -1;
if (pushState != null) {
StringTokenizer tokenizer = new StringTokenizer(pushState, ";");
while (tokenizer.hasMoreTokens()) {
StringTokenizer thisState = new StringTokenizer(tokenizer.nextToken(), "=");
if (thisState.hasMoreTokens()) {
String key = thisState.nextToken();
if ("uidNext".equalsIgnoreCase(key) && thisState.hasMoreTokens()) {
String value = thisState.nextToken();
try {
newUidNext = Integer.parseInt(value);
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Unable to part uidNext value " + value, e);
}
}
}
}
}
return new ImapPushState(newUidNext);
}
@Override
public String toString() {
return "uidNext=" + uidNext;
}
}
private interface ImapSearcher {
List<ImapResponse> search() throws IOException, MessagingException;
}
private static class FetchBodyCallback implements ImapResponseParser.IImapResponseCallback {
private HashMap<String, Message> mMessageMap;
FetchBodyCallback(HashMap<String, Message> mesageMap) {
mMessageMap = mesageMap;
}
@Override
public Object foundLiteral(ImapResponse response,
FixedLengthInputStream literal) throws IOException, Exception {
if (response.mTag == null &&
ImapResponseParser.equalsIgnoreCase(response.get(1), "FETCH")) {
ImapList fetchList = (ImapList)response.getKeyedValue("FETCH");
String uid = fetchList.getKeyedString("UID");
ImapMessage message = (ImapMessage) mMessageMap.get(uid);
message.parse(literal);
// Return placeholder object
return new Integer(1);
}
return null;
}
}
private static class FetchPartCallback implements ImapResponseParser.IImapResponseCallback {
private Part mPart;
FetchPartCallback(Part part) {
mPart = part;
}
@Override
public Object foundLiteral(ImapResponse response,
FixedLengthInputStream literal) throws IOException, Exception {
if (response.mTag == null &&
ImapResponseParser.equalsIgnoreCase(response.get(1), "FETCH")) {
//TODO: check for correct UID
String contentTransferEncoding = mPart.getHeader(
MimeHeader.HEADER_CONTENT_TRANSFER_ENCODING)[0];
return MimeUtility.decodeBody(literal, contentTransferEncoding);
}
return null;
}
}
}
|
package com.iSiteProyect;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
public class ll_Inicio_Login extends Activity {
public static final String DEVICE_EXTRA = "com.blueserial.SOCKET";
public static final String DEVICE_UUID = "com.blueserial.uuid";
public static final String BUFFER_SIZE = "com.blueserial.buffersize";
public static final String TAG = "ISITE PROYECTO";
public int mMaxChars = 50000;//Default
public BluetoothSocket mBTSocket;
public ReadInput mReadThread = null;
public boolean mIsUserInitiatedDisconnect = false;
public Boolean Apuntamiento=false,Booteo=true,Habilitacion=false;;
public UUID mDeviceUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); // Standard SPP UUID
public int mBufferSize = 50000; //Default
public Float NivelGlobal;
public int NivelGlobalInt=0;
public String strInputGlobal="";
public boolean mIsBluetoothConnected = false;
public BluetoothDevice mDevice;
public ProgressBar progressBarBoot;
public ProgressDialog progressDialog;
public Button btn_LogOut;
public Spinner spin_TX,spin_RX,spin_Otros;
public ArrayAdapter<String> TxAdapter,RxAdapter,OtrosAdapter;
public Button btn_Ingresar,btn_Cargar_OPT,btn_SetFreq,btn_Reset,
btn_Apuntamiento,btn_Prueba;
public ToggleButton TB_Login,TB_CwOnOff,TB_Pointing;
public TextView TextFrecuenciaLeida,TextCWEstado,TextPointing,TextPrueba;
public EditText EditFreq,EditPass,EditPrueba;
public ProgressDialog progressDialogBooteo;
public ProgressBar progressBar_Apuntamiento;
public Handler puente;
public MedirBaliza Apuntando;
public VentanaDialogoNivel DialogoNivel;
public Boolean Bool_pointing=false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ll_inicio_login);
ActivityHelper.initialize(this);
Intent intent = getIntent();
Bundle b = intent.getExtras();
mDevice = b.getParcelable(Homescreen.DEVICE_EXTRA);
mDeviceUUID = UUID.fromString(b.getString(Homescreen.DEVICE_UUID));
mMaxChars = b.getInt(Homescreen.BUFFER_SIZE);
Log.d(TAG, "OnCreate");
Toast.makeText(getApplicationContext(), "OnCreate", Toast.LENGTH_LONG).show();
LevantarXML();
Botones();
SetupUI();
progressDialog = new ProgressDialog(ll_Inicio_Login.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("Detectando Nivel del Satelite...");
progressDialog.setMax(100);
progressDialog.setCancelable(true);
progressDialog.show();
}
/*
private void MensajeArranque() {
progressDialog = new ProgressDialog(ll_Inicio_Login.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setMessage("Equipo arrancando\nEspere 2 min aprox ...");
progressDialog.setMax(10);
progressDialog.setProgress(0);
progressDialog.setCancelable(true);
progressDialog.show();
}
*/
private void SetupUI() {
TB_Login.setChecked(true);
progressBar_Apuntamiento.setMax(10);
progressBar_Apuntamiento.setProgress(5);
}
private void Botones() {
btn_Prueba.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
DialogoNivel= new VentanaDialogoNivel();
DialogoNivel.execute();
}
});
btn_SetFreq.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
FuncionEnviar("tx freq "+Float.parseFloat(EditFreq.getText().toString()));
}
});
btn_Reset.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//FuncionEnviar("reset board");
progressDialog.cancel();
}
});
btn_Ingresar.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
TB_Login.setChecked(true);
FuncionEnviar("telnet localhost");
}
});
btn_Cargar_OPT.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
progressDialog.show();
Log.d(TAG, "boton opt");
}
});
btn_Apuntamiento.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(btn_Apuntamiento.getText().toString().equals("Disable")){
FuncionEnviar("rx pointing disable");
btn_Apuntamiento.setText("Enable");
}
else{
FuncionEnviar("rx pointing enable");
btn_Apuntamiento.setText("Disable");
}
}
});
TB_Login.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
Toast.makeText(getApplicationContext(), "Log Telnet ", Toast.LENGTH_SHORT).show();
Habilitacion=isChecked;}
else{Habilitacion=isChecked;
Toast.makeText(getApplicationContext(), "Log Linux ", Toast.LENGTH_SHORT).show();}
}
});
TB_CwOnOff.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
FuncionEnviar("tx cw on");
Toast.makeText(getApplicationContext(), "CW ON", Toast.LENGTH_SHORT).show();
}
else{
FuncionEnviar("tx cw off");
Toast.makeText(getApplicationContext(), "CW OFF", Toast.LENGTH_SHORT).show();}
}
});
TB_Pointing.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
FuncionEnviar("rx pointing on");
}else{
FuncionEnviar("rx pointing off");
}
}
});
}
private void LevantarXML() {
TextFrecuenciaLeida=(TextView) findViewById(R.id.TextFrecuenciaLeida);
TextCWEstado=(TextView) findViewById(R.id.TextCWEstado);
TextPointing=(TextView) findViewById(R.id.TextPointing);
TextPrueba=(TextView) findViewById(R.id.TextPrueba);
btn_Ingresar=(Button) findViewById(R.id.btn_Ingresar);
btn_SetFreq=(Button) findViewById(R.id.btn_SetFreq);
btn_Reset=(Button) findViewById(R.id.btn_Reset);
btn_Apuntamiento=(Button) findViewById(R.id.btnPointingEnable);
btn_Cargar_OPT=(Button) findViewById(R.id.btn_CargarOPT);
btn_Prueba=(Button) findViewById(R.id.btn_Prueba);
TB_CwOnOff=(ToggleButton) findViewById(R.id.TB_CwOnOff);
TB_Login=(ToggleButton) findViewById(R.id.TB_Login);
TB_Pointing=(ToggleButton) findViewById(R.id.TB_Pointing);
EditFreq=(EditText) findViewById(R.id.EditFreq);
EditPass=(EditText) findViewById(R.id.EditPass);
EditPrueba=(EditText) findViewById(R.id.EditPrueba);
progressBar_Apuntamiento=(ProgressBar) findViewById(R.id.progressBar_Apuntamiento);
}
public void FuncionEnviar(String StringEnviado){
try {
mBTSocket.getOutputStream().write((StringEnviado+"\r").getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void FuncionDetectarComando(String detectorString,Boolean hab){
Log.d(TAG, "Entrada General de Datos");
if(hab){
if (detectorString.contains("Username:")){
Log.d(TAG, "Username:");
FuncionEnviar("admin");
}
if(detectorString.contains("Password:")){
Log.d(TAG, "Password:");
FuncionEnviar("P@55w0rd!");
}
if(detectorString.contains(">")){
Log.d(TAG, "telnet >"+strInputGlobal);
}
if(detectorString.contains(("tx cw on"))||detectorString.contains("tx cw off")){
FuncionEnviar("tx cw");
Log.d(TAG, "CW solo"+strInputGlobal); // FRANCO GIOVANAZZI MAMA SOFIA DIEGO
}
if(detectorString.contains("cw =")){
Log.d(TAG, "CW ="+strInputGlobal); // FRANCO GIOVANAZZI MAMA SOFIA DIEGO
TextCWEstado.post(new Runnable() {
public void run() {
int posicion =strInputGlobal.indexOf("=");
TextCWEstado.setText("CW = "+strInputGlobal.substring(posicion+2,posicion+5));
}
});
}
if(detectorString.contains("pointing =")){
TextCWEstado.post(new Runnable() {
public void run() {
int posicion =strInputGlobal.indexOf("=");
TextPointing.setText("Point "+strInputGlobal.substring(posicion+2,posicion+5));
Log.d(TAG, "Pointing = "+strInputGlobal.substring(posicion+2,posicion+5)); // FRANCO GIOVANAZZI MAMA SOFIA DIEGO
}
});
}
if(detectorString.contains("pointing = on")){
Bool_pointing=true;
}
if(detectorString.contains("pointing = off")){
Bool_pointing=false;
}
if(detectorString.contains("Tx Frequency")){
// Log.d(TAG, ""+strInputGlobal); // FRANCO GIOVANAZZI MAMA SOFIA DIEGO
TextFrecuenciaLeida.post(new Runnable() {
public void run() {
int posicion =strInputGlobal.indexOf("=");
TextFrecuenciaLeida.setText(strInputGlobal.substring(posicion+2,posicion+15));
}
});
}
}
else
{
Log.d(TAG, "Linux");
if (detectorString.contains("DRAM Test Successful")){
Log.d(TAG, "DRAM Test Successful antes");
}
if(detectorString.contains("Uncompressing Linux")){
Log.d(TAG, "Uncompressing Linux");
}
if (detectorString.contains("iDirect login:")){
Log.d(TAG, "iDirect login:");
FuncionEnviar("root");
}
if(detectorString.contains("Password:")){
Log.d(TAG, "Password:");
FuncionEnviar("P@55w0rd!");
}
if(detectorString.contains("
Log.d(TAG, "Linux # "+hab);
}
}
}
/////////////////////////////////////////
public class DisConnectBT extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
}
@Override
protected Void doInBackground(Void... params) {
if (mReadThread != null) {
mReadThread.stop();
while (mReadThread.isRunning())
; // Wait until it stops
mReadThread = null;
}
try {
mBTSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
mIsBluetoothConnected = false;
if (mIsUserInitiatedDisconnect) {
finish();
}
}
}
public void msg(String s) {
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}
@Override
protected void onPause() {
/* if (mBTSocket != null && mIsBluetoothConnected) {
new DisConnectBT().execute();
}*/
Log.d(TAG, "Paused");
super.onPause();
}
@Override
protected void onResume() {
if (mBTSocket == null || !mIsBluetoothConnected) {
new ConnectBT().execute();
}
Log.d(TAG, "Resumed");
super.onResume();
}
@Override
protected void onStop() {
if (mBTSocket != null && mIsBluetoothConnected) {
new DisConnectBT().execute();
}
Log.d(TAG, "Stopped");
super.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
}
public class ConnectBT extends AsyncTask<Void, Void, Void> {
private boolean mConnectSuccessful = true;
@Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(ll_Inicio_Login.this, "Espere un momento...", "Conectando");
}
@Override
protected Void doInBackground(Void... devices) {
try {
if (mBTSocket == null || !mIsBluetoothConnected) {
mBTSocket = mDevice.createInsecureRfcommSocketToServiceRecord(mDeviceUUID);
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
mBTSocket.connect();
}
} catch (IOException e) {
// Unable to connect to device
e.printStackTrace();
mConnectSuccessful = false;
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (!mConnectSuccessful) {
Toast.makeText(getApplicationContext(), "Could not connect to device. Is it a Serial device? Also check if the UUID is correct in the settings", Toast.LENGTH_LONG).show();
finish();
} else {
msg("Connected to device");
mIsBluetoothConnected = true;
mReadThread = new ReadInput(); // Kick off input reader
}
progressDialog.dismiss();
}
}
public class ReadInput implements Runnable {
private boolean bStop = false;
private Thread t;
public ReadInput() {
t = new Thread(this, "Input Thread");
t.start();
}
public boolean isRunning() {
return t.isAlive();
}
@Override
public void run() {
InputStream inputStream;
try {
inputStream = mBTSocket.getInputStream();
while (!bStop) {
byte[] buffer = new byte[256];
if (inputStream.available() > 0) {
inputStream.read(buffer);
int i = 0;
for (i = 0; i < buffer.length && buffer[i] != 0; i++) {
}
final String strInput = new String(buffer, 0, i);
Log.d(TAG, "strInput: " + strInput);
FuncionDetectarComando(strInput,Habilitacion);
strInputGlobal=strInput;
DialogoNivel.execute();
}
Thread.sleep(500);
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void stop() {
bStop = true;
}
}
/////////////////////////////////////////
public class MedirBaliza extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
//TextPrueba.setText(strInputGlobal);
}
@Override
protected Void doInBackground(Void... devices) {
// progressBar_Apuntamiento.setProgress((int)(nivel*10.0));
float nivel;
try {
// nivel= Float.parseFloat(String.valueOf(strInputGlobal));
//progressBar_Apuntamiento.setProgress((int)(nivel*10.0));
Log.d(TAG, "progress bar apuntamiento strInputGlobal ="+strInputGlobal);
Log.d(TAG, "progress bar apuntamiento nivel =");
} catch (NumberFormatException nfe){
Log.d(TAG, "progress bar apuntamiento mal="+strInputGlobal);
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
public class VentanaDialogoNivel extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
String[] NivelesAlmacenados = strInputGlobal.split("\r");
float nivelFlotante= Float.parseFloat(NivelesAlmacenados[0])*100;
int NivelBaliza=(int)nivelFlotante;
TextPrueba.setText("String: "+NivelesAlmacenados[0]+" float * 10: "+nivelFlotante +" integer: "+NivelBaliza);
progressDialog.setProgress(NivelBaliza);
}
@Override
protected Void doInBackground(Void... devices) {
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
}
|
/*
* Author : Sravan Kumar
*/
package com.iit.controller;
import java.sql.ResultSet;
import java.util.*;
import java.text.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Date;
import java.sql.SQLException;
import java.util.Properties;
import java.util.Random;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javazoom.upload.MultipartFormDataRequest;
import javazoom.upload.UploadException;
import com.iit.commons.Authenticator;
import com.iit.commons.Commons;
import com.iit.commons.Upload;
import com.iit.dbUtilities.DataService;
import com.iit.experienced.ExperiencedBean;
import com.iit.intern.InternBean;
import com.iit.ra.RABean;
//import com.mysql.jdbc.ResultSet;
//import com.iit.checkbox.*;
/**
* Servlet implementation class ActionServlet
*/
public class ActionServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ActionServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
Upload up = new Upload();
DataService ds = new DataService();
System.out.println(request.getParameter("WhatFor"));
MultipartFormDataRequest mrequest;
String whatFor = request.getParameter("WhatFor");
if(whatFor==null){
try {
mrequest = new MultipartFormDataRequest(request);
System.out.println(mrequest);
whatFor = mrequest.getParameter("WhatFor");
System.out.println("whatFor "+whatFor);
if(whatFor.equals("registerIntern")){
String firstName = mrequest.getParameter("firstName");
String lastName = mrequest.getParameter("lastName");
String joiningDate = mrequest.getParameter("joiningDate");
Date joiningDateSql = Commons.stringToSqlDate(joiningDate);
String leavingDate = mrequest.getParameter("leavingDate");
Date leavingDateSql = Commons.stringToSqlDate(leavingDate);
String contactNumber = mrequest.getParameter("contactNumber");
String emailId = mrequest.getParameter("emailId");
String collegeName = mrequest.getParameter("collegeName");
float cgpa = Float.parseFloat(mrequest.getParameter("percentage"));
int duration = Integer.parseInt(mrequest.getParameter("duration"));
String stream = mrequest.getParameter("stream");
int yearOfStudy = Integer.parseInt(mrequest.getParameter("yearOfStudy"));
String availabilityForF2F = mrequest.getParameter("availabilityForF2F");
String additionalInfo = mrequest.getParameter("additionalInformation");
additionalInfo = ds.getQueryString(additionalInfo);
String interests = mrequest.getParameter("interests");
interests = ds.getQueryString(interests);
String skills = mrequest.getParameter("skills");
String persuing = mrequest.getParameter("persuing");
String appliedthrough=mrequest.getParameter("appliedthrough");
String reasonForUnavailability = mrequest.getParameter("reasonForUnavailability");
reasonForUnavailability = ds.getQueryString(reasonForUnavailability);
InternBean internBean = new InternBean();
internBean.setFirstName(firstName);
internBean.setLastName(lastName);
internBean.setJoiningDate(joiningDateSql);
internBean.setLeavingDate(leavingDateSql);
internBean.setContactNumber(contactNumber);
internBean.setEmailId(emailId);
internBean.setCollegeName(collegeName);
internBean.setCgpa(cgpa);
internBean.setDuration(duration);
internBean.setPersuing(persuing);
//internBean.setJavaRating(javaRating);
//internBean.setAndroidRating(androidRating);
internBean.setSkills(skills);
internBean.setInterests(interests);
internBean.setStream(stream);
internBean.setReasonForUnavailability(reasonForUnavailability);
String fileUploadDir = "/home/hduser/ruralivrs/ProjectFiles/apache-tomcat-6.0.37/webapps/Downloads/internship/interns";
Random randomGenerator = new Random();
int randomNumber = randomGenerator.nextInt(100);
internBean.setYearOfStudy(yearOfStudy);
internBean.setAdditionalInfo(additionalInfo);
internBean.setAvailabilityForF2F(availabilityForF2F);
internBean.setAppliedthrough(appliedthrough);
fileUploadDir = fileUploadDir.substring(65);
fileUploadDir = "http://qassist.cse.iitb.ac.in"+fileUploadDir;
System.out.println("fileUploadDir "+fileUploadDir);
up.UploadingFile(mrequest, fileUploadDir, "resume",firstName+"_"+lastName+"_"+randomNumber );
internBean.setResume(fileUploadDir+"/"+firstName+"_"+lastName+"_"+randomNumber);
internBean.inernRegistration(internBean);
String host = "imap.cse.iitb.ac.in";
String mail_smtp_port = "25";
String mail_user = "reviewsystem@cse.iitb.ac.in";
String mail_password = "review123";
String result = "";
// Recipient's email ID needs to be mentioned.
//String to = "recruitment.iitb@gmail.com,vishwajeet@cse.iitb.ac.in";
String to = "recruitment.iitb@gmail.com";
// Sender's email ID needs to be mentioned.
String from = mail_user;
//String subject = request.getParameter("subject");
String subject = ""+firstName+" "+lastName+""+" Applied For Internship- College - "+collegeName+""+" CGPA - "+cgpa+""+" Duration - "+duration+"";
//String description = request.getParameter("description");
skills = skills.replaceAll(",", "<br>");
String description = "<html>" +
"<body bgcolor='cyan'>"+
"<table cellspacing='0' style='width:100%'>"+
"<tr style='background-color:#e1e1e1'>"+
"<td style='font-weight:bold;padding:7px 9px;width:20%'>"+
"Applicant Name"+
"</td>"+
"<td style='padding:7px 9px 7px 0;width:80%'>"+
""+firstName+" "+lastName+""
+"</td>"
+"</tr>"
+"<tr>"+
"<td style='font-weight:bold;padding:7px 9px;width:20%'>"+
" Applied Through"+
"</td>"+
"<td style='padding:7px 9px 7px 0;width:80%'>"+
""+appliedthrough+""
+"</td>"
+"</tr>"
+"<tr style='background-color:#e1e1e1'>"+
"<td style='font-weight:bold;padding:7px 9px;width:20%'>"+
"Unversity/College:"+
"</td>"+
"<td style='padding:7px 9px 7px 0;width:80%'>"+
""+collegeName+""
+"</td>"
+"</tr>"
+"<tr>"+
"<td style='font-weight:bold;padding:7px 9px;width:20%'>"+
"CGPA"+
"</td>"+
"<td style='padding:7px 9px 7px 0;width:80%'>"+
""+cgpa+""
+"</td>"
+"</tr>"
+"<tr style='background-color:#e1e1e1'>"+
"<td style='font-weight:bold;padding:7px 9px;width:20%'>"+
"Contact Number:"+
"</td>"+
"<td style='padding:7px 9px 7px 0;width:80%'>"+
""+contactNumber+""
+"</td>"
+"</tr>"
+"<tr>"+
"<td style='font-weight:bold;padding:7px 9px;width:20%'>"+
"Email:"+
"</td>"+
"<td style='padding:7px 9px 7px 0;width:80%'>"+
""+emailId+""
+"</td>"
+"</tr>"
+"<tr style='background-color:#e1e1e1'>"+
"<td style='font-weight:bold;padding:7px 9px;width:20%'>"+
"Pursuing:"+
"</td>"+
"<td style='padding:7px 9px 7px 0;width:80%'>"+
""+persuing+""
+"</td>"
+"</tr>"
+"<tr>"+
"<td style='font-weight:bold;padding:7px 9px;width:20%'>"+
"Stream:"+
"</td>"+
"<td style='padding:7px 9px 7px 0;width:80%'>"+
""+stream+""
+"</td>"
+"</tr>"
+"<tr style='background-color:#e1e1e1'>"+
"<td style='font-weight:bold;padding:7px 9px;width:20%'>"+
"Current Year Of Study: "+
"</td>"+
"<td style='padding:7px 9px 7px 0;width:80%'>"+
""+yearOfStudy+""
+"</td>"
+"</tr>"+
"<tr style='background-color:#e1e1e1'>"+
"<td style='font-weight:bold;padding:7px 9px;width:20%'>"+
"Skills:"+
"</td>"+
"<td style='padding:7px 9px 7px 0;width:80%'>"+
""+skills+""
+"<br>"
+"</td>"
+"</tr>"
+"<tr style='background-color:#e1e1e1'>"+
"<td style='font-weight:bold;padding:7px 9px;width:20%'>"+
"Availability for F2F Interview @IIT Bombay"+
"</td>"+
"<td style='padding:7px 9px 7px 0;width:80%'>"+
""+availabilityForF2F+""
+"</td>"
+"</tr>"
+"<tr>"+
"<td style='font-weight:bold;padding:7px 9px;width:20%'>"+
"Feasible Joining Date:"+
"</td>"+
"<td style='padding:7px 9px 7px 0;width:80%'>"+
""+joiningDate+""
+"</td>"
+"<tr style='background-color:#e1e1e1'>"+
"<td style='font-weight:bold;padding:7px 9px;width:20%'>"+
"Additional Information "+
"</td>"+
"<td style='padding:7px 9px 7px 0;width:80%'>"+
""+additionalInfo+""
+"</td>"
+"</tr>"
+"</table>"
+"</body>"
+"</html>";
Properties properties = System.getProperties();
properties.put("mail.smtp.port", mail_smtp_port);
properties.put("mail.smtp.starttls.enable", "true");
properties.setProperty("mail.user", mail_user);
properties.setProperty("mail.password", mail_password);
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.ssl.trust", host);
// Setup mail server
properties.setProperty("mail.smtp.host", host);
Session mailsession = Session.getInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("reviewsystem@cse.iitb.ac.in", "review123");
}
});
try {
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(mailsession);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.addRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
// Set Subject: header field
message.setSubject(subject);
// Now set the actual message
message.setContent(description,"text/html");
// Send message
Transport transport = mailsession.getTransport("smtp");
Transport.send(message);
result = "Sent message successfully....";
//code to redirect to correct page during automatic mails
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException mex) {
mex.printStackTrace();
result = "Error: unable to send message....";
}
response.sendRedirect("InternRegistered.jsp");
}
if(whatFor.equals("registerForJob")){
System.out.println("/////////////// "+mrequest.getParameter("availabilityToF2F"));
String firstName = mrequest.getParameter("firstName");
String lastName = mrequest.getParameter("lastName");
String contactNumber = mrequest.getParameter("contactNumber");
String emailId = mrequest.getParameter("emailId");
String currentLocation = mrequest.getParameter("currentLocation");
String noticePeriod = mrequest.getParameter("noticePeriod");
String currentCompany = mrequest.getParameter("company");
String totalExperience = mrequest.getParameter("experience");
String education = mrequest.getParameter("highestQualification");
//String availability = mrequest.getParameter("availabilityForF2F");
String reasonForWorkHere = mrequest.getParameter("reasonForChange");
String skills = mrequest.getParameter("skills");
String currentCtc = mrequest.getParameter("currentCtc");
String roleAppliedFor = mrequest.getParameter("roleApplied");
String cgpa = mrequest.getParameter("cgpa");
String earliestJoiningDate = mrequest.getParameter("earliestJoiningDate");
String earliestAvailability = mrequest.getParameter("earliestAvailability");
String yearOfPassing = mrequest.getParameter("passedOut");
String immediateJoinee = mrequest.getParameter("immediateJoinee");
String aditionalInfo = mrequest.getParameter("additionalInformation");
String experienceInJava = mrequest.getParameter("experienceInJava");
String availabilityToF2F = mrequest.getParameter("availabilityToF2F");
//String to = "recruitment.iitb@gmail.com";
ExperiencedBean experiencedBean = new ExperiencedBean();
experiencedBean.setFirstName(firstName);
experiencedBean.setLastName(lastName);
experiencedBean.setContactNumber(contactNumber);
experiencedBean.setEmailId(emailId);
experiencedBean.setCurrentLocation(currentLocation);
experiencedBean.setNoticePeriod(noticePeriod);
experiencedBean.setCurrentCompany(currentCompany);
experiencedBean.setTotalExperience(totalExperience);
experiencedBean.setEducation(education);
//experiencedBean.setAvailability(availability);
experiencedBean.setReasonForChange(reasonForWorkHere);
experiencedBean.setSkills(skills);
experiencedBean.setCurrentCtc(currentCtc);
experiencedBean.setRoleAppliedFor(roleAppliedFor);
experiencedBean.setCgpa(cgpa);
experiencedBean.setEarliestJoiningDate(earliestJoiningDate);
experiencedBean.setEarliestAvailability(earliestAvailability);
experiencedBean.setYearOfPassing(yearOfPassing);
experiencedBean.setImmediateJoinee(immediateJoinee);
experiencedBean.setAdiitionalInfo(aditionalInfo);
experiencedBean.setExperienceInJava(experienceInJava);
experiencedBean.setAvailabilityToF2F(availabilityToF2F);
String fileUploadDir = "/home/hduser/ruralivrs/ProjectFiles/apache-tomcat-6.0.37/webapps/Downloads/internship/jobapplicants";
fileUploadDir = fileUploadDir.substring(65);
fileUploadDir = "http://qassist.cse.iitb.ac.in"+fileUploadDir;
System.out.println("fileUploadDir "+fileUploadDir);
Random randomGenerator = new Random();
int randomNumber = randomGenerator.nextInt(100);
up.UploadingFile(mrequest, fileUploadDir, "resume",firstName+"_"+lastName+"_"+randomNumber );
experiencedBean.setResume(fileUploadDir+"/"+firstName+"_"+lastName+"_"+randomNumber);
experiencedBean.registerEmployee(experiencedBean);
String host = "imap.cse.iitb.ac.in";
String mail_smtp_port = "25";
String mail_user = "reviewsystem@cse.iitb.ac.in";
String mail_password = "review123";
String result = "";
// Recipient's email ID needs to be mentioned.
//String to = "recruitment.iitb@gmail.com,vishwajeet@cse.iitb.ac.in";
String to = "recruitment.iitb@gmail.com";
// Sender's email ID needs to be mentioned.
String from = mail_user;
//String subject = request.getParameter("subject");
String subject = ""+firstName+" "+lastName+""+" Applied For Job- Company - "+currentCompany+""+" CGPA - "+cgpa+""+" Years Of Experience - "+totalExperience+"";
//String description = request.getParameter("description");
skills = skills.replaceAll(",", "<br>");
String description = "<html>" +
"<body bgcolor='cyan'>"+
"<table cellspacing='0' style='width:100%'>"+
"<tr style='background-color:#e1e1e1'>"+
"<td style='font-weight:bold;padding:7px 9px;width:20%'>"+
"Applicant Name"+
"</td>"+
"<td style='padding:7px 9px 7px 0;width:80%'>"+
""+firstName+" "+lastName+""
+"</td>"
+"</tr>"
+"<tr>"+
"<td style='font-weight:bold;padding:7px 9px;width:20%'>"+
"Current Employer/Company:"+
"</td>"+
"<td style='padding:7px 9px 7px 0;width:80%'>"+
""+currentCompany+""
+"</td>"
+"</tr>"
+"<tr style='background-color:#e1e1e1'>"+
"<td style='font-weight:bold;padding:7px 9px;width:20%'>"+
"CGPA"+
"</td>"+
"<td style='padding:7px 9px 7px 0;width:80%'>"+
""+cgpa+""
+"</td>"
+"</tr>"
+"<tr>"+
"<td style='font-weight:bold;padding:7px 9px;width:20%'>"+
"Contact Number:"+
"</td>"+
"<td style='padding:7px 9px 7px 0;width:80%'>"+
""+contactNumber+""
+"</td>"
+"</tr>"
+"<tr style='background-color:#e1e1e1'>"+
"<td style='font-weight:bold;padding:7px 9px;width:20%'>"+
"Email:"+
"</td>"+
"<td style='padding:7px 9px 7px 0;width:80%'>"+
""+emailId+""
+"</td>"
+"</tr>"
+"<tr>"+
"<td style='font-weight:bold;padding:7px 9px;width:20%'>"+
"Highest Educational Qualification :"+
"</td>"+
"<td style='padding:7px 9px 7px 0;width:80%'>"+
""+education+""
+"</td>"
+"</tr>"
+"<tr style='background-color:#e1e1e1'>"+
"<td style='font-weight:bold;padding:7px 9px;width:20%'>"+
"Earliest (From-To) Availability For The Interview:"+
"</td>"+
"<td style='padding:7px 9px 7px 0;width:80%'>"+
""+earliestAvailability+""
+"</td>"
+"</tr>"
+"<tr>"+
"<td style='font-weight:bold;padding:7px 9px;width:20%'>"+
"Strong Reasons For Why You Want To Work At IIT-Bombay "+
"</td>"+
"<td style='padding:7px 9px 7px 0;width:80%'>"+
""+reasonForWorkHere+""
+"</td>"
+"</tr>"+
"<tr style='background-color:#e1e1e1'>"+
"<td style='font-weight:bold;padding:7px 9px;width:20%'>"+
"Skills:"+
"</td>"+
"<td style='padding:7px 9px 7px 0;width:80%'>"+
""+skills+""
+"<br>"
+"</td>"
+"</tr>"
+"<tr>"+
"<td style='font-weight:bold;padding:7px 9px;width:20%'>"+
"Availability for F2F Interview @IIT Bombay"+
"</td>"+
"<td style='padding:7px 9px 7px 0;width:80%'>"+
""+availabilityToF2F+""
+"</td>"
+"</tr>"
+"<tr style='background-color:#e1e1e1'>"+
"<td style='font-weight:bold;padding:7px 9px;width:20%'>"+
"If Selected Can Start Working Immediately? "+
"</td>"+
"<td style='padding:7px 9px 7px 0;width:80%'>"+
""+immediateJoinee+""
+"</td>"
+"</tr>"
+"<tr>"+
"<td style='font-weight:bold;padding:7px 9px;width:20%'>"+
"Additional Information:"+
"</td>"+
"<td style='padding:7px 9px 7px 0;width:80%'>"+
""+aditionalInfo+""
+"</td>"
+"</tr>"
+"</table>"
+"</body>"
+"</html>";
Properties properties = System.getProperties();
properties.put("mail.smtp.port", mail_smtp_port);
properties.put("mail.smtp.starttls.enable", "true");
properties.setProperty("mail.user", mail_user);
properties.setProperty("mail.password", mail_password);
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.ssl.trust", host);
// Setup mail server
properties.setProperty("mail.smtp.host", host);
Session mailsession = Session.getInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("reviewsystem@cse.iitb.ac.in", "review123");
}
});
try {
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(mailsession);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.addRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
// Set Subject: header field
message.setSubject(subject);
// Now set the actual message
message.setContent(description,"text/html");
// Send message
Transport transport = mailsession.getTransport("smtp");
Transport.send(message);
result = "Sent message successfully....";
//code to redirect to correct page during automatic mails
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException mex) {
mex.printStackTrace();
result = "Error: unable to send message....";
}
response.sendRedirect("JobApplicantRegistered.jsp");
}
else if(whatFor.equals("registerRA")){
String firstName = mrequest.getParameter("firstName");
String lastName = mrequest.getParameter("lastName");
String joiningDate = mrequest.getParameter("joiningDate");
Date joiningDateSql = Commons.stringToSqlDate(joiningDate);
//String leavingDate = mrequest.getParameter("leavingDate");
//Date leavingDateSql = Commons.stringToSqlDate(leavingDate);
String contactNumber = mrequest.getParameter("contactNumber");
String emailId = mrequest.getParameter("emailId");
String collegeName = mrequest.getParameter("collegeName");
float cgpa = Float.parseFloat(mrequest.getParameter("percentage"));
//int duration = Integer.parseInt(mrequest.getParameter("duration"));
String stream = mrequest.getParameter("stream");
int yearOfStudy = Integer.parseInt(mrequest.getParameter("yearOfStudy"));
String appliedthrough=mrequest.getParameter("appliedthrough");
String availabilityForF2F = mrequest.getParameter("availabilityForF2F");
String additionalInfo = mrequest.getParameter("additionalInformation");
additionalInfo = ds.getQueryString(additionalInfo);
String interests = mrequest.getParameter("interests");
interests = ds.getQueryString(interests);
String skills = mrequest.getParameter("skills");
String persuing = mrequest.getParameter("persuing");
String reasonForUnavailability = mrequest.getParameter("reasonForUnavailability");
reasonForUnavailability = ds.getQueryString(reasonForUnavailability);
RABean raBean = new RABean();
raBean.setFirstName(firstName);
raBean.setLastName(lastName);
raBean.setJoiningDate(joiningDateSql);
//internBean.setLeavingDate(leavingDateSql);
raBean.setContactNumber(contactNumber);
raBean.setEmailId(emailId);
raBean.setCollegeName(collegeName);
raBean.setCgpa(cgpa);
//internBean.setDuration(duration);
raBean.setPersuing(persuing);
//internBean.setJavaRating(javaRating);
//internBean.setAndroidRating(androidRating);
raBean.setSkills(skills);
raBean.setInterests(interests);
raBean.setStream(stream);
raBean.setReasonForUnavailability(reasonForUnavailability);
String fileUploadDir = "/home/hduser/ruralivrs/ProjectFiles/apache-tomcat-6.0.37/webapps/Downloads/internship/ra";
fileUploadDir = fileUploadDir.substring(65);
fileUploadDir = "http://qassist.cse.iitb.ac.in"+fileUploadDir;
System.out.println("fileUploadDir "+fileUploadDir);
Random randomGenerator = new Random();
int randomNumber = randomGenerator.nextInt(100);
raBean.setYearOfStudy(yearOfStudy);
raBean.setAdditionalInfo(additionalInfo);
raBean.setAvailabilityForF2F(availabilityForF2F);
raBean.setAppliedthrough(appliedthrough);
up.UploadingFile(mrequest, fileUploadDir, "resume",firstName+"_"+lastName+"_"+randomNumber );
raBean.setResume(fileUploadDir+"/"+firstName+"_"+lastName+"_"+randomNumber);
raBean.RARegistration(raBean);
String host = "imap.cse.iitb.ac.in";
String mail_smtp_port = "25";
String mail_user = "reviewsystem@cse.iitb.ac.in";
String mail_password = "review123";
String result = "";
// Recipient's email ID needs to be mentioned.
//String to = "recruitment.iitb@gmail.com,vishwajeet@cse.iitb.ac.in,priya.ravi2910@gmail.com";
String to = "recruitment.iitb@gmail.com";
// Sender's email ID needs to be mentioned.
String from = mail_user;
//String subject = request.getParameter("subject");
String subject = ""+firstName+" "+lastName+""+" Applied For RA- College - "+collegeName+""+" CGPA -"+cgpa+"";
//String description = request.getParameter("description");
skills = skills.replaceAll(",", "<br>");
String description = "<html>" +
"<body bgcolor='cyan'>"+
"<table cellspacing='0' style='width:100%'>"+
"<tr style='background-color:#e1e1e1'>"+
"<td style='font-weight:bold;padding:7px 9px;width:20%'>"+
"Applicant Name"+
"</td>"+
"<td style='padding:7px 9px 7px 0;width:80%'>"+
""+firstName+" "+lastName+""
+"</td>"
+"</tr>"
+"<tr>"+
"<td style='font-weight:bold;padding:7px 9px;width:20%'>"+
"Applied Through"+
"</td>"+
"<td style='padding:7px 9px 7px 0;width:80%'>"+
""+appliedthrough+""
+"</td>"
+"</tr>"
+"<tr style='background-color:#e1e1e1'>"+
"<td style='font-weight:bold;padding:7px 9px;width:20%'>"+
"Unversity/College:"+
"</td>"+
"<td style='padding:7px 9px 7px 0;width:80%'>"+
""+collegeName+""
+"</td>"
+"</tr>"
+"<tr>"+
"<td style='font-weight:bold;padding:7px 9px;width:20%'>"+
"CGPA"+
"</td>"+
"<td style='padding:7px 9px 7px 0;width:80%'>"+
""+cgpa+""
+"</td>"
+"</tr>"
+"<tr style='background-color:#e1e1e1'>"+
"<td style='font-weight:bold;padding:7px 9px;width:20%'>"+
"Contact Number:"+
"</td>"+
"<td style='padding:7px 9px 7px 0;width:80%'>"+
""+contactNumber+""
+"</td>"
+"</tr>"
+"<tr>"+
"<td style='font-weight:bold;padding:7px 9px;width:20%'>"+
"Email:"+
"</td>"+
"<td style='padding:7px 9px 7px 0;width:80%'>"+
""+emailId+""
+"</td>"
+"</tr>"
+"<tr style='background-color:#e1e1e1'>"+
"<td style='font-weight:bold;padding:7px 9px;width:20%'>"+
"Pursuing:"+
"</td>"+
"<td style='padding:7px 9px 7px 0;width:80%'>"+
""+persuing+""
+"</td>"
+"</tr>"
+"<tr>"+
"<td style='font-weight:bold;padding:7px 9px;width:20%'>"+
"Stream:"+
"</td>"+
"<td style='padding:7px 9px 7px 0;width:80%'>"+
""+stream+""
+"</td>"
+"</tr>"
+"<tr style='background-color:#e1e1e1'>"+
"<td style='font-weight:bold;padding:7px 9px;width:20%'>"+
"Current Year Of Study: "+
"</td>"+
"<td style='padding:7px 9px 7px 0;width:80%'>"+
""+yearOfStudy+""
+"</td>"
+"</tr>"
+"<tr>"+
"<td style='font-weight:bold;padding:7px 9px;width:20%'>"+
"Skills:"+
"</td>"+
"<td style='padding:7px 9px 7px 0;width:80%'>"+
""+skills+""
+"</td>"
+"</tr>"
+"<tr style='background-color:#e1e1e1'>"+
"<td style='font-weight:bold;padding:7px 9px;width:20%'>"+
"Availability for F2F Interview @IIT Bombay"+
"</td>"+
"<td style='padding:7px 9px 7px 0;width:80%'>"+
""+availabilityForF2F+""
+"</td>"
+"</tr>"
+"<tr>"+
"<td style='font-weight:bold;padding:7px 9px;width:20%'>"+
"Feasible Joining Date:"+
"</td>"+
"<td style='padding:7px 9px 7px 0;width:80%'>"+
""+joiningDate+""
+"</td>"
+"</tr>"
+"<tr style='background-color:#e1e1e1'>"+
"<td style='font-weight:bold;padding:7px 9px;width:20%'>"+
"Additional Information:"+
"</td>"+
"<td style='padding:7px 9px 7px 0;width:80%'>"+
""+additionalInfo+""
+"</td>"
+"</tr>"
+"</table>"
+"</body>"
+"</html>";
Properties properties = System.getProperties();
properties.put("mail.smtp.port", mail_smtp_port);
properties.put("mail.smtp.starttls.enable", "true");
properties.setProperty("mail.user", mail_user);
properties.setProperty("mail.password", mail_password);
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.ssl.trust", host);
// Setup mail server
properties.setProperty("mail.smtp.host", host);
Session mailsession = Session.getInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("reviewsystem@cse.iitb.ac.in", "review123");
}
});
try {
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(mailsession);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.addRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
// Set Subject: header field
message.setSubject(subject);
// Now set the actual message
message.setContent(description,"text/html");
// Send message
Transport transport = mailsession.getTransport("smtp");
Transport.send(message);
result = "Sent message successfully....";
//code to redirect to correct page during automatic mails
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException mex) {
mex.printStackTrace();
result = "Error: unable to send message....";
}
response.sendRedirect("RARegistered.jsp");
}
else if(whatFor.equals("login")){
String userName = mrequest.getParameter("userName");
String password = mrequest.getParameter("passWord");
Authenticator auth = new Authenticator();
String result = auth.authenticateUser(userName, password);
if(result!=null){
response.sendRedirect("Welcome.jsp");
}
else{
response.sendRedirect("Login.jsp?auth=failed");
}
}
else if(whatFor.equals("logout")){
response.sendRedirect("Login.jsp");
}
} catch (UploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else{
if(whatFor.equals("shortlist")){
System.out.println("Stavan !");
//System.out.println("tets");
String[] fruits= request.getParameterValues("checkbox");
String inputDate = request.getParameter("inputDate");
SimpleDateFormat ft =
new SimpleDateFormat ("dd/MM/yyyy");
String inputDateSql = ft.format(inputDate);;
System.out.println(inputDate);
String outputDate = request.getParameter("outputDate");
String outputDateSql = ft.format(outputDate);;
System.out.println(outputDate);
int len=0;
len=fruits.length;
if(len!=0)
{
for(int i=0; i<len; i++)
{
int temp=Integer.parseInt(fruits[i]);
String ra_id="",first_name="",last_name="";
String query1 = "select ra_id,first_name,last_name from ra_applicant where ra_id='"+temp+"'";
String query2 = "Update ra_shortlisted set date_from='"+inputDateSql+"', date_to='"+outputDateSql+"' where ra_id='"+temp+"'";
System.out.println(query1);
System.out.println(query2);
try {
ResultSet rsr = DataService.getResultSet(query1);
while(rsr.next()){
ra_id = rsr.getString(1);
first_name = rsr.getString(2);
last_name = rsr.getString(3);
}
DataService.runQuery("INSERT INTO ra_shortlisted(ra_id,first_name,last_name) VALUES('"+ra_id+"','"+first_name+"','"+last_name+"')");
DataService.runQuery(query2);
//result="updated successfully...";
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//result="error in updating...";
}
}
}
response.sendRedirect("Shortlisted.jsp");
}
if(whatFor.equals("shiftCandidate")){
String candidate_id = request.getParameter("candidate_id");
String action = request.getParameter("status_id");
System.out.println(action);
if(action.equals("shortListIntern")){
String query = "Update intern set status='ShortListed' where intern_id='"+candidate_id+"'";
System.out.println(query);
try {
DataService.runQuery(query);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else if(action.equals("deleteIntern")){
String query = "delete from intern where intern_id='"+candidate_id+"'";
System.out.println(query);
try {
DataService.runQuery(query);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else if(action.equals("shortListEmployee")){
String query = "Update job_applicant set status='ShortListed' where job_applicant_id='"+candidate_id+"'";
System.out.println(query);
try {
DataService.runQuery(query);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else if(action.equals("deleteEmployee")){
String query = "delete from job_applicant where job_applicant_id='"+candidate_id+"'";
System.out.println(query);
try {
DataService.runQuery(query);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else if(action.equals("shortListRA")){
String query = "Update ra_applicant set status='ShortListed' where ra_id='"+candidate_id+"'";
System.out.println(query);
try {
DataService.runQuery(query);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if(action.equals("deleteRA")){
String query = "delete from ra_applicant where ra_id='"+candidate_id+"'";
System.out.println(query);
try {
DataService.runQuery(query);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
|
package com.jme.scene.model.ase;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.logging.Level;
import com.jme.image.Texture;
import com.jme.math.Vector2f;
import com.jme.math.Vector3f;
import com.jme.renderer.ColorRGBA;
import com.jme.scene.Controller;
import com.jme.scene.TriMesh;
import com.jme.scene.model.Face;
import com.jme.scene.model.Model;
import com.jme.scene.state.MaterialState;
import com.jme.scene.state.TextureState;
import com.jme.system.DisplaySystem;
import com.jme.util.LoggingSystem;
import com.jme.util.TextureManager;
/**
* <code>ASEModel</code>
*
* @author Mark Powell
* @version $Id: ASEModel.java,v 1.2 2004-02-13 02:50:10 mojomonkey Exp $
*/
public class ASEModel extends Model {
//ASE file tags.
private static final String OBJECT = "*GEOMOBJECT";
private static final String NUM_VERTEX = "*MESH_NUMVERTEX";
private static final String NUM_FACES = "*MESH_NUMFACES";
private static final String NUM_TVERTEX = "*MESH_NUMTVERTEX";
private static final String VERTEX = "*MESH_VERTEX";
private static final String FACE = "*MESH_FACE";
private static final String NORMALS = "*MESH_NORMALS";
private static final String FACE_NORMAL = "*MESH_FACENORMAL";
private static final String NVERTEX = "*MESH_VERTEXNORMAL";
private static final String TVERTEX = "*MESH_TVERT";
private static final String TFACE = "*MESH_TFACE";
private static final String TEXTURE = "*BITMAP";
private static final String UTILE = "*UVW_U_TILING";
private static final String VTILE = "*UVW_V_TILING";
private static final String UOFFSET = "*UVW_U_OFFSET";
private static final String VOFFSET = "*UVW_V_OFFSET";
private static final String MATERIAL_ID = "*MATERIAL_REF";
private static final String MATERIAL_COUNT = "*MATERIAL_COUNT";
private static final String MATERIAL = "*MATERIAL";
private static final String MATERIAL_NAME = "*MATERIAL_NAME";
private static final String MATERIAL_DIFFUSE = "*MATERIAL_DIFFUSE";
private static final String MATERIAL_AMBIENT = "*MATERIAL_AMBIENT";
private static final String MATERIAL_SPECULAR = "*MATERIAL_SPECULAR";
private static final String MATERIAL_SHINE = "*MATERIAL_SHINE";
//path to the model and texture file.
private String absoluteFilePath;
private BufferedReader reader = null;
private StringTokenizer tokenizer;
private String fileContents;
private int numOfObjects; // The number of objects in the model
private int numOfMaterials; // The number of materials for the model
private ArrayList materials = new ArrayList();
private ArrayList objectList = new ArrayList();
public void load(String file) {
InputStream is = null;
int fileSize = 0;
try {
File f = new File(file);
absoluteFilePath = f.getAbsolutePath();
absoluteFilePath =
absoluteFilePath.substring(
0,
absoluteFilePath.lastIndexOf(File.separator) + 1);
is = new FileInputStream(f);
fileSize = (int) f.length();
reader = new BufferedReader(new InputStreamReader(is));
StringBuffer fc = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
fc.append(line + "\n");
}
fileContents = fc.toString();
// Close the .ase file that we opened
reader.close();
parseFile();
computeNormals();
convertToTriMesh();
} catch (IOException e) {
LoggingSystem.getLogger().log(
Level.WARNING,
"Could not load " + file);
}
}
/**
* <code>getAnimationController</code>
*
* @return @see com.jme.scene.model.Model#getAnimationController()
*/
public Controller getAnimationController() {
return null;
}
private void parseFile() {
ASEMaterialInfo textureInfo = new ASEMaterialInfo();
ASEObject mesh = new ASEObject();
numOfObjects = getObjectCount();
numOfMaterials = getMaterialCount();
//Build texture list (not sure if this makes since, there can only be
//one texture per mesh, and the are reading it in for the entire
//object, not on a per object basis.
for (int i = 0; i < numOfMaterials; i++) {
materials.add(textureInfo);
getMaterialInfo((ASEMaterialInfo) materials.get(i), i + 1);
}
for (int i = 0; i < numOfObjects; i++) {
mesh.materialID = -1;
moveToObject(i + 1);
readObjectInfo(mesh, i + 1);
readObjectData(mesh, i + 1);
objectList.add(mesh);
}
}
private void convertToTriMesh() {
for (int i = 0; i < numOfObjects; i++) {
ASEObject object = (ASEObject) objectList.get(i);
Vector2f[] texCoords2 = new Vector2f[object.getVertices().length];
for (int j = 0; j < object.faces.length; j++) {
int index = object.faces[j].vertIndex[0];
texCoords2[index] = new Vector2f();
texCoords2[index] =
object.tempTexVerts[object.faces[j].coordIndex[0]];
index = object.faces[j].vertIndex[1];
texCoords2[index] = new Vector2f();
texCoords2[index] =
object.tempTexVerts[object.faces[j].coordIndex[1]];
index = object.faces[j].vertIndex[2];
texCoords2[index] = new Vector2f();
texCoords2[index] =
object.tempTexVerts[object.faces[j].coordIndex[2]];
}
int[] indices = new int[object.faces.length * 3];
int count = 0;
for (int j = 0; j < object.faces.length; j++) {
indices[count] = object.faces[j].vertIndex[0];
count++;
indices[count] = object.faces[j].vertIndex[1];
count++;
indices[count] = object.faces[j].vertIndex[2];
count++;
}
object.setIndices(indices);
object.updateVertexBuffer();
object.updateNormalBuffer();
object.setTextures(texCoords2);
this.attachChild(object);
}
for (int j = 0; j < numOfMaterials; j++) {
ASEModel.ASEMaterialInfo mat =
(ASEModel.ASEMaterialInfo) materials.get(j);
if (mat.file.length() > 0) {
MaterialState ms =
DisplaySystem
.getDisplaySystem()
.getRenderer()
.getMaterialState();
ms.setEnabled(true);
ms.setAmbient(
new ColorRGBA(
mat.ambient[0],
mat.ambient[1],
mat.ambient[2],
1));
ms.setDiffuse(
new ColorRGBA(
mat.diffuse[0],
mat.diffuse[1],
mat.diffuse[2],
1));
ms.setSpecular(
new ColorRGBA(
mat.specular[0],
mat.specular[1],
mat.specular[2],
1));
ms.setEmissive(new ColorRGBA(0, 0, 0, 1));
ms.setShininess(mat.shine);
this.setRenderState(ms);
}
}
for (int j = 0; j < numOfMaterials; j++) {
// Check if the current material has a file name
if (((ASEModel.ASEMaterialInfo) materials.get(j)).file.length()
> 0) {
TextureState ts =
DisplaySystem
.getDisplaySystem()
.getRenderer()
.getTextureState();
ts.setEnabled(true);
ts.setTexture(
TextureManager.loadTexture(
((ASEModel.ASEMaterialInfo) materials.get(j)).file,
Texture.MM_LINEAR,
Texture.FM_LINEAR,
true));
this.setRenderState(ts);
}
}
}
private int getObjectCount() {
int objectCount = 0;
tokenizer = new StringTokenizer(fileContents);
while (tokenizer.hasMoreTokens()) {
// Check if we hit the start of an object
if (OBJECT.equals(tokenizer.nextToken())) {
objectCount++;
}
}
return objectCount;
}
/**
*
* <code>getMaterialCount</code> retrieves the number of materials in the
* ASE file. The file is read until the *MATERIAL flag is encountered. Once
* this flag is found, the value is read.
*
* @return the number of materials as defined in the ASE file.
*/
private int getMaterialCount() {
int materialCount = 0;
// Go to the beginning of the file
tokenizer = new StringTokenizer(fileContents);
// GO through the whole file until we hit the end
while (tokenizer.hasMoreTokens()) {
if (MATERIAL_COUNT.equals(tokenizer.nextToken())) {
materialCount = Integer.parseInt(tokenizer.nextToken());
return materialCount;
}
}
//Material tag never found
return 0;
}
private void getMaterialInfo(
ASEMaterialInfo material,
int desiredMaterial) {
String strWord;
int materialCount = 0;
// Go to the beginning of the file
tokenizer = new StringTokenizer(fileContents);
//read through the file until the correct material entry is found.
while (tokenizer.hasMoreTokens()) {
if (MATERIAL.equals(tokenizer.nextToken())) {
materialCount++;
// Check if it's the one we want to stop at, if so break
if (materialCount == desiredMaterial)
break;
}
}
while (tokenizer.hasMoreTokens()) {
strWord = tokenizer.nextToken();
if (strWord.equals(MATERIAL)) {
return;
}
//read material properites.
if (strWord.equals(MATERIAL_AMBIENT)) {
material.ambient[0] = Float.parseFloat(tokenizer.nextToken());
material.ambient[1] = Float.parseFloat(tokenizer.nextToken());
material.ambient[2] = Float.parseFloat(tokenizer.nextToken());
} else if (strWord.equals(MATERIAL_DIFFUSE)) {
material.diffuse[0] = Float.parseFloat(tokenizer.nextToken());
material.diffuse[1] = Float.parseFloat(tokenizer.nextToken());
material.diffuse[2] = Float.parseFloat(tokenizer.nextToken());
} else if (strWord.equals(MATERIAL_SPECULAR)) {
material.specular[0] = Float.parseFloat(tokenizer.nextToken());
material.specular[1] = Float.parseFloat(tokenizer.nextToken());
material.specular[2] = Float.parseFloat(tokenizer.nextToken());
} else if (strWord.equals(MATERIAL_SHINE)) {
material.shine = Float.parseFloat(tokenizer.nextToken());
}
//read texture information.
if (strWord.equals(TEXTURE)) {
material.file =
absoluteFilePath
+ tokenizer.nextToken().replace('"', ' ').trim();
} else if (strWord.equals(MATERIAL_NAME)) {
material.name = tokenizer.nextToken();
} else if (strWord.equals(UTILE)) {
material.uTile = Float.parseFloat(tokenizer.nextToken());
} else if (strWord.equals(VTILE)) {
material.vTile = Float.parseFloat(tokenizer.nextToken());
}
}
}
private void moveToObject(int desiredObject) {
int objectCount = 0;
tokenizer = new StringTokenizer(fileContents);
while (tokenizer.hasMoreTokens()) {
if (OBJECT.equals(tokenizer.nextToken())) {
objectCount++;
if (objectCount == desiredObject)
return;
}
}
}
private void readObjectInfo(ASEObject currentObject, int desiredObject) {
String word;
moveToObject(desiredObject);
while (tokenizer.hasMoreTokens()) {
word = tokenizer.nextToken();
if (word.equals("*NODE_NAME")) {
currentObject.setName(tokenizer.nextToken());
}
if (word.equals(NUM_VERTEX)) {
int numOfVerts = Integer.parseInt(tokenizer.nextToken());
Vector3f[] verts = new Vector3f[numOfVerts];
for (int i = 0; i < verts.length; i++) {
verts[i] = new Vector3f();
}
currentObject.setVertices(verts);
} else if (word.equals(NUM_FACES)) {
int numOfFaces = Integer.parseInt(tokenizer.nextToken());
currentObject.faces = new Face[numOfFaces];
} else if (word.equals(NUM_TVERTEX)) {
int numTexVertex = Integer.parseInt(tokenizer.nextToken());
currentObject.tempTexVerts = new Vector2f[numTexVertex];
} else if (word.equals(OBJECT)) {
return;
}
}
}
private void readObjectData(ASEObject currentObject, int desiredObject) {
// Load the material ID for this object
getData(currentObject, MATERIAL_ID, desiredObject);
// Load the vertices for this object
getData(currentObject, VERTEX, desiredObject);
// Load the texture coordinates for this object
getData(currentObject, TVERTEX, desiredObject);
// Load the vertex faces list for this object
getData(currentObject, FACE, desiredObject);
// Load the texture face list for this object
getData(currentObject, TFACE, desiredObject);
// Load the texture for this object
getData(currentObject, TEXTURE, desiredObject);
// Load the U tile for this object
getData(currentObject, UTILE, desiredObject);
// Load the V tile for this object
getData(currentObject, VTILE, desiredObject);
}
private void getData(
ASEObject currentObject,
String desiredData,
int desiredObject) {
String word;
moveToObject(desiredObject);
// Go through the file until we reach the end
while (tokenizer.hasMoreTokens()) {
word = tokenizer.nextToken();
// If we reached an object tag, stop read because we went to far
if (word.equals(OBJECT)) {
// Stop reading because we are done with the current object
return;
}
// If we hit a vertex tag
else if (word.equals(VERTEX)) {
// Make sure that is the data that we want to read in
if (desiredData.equals(VERTEX)) {
// Read in a vertex
readVertex(currentObject);
}
}
// If we hit a texture vertex
else if (word.equals(TVERTEX)) {
// Make sure that is the data that we want to read in
if (desiredData.equals(TVERTEX)) {
// Read in a texture vertex
readTextureVertex(
currentObject,
(ASEMaterialInfo) materials.get(
currentObject.materialID));
}
}
// If we hit a vertice index to a face
else if (word.equals(FACE)) {
// Make sure that is the data that we want to read in
if (desiredData.equals(FACE)) {
// Read in a face
readFace(currentObject);
}
}
// If we hit a texture index to a face
else if (word.equals(TFACE)) {
// Make sure that is the data that we want to read in
if (desiredData.equals(TFACE)) {
// Read in a texture indice for a face
readTextureFace(currentObject);
}
}
// If we hit the material ID to the object
else if (word.equals(MATERIAL_ID)) {
// Make sure that is the data that we want to read in
if (desiredData.equals(MATERIAL_ID)) {
// Read in the material ID assigned to this object
currentObject.materialID =
(int) Float.parseFloat(tokenizer.nextToken());
return;
}
}
}
}
private void readVertex(ASEObject currentObject) {
int index = 0;
// Read past the vertex index
index = Integer.parseInt(tokenizer.nextToken());
//currentObject.tempVertices[index] = new Vector3f();
//convert to standard coordinate axis.
currentObject.getVertices()[index].x =
Float.parseFloat(tokenizer.nextToken());
currentObject.getVertices()[index].z =
-Float.parseFloat(tokenizer.nextToken());
currentObject.getVertices()[index].y =
Float.parseFloat(tokenizer.nextToken());
}
private void readTextureVertex(
ASEObject currentObject,
ASEMaterialInfo texture) {
int index = 0;
// Here we read past the index of the texture coordinate
index = Integer.parseInt(tokenizer.nextToken());
currentObject.tempTexVerts[index] = new Vector2f();
// Next, we read in the (U, V) texture coordinates.
currentObject.tempTexVerts[index].x =
Float.parseFloat(tokenizer.nextToken());
currentObject.tempTexVerts[index].y =
Float.parseFloat(tokenizer.nextToken());
currentObject.tempTexVerts[index].x *= texture.uTile;
currentObject.tempTexVerts[index].y *= texture.vTile;
}
private void readFace(ASEObject currentObject) {
int index = 0;
// Read past the index of this Face
String temp = tokenizer.nextToken();
if (temp.indexOf(":") > 0) {
temp = temp.substring(0, temp.length() - 1);
}
index = Integer.parseInt(temp);
currentObject.faces[index] = new Face();
tokenizer.nextToken();
currentObject.faces[index].vertIndex[0] =
Integer.parseInt(tokenizer.nextToken());
tokenizer.nextToken();
currentObject.faces[index].vertIndex[1] =
Integer.parseInt(tokenizer.nextToken());
tokenizer.nextToken();
currentObject.faces[index].vertIndex[2] =
Integer.parseInt(tokenizer.nextToken());
}
private void readTextureFace(ASEObject currentObject) {
int index = 0;
// Read past the index for this texture coordinate
index = Integer.parseInt(tokenizer.nextToken());
// Now we read in the UV coordinate index for the current face.
// This will be an index into pTexCoords[] for each point in the face.
currentObject.faces[index].coordIndex[0] =
Integer.parseInt(tokenizer.nextToken());
currentObject.faces[index].coordIndex[1] =
Integer.parseInt(tokenizer.nextToken());
currentObject.faces[index].coordIndex[2] =
Integer.parseInt(tokenizer.nextToken());
}
private void computeNormals() {
if (numOfObjects <= 0) {
return;
}
Vector3f vector1 = new Vector3f();
Vector3f vector2 = new Vector3f();
Vector3f[] triangle = new Vector3f[3];
// Go through each of the objects to calculate their normals
for (int index = 0; index < numOfObjects; index++) {
// Get the current object
ASEObject object = (ASEObject) objectList.get(index);
// Here we allocate all the memory we need to calculate the normals
Vector3f[] tempNormals = new Vector3f[object.faces.length];
Vector3f[] normals = new Vector3f[object.getVertices().length];
// Go though all of the faces of this object
for (int i = 0; i < object.faces.length; i++) {
vector1 =
object
.getVertices()[object
.faces[i]
.vertIndex[0]]
.subtract(
object.getVertices()[object.faces[i].vertIndex[2]]);
vector2 =
object
.getVertices()[object
.faces[i]
.vertIndex[2]]
.subtract(
object.getVertices()[object.faces[i].vertIndex[1]]);
tempNormals[i] = vector1.cross(vector2).normalize();
}
Vector3f sum = new Vector3f();
Vector3f zero = sum;
int shared = 0;
for (int i = 0; i < object.getVertices().length; i++) {
for (int j = 0; j < object.faces.length; j++) {
if (object.faces[j].vertIndex[0] == i
|| object.faces[j].vertIndex[1] == i
|| object.faces[j].vertIndex[2] == i) {
sum = sum.add(tempNormals[j]);
shared++;
}
}
normals[i] = sum.divide((float) (-shared)).normalize();
sum = zero; // Reset the sum
shared = 0; // Reset the shared
}
object.setNormals(normals);
}
}
private class ASEMaterialInfo {
String name; // The texture name
public String file;
// The texture file name (If this is set it's a texture map)
public float[] diffuse = new float[3];
public float[] ambient = new float[3];
public float[] specular = new float[3];
public float shine;
// The color of the object (R, G, B)
float uTile; // u tiling of texture (Currently not used)
float vTile; // v tiling of texture (Currently not used)
float uOffset; // u offset of texture (Currently not used)
float vOffset; // v offset of texture (Currently not used)
};
public class ASEObject extends TriMesh {
public int materialID;
public Vector2f[] tempTexVerts; // The texture's UV coordinates
public Face[] faces; // The faces information of the object
};
}
|
package com.microsoft.adal;
import java.io.UnsupportedEncodingException;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
/**
* TODO: overwrite webview functions TODO: when url is reached call the complete
* to "setresult" for the calling activity Activity will launch webview that is
* defined static. It will set the result back to calling activity.
*
* @author omercan
*/
public class LoginActivity extends Activity {
private final String TAG = "com.microsoft.adal.LoginActivity";
private Button btnCancel;
private WebView wv;
private ProgressDialog spinner;
private String redirectUrl;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// Get the message from the intent
Intent intent = getIntent();
final AuthenticationRequest request = (AuthenticationRequest) intent
.getSerializableExtra(AuthenticationConstants.BROWSER_REQUEST_MESSAGE);
redirectUrl = request.getRedirectUri();
Log.d(TAG, "OnCreate redirect"+redirectUrl);
// cancel action will send the request back to onActivityResult method
btnCancel = (Button) findViewById(R.id.btnCancel);
btnCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent resultIntent = new Intent();
ReturnToCaller(AuthenticationConstants.UIResponse.BROWSER_CODE_CANCEL, resultIntent);
}
});
spinner = new ProgressDialog(this);
spinner.requestWindowFeature(Window.FEATURE_NO_TITLE);
spinner.setMessage(this.getText(R.string.app_loading));
spinner.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialogInterface) {
confirmCancelRequest();
}
});
spinner.show();
// Create the Web View to show the login page
wv = (WebView) findViewById(R.id.webView1);
wv.getSettings().setJavaScriptEnabled(true);
wv.requestFocus(View.FOCUS_DOWN);
// Set focus to the view for touch event
wv.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event) {
int action = event.getAction();
if (action == MotionEvent.ACTION_DOWN
|| action == MotionEvent.ACTION_UP) {
if (!view.hasFocus()) {
view.requestFocus();
}
}
return false;
}
});
wv.getSettings().setLoadWithOverviewMode(true);
wv.getSettings().setDomStorageEnabled(true);
wv.getSettings().setUseWideViewPort(true);
wv.getSettings().setBuiltInZoomControls(true);
wv.getSettings().setPluginState(WebSettings.PluginState.ON);
wv.getSettings().setPluginsEnabled(true);
wv.setWebViewClient(new CustomWebViewClient());
// wv.setVisibility(View.INVISIBLE);
final Activity currentActivity = this;
String startUrl = "about:blank";
try {
startUrl = request.getCodeRequestUrl();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
Log.d(TAG, e.getMessage());
Intent resultIntent = new Intent();
resultIntent.putExtra(AuthenticationConstants.BROWSER_RESPONSE_ERROR_REQUEST, request);
ReturnToCaller(AuthenticationConstants.UIResponse.BROWSER_CODE_ERROR, resultIntent);
}
final String postUrl = startUrl;
wv.post( new Runnable()
{
@Override
public void run()
{
wv.loadUrl( postUrl );
}
} );
}
private void ReturnToCaller(int resultCode, Intent data)
{
Log.d(TAG, "ReturnToCaller=" + resultCode);
setResult(resultCode, data);
this.finish();
}
@Override
public void onBackPressed() {
Log.d(TAG, "Back button is pressed");
// Ask user if they rally want to cancel the flow
if(!wv.canGoBack())
{
confirmCancelRequest();
}
else
{
// Don't use default back pressed action, since user can go back in webview
wv.goBack();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
private void confirmCancelRequest()
{
new AlertDialog.Builder(LoginActivity.this)
.setTitle("Confirm?")
.setMessage("Are you sure you want to exit?")
.setNegativeButton(android.R.string.no, null)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
Intent resultIntent = new Intent();
ReturnToCaller(AuthenticationConstants.UIResponse.BROWSER_CODE_CANCEL, resultIntent);
}
}).create().show();
}
private class CustomWebViewClient extends WebViewClient {
@Override
@SuppressWarnings("deprecation")
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.d(TAG, "shouldOverrideUrlLoading:url=" + url);
if (!spinner.isShowing()) {
spinner.show();
}
if (url.startsWith(redirectUrl)) {
Log.d(TAG, "shouldOverrideUrlLoading: reached redirect");
Intent resultIntent = new Intent();
resultIntent.putExtra(AuthenticationConstants.BROWSER_RESPONSE_FINAL_URL, url);
ReturnToCaller(AuthenticationConstants.UIResponse.BROWSER_CODE_COMPLETE, resultIntent);
view.stopLoading();
return true;
}
return false;
}
@Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
Intent resultIntent = new Intent();
resultIntent.putExtra(AuthenticationConstants.BROWSER_RESPONSE_ERROR_CODE, errorCode);
resultIntent
.putExtra(AuthenticationConstants.BROWSER_RESPONSE_ERROR_MESSAGE, description);
ReturnToCaller(AuthenticationConstants.UIResponse.BROWSER_CODE_ERROR, resultIntent);
}
@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
if (AuthenticationSettings.getInstance().getIgnoreSSLErrors()) {
handler.proceed();
} else {
super.onReceivedSslError(view, handler, error);
handler.cancel();
Intent resultIntent = new Intent();
resultIntent.putExtra(AuthenticationConstants.BROWSER_RESPONSE_ERROR_CODE,
ERROR_FAILED_SSL_HANDSHAKE);
resultIntent.putExtra(AuthenticationConstants.BROWSER_RESPONSE_ERROR_MESSAGE,
error.toString());
ReturnToCaller(AuthenticationConstants.UIResponse.BROWSER_CODE_ERROR, resultIntent);
}
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
Log.d(TAG,"Page started:"+url);
if (!spinner.isShowing()) {
spinner.show();
}
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
Log.d(TAG,"Page finished"+url);
if (spinner.isShowing()) {
spinner.dismiss();
}
/*
* Once web view is fully loaded,set to visible
*/
wv.setVisibility(View.VISIBLE);
}
}
}
|
package com.nigorojr.typebest;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.HashMap;
import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SpringLayout;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
/**
* This class adds the necessary components and creates the window. All the
* other stuff such as reading/writing data etc. are left to MainTypePanel
* class.
*
* @author Naoki Mizuno
*/
public class MainWindow extends JFrame {
private TypePanel typePanel = new TypePanel();
private ClickResponder clickResponder = new ClickResponder();
private JButton restartButton = new JButton("Restart");
private HashMap<String, JMenuItem> menuItem = new HashMap<String, JMenuItem>();
private boolean restartFlag = false;
/**
* Creates a new window with a panel that you type in, and a menu bar.
*/
public MainWindow() {
super();
setTitle("TypeBest");
SpringLayout springLayout = new SpringLayout();
JPanel mainPanel = new JPanel();
mainPanel.setLayout(springLayout);
// Add items to menu
menuItem.put("ch_user", new JMenuItem("Change User"));
menuItem.put("ch_mode", new JMenuItem("Change Practice Mode"));
menuItem.put("ch_font", new JMenuItem("Change Font"));
menuItem.put("ch_layout", new JMenuItem("Change Keyboard Layout"));
menuItem.put("ch_color", new JMenuItem("Change Color"));
menuItem.put("ch_noShuffle", new JCheckBoxMenuItem(
"Don't Shuffle Words"));
menuItem.put("ch_fun", new JCheckBoxMenuItem("Fun"));
// NOTE: "Save Settings" will be added separately
// Add the menu bar
menuBar();
// Box that shows how much time has elapsed
JLabel timeElapsed = typePanel.getTimeElapsedLabel();
springLayout.putConstraint(SpringLayout.SOUTH, timeElapsed, -5,
SpringLayout.NORTH, typePanel);
springLayout.putConstraint(SpringLayout.EAST, timeElapsed, -15,
SpringLayout.EAST, typePanel);
// JLabel that shows the current keyboard layout
JLabel currentKeyboardLayout = typePanel.getCurrentKeyboardLayout();
springLayout.putConstraint(SpringLayout.SOUTH, currentKeyboardLayout,
-5, SpringLayout.NORTH, typePanel);
springLayout.putConstraint(SpringLayout.WEST, currentKeyboardLayout,
15, SpringLayout.WEST, typePanel);
// Window to type in
springLayout.putConstraint(SpringLayout.NORTH, typePanel, 50,
SpringLayout.NORTH, mainPanel);
springLayout.putConstraint(SpringLayout.SOUTH, typePanel, -40,
SpringLayout.SOUTH, mainPanel);
springLayout.putConstraint(SpringLayout.WEST, typePanel, 5,
SpringLayout.WEST, mainPanel);
springLayout.putConstraint(SpringLayout.EAST, typePanel, -5,
SpringLayout.EAST, mainPanel);
addKeyListener(new TypingResponder());
springLayout.putConstraint(SpringLayout.EAST, restartButton, -8,
SpringLayout.EAST, mainPanel);
springLayout.putConstraint(SpringLayout.SOUTH, restartButton, -8,
SpringLayout.SOUTH, mainPanel);
restartButton.addActionListener(clickResponder);
// When this is true, all the typing gets redirected to the button
restartButton.setFocusable(false);
// Add things to the main panel
mainPanel.add(currentKeyboardLayout);
mainPanel.add(timeElapsed);
mainPanel.add(restartButton);
mainPanel.add(typePanel);
// Make the MainTypePanel scrollable (experimental)
JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewportView(typePanel);
// Add to the frame
//getContentPane().add(mainPanel);
getContentPane().add(scrollPane);
// The size of the main window
setSize(800, 400);
// Load the previous user's data
typePanel.loadLastUser();
}
/**
* Adds a menu bar to the main panel.
*/
public void menuBar() {
JMenuBar menu = new JMenuBar();
// TODO: Think what kind of menus to add
JMenu settings = new JMenu("Settings");
for (String key : menuItem.keySet()) {
menuItem.get(key).addActionListener(clickResponder);
settings.add(menuItem.get(key));
}
// This item is added separately so that it shows up at the last of the
// list
JMenuItem save = new JMenuItem("Save Current Settings");
save.addActionListener(clickResponder);
settings.add(save);
menu.add(settings);
setJMenuBar(menu);
}
public void restart() {
typePanel.restart();
}
/**
* When a key is pressed, pass it to the method in MainTypePanel that
* determines what to do.
*/
public class TypingResponder implements KeyListener {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
// Restart when ESCAPE key is pressed twice-in-a-row
if (e.getKeyChar() == KeyEvent.VK_ESCAPE) {
if (restartFlag) {
restartFlag = false;
restart();
}
else
restartFlag = true;
}
else {
restartFlag = false;
typePanel.processPressedKey(e.getKeyChar());
}
}
}
/**
* Determines what to do when a button is pressed.
*/
public class ClickResponder implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == restartButton)
typePanel.restart();
// TODO: Actions when selecting various menu items
else if (e.getSource() == menuItem.get("ch_user"))
typePanel.changeUser();
else if (e.getSource() == menuItem.get("ch_mode"))
// TODO: Change practice mode
;
else if (e.getSource() == menuItem.get("ch_font"))
typePanel.changeFont();
else if (e.getSource() == menuItem.get("ch_layout"))
typePanel.changeKeyboardLayout();
else if (e.getSource() == menuItem.get("ch_color"))
typePanel.changeColor();
else if (e.getSource() == menuItem.get("ch_noShuffle"))
// If selected, don't shuffle
typePanel.changeShuffled(!menuItem.get("ch_noShuffle").isSelected());
else if (e.getSource() == menuItem.get("ch_fun"))
typePanel.changeFun(menuItem.get("ch_fun").isSelected());
else if (e.getActionCommand() == "Save Current Settings")
typePanel.saveSettings();
}
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (InstantiationException e) {
e.printStackTrace();
}
catch (IllegalAccessException e) {
e.printStackTrace();
}
catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
MainWindow mw = new MainWindow();
mw.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mw.setLocationRelativeTo(null);
mw.setVisible(true);
}
}
|
package com.puzzletimer.gui;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.UUID;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import net.miginfocom.swing.MigLayout;
import com.puzzletimer.models.Category;
import com.puzzletimer.models.Scramble;
import com.puzzletimer.models.Solution;
import com.puzzletimer.models.Timing;
import com.puzzletimer.parsers.ScrambleParser;
import com.puzzletimer.parsers.ScrambleParserProvider;
import com.puzzletimer.scramblers.Scrambler;
import com.puzzletimer.scramblers.ScramblerProvider;
import com.puzzletimer.state.CategoryListener;
import com.puzzletimer.state.CategoryManager;
import com.puzzletimer.state.ScrambleManager;
import com.puzzletimer.state.SolutionListener;
import com.puzzletimer.state.SolutionManager;
import com.puzzletimer.statistics.Average;
import com.puzzletimer.statistics.Best;
import com.puzzletimer.statistics.BestAverage;
import com.puzzletimer.statistics.BestMean;
import com.puzzletimer.statistics.Mean;
import com.puzzletimer.statistics.Percentile;
import com.puzzletimer.statistics.StandardDeviation;
import com.puzzletimer.statistics.StatisticalMeasure;
import com.puzzletimer.statistics.Worst;
import com.puzzletimer.util.SolutionUtils;
import com.puzzletimer.util.StringUtils;
@SuppressWarnings("serial")
public class HistoryFrame extends JFrame {
private static class SolutionImporterDialog extends JDialog {
public static class SolutionImporterListener {
public void solutionsImported(Solution[] solutions) {
}
}
private JTextArea textAreaContents;
private JButton buttonOk;
private JButton buttonCancel;
public SolutionImporterDialog(
JFrame owner,
boolean modal,
final UUID categoryId,
final String scramblerId,
final ScrambleParser scrambleParser,
final SolutionImporterListener listener) {
super(owner, modal);
setTitle("Solution Importer");
setMinimumSize(new Dimension(640, 480));
setPreferredSize(getMinimumSize());
createComponents();
// ok button
this.buttonOk.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
String contents =
SolutionImporterDialog.this.textAreaContents.getText();
Date start = new Date();
ArrayList<Solution> solutions = new ArrayList<Solution>();
for (String line : contents.split("\n")) {
line = line.trim();
// ignore blank lines and comments
if (line.length() == 0 || line.startsWith("
continue;
}
// separate time from scramble
String[] parts = line.split("\\s+", 2);
// time
long time = SolutionUtils.parseTime(parts[0]);
Timing timing =
new Timing(
start,
new Date(start.getTime() + time));
// scramble
Scramble scramble = new Scramble(scramblerId, new String[0]);
if (parts.length > 1) {
scramble = new Scramble(
scramblerId,
scrambleParser.parse(parts[1]));
}
solutions.add(
new Solution(
UUID.randomUUID(),
categoryId,
scramble,
timing,
""));
start = new Date(start.getTime() + time);
}
Solution[] solutionsArray = new Solution[solutions.size()];
solutions.toArray(solutionsArray);
listener.solutionsImported(solutionsArray);
SolutionImporterDialog.this.dispose();
}
});
// cancel button
this.buttonCancel.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
SolutionImporterDialog.this.dispose();
}
});
// esc key closes window
this.getRootPane().registerKeyboardAction(
new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
SolutionImporterDialog.this.dispose();
}
},
KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
JComponent.WHEN_IN_FOCUSED_WINDOW);
}
private void createComponents() {
setLayout(
new MigLayout(
"fill",
"",
"[pref!][fill]16[pref!]"));
// labelSolutions
add(new JLabel("Solutions"), "wrap");
// textAreaContents
this.textAreaContents = new JTextArea(
"# one solution per line\n" +
"# format: time [scramble]");
add(this.textAreaContents, "growx, wrap");
// buttonOk
this.buttonOk = new JButton("OK");
add(this.buttonOk, "right, width 100, span 2, split");
// buttonCancel
this.buttonCancel = new JButton("Cancel");
add(this.buttonCancel, "width 100");
}
}
private static class SolutionEditingDialog extends JDialog {
public static class SolutionEditingDialogListener {
public void solutionEdited(Solution solution) {
}
}
private JTextField textFieldStart;
private JTextField textFieldTime;
private JComboBox comboBoxPenalty;
private JTextField textFieldScramble;
private JButton buttonOk;
private JButton buttonCancel;
public SolutionEditingDialog(
JFrame owner,
boolean modal,
final Solution solution,
final SolutionEditingDialogListener listener) {
super(owner, modal);
setTitle("Solution Editor");
setMinimumSize(new Dimension(480, 200));
setPreferredSize(getMinimumSize());
createComponents();
// start
DateFormat dateFormat =
DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
this.textFieldStart.setText(
dateFormat.format(solution.getTiming().getStart()));
// time
this.textFieldTime.setText(
SolutionUtils.formatMinutes(solution.getTiming().getElapsedTime()));
// penalty
this.comboBoxPenalty.addItem("");
this.comboBoxPenalty.addItem("+2");
this.comboBoxPenalty.addItem("DNF");
this.comboBoxPenalty.setSelectedItem(solution.getPenalty());
// scramble
this.textFieldScramble.setText(StringUtils.join(" ", solution.getScramble().getSequence()));
this.textFieldScramble.setCaretPosition(0);
// ok button
this.buttonOk.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
// timing
long time =
SolutionUtils.parseTime(
SolutionEditingDialog.this.textFieldTime.getText());
Timing timing =
new Timing(
solution.getTiming().getStart(),
new Date(solution.getTiming().getStart().getTime() + time));
// penalty
String penalty =
(String) SolutionEditingDialog.this.comboBoxPenalty.getSelectedItem();
listener.solutionEdited(
solution
.setTiming(timing)
.setPenalty(penalty));
SolutionEditingDialog.this.dispose();
}
});
// cancel button
this.buttonCancel.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
SolutionEditingDialog.this.dispose();
}
});
// esc key closes window
this.getRootPane().registerKeyboardAction(
new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
SolutionEditingDialog.this.dispose();
}
},
KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
JComponent.WHEN_IN_FOCUSED_WINDOW);
}
private void createComponents() {
setLayout(
new MigLayout(
"fill, wrap",
"[pref!][fill]",
"[pref!]8[pref!]8[pref!]8[pref!]16[bottom]"));
// labelStart
add(new JLabel("Start:"));
// textFieldStart
this.textFieldStart = new JTextField();
this.textFieldStart.setEditable(false);
add(this.textFieldStart);
// labelTime
add(new JLabel("Time:"));
// textFieldTime
this.textFieldTime = new JTextField();
add(this.textFieldTime);
// labelPenalty
add(new JLabel("Penalty:"));
// comboBoxPenalty
this.comboBoxPenalty = new JComboBox();
add(this.comboBoxPenalty);
// labelScramble
add(new JLabel("Scramble:"));
// textFieldScramble
this.textFieldScramble = new JTextField();
this.textFieldScramble.setEditable(false);
add(this.textFieldScramble);
// buttonOk
this.buttonOk = new JButton("OK");
add(this.buttonOk, "right, width 100, span 2, split");
// buttonCancel
this.buttonCancel = new JButton("Cancel");
add(this.buttonCancel, "width 100");
}
}
private HistogramPanel histogramPanel;
private GraphPanel graphPanel;
private JLabel labelMean;
private JLabel labelBest;
private JLabel labelMeanOf3;
private JLabel labelBestMeanOf3;
private JLabel labelStandardDeviation;
private JLabel labelLowerQuartile;
private JLabel labelMeanOf10;
private JLabel labelBestMeanOf10;
private JLabel labelMedian;
private JLabel labelMeanOf100;
private JLabel labelBestMeanOf100;
private JLabel labelUpperQuartile;
private JLabel labelAverageOf5;
private JLabel labelBestAverageOf5;
private JLabel labelWorst;
private JLabel labelAverageOf12;
private JLabel labelBestAverageOf12;
private JTable table;
private JButton buttonAddSolutions;
private JButton buttonEdit;
private JButton buttonRemove;
private JButton buttonEnqueueScrambles;
private JButton buttonOk;
public HistoryFrame(
final ScramblerProvider scramblerProvider,
final ScrambleParserProvider scrambleParserProvider,
final CategoryManager categoryManager,
final ScrambleManager scrambleManager,
final SolutionManager solutionManager) {
super();
setMinimumSize(new Dimension(800, 600));
setPreferredSize(getMinimumSize());
createComponents();
// title
categoryManager.addCategoryListener(new CategoryListener() {
@Override
public void categoriesUpdated(Category[] categories, Category currentCategory) {
setTitle("History - " + currentCategory.getDescription());
}
});
categoryManager.notifyListeners();
// statistics, table
solutionManager.addSolutionListener(new SolutionListener() {
@Override
public void solutionsUpdated(Solution[] solutions) {
int[] selectedRows = new int[solutions.length];
for (int i = 0; i < selectedRows.length; i++) {
selectedRows[i] = i;
}
HistoryFrame.this.histogramPanel.setSolutions(solutions);
HistoryFrame.this.graphPanel.setSolutions(solutions);
updateStatistics(solutions, selectedRows);
updateTable(solutions);
}
});
solutionManager.notifyListeners();
// table selection
this.table.getSelectionModel().addListSelectionListener(
new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent event) {
Solution[] solutions = solutionManager.getSolutions();
Solution[] selectedSolutions;
int[] selectedRows = HistoryFrame.this.table.getSelectedRows();
if (selectedRows.length <= 0) {
selectedRows = new int[HistoryFrame.this.table.getRowCount()];
for (int i = 0; i < selectedRows.length; i++) {
selectedRows[i] = i;
}
selectedSolutions = solutions;
} else {
selectedSolutions = new Solution[selectedRows.length];
for (int i = 0; i < selectedSolutions.length; i++) {
selectedSolutions[i] = solutions[selectedRows[i]];
}
}
HistoryFrame.this.histogramPanel.setSolutions(selectedSolutions);
HistoryFrame.this.graphPanel.setSolutions(selectedSolutions);
updateStatistics(selectedSolutions, selectedRows);
HistoryFrame.this.buttonEdit.setEnabled(
HistoryFrame.this.table.getSelectedRowCount() == 1);
HistoryFrame.this.buttonRemove.setEnabled(
HistoryFrame.this.table.getSelectedRowCount() > 0);
HistoryFrame.this.buttonEnqueueScrambles.setEnabled(
HistoryFrame.this.table.getSelectedRowCount() > 0);
}
});
// add solutions button
this.buttonAddSolutions.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SolutionImporterDialog.SolutionImporterListener listener =
new SolutionImporterDialog.SolutionImporterListener() {
@Override
public void solutionsImported(Solution[] solutions) {
for (Solution solution : solutions) {
solutionManager.addSolution(solution);
}
}
};
Category currentCategory = categoryManager.getCurrentCategory();
Scrambler currentScrambler = scramblerProvider.get(currentCategory.getScramblerId());
String puzzleId = currentScrambler.getScramblerInfo().getPuzzleId();
ScrambleParser scrambleParser = scrambleParserProvider.get(puzzleId);
SolutionImporterDialog solutionEditingDialog =
new SolutionImporterDialog(
HistoryFrame.this,
true,
currentCategory.getCategoryId(),
currentCategory.getScramblerId(),
scrambleParser,
listener);
solutionEditingDialog.setLocationRelativeTo(null);
solutionEditingDialog.setVisible(true);
}
});
// edit button
this.buttonEdit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Solution[] solutions = solutionManager.getSolutions();
Solution solution = solutions[HistoryFrame.this.table.getSelectedRow()];
HistoryFrame.SolutionEditingDialog.SolutionEditingDialogListener listener =
new HistoryFrame.SolutionEditingDialog.SolutionEditingDialogListener() {
@Override
public void solutionEdited(Solution solution) {
solutionManager.updateSolution(solution);
}
};
SolutionEditingDialog solutionEditingDialog =
new SolutionEditingDialog(
HistoryFrame.this,
true,
solution,
listener);
solutionEditingDialog.setLocationRelativeTo(null);
solutionEditingDialog.setVisible(true);
}
});
// remove button
this.buttonRemove.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Solution[] solutions = solutionManager.getSolutions();
int[] selectedRows = HistoryFrame.this.table.getSelectedRows();
for (int i = 0; i < selectedRows.length; i++) {
solutionManager.removeSolution(solutions[selectedRows[i]]);
}
}
});
// enqueue scrambles button
this.buttonEnqueueScrambles.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Solution[] solutions = solutionManager.getSolutions();
int[] selectedRows = HistoryFrame.this.table.getSelectedRows();
Scramble[] selectedScrambles = new Scramble[selectedRows.length];
for (int i = 0; i < selectedScrambles.length; i++) {
selectedScrambles[i] = solutions[selectedRows[i]].getScramble();
}
scrambleManager.addScrambles(selectedScrambles);
}
});
// close button
this.setDefaultCloseOperation(HIDE_ON_CLOSE);
this.buttonOk.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
HistoryFrame.this.setVisible(false);
}
});
// esc key closes window
this.getRootPane().registerKeyboardAction(
new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
HistoryFrame.this.setVisible(false);
}
},
KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
JComponent.WHEN_IN_FOCUSED_WINDOW);
}
private void createComponents() {
setLayout(
new MigLayout(
"fill",
"[][pref!]",
"[pref!][pref!]12[pref!][pref!]12[pref!][pref!]12[pref!][]16[pref!]"));
// labelHistogram
add(new JLabel("Histogram"), "span, wrap");
// histogram
this.histogramPanel = new HistogramPanel(new Solution[0], 17);
add(this.histogramPanel, "growx, height 90, span, wrap");
// labelGraph
add(new JLabel("Graph"), "span, wrap");
// Graph
this.graphPanel = new GraphPanel(new Solution[0]);
add(this.graphPanel, "growx, height 90, span, wrap");
// labelStatistics
add(new JLabel("Statistics"), "span, wrap");
// panelStatistics
JPanel panelStatistics = new JPanel(
new MigLayout(
"fill, insets 0 n 0 n",
"[][pref!]32[][pref!]32[][pref!]32[][pref!]",
"[pref!]1[pref!]1[pref!]1[pref!]1[pref!]"));
add(panelStatistics, "growx, span, wrap");
// labelMean
panelStatistics.add(new JLabel("Mean:"), "");
this.labelMean = new JLabel("XX:XX.XX");
panelStatistics.add(this.labelMean, "");
// labelBest
panelStatistics.add(new JLabel("Best:"), "");
this.labelBest = new JLabel("XX:XX.XX");
panelStatistics.add(this.labelBest, "");
// labelMeanOf3
panelStatistics.add(new JLabel("Mean of 3:"), "");
this.labelMeanOf3 = new JLabel("XX:XX.XX");
panelStatistics.add(this.labelMeanOf3, "");
// labelBestMeanOf3
panelStatistics.add(new JLabel("Best mean of 3:"), "");
this.labelBestMeanOf3 = new JLabel("XX:XX.XX");
panelStatistics.add(this.labelBestMeanOf3, "wrap");
// labelStandardDeviation
panelStatistics.add(new JLabel("Standard Deviation:"), "");
this.labelStandardDeviation = new JLabel("XX:XX.XX");
panelStatistics.add(this.labelStandardDeviation, "");
// labelLowerQuartile
panelStatistics.add(new JLabel("Lower quartile:"), "");
this.labelLowerQuartile = new JLabel("XX:XX.XX");
panelStatistics.add(this.labelLowerQuartile, "");
// labelMeanOf10
panelStatistics.add(new JLabel("Mean of 10:"), "");
this.labelMeanOf10 = new JLabel("XX:XX.XX");
panelStatistics.add(this.labelMeanOf10, "");
// labelBestMeanOf10
panelStatistics.add(new JLabel("Best mean of 10:"), "");
this.labelBestMeanOf10 = new JLabel("XX:XX.XX");
panelStatistics.add(this.labelBestMeanOf10, "wrap");
// labelMedian
panelStatistics.add(new JLabel("Median:"), "skip 2");
this.labelMedian = new JLabel("XX:XX.XX");
panelStatistics.add(this.labelMedian, "");
// labelMeanOf100
panelStatistics.add(new JLabel("Mean of 100:"), "");
this.labelMeanOf100 = new JLabel("XX:XX.XX");
panelStatistics.add(this.labelMeanOf100, "");
// labelBestMeanOf100
panelStatistics.add(new JLabel("Best mean of 100:"), "");
this.labelBestMeanOf100 = new JLabel("XX:XX.XX");
panelStatistics.add(this.labelBestMeanOf100, "wrap");
// labelUpperQuartile
panelStatistics.add(new JLabel("Upper quartile:"), "skip 2");
this.labelUpperQuartile = new JLabel("XX:XX.XX");
panelStatistics.add(this.labelUpperQuartile, "");
// labelAverageOf5
panelStatistics.add(new JLabel("Average of 5:"), "");
this.labelAverageOf5 = new JLabel("XX:XX.XX");
panelStatistics.add(this.labelAverageOf5, "");
// labelBestAverageOf5
panelStatistics.add(new JLabel("Best average of 5:"), "");
this.labelBestAverageOf5 = new JLabel("XX:XX.XX");
panelStatistics.add(this.labelBestAverageOf5, "wrap");
// labelWorst
panelStatistics.add(new JLabel("Worst:"), "skip 2");
this.labelWorst = new JLabel("XX:XX.XX");
panelStatistics.add(this.labelWorst, "");
// labelAverageOf12
panelStatistics.add(new JLabel("Average of 12:"), "");
this.labelAverageOf12 = new JLabel("XX:XX.XX");
panelStatistics.add(this.labelAverageOf12, "");
// labelBestAverageOf12
panelStatistics.add(new JLabel("Best average of 12:"), "");
this.labelBestAverageOf12 = new JLabel("XX:XX.XX");
panelStatistics.add(this.labelBestAverageOf12, "");
// labelSolutions
JLabel labelTimes = new JLabel("Solutions");
add(labelTimes, "span, wrap");
// table
this.table = new JTable();
this.table.setShowVerticalLines(false);
JScrollPane scrollPane = new JScrollPane(this.table);
this.table.setFillsViewportHeight(true);
add(scrollPane, "grow");
// buttonAddSolutions
this.buttonAddSolutions = new JButton("Add solutions...");
add(this.buttonAddSolutions, "growx, top, split 4, flowy");
// buttonEdit
this.buttonEdit = new JButton("Edit...");
this.buttonEdit.setEnabled(false);
add(this.buttonEdit, "growx, top");
// buttonRemove
this.buttonRemove = new JButton("Remove");
this.buttonRemove.setEnabled(false);
add(this.buttonRemove, "growx, top");
// buttonEnqueueScrambles
this.buttonEnqueueScrambles = new JButton("Enqueue scrambles");
this.buttonEnqueueScrambles.setEnabled(false);
add(this.buttonEnqueueScrambles, "growx, top, gaptop 20, wrap");
// buttonOk
this.buttonOk = new JButton("OK");
add(this.buttonOk, "width 100, right, span");
}
private void updateStatistics(Solution[] solutions, final int[] selectedRows) {
JLabel labels[] = {
this.labelMean,
this.labelBest,
this.labelMeanOf3,
this.labelBestMeanOf3,
this.labelStandardDeviation,
this.labelLowerQuartile,
this.labelMeanOf10,
this.labelBestMeanOf10,
this.labelMedian,
this.labelMeanOf100,
this.labelBestMeanOf100,
this.labelUpperQuartile,
this.labelAverageOf5,
this.labelBestAverageOf5,
this.labelWorst,
this.labelAverageOf12,
this.labelBestAverageOf12,
};
StatisticalMeasure[] measures = {
new Mean(1, Integer.MAX_VALUE),
new Best(1, Integer.MAX_VALUE),
new Mean(3, 3),
new BestMean(3, Integer.MAX_VALUE),
new StandardDeviation(1, Integer.MAX_VALUE),
new Percentile(1, Integer.MAX_VALUE, 0.25),
new Mean(10, 10),
new BestMean(10, Integer.MAX_VALUE),
new Percentile(1, Integer.MAX_VALUE, 0.5),
new Mean(100, 100),
new BestMean(100, Integer.MAX_VALUE),
new Percentile(1, Integer.MAX_VALUE, 0.75),
new Average(5, 5),
new BestAverage(5, Integer.MAX_VALUE),
new Worst(1, Integer.MAX_VALUE),
new Average(12, 12),
new BestAverage(12, Integer.MAX_VALUE),
};
boolean[] clickable = {
false,
true,
true,
true,
false,
false,
true,
true,
false,
true,
true,
false,
true,
true,
true,
true,
true,
};
for (int i = 0; i < labels.length; i++) {
if (solutions.length >= measures[i].getMinimumWindowSize()) {
int size = Math.min(solutions.length, measures[i].getMaximumWindowSize());
Solution[] window = new Solution[size];
for (int j = 0; j < size; j++) {
window[j] = solutions[j];
}
measures[i].setSolutions(window);
labels[i].setText(SolutionUtils.formatMinutes(measures[i].getValue()));
} else {
labels[i].setText("XX:XX.XX");
}
if (clickable[i]) {
MouseListener[] mouseListeners = labels[i].getMouseListeners();
for (MouseListener mouseListener : mouseListeners) {
labels[i].removeMouseListener(mouseListener);
}
labels[i].setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
if (solutions.length >= measures[i].getMinimumWindowSize()) {
labels[i].setCursor(new Cursor(Cursor.HAND_CURSOR));
final int windowSize = measures[i].getMinimumWindowSize();
final int windowPosition = measures[i].getWindowPosition();
labels[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
HistoryFrame.this.table.removeRowSelectionInterval(
0, HistoryFrame.this.table.getRowCount() - 1);
for (int i = 0; i < windowSize; i++) {
HistoryFrame.this.table.addRowSelectionInterval(
selectedRows[windowPosition + i],
selectedRows[windowPosition + i]);
}
}
});
}
}
}
}
private void updateTable(Solution[] solutions) {
DefaultTableModel tableModel = new DefaultTableModel() {
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
for (String column : new String[] { "#", "Start", "Time", "Penalty", "Scramble" }) {
tableModel.addColumn(column);
}
this.table.setModel(tableModel);
this.table.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
int[] columnsWidth = { 100, 400, 200, 200, 1000 };
for (int i = 0; i < columnsWidth.length; i++) {
TableColumn indexColumn = this.table.getColumnModel().getColumn(i);
indexColumn.setPreferredWidth(columnsWidth[i]);
}
for (int i = 0; i < solutions.length; i++) {
// start
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
String sStart = dateFormat.format(solutions[i].getTiming().getStart());
// time
String sTime = SolutionUtils.formatMinutes(solutions[i].getTiming().getElapsedTime());
tableModel.addRow(new Object[] {
solutions.length - i,
sStart,
sTime,
solutions[i].getPenalty(),
StringUtils.join(" ", solutions[i].getScramble().getSequence()),
});
}
}
}
|
package com.shsrobotics.library;
import java.util.LinkedList;
public abstract class TaskList extends Thread {
private LinkedList<Task> list;
private RunType runType;
private int pTaskCount = 0;
final Object lock = new Object();
private boolean runOnce = false;
public TaskList() {
runType = RunType.SEQUENTIAL;
}
/**
* starts the task list.
*/
@Override
public synchronized void start() {
if ( !runOnce ) {
runOnce = true;
super.start();
}
else {
new IllegalThreadStateException("Tried to run a TaskList more than once. Can only run a thread once!").printStackTrace();
}
}
public final void run() {
if ( runOnce ) {
return;
}
runTasks();
}
/**
* You might experience some difficulties with t. Just don't try to stop t with stop() or start with start(), because t is not running.
* @param t
* @return The wrapped task. If in sequential mode, this is probably useless.
* @throws InterruptedException if the task is started on sequential mode and this thread is interrupted.
*/
protected Task begin(final Task t) throws InterruptedException { // TODO put waitForThreads at beginning of begin() (for sequential)
t.stop();
Task w;
w = new Task() {
@Override
protected void initialize() {
t.initialize();
}
@Override
protected void execute() {
t.execute();
}
@Override
protected boolean isFinished() {
return t.isFinished();
}
@Override
protected void end() {
t.end();
synchronized(lock) {
lock.notifyAll();
}
}
};
if ( runType == RunType.PARALLEL ) {
pTaskCount++;
}
else if ( runType == RunType.SEQUENTIAL ) {
waitForThreads();
}
w.start();
return w;
}
/**
* Waits for all threads executed since the last call to wait to finish.
* @throws InterruptedException
*/
protected void waitForThreads() throws InterruptedException {
while ( pTaskCount != 0 ) {
synchronized(lock) {
lock.wait();
pTaskCount
}
}
}
protected void runSequential() {
runType = RunType.SEQUENTIAL;
}
protected void runParallel() {
runType = RunType.PARALLEL;
}
protected abstract void runTasks();
private enum RunType {
PARALLEL, SEQUENTIAL;
}
}
|
package com.twu.biblioteca;
import java.io.*;
public class BibliotecaApp
{
private static Library library;
private static BufferedReader in;
private static PrintStream out;
public static void main(String[] args)
{
program(System.in, System.out);
}
static void program(InputStream inStream, PrintStream outStream)
{
setStreams(inStream, outStream);
boolean success = login();
if(!success)
{
return;
}
out.println();
out.println("Welcome!");
library = new Library();
mainLoop();
}
private static boolean login()
{
while (true)
{
out.println("Enter library number:");
String username = getInput();
if(username.equals("q"))
{
out.println();
quit();
return false;
}
if(!username.equals(Generate.libraryNumber()))
{
out.println("Unrecognisable library number.\n");
continue;
}
out.println("Enter password:");
String password = getInput();
if(!password.equals(Generate.password()))
{
out.println("Invalid password.\n");
continue;
}
return true;
}
}
private static void setStreams(InputStream inStream, PrintStream outStream)
{
in = new BufferedReader(new InputStreamReader(inStream));
out = outStream;
}
private static void mainLoop()
{
boolean cont = true;
while (cont)
{
printMenuOptions();
String input = getInput();
cont = selectMenuOption(input);
}
}
private static String getInput()
{
try
{
return in.readLine();
}
catch (IOException e)
{
e.printStackTrace();
return null;
}
}
private static void printMenuOptions()
{
out.println("Menu Options:\n" +
"\tList Books: enter \"b\"\n" +
"\tCheckout Book: enter \"c\"\n" +
"\tReturn Book: enter \"r\"\n" +
"\tList Movies: enter \"m\"\n" +
"\tCheckout Movie: enter \"k\"\n" +
"\tQuit: enter \"q\"");
}
private static boolean selectMenuOption(String input)
{
out.println();
if(input == null || input.length() != 1)
{
out.println("Select a valid option!");
return true;
}
char c = input.charAt(0);
switch (c)
{
case 'b':
out.println(library.printTypeList(Library.Item.book));
break;
case 'c':
checkoutOption(Library.Item.book);
break;
case 'r':
returnBookOption();
break;
case 'm':
out.println(library.printTypeList(Library.Item.movie));
break;
case 'k':
checkoutOption(Library.Item.movie);
break;
case 'q':
quit();
return false;
default:
out.println("Select a valid option!");
}
return true;
}
private static void checkoutOption(Library.Item type)
{
out.println(library.printTypeList(type));
out.println("Select " + type + " to checkout: enter index");
String input = getInput();
out.println();
int index;
try
{
index = Integer.parseInt(input);
}
catch (NumberFormatException ex)
{
out.println("Not a valid index of a " + type + "!\n");
return;
}
boolean success = library.checkout(type, index - 1);
if (success)
{
out.println("Thank you! Enjoy the " + type + ".\n");
}
else
{
out.println("That " + type + " is not available!\n");
}
}
private static void returnBookOption()
{
out.println("Enter title of the book you are returning:");
String input = getInput();
out.println();
boolean success = library.returnBook(input);
if(success)
{
out.println("Thank you for returning the book.\n");
}
else
{
out.println("That is not a valid book to return.\n");
}
}
private static void quit()
{
out.println("Quit!");
}
}
|
package com.gimranov.zandy.app;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Authenticator;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.apache.http.util.ByteArrayBuffer;
import org.json.JSONException;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.MimeTypeMap;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.BufferType;
import android.widget.Toast;
import com.gimranov.zandy.app.data.Attachment;
import com.gimranov.zandy.app.data.Database;
import com.gimranov.zandy.app.data.Item;
import com.gimranov.zandy.app.task.APIRequest;
import com.gimranov.zandy.app.task.ZoteroAPITask;
/**
* This Activity handles displaying and editing attachments. It works almost the same as
* ItemDataActivity and TagActivity, using a simple ArrayAdapter on Bundles with the creator info.
*
* This currently operates by showing the attachments for a given item
*
* @author ajlyon
*
*/
public class AttachmentActivity extends ListActivity {
private static final String TAG = "com.gimranov.zandy.app.AttachmentActivity";
static final int DIALOG_CONFIRM_NAVIGATE = 4;
static final int DIALOG_FILE_PROGRESS = 6;
static final int DIALOG_CONFIRM_DELETE = 5;
static final int DIALOG_NOTE = 3;
static final int DIALOG_NEW = 1;
public Item item;
private ProgressDialog mProgressDialog;
private ProgressThread progressThread;
private Database db;
/**
* For <= Android 2.1 (API 7), we can't pass bundles to showDialog(), so set this instead
*/
private Bundle b = new Bundle();
private ArrayList<File> tmpFiles;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tmpFiles = new ArrayList<File>();
db = new Database(this);
/* Get the incoming data from the calling activity */
final String itemKey = getIntent().getStringExtra("com.gimranov.zandy.app.itemKey");
Item item = Item.load(itemKey, db);
this.item = item;
if (item == null) {
Log.e(TAG, "AttachmentActivity started without itemKey; finishing.");
finish();
return;
}
this.setTitle(getResources().getString(R.string.attachments_for_item,item.getTitle()));
ArrayList<Attachment> rows = Attachment.forItem(item, db);
/*
* We use the standard ArrayAdapter, passing in our data as a Attachment.
* Since it's no longer a simple TextView, we need to override getView, but
* we can do that anonymously.
*/
setListAdapter(new ArrayAdapter<Attachment>(this, R.layout.list_attach, rows) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row;
// We are reusing views, but we need to initialize it if null
if (null == convertView) {
LayoutInflater inflater = getLayoutInflater();
row = inflater.inflate(R.layout.list_attach, null);
} else {
row = convertView;
}
ImageView tvType = (ImageView)row.findViewById(R.id.attachment_type);
TextView tvSummary = (TextView)row.findViewById(R.id.attachment_summary);
Attachment att = getItem(position);
Log.d(TAG, "Have an attachment: "+att.title + " fn:"+att.filename + " status:" + att.status);
tvType.setImageResource(Item.resourceForType(att.getType()));
try {
Log.d(TAG, att.content.toString(4));
} catch (JSONException e) {
Log.e(TAG, "JSON parse exception when reading attachment content", e);
}
if (att.getType().equals("note")) {
String note = att.content.optString("note","");
if (note.length() > 40) {
note = note.substring(0,40);
}
tvSummary.setText(note);
} else {
StringBuffer status = new StringBuffer(getResources().getString(R.string.status));
if (att.status == Attachment.AVAILABLE)
status.append(getResources().getString(R.string.attachment_zfs_available));
else if (att.status == Attachment.LOCAL)
status.append(getResources().getString(R.string.attachment_zfs_local));
else
status.append(getResources().getString(R.string.attachment_unknown));
tvSummary.setText(att.title + " " + status.toString());
}
return row;
}
});
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
// Warning here because Eclipse can't tell whether my ArrayAdapter is
// being used with the correct parametrization.
@SuppressWarnings("unchecked")
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
// If we have a click on an entry, show its note
ArrayAdapter<Attachment> adapter = (ArrayAdapter<Attachment>) parent.getAdapter();
Attachment row = adapter.getItem(position);
if (row.content.has("note")) {
Log.d(TAG, "Trying to start note view activity for: "+row.key);
Intent i = new Intent(getBaseContext(), NoteActivity.class);
i.putExtra("com.gimranov.zandy.app.attKey", row.key);//row.content.optString("note", ""));
startActivity(i);
}
return true;
}
});
lv.setOnItemClickListener(new OnItemClickListener() {
// Warning here because Eclipse can't tell whether my ArrayAdapter is
// being used with the correct parametrization.
@SuppressWarnings("unchecked")
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// If we have a long click on an entry, do something...
ArrayAdapter<Attachment> adapter = (ArrayAdapter<Attachment>) parent.getAdapter();
Attachment row = adapter.getItem(position);
String url = (row.url != null && !row.url.equals("")) ?
row.url : row.content.optString("url");
if (!row.getType().equals("note")) {
Bundle b = new Bundle();
b.putString("title", row.title);
b.putString("attachmentKey", row.key);
b.putString("content", url);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
int linkMode = row.content.optInt("linkMode", Attachment.MODE_IMPORTED_URL);
if (settings.getBoolean("webdav_enabled", false))
b.putString("mode", "webdav");
else
b.putString("mode", "zfs");
if (linkMode == Attachment.MODE_IMPORTED_FILE
|| linkMode == Attachment.MODE_IMPORTED_URL) {
loadFileAttachment(b);
} else {
AttachmentActivity.this.b = b;
showDialog(DIALOG_CONFIRM_NAVIGATE);
}
}
if (row.getType().equals("note")) {
Bundle b = new Bundle();
b.putString("attachmentKey", row.key);
b.putString("itemKey", itemKey);
b.putString("content", row.content.optString("note", ""));
removeDialog(DIALOG_NOTE);
AttachmentActivity.this.b = b;
showDialog(DIALOG_NOTE);
}
return;
}
});
}
@Override
public void onDestroy() {
if (db != null) db.close();
if (tmpFiles != null) {
for (File f : tmpFiles) {
if (!f.delete()) {
Log.e(TAG, "Failed to delete temporary file on activity close.");
}
}
tmpFiles.clear();
}
super.onDestroy();
}
@Override
public void onResume() {
if (db == null) db = new Database(this);
super.onResume();
}
protected Dialog onCreateDialog(int id) {
final String attachmentKey = b.getString("attachmentKey");
final String itemKey = b.getString("itemKey");
final String content = b.getString("content");
final String mode = b.getString("mode");
AlertDialog dialog;
switch (id) {
case DIALOG_CONFIRM_NAVIGATE:
dialog = new AlertDialog.Builder(this)
.setTitle(getResources().getString(R.string.view_online_warning))
.setPositiveButton(getResources().getString(R.string.view), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// The behavior for invalid URIs might be nasty, but
// we'll cross that bridge if we come to it.
try {
Uri uri = Uri.parse(content);
startActivity(new Intent(Intent.ACTION_VIEW)
.setData(uri));
} catch (ActivityNotFoundException e) {
// There can be exceptions here; not sure what would prompt us to have
// URIs that the browser can't load, but it apparently happens.
Toast.makeText(getApplicationContext(),
getResources().getString(R.string.attachment_intent_failed_for_uri, content),
Toast.LENGTH_SHORT).show();
}
}
}).setNeutralButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// do nothing
}
}).create();
return dialog;
case DIALOG_CONFIRM_DELETE:
dialog = new AlertDialog.Builder(this)
.setTitle(getResources().getString(R.string.attachment_delete_confirm))
.setPositiveButton(getResources().getString(R.string.menu_delete), new DialogInterface.OnClickListener() {
@SuppressWarnings("unchecked")
public void onClick(DialogInterface dialog, int whichButton) {
Attachment a = Attachment.load(attachmentKey, db);
a.delete(db);
ArrayAdapter<Attachment> la = (ArrayAdapter<Attachment>) getListAdapter();
la.clear();
for (Attachment at : Attachment.forItem(Item.load(itemKey, db), db)) {
la.add(at);
}
}
}).setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// do nothing
}
}).create();
return dialog;
case DIALOG_NOTE:
final EditText input = new EditText(this);
input.setText(content, BufferType.EDITABLE);
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setTitle(getResources().getString(R.string.note))
.setView(input)
.setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
@SuppressWarnings("unchecked")
public void onClick(DialogInterface dialog, int whichButton) {
Editable value = input.getText();
String fixed = value.toString().replaceAll("\n\n", "\n<br>");
if (mode != null && mode.equals("new")) {
Log.d(TAG, "Attachment created with parent key: "+itemKey);
Attachment att = new Attachment(getBaseContext(), "note", itemKey);
att.setNoteText(fixed);
att.dirty = APIRequest.API_NEW;
att.save(db);
} else {
Attachment att = Attachment.load(attachmentKey, db);
att.setNoteText(fixed);
att.dirty = APIRequest.API_DIRTY;
att.save(db);
}
ArrayAdapter<Attachment> la = (ArrayAdapter<Attachment>) getListAdapter();
la.clear();
for (Attachment a : Attachment.forItem(Item.load(itemKey, db), db)) {
la.add(a);
}
la.notifyDataSetChanged();
}
}).setNeutralButton(getResources().getString(R.string.cancel),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// do nothing
}
});
// We only want the delete option when this isn't a new note
if (mode == null || !"new".equals(mode)) {
builder = builder.setNegativeButton(getResources().getString(R.string.menu_delete), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Bundle b = new Bundle();
b.putString("attachmentKey", attachmentKey);
b.putString("itemKey", itemKey);
removeDialog(DIALOG_CONFIRM_DELETE);
AttachmentActivity.this.b = b;
showDialog(DIALOG_CONFIRM_DELETE);
}
});
}
dialog = builder.create();
return dialog;
case DIALOG_FILE_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setMessage(getResources().getString(R.string.attachment_downloading, b.getString("title")));
mProgressDialog.setIndeterminate(true);
return mProgressDialog;
default:
Log.e(TAG, "Invalid dialog requested");
return null;
}
}
protected void onPrepareDialog(int id, Dialog dialog) {
switch(id) {
case DIALOG_FILE_PROGRESS:
mProgressDialog.setMessage(getResources().getString(R.string.attachment_downloading, b.getString("title")));
progressThread = new ProgressThread(handler, b);
progressThread.start();
}
}
private void showAttachment(Attachment att) {
if (att.status == Attachment.LOCAL) {
Log.d(TAG,"Starting to display local attachment");
Uri uri = Uri.fromFile(new File(att.filename));
String mimeType = att.content.optString("mimeType","application/pdf");
try {
startActivity(new Intent(Intent.ACTION_VIEW)
.setDataAndType(uri,mimeType));
} catch (ActivityNotFoundException e) {
Log.e(TAG, "No activity for intent", e);
Toast.makeText(getApplicationContext(),
getResources().getString(R.string.attachment_intent_failed, mimeType),
Toast.LENGTH_SHORT).show();
}
}
}
/**
* This mainly is to move the logic out of the onClick callback above
* Decides whether to download or view, and launches the appropriate action
* @param b
*/
private void loadFileAttachment(Bundle b) {
Attachment att = Attachment.load(b.getString("attachmentKey"), db);
if (!ServerCredentials.sBaseStorageDir.exists())
ServerCredentials.sBaseStorageDir.mkdirs();
if (!ServerCredentials.sDocumentStorageDir.exists())
ServerCredentials.sDocumentStorageDir.mkdirs();
File attFile = new File(att.filename);
if (att.status == Attachment.AVAILABLE
// Zero-length or nonexistent gives length == 0
|| (attFile != null && attFile.length() == 0)) {
Log.d(TAG,"Starting to try and download attachment (status: "+att.status+", fn: "+att.filename+")");
this.b = b;
showDialog(DIALOG_FILE_PROGRESS);
} else showAttachment(att);
}
/**
* Refreshes the current list adapter
*/
@SuppressWarnings("unchecked")
private void refreshView() {
ArrayAdapter<Attachment> la = (ArrayAdapter<Attachment>) getListAdapter();
la.clear();
for (Attachment at : Attachment.forItem(item, db)) {
la.add(at);
}
}
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.arg2) {
case ProgressThread.STATE_DONE:
if(mProgressDialog.isShowing())
dismissDialog(DIALOG_FILE_PROGRESS);
refreshView();
if (null != msg.obj)
showAttachment((Attachment)msg.obj);
break;
case ProgressThread.STATE_FAILED:
// Notify that we failed to get anything
Toast.makeText(getApplicationContext(),
getResources().getString(R.string.attachment_no_download_url),
Toast.LENGTH_SHORT).show();
if(mProgressDialog.isShowing())
dismissDialog(DIALOG_FILE_PROGRESS);
// Let's try to fall back on an online version
AttachmentActivity.this.b = msg.getData();
showDialog(DIALOG_CONFIRM_NAVIGATE);
refreshView();
break;
case ProgressThread.STATE_UNZIPPING:
mProgressDialog.setMax(msg.arg1);
mProgressDialog.setProgress(0);
mProgressDialog.setMessage(getResources().getString(R.string.attachment_unzipping));
break;
case ProgressThread.STATE_RUNNING:
mProgressDialog.setMax(msg.arg1);
mProgressDialog.setProgress(0);
mProgressDialog.setIndeterminate(false);
break;
default:
mProgressDialog.setProgress(msg.arg1);
break;
}
}
};
private class ProgressThread extends Thread {
Handler mHandler;
Bundle arguments;
final static int STATE_DONE = 5;
final static int STATE_FAILED = 3;
final static int STATE_RUNNING = 1;
final static int STATE_UNZIPPING = 6;
ProgressThread(Handler h, Bundle b) {
mHandler = h;
arguments = b;
}
@SuppressWarnings("unchecked")
public void run() {
// Setup
final String attachmentKey = arguments.getString("attachmentKey");
final String mode = arguments.getString("mode");
URL url;
File file;
String urlstring;
Attachment att = Attachment.load(attachmentKey, db);
String sanitized = att.title.replace(' ', '_');
// If no 1-6-character extension, try to add one using MIME type
if (!sanitized.matches(".*\\.[a-zA-Z0-9]{1,6}$")) {
String extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(att.getType());
if (extension != null) sanitized = sanitized + "." + extension;
}
sanitized = sanitized.replaceFirst("^(.*?)(\\.[^.]*)?$", "$1"+"_"+att.key+"$2");
file = new File(ServerCredentials.sDocumentStorageDir,sanitized);
if (!ServerCredentials.sBaseStorageDir.exists())
ServerCredentials.sBaseStorageDir.mkdirs();
if (!ServerCredentials.sDocumentStorageDir.exists())
ServerCredentials.sDocumentStorageDir.mkdirs();
final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
if ("webdav".equals(mode)) {
urlstring = settings.getString("webdav_path", "")+"/"+att.key+".zip";
Authenticator.setDefault (new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication (settings.getString("webdav_username", ""),
settings.getString("webdav_password", "").toCharArray());
}
});
} else {
urlstring = att.url+"?key="+settings.getString("user_key","");
}
try {
try {
url = new URL(urlstring);
} catch (MalformedURLException e) {
// Alert that we don't have a valid download URL and return
Message msg = mHandler.obtainMessage();
msg.arg2 = STATE_FAILED;
msg.setData(arguments);
mHandler.sendMessage(msg);
Log.e(TAG, "Download URL not valid: "+urlstring, e);
return;
}
//this is the downloader method
long startTime = System.currentTimeMillis();
Log.d(TAG, "download beginning");
Log.d(TAG, "download url:" + url.toString());
Log.d(TAG, "downloaded file name:" + file.getPath());
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
ucon.setRequestProperty("User-Agent","Mozilla/5.0 ( compatible ) ");
ucon.setRequestProperty("Accept","*/*");
Message msg = mHandler.obtainMessage();
msg.arg1 = ucon.getContentLength();
msg.arg2 = STATE_RUNNING;
mHandler.sendMessage(msg);
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is, 16000);
// Buffer up to 512KB at a time
int bufferSize = Math.max(1000, Math.min(ucon.getContentLength(), 512*1024));
ByteArrayBuffer baf = new ByteArrayBuffer(bufferSize);
int current = 0;
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
* TODO read in chunks instead of byte by byte
*/
while ((current = bis.read()) != -1) {
baf.append((byte) current);
if (baf.length() % 2048 == 0) {
msg = mHandler.obtainMessage();
msg.arg1 = baf.length();
mHandler.sendMessage(msg);
}
}
/* Save to temporary directory for WebDAV */
if ("webdav".equals(mode)) {
if (!ServerCredentials.sCacheDir.exists())
ServerCredentials.sCacheDir.mkdirs();
File tmpFile = File.createTempFile("zandy", ".zip",ServerCredentials.sCacheDir);
// Keep track of temp files that we've created.
if (tmpFiles == null) tmpFiles = new ArrayList<File>();
tmpFiles.add(tmpFile);
FileOutputStream fos = new FileOutputStream(tmpFile);
fos.write(baf.toByteArray());
fos.close();
ZipFile zf = new ZipFile(tmpFile);
Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zf.entries();
do {
ZipEntry entry = entries.nextElement();
// Change the message to reflect that we're unzipping now
msg = mHandler.obtainMessage();
msg.arg1 = (int) entry.getSize();
msg.arg2 = STATE_UNZIPPING;
mHandler.sendMessage(msg);
String name64 = entry.getName();
byte[] byteName = Base64.decode(name64.getBytes(), 0, name64.length() - 5, Base64.DEFAULT);
String name = new String(byteName);
Log.d(TAG, "Found file "+name+" from encoded "+name64);
// If the linkMode is not an imported URL (snapshot) and the MIME type isn't text/html,
// then we unzip it and we're happy. If either of the preceding is true, we skip the file
// unless the filename includes .htm (covering .html automatically)
if ( (!att.getType().equals("text/html")) || name.contains(".htm")) {
FileOutputStream fos2 = new FileOutputStream(file);
InputStream entryStream = zf.getInputStream(entry);
ByteArrayBuffer baf2 = new ByteArrayBuffer(100);
while ((current = entryStream.read()) != -1) {
baf2.append((byte) current);
if (baf2.length() % 2048 == 0) {
msg = mHandler.obtainMessage();
msg.arg1 = baf2.length();
mHandler.sendMessage(msg);
}
}
fos2.write(baf2.toByteArray());
fos2.close();
Log.d(TAG, "Finished reading file");
} else {
Log.d(TAG, "Skipping file: "+name);
}
} while (entries.hasMoreElements());
zf.close();
// We remove the file from the ArrayList if deletion succeeded;
// otherwise deletion is put off until the activity exits.
if (tmpFile.delete()) {
tmpFiles.remove(tmpFile);
}
} else {
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
}
Log.d(TAG, "download ready in "
+ ((System.currentTimeMillis() - startTime) / 1000)
+ " sec");
} catch (IOException e) {
Log.e(TAG, "Error: ",e);
AttachmentActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(AttachmentActivity.this,
R.string.attachment_download_failed_cant_write,
Toast.LENGTH_SHORT).show();
}
});
}
att.filename = file.getPath();
File newFile = new File(att.filename);
Message msg = mHandler.obtainMessage();
if (newFile.length() > 0) {
att.status = Attachment.LOCAL;
Log.d(TAG,"File downloaded: "+att.filename);
msg.obj = att;
} else {
Log.d(TAG, "File not downloaded: "+att.filename);
att.status = Attachment.AVAILABLE;
msg.obj = null;
}
att.save(db);
msg.arg2 = STATE_DONE;
mHandler.sendMessage(msg);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.zotero_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Bundle b = new Bundle();
// Handle item selection
switch (item.getItemId()) {
case R.id.do_sync:
if (!ServerCredentials.check(getApplicationContext())) {
Toast.makeText(getApplicationContext(), getResources().getString(R.string.sync_log_in_first),
Toast.LENGTH_SHORT).show();
return true;
}
Log.d(TAG, "Preparing sync requests, starting with present item");
new ZoteroAPITask(getBaseContext()).execute(APIRequest.update(this.item));
Toast.makeText(getApplicationContext(), getResources().getString(R.string.sync_started),
Toast.LENGTH_SHORT).show();
return true;
case R.id.do_new:
b.putString("itemKey", this.item.getKey());
b.putString("mode", "new");
removeDialog(DIALOG_NOTE);
this.b = b;
showDialog(DIALOG_NOTE);
return true;
case R.id.do_prefs:
startActivity(new Intent(this, SettingsActivity.class));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
|
package com.swooby.alfred;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.service.notification.StatusBarNotification;
import android.speech.tts.TextToSpeech;
import android.support.annotation.NonNull;
import android.support.annotation.StringRes;
import com.smartfoo.android.core.FooListenerManager;
import com.smartfoo.android.core.FooRun;
import com.smartfoo.android.core.FooString;
import com.smartfoo.android.core.collections.FooLongSparseArray;
import com.smartfoo.android.core.logging.FooLog;
import com.smartfoo.android.core.media.FooAudioStreamVolumeObserver;
import com.smartfoo.android.core.media.FooAudioStreamVolumeObserver.OnAudioStreamVolumeChangedListener;
import com.smartfoo.android.core.media.FooAudioUtils;
import com.smartfoo.android.core.network.FooCellularStateListener;
import com.smartfoo.android.core.network.FooCellularStateListener.FooCellularHookStateCallbacks;
import com.smartfoo.android.core.network.FooDataConnectionListener;
import com.smartfoo.android.core.network.FooDataConnectionListener.FooDataConnectionInfo;
import com.smartfoo.android.core.network.FooDataConnectionListener.FooDataConnectionListenerCallbacks;
import com.smartfoo.android.core.notification.FooNotificationListenerManager.NotConnectedReason;
import com.smartfoo.android.core.platform.FooChargePortListener;
import com.smartfoo.android.core.platform.FooChargePortListener.ChargePort;
import com.smartfoo.android.core.platform.FooChargePortListener.FooChargePortListenerCallbacks;
import com.smartfoo.android.core.platform.FooHandler;
import com.smartfoo.android.core.platform.FooPlatformUtils;
import com.smartfoo.android.core.platform.FooScreenListener;
import com.smartfoo.android.core.platform.FooScreenListener.FooScreenListenerCallbacks;
import com.smartfoo.android.core.texttospeech.FooTextToSpeech;
import com.smartfoo.android.core.texttospeech.FooTextToSpeechBuilder;
import com.swooby.alfred.NotificationManager.NotificationStatus;
import com.swooby.alfred.NotificationManager.NotificationStatusNotificationAccessNotEnabled;
import com.swooby.alfred.NotificationManager.NotificationStatusProfileNotEnabled;
import com.swooby.alfred.NotificationManager.NotificationStatusRunning;
import com.swooby.alfred.NotificationParserManager.NotificationParserManagerCallbacks;
import com.swooby.alfred.NotificationParserManager.NotificationParserManagerConfiguration;
import com.swooby.alfred.ProfileManager.HeadsetType;
import com.swooby.alfred.ProfileManager.ProfileManagerCallbacks;
import com.swooby.alfred.ProfileManager.ProfileManagerConfiguration;
import com.swooby.alfred.TextToSpeechManager.TextToSpeechManagerCallbacks;
import com.swooby.alfred.TextToSpeechManager.TextToSpeechManagerConfiguration;
import com.swooby.alfred.notification.parsers.AbstractNotificationParser;
import com.swooby.alfred.notification.parsers.AlfredNotificationParser;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public class AlfredManager
{
private static final String TAG = FooLog.TAG(AlfredManager.class);
public interface AlfredManagerCallbacks
{
Activity getActivity();
void onNotificationListenerConnected();
boolean onNotificationListenerNotConnected(NotConnectedReason reason);
void onProfileEnabled(String profileToken);
void onProfileDisabled(String profileToken);
void onTextToSpeechAudioStreamVolumeChanged(int audioStreamType, int volume);
}
private final Context mApplicationContext;
private final FooHandler mHandler;
private final AppPreferences mAppPreferences;
private final FooListenerManager<AlfredManagerCallbacks> mListenerManager;
private final NotificationManager mNotificationManager;
private final TextToSpeechManager mTextToSpeechManager;
private final NotificationParserManager mNotificationParserManager;
private final FooScreenListener mScreenListener;
private final FooChargePortListener mChargePortListener;
private final FooCellularStateListener mCellularStateListener;
private final FooCellularHookStateCallbacks mCellularHookStateCallbacks;
private final FooDataConnectionListener mDataConnectionListener;
private final FooDataConnectionListenerCallbacks mDataConnectionListenerCallbacks;
private final FooAudioStreamVolumeObserver mAudioStreamVolumeObserver;
private final ProfileManager mProfileManager;
private boolean mIsStarted;
public AlfredManager(@NonNull Context applicationContext)
{
FooLog.v(TAG, "+AlfredManager(applicationContext=" + applicationContext + ')');
FooRun.throwIllegalArgumentExceptionIfNull(applicationContext, "applicationContext");
mApplicationContext = applicationContext;
mHandler = new FooHandler();
mAppPreferences = new AppPreferences(mApplicationContext);
// Create Managers/etc
mListenerManager = new FooListenerManager<>();
mNotificationManager = new NotificationManager(mApplicationContext);
mTextToSpeechManager = new TextToSpeechManager(mApplicationContext, new TextToSpeechManagerConfiguration()
{
@Override
public String getVoiceName()
{
return mAppPreferences.getTextToSpeechVoiceName();
}
@Override
public void setVoiceName(String voiceName)
{
mAppPreferences.setTextToSpeechVoiceName(voiceName);
}
@Override
public int getAudioStreamType()
{
return mAppPreferences.getTextToSpeechAudioStreamType();
}
@Override
public boolean isTextToSpeechEnabled()
{
return AlfredManager.this.isTextToSpeechEnabled();
}
});
mNotificationParserManager = new NotificationParserManager(mApplicationContext, new NotificationParserManagerConfiguration()
{
@Override
public boolean isNotificationParserEnabled()
{
return AlfredManager.this.isProfileEnabled();
}
@NonNull
@Override
public TextToSpeechManager getTextToSpeech()
{
return AlfredManager.this.getTextToSpeechManager();
}
});
mScreenListener = new FooScreenListener(mApplicationContext);
mChargePortListener = new FooChargePortListener(mApplicationContext);
mCellularStateListener = new FooCellularStateListener(mApplicationContext);
mCellularHookStateCallbacks = new FooCellularHookStateCallbacks()
{
@Override
public void onCellularOffHook()
{
AlfredManager.this.onCellularOffHook();
}
@Override
public void onCellularOnHook()
{
AlfredManager.this.onCellularOnHook();
}
};
mDataConnectionListener = new FooDataConnectionListener(mApplicationContext);
mDataConnectionListenerCallbacks = new FooDataConnectionListenerCallbacks()
{
@Override
public void onDataConnected(FooDataConnectionInfo dataConnectionInfo)
{
AlfredManager.this.onDataConnected(dataConnectionInfo);
}
@Override
public void onDataDisconnected(FooDataConnectionInfo dataConnectionInfo)
{
AlfredManager.this.onDataDisconnected(dataConnectionInfo);
}
};
mAudioStreamVolumeObserver = new FooAudioStreamVolumeObserver(mApplicationContext);
mProfileManager = new ProfileManager(mApplicationContext, new ProfileManagerConfiguration()
{
@Override
public String getProfileToken()
{
return mAppPreferences.getProfileToken();
}
@Override
public void setProfileToken(String profileToken)
{
mAppPreferences.setProfileToken(profileToken);
}
});
FooLog.v(TAG, "-AlfredManager(applicationContext=" + applicationContext + ')');
}
@NonNull
public String getString(@StringRes int resId, Object... formatArgs)
{
return mApplicationContext.getString(resId, formatArgs);
}
@NonNull
public Context getApplicationContext()
{
return mApplicationContext;
}
@NonNull
public TextToSpeechManager getTextToSpeechManager()
{
return mTextToSpeechManager;
}
@NonNull
public ProfileManager getProfileManager()
{
return mProfileManager;
}
@NonNull
public NotificationParserManager getNotificationParserManager()
{
return mNotificationParserManager;
}
public boolean isStarted()
{
return mIsStarted;
}
public void start()
{
if (isStarted())
{
return;
}
mIsStarted = true;
mNotificationManager.notifyInitializing("Text To Speech", "TBD text", "TBD subtext");
final long timeStartMillis = System.currentTimeMillis();
mTextToSpeechManager.attach(new TextToSpeechManagerCallbacks()
{
@Override
public void onTextToSpeechInitialized(int status)
{
long timeElapsedMillis = System.currentTimeMillis() - timeStartMillis;
super.onTextToSpeechInitialized(status);
AlfredManager.this.onTextToSpeechInitialized(status, timeElapsedMillis);
}
});
mNotificationParserManager.attach(new NotificationParserManagerCallbacks()
{
@Override
public boolean onNotificationListenerConnected(StatusBarNotification[] activeNotifications)
{
return AlfredManager.this.onNotificationListenerConnected();
}
@Override
public void onNotificationListenerNotConnected(NotConnectedReason reason)
{
AlfredManager.this.onNotificationListenerNotConnected(reason, 200);
}
@Override
public void onNotificationParsed(@NonNull AbstractNotificationParser parser)
{
AlfredManager.this.onNotificationParsed(parser);
}
});
mScreenListener.attach(new FooScreenListenerCallbacks()
{
@Override
public void onScreenOff()
{
AlfredManager.this.onScreenOff();
}
@Override
public void onScreenOn()
{
AlfredManager.this.onScreenOn();
}
});
mChargePortListener.attach(new FooChargePortListenerCallbacks()
{
@Override
public void onChargePortConnected(ChargePort chargePort)
{
AlfredManager.this.onChargePortConnected(chargePort);
}
@Override
public void onChargePortDisconnected(ChargePort chargePort)
{
AlfredManager.this.onChargePortDisconnected(chargePort);
}
});
mCellularStateListener.start(mCellularHookStateCallbacks, null);
mDataConnectionListener.start(mDataConnectionListenerCallbacks);
for (int audioStreamType : FooAudioUtils.getAudioStreamTypes())
{
volumeObserverStart(audioStreamType);
}
// TODO:(pv) Phone doze listener
mProfileManager.attach(new ProfileManagerCallbacks()
{
@Override
public void onHeadsetConnectionChanged(HeadsetType headsetType, String headsetName, boolean isConnected)
{
AlfredManager.this.onHeadsetConnectionChanged(headsetType, headsetName, isConnected);
}
@Override
void onProfileEnabled(String profileToken)
{
AlfredManager.this.onProfileEnabled(profileToken);
}
@Override
void onProfileDisabled(String profileToken)
{
AlfredManager.this.onProfileDisabled(profileToken);
}
/*
@Override
public void onProfileStateChanged(String profileName, boolean enabled)
{
}
*/
});
//updateEnabledState("onCreate");
}
/*
private SpeechRecognizer mSpeechRecognizer;
public boolean isSpeechRecognitionAvailable()
{
return SpeechRecognizer.isRecognitionAvailable(this);
}
*/
public void attach(AlfredManagerCallbacks callbacks)
{
FooLog.i(TAG, "attach(callbacks=" + callbacks + ')');
mListenerManager.attach(callbacks);
if (callbacks.getActivity() != null)
{
}
}
public void detach(AlfredManagerCallbacks callbacks)
{
FooLog.i(TAG, "detach(callbacks=" + callbacks + ')');
mListenerManager.detach(callbacks);
}
private boolean isProfileEnabled()
{
return mProfileManager.isEnabled();
}
private boolean isTextToSpeechEnabled()
{
return isProfileEnabled() && mCellularStateListener.isOnHook();
}
public boolean isHeadless()
{
for (AlfredManagerCallbacks callbacks : mListenerManager.beginTraversing())
{
if (callbacks.getActivity() != null)
{
return false;
}
}
mListenerManager.endTraversing();
return true;
}
private void notification(@NonNull NotificationStatus notificationStatus,
String text,
String subtext)
{
if (notificationStatus instanceof NotificationStatusProfileNotEnabled)
{
mNotificationManager.notifyPaused(notificationStatus, text, subtext);
}
else
{
mNotificationManager.notifyRunning(notificationStatus, text, subtext);
}
}
private void onTextToSpeechInitialized(int status, long timeElapsedMillis)
{
FooLog.i(TAG, "onTextToSpeechInitialized: timeElapsedMillis == " + timeElapsedMillis +
", status == " + FooTextToSpeech.statusToString(status));
if (status != TextToSpeech.SUCCESS)
{
return;
}
}
private void onProfileEnabled(String profileToken)
{
FooLog.i(TAG, "onProfileEnabled(profileToken=" + FooString.quote(profileToken) + ')');
mTextToSpeechManager.clear();
// !!!!!!THIS IS WHERE THE REAL APP LOGIC ACTUALLY STARTS!!!!!!
NotificationStatus notificationStatus;
boolean isNotificationListenerConnected = mNotificationParserManager.isNotificationListenerConnected();
if (isNotificationListenerConnected)
{
notificationStatus = new NotificationStatusRunning(mApplicationContext);
}
else
{
notificationStatus = new NotificationStatusNotificationAccessNotEnabled(mApplicationContext,
getString(R.string.alfred_running),
getString(R.string.alfred_waiting_for_notification_access),
null); // <-- TODO:(pv) Put above/below speech in here
}
notification(notificationStatus, "TBD text", "onProfileEnabled");
for (AlfredManagerCallbacks callbacks : mListenerManager.beginTraversing())
{
callbacks.onProfileEnabled(profileToken);
}
mListenerManager.endTraversing();
if (isNotificationListenerConnected)
{
onNotificationListenerConnected();
}
}
private void onProfileDisabled(String profileToken)
{
FooLog.i(TAG, "onProfileDisabled(profileToken=" + FooString.quote(profileToken) + ')');
NotificationStatus notificationStatus = new NotificationStatusProfileNotEnabled(mApplicationContext, profileToken);
notification(notificationStatus, "TBD text", "onProfileDisabled");
mTextToSpeechManager.clear();
for (AlfredManagerCallbacks callbacks : mListenerManager.beginTraversing())
{
callbacks.onProfileDisabled(profileToken);
}
mListenerManager.endTraversing();
}
private class DelayedRunnableNotificationListenerNotConnected
implements Runnable
{
private final String TAG = FooLog.TAG(DelayedRunnableNotificationListenerNotConnected.class);
private final NotConnectedReason mReason;
public DelayedRunnableNotificationListenerNotConnected(NotConnectedReason reason)
{
mReason = reason;
}
@Override
public void run()
{
FooLog.v(TAG, "+run()");
onNotificationListenerNotConnected(mReason, 0);
FooLog.v(TAG, "-run()");
}
}
private DelayedRunnableNotificationListenerNotConnected mDelayedRunnableNotificationAccessSettingDisabled;
private boolean onNotificationListenerConnected()
{
FooLog.i(TAG, "onNotificationListenerConnected()");
mHandler.removeCallbacks(mDelayedRunnableNotificationAccessSettingDisabled);
mDelayedRunnableNotificationAccessSettingDisabled = null;
for (AlfredManagerCallbacks callbacks : mListenerManager.beginTraversing())
{
callbacks.onNotificationListenerConnected();
}
mListenerManager.endTraversing();
mNotificationParserManager.initializeActiveNotifications();
NotificationStatus notificationStatus;
boolean isProfileEnabled = isProfileEnabled();
if (isProfileEnabled)
{
notificationStatus = new NotificationStatusRunning(mApplicationContext);
}
else
{
String profileToken = mProfileManager.getProfileToken();
notificationStatus = new NotificationStatusProfileNotEnabled(mApplicationContext, profileToken);
}
notification(notificationStatus, "TBD text", "onNotificationAccessSettingConfirmedEnabled");
return true;
}
/**
* @param reason reason
* @param ifHeadlessDelayMillis > 0 to delay the given milliseconds if no UI is attached
*/
private void onNotificationListenerNotConnected(NotConnectedReason reason, int ifHeadlessDelayMillis)
{
FooLog.w(TAG, "onNotificationListenerNotConnected(reason=" + reason +
", ifHeadlessDelayMillis=" + ifHeadlessDelayMillis + ')');
boolean headless = true;
boolean handled = false;
for (AlfredManagerCallbacks callbacks : mListenerManager.beginTraversing())
{
headless &= callbacks.getActivity() == null;
handled |= callbacks.onNotificationListenerNotConnected(reason);
}
mListenerManager.endTraversing();
if (headless && ifHeadlessDelayMillis > 0)
{
mDelayedRunnableNotificationAccessSettingDisabled = new DelayedRunnableNotificationListenerNotConnected(reason);
mHandler.postDelayed(mDelayedRunnableNotificationAccessSettingDisabled, ifHeadlessDelayMillis);
return;
}
String title = getNotificationListenerNotConnectedTitle(reason);
String message = getNotificationListenerNotConnectedMessage(reason);
if (headless)
{
String separator = getString(R.string.alfred_line_separator);
String text = FooString.join(separator, title, message);
FooPlatformUtils.toastLong(mApplicationContext, text);
}
mTextToSpeechManager.speak(new FooTextToSpeechBuilder()
.appendSpeech(title)
.appendSilenceWordBreak()
.appendSpeech(message));
NotificationStatus notificationStatus;
boolean isProfileEnabled = isProfileEnabled();
if (isProfileEnabled)
{
notificationStatus = new NotificationStatusNotificationAccessNotEnabled(mApplicationContext,
getString(R.string.alfred_running),
getString(R.string.alfred_waiting_for_notification_access)
, null);
}
else
{
String profileToken = mProfileManager.getProfileToken();
notificationStatus = new NotificationStatusProfileNotEnabled(mApplicationContext, profileToken);
}
notification(notificationStatus, "TBD text", "onNotificationAccessSettingDisabled");
}
public String getNotificationListenerNotConnectedTitle(@NonNull NotConnectedReason reason)
{
FooRun.throwIllegalArgumentExceptionIfNull(reason, "reason");
int resId;
switch (reason)
{
case ConfirmedNotEnabled:
resId = R.string.alfred_notification_access_not_enabled;
break;
case ConnectedTimeout:
resId = R.string.alfred_notification_listener_bind_timeout;
break;
default:
throw new IllegalArgumentException("Unhandled reason == " + reason);
}
return getString(resId);
}
public String getNotificationListenerNotConnectedMessage(@NonNull NotConnectedReason reason)
{
FooRun.throwIllegalArgumentExceptionIfNull(reason, "reason");
int resId;
switch (reason)
{
case ConfirmedNotEnabled:
resId = R.string.alfred_please_enable_notification_access_for_the_X_application;
break;
case ConnectedTimeout:
resId = R.string.alfred_please_reenable_notification_access_for_the_X_application;
break;
default:
throw new IllegalArgumentException("Unhandled reason == " + reason);
}
String appName = getString(R.string.alfred_app_name);
return getString(resId, appName);
}
private void onNotificationParsed(@NonNull AbstractNotificationParser parser)
{
if (parser instanceof AlfredNotificationParser)
{
onAlfredNotificationParsed((AlfredNotificationParser) parser);
}
}
private void onAlfredNotificationParsed(AlfredNotificationParser parser)
{
}
private void onHeadsetConnectionChanged(HeadsetType headsetType, String headsetName, boolean isConnected)
{
FooLog.i(TAG, "onHeadsetConnectionChanged(headsetType=" + headsetType +
", headsetName=" + FooString.quote(headsetName) +
", isConnected=" + isConnected + ')');
if (headsetName == null)
{
headsetName = "";
}
int resId;
switch (headsetType)
{
case Bluetooth:
resId = isConnected ? R.string.alfred_bluetooth_headphone_X_connected : R.string.alfred_bluetooth_headphone_X_disconnected;
break;
case Wired:
resId = isConnected ? R.string.alfred_wired_headphone_X_connected : R.string.alfred_wired_headphone_X_disconnected;
break;
default:
throw new IllegalArgumentException("Unhandled headsetType == " + headsetType);
}
String speech = getString(resId, headsetName);
mTextToSpeechManager.speak(speech);
}
private void onScreenOff()
{
FooLog.i(TAG, "onScreenOff()");
updateScreenInfo();
}
private void onScreenOn()
{
FooLog.i(TAG, "onScreenOn()");
updateScreenInfo();
}
private long mTimeScreenOnMs = -1;
private long mTimeScreenOffMs = -1;
private void updateScreenInfo()
{
String speech;
if (mScreenListener.isScreenOn())
{
mTimeScreenOnMs = System.currentTimeMillis();
if (mTimeScreenOffMs != -1)
{
long durationMs = mTimeScreenOnMs - mTimeScreenOffMs;
mTimeScreenOffMs = -1;
speech = getString(R.string.alfred_screen_on_after_being_off_for_X, FooString.getTimeDurationString(mApplicationContext, durationMs, TimeUnit.SECONDS));
}
else
{
speech = getString(R.string.alfred_screen_on);
}
}
else
{
mTimeScreenOffMs = System.currentTimeMillis();
if (mTimeScreenOnMs != -1)
{
long durationMs = mTimeScreenOffMs - mTimeScreenOnMs;
mTimeScreenOnMs = -1;
speech = getString(R.string.alfred_screen_off_after_being_on_for_X, FooString.getTimeDurationString(mApplicationContext, durationMs, TimeUnit.SECONDS));
}
else
{
speech = getString(R.string.alfred_screen_off);
}
}
mTextToSpeechManager.speak(speech);
}
private void updateChargePortInfo()
{
for (ChargePort chargingPort : mChargePortListener.getChargingPorts())
{
onChargePortConnected(chargingPort);
}
}
private final Map<ChargePort, Long> mTimeChargingConnected = new HashMap<>();
private final Map<ChargePort, Long> mTimeChargingDisconnected = new HashMap<>();
private void onChargePortConnected(ChargePort chargePort)
{
FooLog.i(TAG, "onChargePortConnected(chargePort=" + chargePort + ')');
long now = System.currentTimeMillis();
mTimeChargingConnected.put(chargePort, now);
String speech;
String chargePortName = getString(chargePort.getStringRes());
//FooLog.i(TAG, "onChargePortConnected: chargePortName == " + FooString.quote(chargePortName));
Long timeChargingDisconnectedMs = mTimeChargingDisconnected.remove(chargePort);
if (timeChargingDisconnectedMs != null)
{
long elapsedMs = now - timeChargingDisconnectedMs;
speech = getString(R.string.alfred_X_connected_after_being_disconnected_for_Y,
chargePortName,
FooString.getTimeDurationString(mApplicationContext, elapsedMs, TimeUnit.SECONDS));
}
else
{
speech = getString(R.string.alfred_X_connected, chargePortName);
}
mTextToSpeechManager.speak(speech);
}
private void onChargePortDisconnected(ChargePort chargePort)
{
FooLog.i(TAG, "onChargePortDisconnected(chargePort=" + chargePort + ')');
long now = System.currentTimeMillis();
mTimeChargingDisconnected.put(chargePort, now);
String speech;
String chargePortName = getString(chargePort.getStringRes());
//FooLog.i(TAG, "onChargePortDisconnected: chargePortName == " + FooString.quote(chargePortName));
Long timeChargingConnectedMs = mTimeChargingConnected.remove(chargePort);
if (timeChargingConnectedMs != null)
{
long elapsedMs = now - timeChargingConnectedMs;
speech = getString(R.string.alfred_X_disconnected_after_being_connected_for_Y,
chargePortName,
FooString.getTimeDurationString(mApplicationContext, elapsedMs, TimeUnit.SECONDS));
}
else
{
speech = getString(R.string.alfred_X_disconnected, chargePortName);
}
mTextToSpeechManager.speak(speech);
}
private void updateDataConnectionInfo()
{
FooDataConnectionInfo dataConnectionInfo = mDataConnectionListener.getDataConnectionInfo();
if (dataConnectionInfo.isConnected())
{
onDataConnected(dataConnectionInfo);
}
else
{
onDataDisconnected(dataConnectionInfo);
}
}
private void onCellularOffHook()
{
mTextToSpeechManager.speak("Phone Call Started");
}
private void onCellularOnHook()
{
mTextToSpeechManager.speak("Phone Call Ended");
}
private final FooLongSparseArray<Long> mTimeDataConnected = new FooLongSparseArray<>();
private final FooLongSparseArray<Long> mTimeDataDisconnected = new FooLongSparseArray<>();
private void onDataConnected(FooDataConnectionInfo dataConnectionInfo)
{
FooLog.i(TAG, "onDataConnected(dataConnectionInfo=" + dataConnectionInfo + ')');
long now = System.currentTimeMillis();
int dataConnectionType = dataConnectionInfo.getType();
mTimeDataConnected.put(dataConnectionType, now);
String speech;
String dataConnectionTypeName = getString(dataConnectionInfo.getNetworkTypeResourceId(BuildConfig.DEBUG));
//FooLog.i(TAG, "onDataConnected: dataConnectionTypeName == " + FooString.quote(dataConnectionTypeName));
Long timeDataDisconnectedMs = mTimeDataDisconnected.remove(dataConnectionType);
if (timeDataDisconnectedMs != null)
{
long elapsedMs = now - timeDataDisconnectedMs;
speech = dataConnectionTypeName + " connected after being disconnected for " +
FooString.getTimeDurationString(mApplicationContext, elapsedMs, TimeUnit.SECONDS);
}
else
{
speech = dataConnectionTypeName + " connected";
}
mTextToSpeechManager.speak(speech);
}
private void onDataDisconnected(FooDataConnectionInfo dataConnectionInfo)
{
FooLog.i(TAG, "onDataDisconnected(dataConnectionInfo=" + dataConnectionInfo + ')');
long now = System.currentTimeMillis();
int dataConnectionType = dataConnectionInfo.getType();
mTimeDataDisconnected.put(dataConnectionType, now);
String speech;
String dataConnectionTypeName = getString(dataConnectionInfo.getNetworkTypeResourceId(BuildConfig.DEBUG));
//FooLog.i(TAG, "onDataDisconnected: dataConnectionTypeName == " + FooString.quote(dataConnectionTypeName));
Long timeDataConnectedMs = mTimeDataConnected.remove(dataConnectionType);
if (timeDataConnectedMs != null)
{
long elapsedMs = now - timeDataConnectedMs;
speech = dataConnectionTypeName + " disconnected after being connected for " +
FooString.getTimeDurationString(mApplicationContext, elapsedMs, TimeUnit.SECONDS);
}
else
{
speech = dataConnectionTypeName + " disconnected";
}
mTextToSpeechManager.speak(speech);
}
// Volume (candidate for a dedicated class)
private void volumeObserverStart(int audioStreamType)
{
mAudioStreamVolumeObserver.attach(audioStreamType, new OnAudioStreamVolumeChangedListener()
{
@Override
public void onAudioStreamVolumeChanged(int audioStreamType, int volume, int volumeMax, int volumePercent)
{
AlfredManager.this.onAudioStreamVolumeChanged(audioStreamType, volume, volumeMax, volumePercent);
}
});
}
private void onAudioStreamVolumeChanged(int audioStreamType, int volume, int volumeMax, int volumePercent)
{
String audioStreamTypeName = FooAudioUtils.audioStreamTypeToString(mApplicationContext, audioStreamType);
String text = getString(R.string.alfred_X_volume_Y_percent, audioStreamTypeName, volumePercent);
mTextToSpeechManager.speak(text);
if (audioStreamType == mTextToSpeechManager.getAudioStreamType())
{
for (AlfredManagerCallbacks callbacks : mListenerManager.beginTraversing())
{
callbacks.onTextToSpeechAudioStreamVolumeChanged(audioStreamType, volume);
}
mListenerManager.endTraversing();
}
}
}
|
package com.yechaoa.yutils;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import android.text.TextUtils;
import java.util.Stack;
@TargetApi(14)
public class ActivityUtil {
//Stack()
private static Stack<Activity> activityStack = new Stack<>();
//ActivityAPI14+Android 4.0+
private static final MyActivityLifecycleCallbacks instance = new MyActivityLifecycleCallbacks();
private static class MyActivityLifecycleCallbacks implements Application.ActivityLifecycleCallbacks {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
@Override
public void onActivityStarted(Activity activity) {
}
@Override
public void onActivityResumed(Activity activity) {
activityStack.remove(activity);
activityStack.push(activity);
}
@Override
public void onActivityPaused(Activity activity) {
}
@Override
public void onActivityStopped(Activity activity) {
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
activityStack.remove(activity);
}
}
public static Application.ActivityLifecycleCallbacks getActivityLifecycleCallbacks() {
return instance;
}
/**
* Activity
*/
public static Activity getCurrentActivity() {
Activity activity = null;
if (!activityStack.isEmpty())
activity = activityStack.peek();
return activity;
}
/**
* Activity
*/
public static String getCurrentActivityName() {
Activity activity = getCurrentActivity();
String name = "";
if (activity != null) {
name = activity.getComponentName().getClassName();
}
return name;
}
/**
* Activity
*/
public static void finishActivity(Activity activity) {
if (activity != null) {
activityStack.remove(activity);
activity.finish();
}
}
/**
* Activity
*/
public static void closeAllActivity() {
while (true) {
Activity activity = getCurrentActivity();
if (null == activity) {
break;
}
finishActivity(activity);
}
}
public static void closeActivityByName(String name) {
int index = activityStack.size() - 1;
while (true) {
Activity activity = activityStack.get(index);
if (null == activity) {
break;
}
String activityName = activity.getComponentName().getClassName();
if (!TextUtils.equals(name, activityName)) {
index
if (index < 0) {
break;
}
continue;
}
finishActivity(activity);
break;
}
}
public static Stack<Activity> getActivityStack() {
Stack<Activity> stack = new Stack<>();
stack.addAll(activityStack);
return stack;
}
}
|
package de.htwdd.htwdresden;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.widget.RemoteViews;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import java.nio.charset.Charset;
import java.text.DateFormatSymbols;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Iterator;
import de.htwdd.htwdresden.classes.Const;
import de.htwdd.htwdresden.classes.EventBus;
import de.htwdd.htwdresden.classes.MensaHelper;
import de.htwdd.htwdresden.classes.VolleyDownloader;
import de.htwdd.htwdresden.database.MensaDAO;
import de.htwdd.htwdresden.events.UpdateMensaEvent;
import de.htwdd.htwdresden.types.Meal;
public class MensaWidget extends AppWidgetProvider {
private static final String[] nameOfDays = DateFormatSymbols.getInstance().getWeekdays();
static void updateAppWidget(final Context context, final AppWidgetManager appWidgetManager, final int appWidgetId) {
// Construct the RemoteViews object
final Bundle options = appWidgetManager.getAppWidgetOptions(appWidgetId);
final int minHeight = options.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT);
final RemoteViews views = getRemoteViews(context, minHeight);
final Calendar calendar = GregorianCalendar.getInstance();
// Erstelle Intent zum Starten der App
final Intent intent = new Intent(context, MainActivity.class);
intent.setAction(Const.IntentParams.START_ACTION_MENSA);
final PendingIntent pendingIntent = PendingIntent.getActivity(context, PendingIntent.FLAG_UPDATE_CURRENT, intent, 0);
views.setOnClickPendingIntent(R.id.mensa_widget_layout, pendingIntent);
// Bestimme Tag, welcher angezeigt werden soll
views.setTextViewText(R.id.widget_mensa_date, context.getString(R.string.mensa_date, context.getString(R.string.mensa_date_today)));
if (calendar.get(Calendar.HOUR_OF_DAY) > 15) {
calendar.add(Calendar.DAY_OF_YEAR, 1);
views.setTextViewText(R.id.widget_mensa_date, context.getString(R.string.mensa_date, nameOfDays[calendar.get(Calendar.DAY_OF_WEEK)]));
}
if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
// Ersten Tag in der Woche berechnen
calendar.add(Calendar.WEEK_OF_YEAR, 1);
calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek());
views.setTextViewText(R.id.widget_mensa_date, context.getString(R.string.mensa_date, nameOfDays[2]));
}
// Lade Daten aus der Datenbank
final ArrayList<Meal> meals = MensaDAO.getMealsByDate(calendar);
// Daten bereinigen und aufarbeiten
for (final Iterator<Meal> iterator = meals.iterator(); iterator.hasNext(); ) {
final Meal meal = iterator.next();
// Ausverkaufte und KombinierBar entfernen
if (meal.getTitle() == null || meal.getTitle().matches(".*kombinierBAR:.*") || (meal.getPrice() != null && meal.getPrice().equals("ausverkauft"))) {
iterator.remove();
}
}
// Anzeigen der Gerichte
final Resources ressource = context.getResources();
final String packageName = context.getPackageName();
final int cells = minHeight <= 65 ? 4 : 8;
for (int i = 1; i < cells + 1; i++) {
final int mealName = ressource.getIdentifier("widget_mensa_item_meal_" + i, "id", packageName);
final int mealPrice = ressource.getIdentifier("widget_mensa_item_price_" + i, "id", packageName);
if (meals.size() < i) {
views.setTextViewText(mealName, null);
views.setTextViewText(mealPrice, null);
continue;
}
final Meal meal = meals.get(i - 1);
views.setTextViewText(mealName, meal.getTitle());
views.setTextViewText(mealPrice, context.getString(R.string.mensa_price, meal.getPrice()));
}
if (meals.size() != 0)
views.setTextViewText(R.id.info_message, null);
else views.setTextViewText(R.id.info_message, ressource.getText(R.string.mensa_no_offer));
// Instruct the widget manager to update the widget
appWidgetManager.updateAppWidget(appWidgetId, views);
}
@Override
public void onUpdate(final Context context, final AppWidgetManager appWidgetManager, final int[] appWidgetIds) {
final Calendar calendar = GregorianCalendar.getInstance();
final int hour_of_Day = calendar.get(Calendar.HOUR_OF_DAY);
if (hour_of_Day >= 10 && hour_of_Day <= 15 && calendar.get(Calendar.DAY_OF_WEEK) >= Calendar.MONDAY && calendar.get(Calendar.DAY_OF_WEEK) < Calendar.SATURDAY) {
final Response.Listener<String> stringListener = new Response.Listener<String>() {
@Override
public void onResponse(String response) {
final MensaHelper mensaHelper = new MensaHelper(context, (short) 9);
// Parse und speichere Ergebnis
response = new String(response.getBytes(Charset.forName("iso-8859-1")), Charset.forName("UTF-8"));
MensaDAO.updateMealsByDay(GregorianCalendar.getInstance(), mensaHelper.parseCurrentDay(response));
EventBus.getInstance().post(new UpdateMensaEvent(0));
// Widgets updaten
for (int appWidgetId : appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId);
}
}
};
// Download der Informationen
final StringRequest stringRequest = new StringRequest(MensaHelper.getMensaUrl(0), stringListener, null);
VolleyDownloader.getInstance(context).addToRequestQueue(stringRequest);
return;
}
// There may be multiple widgets active, so update all of them
for (int appWidgetId : appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId);
}
}
@Override
public void onEnabled(final Context context) {
// Enter relevant functionality for when the first widget is created
}
@Override
public void onDisabled(final Context context) {
// Enter relevant functionality for when the last widget is disabled
}
@Override
public void onAppWidgetOptionsChanged(final Context context,final AppWidgetManager appWidgetManager, int appWidgetId,final Bundle newOptions) {
updateAppWidget(context, appWidgetManager, appWidgetId);
super.onAppWidgetOptionsChanged(context, appWidgetManager, appWidgetId, newOptions);
}
private static RemoteViews getRemoteViews(@NonNull final Context context, int height) {
if (Const.widget.getCellsForSize(height) == 1)
return new RemoteViews(context.getPackageName(), R.layout.widget_mensa_list);
else return new RemoteViews(context.getPackageName(), R.layout.widget_mensa_grid);
}
}
|
package net.ficbook.gfoxsh;
import android.app.Activity;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Build;
import android.view.View;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.DownloadListener;
import android.webkit.ValueCallback;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.content.*;
public class MainActivity extends Activity {
final Activity activity = this;
private WebView mainWebView;
private ValueCallback < Uri > mUploadMessage;
public ValueCallback < Uri[] > uploadMessage;
public static final int REQUEST_SELECT_FILE = 100;
private final static int FILECHOOSER_RESULTCODE = 1;
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (requestCode == REQUEST_SELECT_FILE) {
if (uploadMessage == null)
return;
uploadMessage.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, intent));
uploadMessage = null;
}
} else if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == mUploadMessage)
return;
Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.main);
mainWebView = (WebView) findViewById(R.id.mainWebView);
WebSettings webSettings = mainWebView.getSettings();
webSettings.setAppCacheMaxSize(200 * 1024 * 1024);
webSettings.setAppCachePath(getApplicationContext().getCacheDir().getAbsolutePath());
webSettings.setAllowFileAccess(true);
webSettings.setAppCacheEnabled(true);
webSettings.setJavaScriptEnabled(true);
cachemode();
mainWebView.setWebViewClient(new MyCustomWebViewClient());
mainWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
mainWebView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
webSettings.setAllowContentAccess(true);
mainWebView.setWebChromeClient(new WebChromeClient() {
protected void openFileChooser(ValueCallback uploadMsg, String acceptType) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
|
package org.mozilla.focus.utils;
import android.content.Context;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class IOUtils {
public static JSONObject readAsset(Context context, String fileName) throws IOException {
try (final BufferedReader reader =
new BufferedReader(new InputStreamReader(context.getAssets().open(fileName)))){
final StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
return new JSONObject(builder.toString());
} catch (JSONException e) {
throw new AssertionError("Corrupt JSON asset (" + fileName + ")", e);
}
}
}
|
package org.wikipedia.page;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import com.google.android.material.snackbar.Snackbar;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.wikipedia.BackPressedHandler;
import org.wikipedia.Constants;
import org.wikipedia.Constants.InvokeSource;
import org.wikipedia.LongPressHandler;
import org.wikipedia.R;
import org.wikipedia.WikipediaApp;
import org.wikipedia.activity.FragmentUtil;
import org.wikipedia.analytics.FindInPageFunnel;
import org.wikipedia.analytics.GalleryFunnel;
import org.wikipedia.analytics.LoginFunnel;
import org.wikipedia.analytics.PageScrollFunnel;
import org.wikipedia.analytics.TabFunnel;
import org.wikipedia.auth.AccountUtil;
import org.wikipedia.bridge.CommunicationBridge;
import org.wikipedia.bridge.JavaScriptActionHandler;
import org.wikipedia.dataclient.ServiceFactory;
import org.wikipedia.dataclient.WikiSite;
import org.wikipedia.dataclient.okhttp.OkHttpWebViewClient;
import org.wikipedia.descriptions.DescriptionEditActivity;
import org.wikipedia.descriptions.DescriptionEditTutorialActivity;
import org.wikipedia.edit.EditHandler;
import org.wikipedia.gallery.GalleryActivity;
import org.wikipedia.history.HistoryEntry;
import org.wikipedia.history.UpdateHistoryTask;
import org.wikipedia.language.LangLinksActivity;
import org.wikipedia.login.LoginActivity;
import org.wikipedia.media.AvPlayer;
import org.wikipedia.media.DefaultAvPlayer;
import org.wikipedia.media.MediaPlayerImplementation;
import org.wikipedia.page.action.PageActionTab;
import org.wikipedia.page.leadimages.LeadImagesHandler;
import org.wikipedia.page.leadimages.PageHeaderView;
import org.wikipedia.page.references.ReferenceDialog;
import org.wikipedia.page.references.References;
import org.wikipedia.page.shareafact.ShareHandler;
import org.wikipedia.page.tabs.Tab;
import org.wikipedia.readinglist.ReadingListBookmarkMenu;
import org.wikipedia.readinglist.database.ReadingListDbHelper;
import org.wikipedia.readinglist.database.ReadingListPage;
import org.wikipedia.settings.Prefs;
import org.wikipedia.suggestededits.SuggestedEditsSummary;
import org.wikipedia.util.ActiveTimer;
import org.wikipedia.util.AnimationUtil;
import org.wikipedia.util.DimenUtil;
import org.wikipedia.util.FeedbackUtil;
import org.wikipedia.util.GeoUtil;
import org.wikipedia.util.ShareUtil;
import org.wikipedia.util.StringUtil;
import org.wikipedia.util.ThrowableUtil;
import org.wikipedia.util.UriUtil;
import org.wikipedia.util.log.L;
import org.wikipedia.views.ObservableWebView;
import org.wikipedia.views.SwipeRefreshLayoutWithScroll;
import org.wikipedia.views.WikiErrorView;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import io.reactivex.Completable;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers;
import static android.app.Activity.RESULT_OK;
import static org.wikipedia.Constants.ACTIVITY_REQUEST_GALLERY;
import static org.wikipedia.Constants.InvokeSource.BOOKMARK_BUTTON;
import static org.wikipedia.Constants.InvokeSource.PAGE_ACTIVITY;
import static org.wikipedia.descriptions.DescriptionEditTutorialActivity.DESCRIPTION_SELECTED_TEXT;
import static org.wikipedia.page.PageActivity.ACTION_RESUME_READING;
import static org.wikipedia.page.PageCacher.loadIntoCache;
import static org.wikipedia.settings.Prefs.isDescriptionEditTutorialEnabled;
import static org.wikipedia.settings.Prefs.isLinkPreviewEnabled;
import static org.wikipedia.util.DimenUtil.getContentTopOffsetPx;
import static org.wikipedia.util.DimenUtil.leadImageHeightForDevice;
import static org.wikipedia.util.ResourceUtil.getThemedAttributeId;
import static org.wikipedia.util.ResourceUtil.getThemedColor;
import static org.wikipedia.util.ThrowableUtil.isOffline;
import static org.wikipedia.util.UriUtil.decodeURL;
import static org.wikipedia.util.UriUtil.visitInExternalBrowser;
public class PageFragment extends Fragment implements BackPressedHandler {
public interface Callback {
void onPageShowBottomSheet(@NonNull BottomSheetDialog dialog);
void onPageShowBottomSheet(@NonNull BottomSheetDialogFragment dialog);
void onPageDismissBottomSheet();
void onPageLoadPage(@NonNull PageTitle title, @NonNull HistoryEntry entry);
void onPageInitWebView(@NonNull ObservableWebView v);
void onPageShowLinkPreview(@NonNull HistoryEntry entry);
void onPageLoadMainPageInForegroundTab();
void onPageUpdateProgressBar(boolean visible, boolean indeterminate, int value);
void onPageShowThemeChooser();
void onPageStartSupportActionMode(@NonNull ActionMode.Callback callback);
void onPageHideSoftKeyboard();
void onPageAddToReadingList(@NonNull PageTitle title, @NonNull InvokeSource source);
void onPageRemoveFromReadingLists(@NonNull PageTitle title);
void onPageLoadError(@NonNull PageTitle title);
void onPageLoadErrorBackPressed();
void onPageHideAllContent();
void onPageSetToolbarFadeEnabled(boolean enabled);
void onPageSetToolbarElevationEnabled(boolean enabled);
}
private boolean pageRefreshed;
private boolean errorState = false;
private static final int REFRESH_SPINNER_ADDITIONAL_OFFSET = (int) (16 * DimenUtil.getDensityScalar());
private PageFragmentLoadState pageFragmentLoadState;
private PageViewModel model;
@NonNull private TabFunnel tabFunnel = new TabFunnel();
private PageScrollFunnel pageScrollFunnel;
private LeadImagesHandler leadImagesHandler;
private PageHeaderView pageHeaderView;
private ObservableWebView webView;
private CoordinatorLayout containerView;
private SwipeRefreshLayoutWithScroll refreshView;
private WikiErrorView errorView;
private PageActionTabLayout tabLayout;
private ToCHandler tocHandler;
private WebViewScrollTriggerListener scrollTriggerListener = new WebViewScrollTriggerListener();
private CommunicationBridge bridge;
private LinkHandler linkHandler;
private EditHandler editHandler;
private ActionMode findInPageActionMode;
private ShareHandler shareHandler;
private CompositeDisposable disposables = new CompositeDisposable();
private ActiveTimer activeTimer = new ActiveTimer();
private References references;
@Nullable private AvPlayer avPlayer;
@Nullable private AvCallback avCallback;
private WikipediaApp app;
@NonNull
private final SwipeRefreshLayout.OnRefreshListener pageRefreshListener = this::refreshPage;
private PageActionTab.Callback pageActionTabsCallback = new PageActionTab.Callback() {
@Override
public void onAddToReadingListTabSelected() {
Prefs.shouldShowBookmarkToolTip(false);
if (model.isInReadingList()) {
new ReadingListBookmarkMenu(tabLayout, new ReadingListBookmarkMenu.Callback() {
@Override
public void onAddRequest(@Nullable ReadingListPage page) {
addToReadingList(getTitle(), BOOKMARK_BUTTON);
}
@Override
public void onDeleted(@Nullable ReadingListPage page) {
if (callback() != null) {
callback().onPageRemoveFromReadingLists(getTitle());
}
}
@Override
public void onShare() {
// ignore
}
}).show(getTitle());
} else {
addToReadingList(getTitle(), BOOKMARK_BUTTON);
}
}
@Override
public void onSharePageTabSelected() {
sharePageLink();
}
@Override
public void onChooseLangTabSelected() {
startLangLinksActivity();
}
@Override
public void onFindInPageTabSelected() {
showFindInPage();
}
@Override
public void onFontAndThemeTabSelected() {
showThemeChooser();
}
@Override
public void onViewToCTabSelected() {
tocHandler.show();
}
@Override
public void updateBookmark(boolean pageSaved) {
setBookmarkIconForPageSavedState(pageSaved);
}
};
public ObservableWebView getWebView() {
return webView;
}
public PageTitle getTitle() {
return model.getTitle();
}
@Nullable public PageTitle getTitleOriginal() {
return model.getTitleOriginal();
}
@NonNull public ShareHandler getShareHandler() {
return shareHandler;
}
@Nullable public Page getPage() {
return model.getPage();
}
public HistoryEntry getHistoryEntry() {
return model.getCurEntry();
}
public EditHandler getEditHandler() {
return editHandler;
}
public ViewGroup getContainerView() {
return containerView;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AnimationUtil.setSharedElementTransitions(requireActivity());
app = (WikipediaApp) requireActivity().getApplicationContext();
model = new PageViewModel();
pageFragmentLoadState = new PageFragmentLoadState();
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
final Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_page, container, false);
pageHeaderView = rootView.findViewById(R.id.page_header_view);
DimenUtil.setViewHeight(pageHeaderView, leadImageHeightForDevice());
webView = rootView.findViewById(R.id.page_web_view);
initWebViewListeners();
containerView = rootView.findViewById(R.id.page_contents_container);
refreshView = rootView.findViewById(R.id.page_refresh_container);
int swipeOffset = getContentTopOffsetPx(requireActivity()) + REFRESH_SPINNER_ADDITIONAL_OFFSET;
refreshView.setProgressViewOffset(false, -swipeOffset, swipeOffset);
refreshView.setColorSchemeResources(getThemedAttributeId(requireContext(), R.attr.colorAccent));
refreshView.setScrollableChild(webView);
refreshView.setOnRefreshListener(pageRefreshListener);
tabLayout = rootView.findViewById(R.id.page_actions_tab_layout);
tabLayout.setPageActionTabsCallback(pageActionTabsCallback);
errorView = rootView.findViewById(R.id.page_error);
return rootView;
}
@Override
public void onDestroyView() {
if (avPlayer != null) {
avPlayer.deinit();
avPlayer = null;
}
//uninitialize the bridge, so that no further JS events can have any effect.
bridge.cleanup();
tocHandler.log();
shareHandler.dispose();
leadImagesHandler.dispose();
disposables.clear();
webView.clearAllListeners();
((ViewGroup) webView.getParent()).removeView(webView);
webView = null;
super.onDestroyView();
}
@Override
public void onDestroy() {
super.onDestroy();
app.getRefWatcher().watch(this);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
if (callback() != null) {
callback().onPageInitWebView(webView);
}
updateFontSize();
// Explicitly set background color of the WebView (independently of CSS, because
// the background may be shown momentarily while the WebView loads content,
// creating a seizure-inducing effect, or at the very least, a migraine with aura).
webView.setBackgroundColor(getThemedColor(requireActivity(), R.attr.paper_color));
bridge = new CommunicationBridge(webView, requireActivity());
setupMessageHandlers();
sendDecorOffsetMessage();
errorView.setRetryClickListener((v) -> refreshPage());
errorView.setBackClickListener((v) -> {
boolean back = onBackPressed();
// Needed if we're coming from another activity or fragment
if (!back && callback() != null) {
// noinspection ConstantConditions
callback().onPageLoadErrorBackPressed();
}
});
editHandler = new EditHandler(this, bridge);
pageFragmentLoadState.setEditHandler(editHandler);
tocHandler = new ToCHandler(this, requireActivity().getWindow().getDecorView().findViewById(R.id.toc_container),
requireActivity().getWindow().getDecorView().findViewById(R.id.page_scroller_button), bridge);
// TODO: initialize View references in onCreateView().
leadImagesHandler = new LeadImagesHandler(this, bridge, webView, pageHeaderView);
shareHandler = new ShareHandler(this, bridge);
if (callback() != null) {
new LongPressHandler(webView, HistoryEntry.SOURCE_INTERNAL_LINK, new PageContainerLongPressHandler(this));
}
pageFragmentLoadState.setUp(model, this, webView, bridge, leadImagesHandler, getCurrentTab());
if (shouldLoadFromBackstack(requireActivity()) || savedInstanceState != null) {
reloadFromBackstack();
}
}
public void reloadFromBackstack() {
pageFragmentLoadState.setTab(getCurrentTab());
if (!pageFragmentLoadState.backStackEmpty()) {
pageFragmentLoadState.loadFromBackStack();
} else {
loadMainPageInForegroundTab();
}
}
void setToolbarFadeEnabled(boolean enabled) {
if (callback() != null) {
callback().onPageSetToolbarFadeEnabled(enabled);
}
}
private boolean shouldLoadFromBackstack(@NonNull Activity activity) {
return activity.getIntent() != null
&& (ACTION_RESUME_READING.equals(activity.getIntent().getAction())
|| activity.getIntent().hasExtra(Constants.INTENT_APP_SHORTCUT_CONTINUE_READING));
}
private void initWebViewListeners() {
webView.addOnUpOrCancelMotionEventListener(() -> {
// update our session, since it's possible for the user to remain on the page for
// a long time, and we wouldn't want the session to time out.
app.getSessionFunnel().touchSession();
});
webView.addOnScrollChangeListener((int oldScrollY, int scrollY, boolean isHumanScroll) -> {
if (pageScrollFunnel != null) {
pageScrollFunnel.onPageScrolled(oldScrollY, scrollY, isHumanScroll);
}
});
webView.addOnContentHeightChangedListener(scrollTriggerListener);
webView.setWebViewClient(new OkHttpWebViewClient() {
@NonNull @Override public PageViewModel getModel() {
return model;
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (!isAdded()) {
return;
}
pageFragmentLoadState.onPageFinished();
updateProgressBar(false, true, 0);
webView.setVisibility(View.VISIBLE);
bridge.execute(JavaScriptActionHandler.setUp(leadImagesHandler.getPaddingTop()));
onPageLoadComplete();
}
});
}
private void handleInternalLink(@NonNull PageTitle title) {
if (!isResumed()) {
return;
}
// If it's a Special page, launch it in an external browser, since mobileview
// doesn't support the Special namespace.
// TODO: remove when Special pages are properly returned by the server
// If this is a Talk page also show in external browser since we don't handle those pages
// in the app very well at this time.
if (title.isSpecial() || title.isTalkPage()) {
visitInExternalBrowser(requireActivity(), Uri.parse(title.getMobileUri()));
return;
}
dismissBottomSheet();
HistoryEntry historyEntry = new HistoryEntry(title, HistoryEntry.SOURCE_INTERNAL_LINK);
if (model.getTitle() != null) {
historyEntry.setReferrer(model.getTitle().getCanonicalUri());
}
if (title.namespace() != Namespace.MAIN || !isLinkPreviewEnabled()) {
loadPage(title, historyEntry);
} else {
Callback callback = callback();
if (callback != null) {
callback.onPageShowLinkPreview(historyEntry);
}
}
}
@Override
public void onPause() {
super.onPause();
activeTimer.pause();
addTimeSpentReading(activeTimer.getElapsedSec());
pageFragmentLoadState.updateCurrentBackStackItem();
app.commitTabState();
closePageScrollFunnel();
long time = app.getTabList().size() >= 1 && !pageFragmentLoadState.backStackEmpty()
? System.currentTimeMillis()
: 0;
Prefs.pageLastShown(time);
}
@Override
public void onResume() {
super.onResume();
initPageScrollFunnel();
activeTimer.resume();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
sendDecorOffsetMessage();
// if the screen orientation changes, then re-layout the lead image container,
// but only if we've finished fetching the page.
if (!pageFragmentLoadState.isLoading() && !errorState) {
pageFragmentLoadState.onConfigurationChanged();
}
}
public Tab getCurrentTab() {
return app.getTabList().get(app.getTabList().size() - 1);
}
private void setCurrentTabAndReset(int position) {
// move the selected tab to the bottom of the list, and navigate to it!
// (but only if it's a different tab than the one currently in view!
if (position < app.getTabList().size() - 1) {
Tab tab = app.getTabList().remove(position);
app.getTabList().add(tab);
pageFragmentLoadState.setTab(tab);
}
if (app.getTabCount() > 0) {
app.getTabList().get(app.getTabList().size() - 1).squashBackstack();
pageFragmentLoadState.loadFromBackStack();
}
}
public void openInNewBackgroundTab(@NonNull PageTitle title, @NonNull HistoryEntry entry) {
if (app.getTabCount() == 0) {
openInNewTab(title, entry, getForegroundTabPosition());
pageFragmentLoadState.loadFromBackStack();
} else {
openInNewTab(title, entry, getBackgroundTabPosition());
((PageActivity) requireActivity()).animateTabsButton();
}
}
public void openInNewForegroundTab(@NonNull PageTitle title, @NonNull HistoryEntry entry) {
openInNewTab(title, entry, getForegroundTabPosition());
pageFragmentLoadState.loadFromBackStack();
}
private void openInNewTab(@NonNull PageTitle title, @NonNull HistoryEntry entry, int position) {
int selectedTabPosition = -1;
for (Tab tab : app.getTabList()) {
if (tab.getBackStackPositionTitle() != null && tab.getBackStackPositionTitle().equals(title)) {
selectedTabPosition = app.getTabList().indexOf(tab);
break;
}
}
if (selectedTabPosition >= 0) {
setCurrentTabAndReset(selectedTabPosition);
return;
}
tabFunnel.logOpenInNew(app.getTabList().size());
if (shouldCreateNewTab()) {
// create a new tab
Tab tab = new Tab();
boolean isForeground = position == getForegroundTabPosition();
// if the requested position is at the top, then make its backstack current
if (isForeground) {
pageFragmentLoadState.setTab(tab);
}
// put this tab in the requested position
app.getTabList().add(position, tab);
trimTabCount();
// add the requested page to its backstack
tab.getBackStack().add(new PageBackStackItem(title, entry));
if (!isForeground) {
loadIntoCache(title);
}
requireActivity().invalidateOptionsMenu();
} else {
pageFragmentLoadState.setTab(getCurrentTab());
getCurrentTab().getBackStack().add(new PageBackStackItem(title, entry));
}
}
public void openFromExistingTab(@NonNull PageTitle title, @NonNull HistoryEntry entry) {
// find the tab in which this title appears...
int selectedTabPosition = -1;
for (Tab tab : app.getTabList()) {
if (tab.getBackStackPositionTitle() != null && tab.getBackStackPositionTitle().equals(title)) {
selectedTabPosition = app.getTabList().indexOf(tab);
break;
}
}
if (selectedTabPosition == -1) {
loadPage(title, entry, true, true);
return;
}
setCurrentTabAndReset(selectedTabPosition);
}
public void loadPage(@NonNull PageTitle title, @NonNull HistoryEntry entry, boolean pushBackStack, boolean squashBackstack) {
//is the new title the same as what's already being displayed?
if (!getCurrentTab().getBackStack().isEmpty()
&& getCurrentTab().getBackStack().get(getCurrentTab().getBackStackPosition()).getTitle().equals(title)) {
if (model.getPage() == null) {
pageFragmentLoadState.loadFromBackStack();
} else if (!TextUtils.isEmpty(title.getFragment())) {
scrollToSection(title.getFragment());
}
return;
}
if (squashBackstack) {
if (app.getTabCount() > 0) {
app.getTabList().get(app.getTabList().size() - 1).clearBackstack();
}
}
loadPage(title, entry, pushBackStack, 0);
}
public void loadPage(@NonNull PageTitle title, @NonNull HistoryEntry entry,
boolean pushBackStack, int stagedScrollY) {
loadPage(title, entry, pushBackStack, stagedScrollY, false);
}
/**
* Load a new page into the WebView in this fragment.
* This shall be the single point of entry for loading content into the WebView, whether it's
* loading an entirely new page, refreshing the current page, retrying a failed network
* request, etc.
* @param title Title of the new page to load.
* @param entry HistoryEntry associated with the new page.
* @param pushBackStack Whether to push the new page onto the backstack.
*/
public void loadPage(@NonNull PageTitle title, @NonNull HistoryEntry entry,
boolean pushBackStack, int stagedScrollY, boolean isRefresh) {
webView.setVisibility(View.GONE);
// clear the title in case the previous page load had failed.
clearActivityActionBarTitle();
// update the time spent reading of the current page, before loading the new one
addTimeSpentReading(activeTimer.getElapsedSec());
activeTimer.reset();
// disable sliding of the ToC while sections are loading
tocHandler.setEnabled(false);
errorState = false;
errorView.setVisibility(View.GONE);
tabLayout.enableAllTabs();
model.setTitle(title);
model.setTitleOriginal(title);
model.setCurEntry(entry);
model.setReadingListPage(null);
model.setForceNetwork(isRefresh);
updateProgressBar(true, true, 0);
this.pageRefreshed = isRefresh;
references = null;
closePageScrollFunnel();
pageFragmentLoadState.load(pushBackStack);
scrollTriggerListener.setStagedScrollY(stagedScrollY);
updateBookmarkAndMenuOptions();
}
public Bitmap getLeadImageBitmap() {
return leadImagesHandler.getLeadImageBitmap();
}
/**
* Update the WebView's base font size, based on the specified font size from the app
* preferences.
*/
public void updateFontSize() {
webView.getSettings().setDefaultFontSize((int) app.getFontSize(requireActivity().getWindow()));
}
public void updateBookmarkAndMenuOptions() {
if (!isAdded()) {
return;
}
pageActionTabsCallback.updateBookmark(model.isInReadingList());
requireActivity().invalidateOptionsMenu();
}
public void updateBookmarkAndMenuOptionsFromDao() {
disposables.add(Observable.fromCallable(() -> ReadingListDbHelper.instance().findPageInAnyList(getTitle())).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doAfterTerminate(() -> {
pageActionTabsCallback.updateBookmark(model.getReadingListPage() != null);
requireActivity().invalidateOptionsMenu();
})
.subscribe(page -> model.setReadingListPage(page),
throwable -> model.setReadingListPage(null)));
}
public void onActionModeShown(ActionMode mode) {
// make sure we have a page loaded, since shareHandler makes references to it.
if (model.getPage() != null) {
shareHandler.onTextSelected(mode);
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Constants.ACTIVITY_REQUEST_EDIT_SECTION
&& resultCode == EditHandler.RESULT_REFRESH_PAGE) {
pageFragmentLoadState.backFromEditing(data);
FeedbackUtil.showMessage(requireActivity(), R.string.edit_saved_successfully);
// and reload the page...
loadPage(model.getTitleOriginal(), model.getCurEntry(), false, false);
} else if (requestCode == Constants.ACTIVITY_REQUEST_DESCRIPTION_EDIT_TUTORIAL
&& resultCode == RESULT_OK) {
Prefs.setDescriptionEditTutorialEnabled(false);
startDescriptionEditActivity(data.getStringExtra(DESCRIPTION_SELECTED_TEXT));
} else if (requestCode == Constants.ACTIVITY_REQUEST_DESCRIPTION_EDIT
&& resultCode == RESULT_OK) {
refreshPage();
FeedbackUtil.showMessage(requireActivity(), R.string.description_edit_success_saved_snackbar);
}
}
public void sharePageLink() {
if (getPage() != null) {
ShareUtil.shareText(requireActivity(), getPage().getTitle());
}
}
public View getHeaderView() {
return pageHeaderView;
}
public void showFindInPage() {
if (model.getPage() == null) {
return;
}
final FindInPageFunnel funnel = new FindInPageFunnel(app, model.getTitle().getWikiSite(),
model.getPage().getPageProperties().getPageId());
final FindInWebPageActionProvider findInPageActionProvider
= new FindInWebPageActionProvider(this, funnel);
startSupportActionMode(new ActionMode.Callback() {
private final String actionModeTag = "actionModeFindInPage";
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
findInPageActionMode = mode;
MenuItem menuItem = menu.add(R.string.menu_page_find_in_page);
menuItem.setActionProvider(findInPageActionProvider);
menuItem.expandActionView();
setToolbarElevationEnabled(false);
return true;
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
mode.setTag(actionModeTag);
return false;
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
return false;
}
@Override
public void onDestroyActionMode(ActionMode mode) {
if (webView == null || !isAdded()) {
return;
}
findInPageActionMode = null;
funnel.setPageHeight(webView.getContentHeight());
funnel.logDone();
webView.clearMatches();
hideSoftKeyboard();
setToolbarElevationEnabled(true);
}
});
}
public boolean closeFindInPage() {
if (findInPageActionMode != null) {
findInPageActionMode.finish();
return true;
}
return false;
}
/**
* Scroll to a specific section in the WebView.
* @param sectionAnchor Anchor link of the section to scroll to.
*/
public void scrollToSection(@NonNull String sectionAnchor) {
if (!isAdded() || tocHandler == null) {
return;
}
tocHandler.scrollToSection(sectionAnchor);
}
public void onPageLoadComplete() {
refreshView.setEnabled(true);
refreshView.setRefreshing(false);
requireActivity().invalidateOptionsMenu();
initPageScrollFunnel();
if (model.getReadingListPage() != null) {
final ReadingListPage page = model.getReadingListPage();
final PageTitle title = model.getTitle();
disposables.add(Completable.fromAction(() -> {
if (!TextUtils.equals(page.thumbUrl(), title.getThumbUrl())
|| !TextUtils.equals(page.description(), title.getDescription())) {
page.thumbUrl(title.getThumbUrl());
page.description(title.getDescription());
ReadingListDbHelper.instance().updatePage(page);
}
}).subscribeOn(Schedulers.io()).subscribe());
}
if (!errorState) {
setupToC(model, pageFragmentLoadState.isFirstPage());
editHandler.setPage(model.getPage());
}
checkAndShowBookmarkOnboarding();
}
public void onPageLoadError(@NonNull Throwable caught) {
if (!isAdded()) {
return;
}
updateProgressBar(false, true, 0);
refreshView.setRefreshing(false);
if (pageRefreshed) {
pageRefreshed = false;
}
hidePageContent();
errorView.setError(caught);
errorView.setVisibility(View.VISIBLE);
View contentTopOffset = errorView.findViewById(R.id.view_wiki_error_article_content_top_offset);
View tabLayoutOffset = errorView.findViewById(R.id.view_wiki_error_article_tab_layout_offset);
contentTopOffset.setLayoutParams(getContentTopOffsetParams(requireContext()));
contentTopOffset.setVisibility(View.VISIBLE);
tabLayoutOffset.setLayoutParams(getTabLayoutOffsetParams());
tabLayoutOffset.setVisibility(View.VISIBLE);
disableActionTabs(caught);
refreshView.setEnabled(!ThrowableUtil.is404(caught));
errorState = true;
if (callback() != null) {
callback().onPageLoadError(getTitle());
}
}
public void refreshPage() {
refreshPage(0);
}
public void refreshPage(int stagedScrollY) {
if (pageFragmentLoadState.isLoading()) {
refreshView.setRefreshing(false);
return;
}
errorView.setVisibility(View.GONE);
tabLayout.enableAllTabs();
errorState = false;
model.setCurEntry(new HistoryEntry(model.getTitle(), HistoryEntry.SOURCE_HISTORY));
loadPage(model.getTitle(), model.getCurEntry(), false, stagedScrollY, app.isOnline());
}
boolean isLoading() {
return pageFragmentLoadState.isLoading();
}
CommunicationBridge getBridge() {
return bridge;
}
private void setupToC(@NonNull PageViewModel model, boolean isFirstPage) {
tocHandler.setupToC(model.getPage(), model.getTitle().getWikiSite(), isFirstPage);
tocHandler.setEnabled(true);
}
private void setBookmarkIconForPageSavedState(boolean pageSaved) {
View bookmarkTab = tabLayout.getChildAt(PageActionTab.ADD_TO_READING_LIST.code());
if (bookmarkTab != null) {
((ImageView) bookmarkTab).setImageResource(pageSaved ? R.drawable.ic_bookmark_white_24dp
: R.drawable.ic_bookmark_border_white_24dp);
}
}
protected void clearActivityActionBarTitle() {
FragmentActivity currentActivity = requireActivity();
if (currentActivity instanceof PageActivity) {
((PageActivity) currentActivity).clearActionBarTitle();
}
}
private boolean shouldCreateNewTab() {
return !getCurrentTab().getBackStack().isEmpty();
}
private int getBackgroundTabPosition() {
return Math.max(0, getForegroundTabPosition() - 1);
}
private int getForegroundTabPosition() {
return app.getTabList().size();
}
private void setupMessageHandlers() {
linkHandler = new LinkHandler(requireActivity()) {
@Override public void onPageLinkClicked(@NonNull String anchor, @NonNull String linkText) {
dismissBottomSheet();
//Todo: mobile-html: add bridge communication
}
@Override public void onInternalLinkClicked(@NonNull PageTitle title) {
handleInternalLink(title);
}
@Override public WikiSite getWikiSite() {
return model.getTitle().getWikiSite();
}
};
bridge.addListener("link_clicked", linkHandler);
bridge.addListener("reference_clicked", (String messageType, JSONObject messagePayload) -> {
if (!isAdded()) {
L.d("Detached from activity, so stopping reference click.");
return;
}
disposables.add(getReferences()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(references -> {
this.references = references;
int selectedIndex = messagePayload.getInt("selectedIndex");
JSONArray referencesGroup = messagePayload.getJSONArray("referencesGroup");
List<References.Reference> adjacentReferencesList = new ArrayList<>();
for (int i = 0; i < referencesGroup.length(); i++) {
JSONObject reference = (JSONObject) referencesGroup.get(i);
String getReferenceText = StringUtils.defaultString(reference.optString("text"));
String getReferenceId = UriUtil.getFragment(StringUtils.defaultString(reference.optString("href")));
References.Reference getReference = references.getReferencesMap().get(getReferenceId);
if (getReference != null) {
getReference.setText(getReferenceText);
adjacentReferencesList.add(getReference);
}
}
if (adjacentReferencesList.size() > 0) {
showBottomSheet(new ReferenceDialog(requireActivity(), selectedIndex, adjacentReferencesList, linkHandler));
}
}, L::d));
});
bridge.addListener("image_clicked", (String messageType, JSONObject messagePayload) -> {
try {
String href = decodeURL(messagePayload.getString("href"));
if (href.startsWith("./File:")) {
if (app.isOnline()) {
String filename = UriUtil.removeInternalLinkPrefix(href);
WikiSite wiki = model.getTitle().getWikiSite();
requireActivity().startActivityForResult(GalleryActivity.newIntent(requireActivity(),
model.getTitleOriginal(), filename, wiki, GalleryFunnel.SOURCE_NON_LEAD_IMAGE),
ACTIVITY_REQUEST_GALLERY);
} else {
Snackbar snackbar = FeedbackUtil.makeSnackbar(requireActivity(), getString(R.string.gallery_not_available_offline_snackbar), FeedbackUtil.LENGTH_DEFAULT);
snackbar.setAction(R.string.gallery_not_available_offline_snackbar_dismiss, view -> snackbar.dismiss());
snackbar.show();
}
} else {
linkHandler.onUrlClick(href, messagePayload.optString("title"), "");
}
} catch (JSONException e) {
L.logRemoteErrorIfProd(e);
}
});
bridge.addListener("media_clicked", (String messageType, JSONObject messagePayload) -> {
try {
String href = decodeURL(messagePayload.getString("href"));
String filename = StringUtil.removeUnderscores(UriUtil.removeInternalLinkPrefix(href));
WikiSite wiki = model.getTitle().getWikiSite();
requireActivity().startActivityForResult(GalleryActivity.newIntent(requireActivity(),
model.getTitleOriginal(), filename, wiki,
GalleryFunnel.SOURCE_NON_LEAD_IMAGE),
ACTIVITY_REQUEST_GALLERY);
} catch (JSONException e) {
L.logRemoteErrorIfProd(e);
}
});
bridge.addListener("pronunciation_clicked", (String messageType, JSONObject messagePayload) -> {
if (avPlayer == null) {
avPlayer = new DefaultAvPlayer(new MediaPlayerImplementation());
avPlayer.init();
}
if (avCallback == null) {
avCallback = new AvCallback();
}
if (!avPlayer.isPlaying()) {
updateProgressBar(true, true, 0);
avPlayer.play(getPage().getTitlePronunciationUrl(), avCallback, avCallback);
} else {
updateProgressBar(false, true, 0);
avPlayer.stop();
}
});
bridge.addListener("footer_item_selected", (String messageType, JSONObject messagePayload) -> {
String itemType = messagePayload.optString("itemType");
if ("talkPage".equals(itemType) && model.getTitle() != null) {
PageTitle talkPageTitle = new PageTitle("Talk", model.getTitle().getPrefixedText(), model.getTitle().getWikiSite());
visitInExternalBrowser(requireContext(), Uri.parse(talkPageTitle.getMobileUri()));
} else if ("languages".equals(itemType)) {
startLangLinksActivity();
} else if ("lastEdited".equals(itemType) && model.getTitle() != null) {
visitInExternalBrowser(requireContext(), Uri.parse(model.getTitle().getUriForAction("history")));
} else if ("coordinate".equals(itemType) && model.getPage() != null && model.getPage().getPageProperties().getGeo() != null) {
GeoUtil.sendGeoIntent(requireActivity(), model.getPage().getPageProperties().getGeo(), model.getPage().getDisplayTitle());
} else if ("disambiguation".equals(itemType)) {
// TODO
// messagePayload contains an array of URLs called "payload".
} else if ("referenceList".equals(itemType)) {
// TODO: show full list of references.
}
});
bridge.addListener("read_more_titles_retrieved", (String messageType, JSONObject messagePayload) -> {
// TODO: do something with this.
L.v(messagePayload.toString());
});
bridge.addListener("view_in_browser", (String messageType, JSONObject messagePayload) -> {
if (model.getTitle() != null) {
visitInExternalBrowser(requireContext(), Uri.parse(model.getTitle().getMobileUri()));
}
});
}
public void verifyBeforeEditingDescription(@Nullable String text) {
if (getPage() != null && getPage().getPageProperties().canEdit()) {
if (!AccountUtil.isLoggedIn() && Prefs.getTotalAnonDescriptionsEdited() >= getResources().getInteger(R.integer.description_max_anon_edits)) {
new AlertDialog.Builder(requireActivity())
.setMessage(R.string.description_edit_anon_limit)
.setPositiveButton(R.string.page_editing_login, (DialogInterface dialogInterface, int i) ->
startActivity(LoginActivity.newIntent(requireContext(), LoginFunnel.SOURCE_EDIT)))
.setNegativeButton(R.string.description_edit_login_cancel_button_text, null)
.show();
} else {
startDescriptionEditActivity(text);
}
} else {
getEditHandler().showUneditableDialog();
}
}
private void startDescriptionEditActivity(@Nullable String text) {
if (isDescriptionEditTutorialEnabled()) {
startActivityForResult(DescriptionEditTutorialActivity.newIntent(requireContext(), text),
Constants.ACTIVITY_REQUEST_DESCRIPTION_EDIT_TUTORIAL);
} else {
SuggestedEditsSummary sourceSummary = new SuggestedEditsSummary(getTitle().getPrefixedText(), getTitle().getWikiSite().languageCode(), getTitle(),
getTitle().getDisplayText(), getTitle().getDisplayText(), getTitle().getDescription(), getTitle().getThumbUrl(),
null, null, null, null);
startActivityForResult(DescriptionEditActivity.newIntent(requireContext(), getTitle(), text, sourceSummary, null, PAGE_ACTIVITY),
Constants.ACTIVITY_REQUEST_DESCRIPTION_EDIT);
}
}
/**
* Convenience method for hiding all the content of a page.
*/
private void hidePageContent() {
leadImagesHandler.hide();
webView.setVisibility(View.INVISIBLE);
if (callback() != null) {
callback().onPageHideAllContent();
}
}
@Override
public boolean onBackPressed() {
if (tocHandler != null && tocHandler.isVisible()) {
tocHandler.hide();
return true;
}
if (closeFindInPage()) {
return true;
}
if (pageFragmentLoadState.goBack()) {
return true;
}
return false;
}
public void goForward() {
pageFragmentLoadState.goForward();
}
private void checkAndShowBookmarkOnboarding() {
if (Prefs.shouldShowBookmarkToolTip() && Prefs.getOverflowReadingListsOptionClickCount() == 2) {
View targetView = tabLayout.getChildAt(PageActionTab.ADD_TO_READING_LIST.code());
FeedbackUtil.showTapTargetView(requireActivity(), targetView,
R.string.tool_tip_bookmark_icon_title, R.string.tool_tip_bookmark_icon_text, null);
Prefs.shouldShowBookmarkToolTip(false);
}
}
private void sendDecorOffsetMessage() {
//Todo: mobile-html: add bridge communication
}
private void initPageScrollFunnel() {
if (model.getPage() != null) {
pageScrollFunnel = new PageScrollFunnel(app, model.getPage().getPageProperties().getPageId());
}
}
private void closePageScrollFunnel() {
if (pageScrollFunnel != null && webView.getContentHeight() > 0) {
pageScrollFunnel.setViewportHeight(webView.getHeight());
pageScrollFunnel.setPageHeight(webView.getContentHeight());
pageScrollFunnel.logDone();
}
pageScrollFunnel = null;
}
public void showBottomSheet(@NonNull BottomSheetDialog dialog) {
Callback callback = callback();
if (callback != null) {
callback.onPageShowBottomSheet(dialog);
}
}
public void showBottomSheet(@NonNull BottomSheetDialogFragment dialog) {
Callback callback = callback();
if (callback != null) {
callback.onPageShowBottomSheet(dialog);
}
}
private void dismissBottomSheet() {
Callback callback = callback();
if (callback != null) {
callback.onPageDismissBottomSheet();
}
}
public void loadPage(@NonNull PageTitle title, @NonNull HistoryEntry entry) {
Callback callback = callback();
if (callback != null) {
callback.onPageLoadPage(title, entry);
}
}
private void loadMainPageInForegroundTab() {
Callback callback = callback();
if (callback != null) {
callback.onPageLoadMainPageInForegroundTab();
}
}
private void updateProgressBar(boolean visible, boolean indeterminate, int value) {
Callback callback = callback();
if (callback != null) {
callback.onPageUpdateProgressBar(visible, indeterminate, value);
}
}
private void showThemeChooser() {
Callback callback = callback();
if (callback != null) {
callback.onPageShowThemeChooser();
}
}
public void startSupportActionMode(@NonNull ActionMode.Callback actionModeCallback) {
if (callback() != null) {
callback().onPageStartSupportActionMode(actionModeCallback);
}
}
public void hideSoftKeyboard() {
Callback callback = callback();
if (callback != null) {
callback.onPageHideSoftKeyboard();
}
}
public void setToolbarElevationEnabled(boolean enabled) {
Callback callback = callback();
if (callback != null) {
callback.onPageSetToolbarElevationEnabled(enabled);
}
}
public void addToReadingList(@NonNull PageTitle title, @NonNull InvokeSource source) {
Callback callback = callback();
if (callback != null) {
callback.onPageAddToReadingList(title, source);
}
}
public void startLangLinksActivity() {
Intent langIntent = new Intent();
langIntent.setClass(requireActivity(), LangLinksActivity.class);
langIntent.setAction(LangLinksActivity.ACTION_LANGLINKS_FOR_TITLE);
langIntent.putExtra(LangLinksActivity.EXTRA_PAGETITLE, model.getTitle());
requireActivity().startActivityForResult(langIntent, Constants.ACTIVITY_REQUEST_LANGLINKS);
}
private void trimTabCount() {
while (app.getTabList().size() > Constants.MAX_TABS) {
app.getTabList().remove(0);
}
}
@SuppressLint("CheckResult")
private void addTimeSpentReading(int timeSpentSec) {
if (model.getCurEntry() == null) {
return;
}
model.setCurEntry(new HistoryEntry(model.getCurEntry().getTitle(),
new Date(),
model.getCurEntry().getSource(),
timeSpentSec));
Completable.fromAction(new UpdateHistoryTask(model.getCurEntry()))
.subscribeOn(Schedulers.io())
.subscribe(() -> { }, L::e);
}
private LinearLayout.LayoutParams getContentTopOffsetParams(@NonNull Context context) {
return new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, getContentTopOffsetPx(context));
}
private LinearLayout.LayoutParams getTabLayoutOffsetParams() {
return new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, tabLayout.getHeight());
}
private void disableActionTabs(@Nullable Throwable caught) {
boolean offline = isOffline(caught);
for (int i = 0; i < tabLayout.getChildCount(); i++) {
if (!(offline && PageActionTab.of(i).equals(PageActionTab.ADD_TO_READING_LIST))) {
tabLayout.disableTab(i);
}
}
}
private class AvCallback implements AvPlayer.Callback, AvPlayer.ErrorCallback {
@Override
public void onSuccess() {
if (avPlayer != null) {
avPlayer.stop();
updateProgressBar(false, true, 0);
}
}
@Override
public void onError() {
if (avPlayer != null) {
avPlayer.stop();
updateProgressBar(false, true, 0);
}
}
}
private class WebViewScrollTriggerListener implements ObservableWebView.OnContentHeightChangedListener {
private int stagedScrollY;
void setStagedScrollY(int stagedScrollY) {
this.stagedScrollY = stagedScrollY;
}
@Override
public void onContentHeightChanged(int contentHeight) {
if (stagedScrollY > 0 && (contentHeight * DimenUtil.getDensityScalar() - webView.getHeight()) > stagedScrollY) {
webView.setScrollY(stagedScrollY);
stagedScrollY = 0;
}
}
}
@Nullable
public Callback callback() {
return FragmentUtil.getCallback(this, Callback.class);
}
@Nullable String getLeadImageEditLang() {
return leadImagesHandler.getCallToActionEditLang();
}
private Observable<References> getReferences() {
return references == null ? ServiceFactory.getRest(getTitle().getWikiSite()).getReferences(getTitle().getConvertedText()) : Observable.just(references);
}
void openImageInGallery(@NonNull String language) {
leadImagesHandler.openImageInGallery(language);
}
}
|
package com.hbm.devices.scan.ui.android;
import com.hbm.devices.scan.announce.Announce;
import com.hbm.devices.scan.announce.AnnounceDeserializer;
import com.hbm.devices.scan.ui.android.DisplayNotifier;
import com.hbm.devices.scan.ui.android.DisplayUpdateEventGenerator;
import java.io.IOException;
import java.lang.Override;
import java.util.ArrayList;
import java.io.InputStream;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import java.util.Properties;
import org.junit.Test;
import static org.junit.Assert.*;
public class DisplayUpdateEventGeneratorTest implements DisplayNotifier, Observer {
private List<Announce> oldList = new ArrayList<Announce>();
private List<Announce> newList = new ArrayList<Announce>();
private List<Announce> oldListClone;
private List<DisplayEventAt> events = new ArrayList<DisplayEventAt>();
private boolean fillNewList;
private static final String DEVICE1;
private static final String DEVICE1UPDATE;
private static final String DEVICE2;
private static final String DEVICE3;
private static final String DEVICE4;
private static final String DEVICE5;
private static final String DEVICE6;
@Test
public void testCompareLists() throws Exception {
AnnounceDeserializer parser = new AnnounceDeserializer();
parser.addObserver(this);
parser.update(null, DEVICE1);
parser.update(null, DEVICE2);
parser.update(null, DEVICE3);
parser.update(null, DEVICE4);
parser.update(null, DEVICE5);
fillNewList = true;
parser.update(null, DEVICE1UPDATE);
parser.update(null, DEVICE2);
parser.update(null, DEVICE6);
parser.update(null, DEVICE5);
parser.update(null, DEVICE4);
assertEquals(oldList.size(), 5);
assertEquals(newList.size(), 5);
oldListClone = new ArrayList<>(oldList.size());
for (Announce item: oldList) {
oldListClone.add(item);
}
assertEquals("Cloned old list not equals to oldList", oldList, oldListClone);
DisplayUpdateEventGenerator eventGenerator = new DisplayUpdateEventGenerator(this);
eventGenerator.compareLists(oldList, newList);
assertEquals("oldList not the same as newList after compareList", oldList, newList);
assertEquals("updated events list not the same as newList after compareList", oldListClone, newList);
}
@Override
public void notifyRemoveAt(int position) {
oldListClone.remove(position);
events.add(new DisplayEventAt(DisplayEvents.REMOVE, position));
}
@Override
public void notifyMoved(int fromPosition, int toPosition) {
Announce announce = oldListClone.remove(fromPosition);
oldListClone.add(toPosition, announce);
events.add(new DisplayEventAt(DisplayEvents.MOVE, fromPosition, toPosition));
}
@Override
public void notifyChangeAt(int position) {
oldListClone.set(position, newList.get(position));
events.add(new DisplayEventAt(DisplayEvents.UPDATE, position));
}
@Override
public void notifyAddAt(int position) {
oldListClone.add(newList.get(position));
events.add(new DisplayEventAt(DisplayEvents.ADD, position));
}
@Override
public void update(Observable o, Object arg) {
final Announce announce = (Announce)arg;
if (fillNewList) {
newList.add(announce);
} else {
oldList.add(announce);
}
}
static {
try (final InputStream is = FakeMessageReceiver.class.getResourceAsStream("/devices.properties")) {
final Properties props = new Properties();
props.load(is);
DEVICE1 = props.getProperty("scan.announce.device1");
DEVICE1UPDATE = props.getProperty("scan.announce.device1update");
DEVICE2 = props.getProperty("scan.announce.device2");
DEVICE3 = props.getProperty("scan.announce.device3");
DEVICE4 = props.getProperty("scan.announce.device4");
DEVICE5 = props.getProperty("scan.announce.device5");
DEVICE6 = props.getProperty("scan.announce.device6");
} catch (IOException e) {
throw new ExceptionInInitializerError(e);
}
}
enum DisplayEvents {
REMOVE, ADD, MOVE, UPDATE
}
class DisplayEventAt {
DisplayEvents event;
int position;
int fromPosition;
int toPosition;
DisplayEventAt(DisplayEvents ev, int pos) {
this.event = ev;
this.position = pos;
}
DisplayEventAt(DisplayEvents ev, int from, int to) {
this.event = ev;
this.fromPosition = from;
this.toPosition = to;
}
}
}
|
package com.moilioncircle.redis.replicator;
import com.moilioncircle.redis.replicator.rdb.RdbFilter;
import com.moilioncircle.redis.replicator.rdb.RdbListener;
import com.moilioncircle.redis.replicator.rdb.datatype.KeyValuePair;
import junit.framework.TestCase;
import org.junit.Assert;
import org.junit.Test;
import redis.clients.jedis.Jedis;
import javax.net.ssl.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.concurrent.atomic.AtomicInteger;
public class RedisSocketReplicatorSSLTest extends TestCase {
private static void setJvmTrustStore(String trustStoreFilePath, String trustStoreType) {
Assert.assertTrue(String.format("Could not find trust store at '%s'.", trustStoreFilePath),
new File(trustStoreFilePath).exists());
System.setProperty("javax.net.ssl.trustStore", trustStoreFilePath);
System.setProperty("javax.net.ssl.trustStoreType", trustStoreType);
}
// @Test
// public void testSsl() throws IOException {
// setJvmTrustStore("src/test/resources/keystore/truststore.jceks", "jceks");
// Replicator replicator = new RedisReplicator("127.0.0.1", 56379, Configuration.defaultSetting().setSsl(true));
// final AtomicInteger acc = new AtomicInteger(0);
// Jedis jedis = null;
// try {
// jedis = new Jedis("127.0.0.1", 6379);
// jedis.set("ssl", "true");
// } finally {
// jedis.close();
// replicator.addRdbFilter(new RdbFilter() {
// @Override
// public boolean accept(KeyValuePair<?> kv) {
// return kv.getKey().equals("ssl");
// replicator.addRdbListener(new RdbListener() {
// @Override
// public void preFullSync(Replicator replicator) {
// @Override
// public void handle(Replicator replicator, KeyValuePair<?> kv) {
// acc.incrementAndGet();
// @Override
// public void postFullSync(Replicator replicator, long checksum) {
// Jedis jedis = null;
// try {
// jedis = new Jedis("127.0.0.1", 6379);
// jedis.del("ssl");
// } finally {
// jedis.close();
// try {
// replicator.close();
// } catch (IOException e) {
// e.printStackTrace();
// replicator.addCloseListener(new CloseListener() {
// @Override
// public void handle(Replicator replicator) {
// System.out.println("close testSsl");
// assertEquals(1, acc.get());
// replicator.open();
// @Test
// public void testSsl1() throws IOException {
// setJvmTrustStore("src/test/resources/keystore/truststore.jceks", "jceks");
// Replicator replicator = new RedisReplicator("localhost", 56379,
// Configuration.defaultSetting().setSsl(true)
// .setReadTimeout(0)
// .setSslSocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault())
// .setHostnameVerifier(new BasicHostnameVerifier())
// .setSslParameters(new SSLParameters()));
// final AtomicInteger acc = new AtomicInteger(0);
// Jedis jedis = null;
// try {
// jedis = new Jedis("127.0.0.1", 6379);
// jedis.set("ssl1", "true");
// } finally {
// jedis.close();
// replicator.addRdbFilter(new RdbFilter() {
// @Override
// public boolean accept(KeyValuePair<?> kv) {
// return kv.getKey().equals("ssl1");
// replicator.addRdbListener(new RdbListener() {
// @Override
// public void preFullSync(Replicator replicator) {
// @Override
// public void handle(Replicator replicator, KeyValuePair<?> kv) {
// acc.incrementAndGet();
// @Override
// public void postFullSync(Replicator replicator, long checksum) {
// Jedis jedis = null;
// try {
// jedis = new Jedis("127.0.0.1", 6379);
// jedis.del("ssl1");
// } finally {
// jedis.close();
// try {
// replicator.close();
// } catch (IOException e) {
// e.printStackTrace();
// replicator.addCloseListener(new CloseListener() {
// @Override
// public void handle(Replicator replicator) {
// System.out.println("close testSsl1");
// assertEquals(1, acc.get());
// replicator.open();
@Test
public void testSsl2() throws Exception {
setJvmTrustStore("src/test/resources/keystore/truststore.jceks", "jceks");
Replicator replicator = new RedisReplicator("localhost", 56379,
Configuration.defaultSetting().setSsl(true)
.setHostnameVerifier(new BasicHostnameVerifier())
.setSslParameters(new SSLParameters())
.setSslSocketFactory(createTrustStoreSslSocketFactory()));
final AtomicInteger acc = new AtomicInteger(0);
Jedis jedis = null;
try {
jedis = new Jedis("127.0.0.1", 6379);
jedis.set("ssl2", "true");
} finally {
jedis.close();
}
replicator.addRdbFilter(new RdbFilter() {
@Override
public boolean accept(KeyValuePair<?> kv) {
return kv.getKey().equals("ssl2");
}
});
replicator.addRdbListener(new RdbListener() {
@Override
public void preFullSync(Replicator replicator) {
}
@Override
public void handle(Replicator replicator, KeyValuePair<?> kv) {
acc.incrementAndGet();
}
@Override
public void postFullSync(Replicator replicator, long checksum) {
Jedis jedis = null;
try {
jedis = new Jedis("127.0.0.1", 6379);
jedis.del("ssl2");
} finally {
jedis.close();
}
try {
replicator.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
replicator.addCloseListener(new CloseListener() {
@Override
public void handle(Replicator replicator) {
System.out.println("close testSsl2");
assertEquals(1, acc.get());
}
});
replicator.open();
}
@Test
public void testSsl3() throws Exception {
setJvmTrustStore("src/test/resources/keystore/truststore.jceks", "jceks");
Replicator replicator = new RedisReplicator("localhost", 56379,
Configuration.defaultSetting().setSsl(true)
.setHostnameVerifier(new BasicHostnameVerifier())
.setSslParameters(new SSLParameters())
.setSslSocketFactory(createTrustNoOneSslSocketFactory()));
final AtomicInteger acc = new AtomicInteger(0);
Jedis jedis = null;
try {
jedis = new Jedis("127.0.0.1", 6379);
jedis.set("ssl3", "true");
} finally {
jedis.close();
}
replicator.addRdbFilter(new RdbFilter() {
@Override
public boolean accept(KeyValuePair<?> kv) {
return kv.getKey().equals("ssl3");
}
});
replicator.addRdbListener(new RdbListener() {
@Override
public void preFullSync(Replicator replicator) {
}
@Override
public void handle(Replicator replicator, KeyValuePair<?> kv) {
acc.incrementAndGet();
}
@Override
public void postFullSync(Replicator replicator, long checksum) {
Jedis jedis = null;
try {
jedis = new Jedis("127.0.0.1", 6379);
jedis.del("ssl3");
} finally {
jedis.close();
}
try {
replicator.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
replicator.addCloseListener(new CloseListener() {
@Override
public void handle(Replicator replicator) {
System.out.println("close testSsl3");
assertEquals(1, acc.get());
}
});
try {
replicator.open();
fail();
} catch (Exception e) {
}
}
@Test
public void testSsl4() throws Exception {
setJvmTrustStore("src/test/resources/keystore/truststore.jceks", "jceks");
Replicator replicator = new RedisReplicator("127.0.0.1", 56379,
Configuration.defaultSetting().setSsl(true)
.setHostnameVerifier(new BasicHostnameVerifier())
.setSslParameters(new SSLParameters())
.setSslSocketFactory(createTrustStoreSslSocketFactory()));
final AtomicInteger acc = new AtomicInteger(0);
Jedis jedis = null;
try {
jedis = new Jedis("127.0.0.1", 6379);
jedis.set("ssl4", "true");
} finally {
jedis.close();
}
replicator.addRdbFilter(new RdbFilter() {
@Override
public boolean accept(KeyValuePair<?> kv) {
return kv.getKey().equals("ssl4");
}
});
replicator.addRdbListener(new RdbListener() {
@Override
public void preFullSync(Replicator replicator) {
}
@Override
public void handle(Replicator replicator, KeyValuePair<?> kv) {
acc.incrementAndGet();
}
@Override
public void postFullSync(Replicator replicator, long checksum) {
Jedis jedis = null;
try {
jedis = new Jedis("127.0.0.1", 6379);
jedis.del("ssl4");
} finally {
jedis.close();
}
try {
replicator.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
replicator.addCloseListener(new CloseListener() {
@Override
public void handle(Replicator replicator) {
System.out.println("close testSsl4");
assertEquals(0, acc.get());
}
});
replicator.open();
}
private static SSLSocketFactory createTrustStoreSslSocketFactory() throws Exception {
KeyStore trustStore = KeyStore.getInstance("jceks");
InputStream inputStream = null;
try {
inputStream = new FileInputStream("src/test/resources/keystore/truststore.jceks");
trustStore.load(inputStream, null);
} finally {
inputStream.close();
}
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("PKIX");
trustManagerFactory.init(trustStore);
TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustManagers, new SecureRandom());
return sslContext.getSocketFactory();
}
private static SSLSocketFactory createTrustNoOneSslSocketFactory() throws Exception {
TrustManager[] unTrustManagers = new TrustManager[]{
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkClientTrusted(X509Certificate[] chain, String authType) {
throw new RuntimeException(new InvalidAlgorithmParameterException());
}
public void checkServerTrusted(X509Certificate[] chain, String authType) {
throw new RuntimeException(new InvalidAlgorithmParameterException());
}
}
};
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, unTrustManagers, new SecureRandom());
return sslContext.getSocketFactory();
}
private static class BasicHostnameVerifier implements HostnameVerifier {
private static final String COMMON_NAME_RDN_PREFIX = "CN=";
@Override
public boolean verify(String hostname, SSLSession session) {
X509Certificate peerCertificate;
try {
peerCertificate = (X509Certificate) session.getPeerCertificates()[0];
} catch (SSLPeerUnverifiedException e) {
throw new IllegalStateException("The session does not contain a peer X.509 certificate.");
}
String peerCertificateCN = getCommonName(peerCertificate);
return hostname.equals(peerCertificateCN);
}
private String getCommonName(X509Certificate peerCertificate) {
String subjectDN = peerCertificate.getSubjectDN().getName();
String[] dnComponents = subjectDN.split(",");
for (String dnComponent : dnComponents) {
if (dnComponent.startsWith(COMMON_NAME_RDN_PREFIX)) {
return dnComponent.substring(COMMON_NAME_RDN_PREFIX.length());
}
}
throw new IllegalArgumentException("The certificate has no common name.");
}
}
}
|
package com.moilioncircle.redis.replicator;
import com.moilioncircle.redis.replicator.rdb.RdbFilter;
import com.moilioncircle.redis.replicator.rdb.RdbListener;
import com.moilioncircle.redis.replicator.rdb.datatype.KeyValuePair;
import junit.framework.TestCase;
import org.junit.Assert;
import org.junit.Test;
import redis.clients.jedis.Jedis;
import javax.net.ssl.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.concurrent.atomic.AtomicInteger;
public class RedisSocketReplicatorSSLTest extends TestCase {
private static void setJvmTrustStore(String trustStoreFilePath, String trustStoreType) {
Assert.assertTrue(String.format("Could not find trust store at '%s'.", trustStoreFilePath),
new File(trustStoreFilePath).exists());
System.setProperty("javax.net.ssl.trustStore", trustStoreFilePath);
System.setProperty("javax.net.ssl.trustStoreType", trustStoreType);
}
// @Test
// public void testSsl() throws IOException {
// setJvmTrustStore("src/test/resources/keystore/truststore.jceks", "jceks");
// Replicator replicator = new RedisReplicator("127.0.0.1", 56379, Configuration.defaultSetting().setSsl(true));
// final AtomicInteger acc = new AtomicInteger(0);
// Jedis jedis = null;
// try {
// jedis = new Jedis("127.0.0.1", 6379);
// jedis.set("ssl", "true");
// } finally {
// jedis.close();
// replicator.addRdbFilter(new RdbFilter() {
// @Override
// public boolean accept(KeyValuePair<?> kv) {
// return kv.getKey().equals("ssl");
// replicator.addRdbListener(new RdbListener() {
// @Override
// public void preFullSync(Replicator replicator) {
// @Override
// public void handle(Replicator replicator, KeyValuePair<?> kv) {
// acc.incrementAndGet();
// @Override
// public void postFullSync(Replicator replicator, long checksum) {
// Jedis jedis = null;
// try {
// jedis = new Jedis("127.0.0.1", 6379);
// jedis.del("ssl");
// } finally {
// jedis.close();
// try {
// replicator.close();
// } catch (IOException e) {
// e.printStackTrace();
// replicator.addCloseListener(new CloseListener() {
// @Override
// public void handle(Replicator replicator) {
// System.out.println("close testSsl");
// assertEquals(1, acc.get());
// replicator.open();
// @Test
// public void testSsl1() throws IOException {
// setJvmTrustStore("src/test/resources/keystore/truststore.jceks", "jceks");
// Replicator replicator = new RedisReplicator("localhost", 56379,
// Configuration.defaultSetting().setSsl(true)
// .setReadTimeout(0)
// .setSslSocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault())
// .setHostnameVerifier(new BasicHostnameVerifier())
// .setSslParameters(new SSLParameters()));
// final AtomicInteger acc = new AtomicInteger(0);
// Jedis jedis = null;
// try {
// jedis = new Jedis("127.0.0.1", 6379);
// jedis.set("ssl1", "true");
// } finally {
// jedis.close();
// replicator.addRdbFilter(new RdbFilter() {
// @Override
// public boolean accept(KeyValuePair<?> kv) {
// return kv.getKey().equals("ssl1");
// replicator.addRdbListener(new RdbListener() {
// @Override
// public void preFullSync(Replicator replicator) {
// @Override
// public void handle(Replicator replicator, KeyValuePair<?> kv) {
// acc.incrementAndGet();
// @Override
// public void postFullSync(Replicator replicator, long checksum) {
// Jedis jedis = null;
// try {
// jedis = new Jedis("127.0.0.1", 6379);
// jedis.del("ssl1");
// } finally {
// jedis.close();
// try {
// replicator.close();
// } catch (IOException e) {
// e.printStackTrace();
// replicator.addCloseListener(new CloseListener() {
// @Override
// public void handle(Replicator replicator) {
// System.out.println("close testSsl1");
// assertEquals(1, acc.get());
// replicator.open();
@Test
public void testSsl2() throws Exception {
setJvmTrustStore("src/test/resources/keystore/truststore.jceks", "jceks");
Replicator replicator = new RedisReplicator("localhost", 56379,
Configuration.defaultSetting().setSsl(true)
.setHostnameVerifier(new BasicHostnameVerifier())
.setSslParameters(new SSLParameters())
.setSslSocketFactory(createTrustStoreSslSocketFactory()));
final AtomicInteger acc = new AtomicInteger(0);
Jedis jedis = null;
try {
jedis = new Jedis("127.0.0.1", 6379);
jedis.set("ssl2", "true");
} finally {
jedis.close();
}
replicator.addRdbFilter(new RdbFilter() {
@Override
public boolean accept(KeyValuePair<?> kv) {
return kv.getKey().equals("ssl2");
}
});
replicator.addRdbListener(new RdbListener() {
@Override
public void preFullSync(Replicator replicator) {
}
@Override
public void handle(Replicator replicator, KeyValuePair<?> kv) {
acc.incrementAndGet();
}
@Override
public void postFullSync(Replicator replicator, long checksum) {
Jedis jedis = null;
try {
jedis = new Jedis("127.0.0.1", 6379);
jedis.del("ssl2");
} finally {
jedis.close();
}
try {
replicator.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
replicator.addCloseListener(new CloseListener() {
@Override
public void handle(Replicator replicator) {
System.out.println("close testSsl2");
assertEquals(1, acc.get());
}
});
replicator.open();
}
@Test
public void testSsl3() throws Exception {
setJvmTrustStore("src/test/resources/keystore/truststore.jceks", "jceks");
Replicator replicator = new RedisReplicator("localhost", 56379,
Configuration.defaultSetting().setSsl(true)
.setHostnameVerifier(new BasicHostnameVerifier())
.setSslParameters(new SSLParameters())
.setSslSocketFactory(createTrustNoOneSslSocketFactory()));
final AtomicInteger acc = new AtomicInteger(0);
Jedis jedis = null;
try {
jedis = new Jedis("127.0.0.1", 6379);
jedis.set("ssl3", "true");
} finally {
jedis.close();
}
replicator.addRdbFilter(new RdbFilter() {
@Override
public boolean accept(KeyValuePair<?> kv) {
return kv.getKey().equals("ssl3");
}
});
replicator.addRdbListener(new RdbListener() {
@Override
public void preFullSync(Replicator replicator) {
}
@Override
public void handle(Replicator replicator, KeyValuePair<?> kv) {
System.out.println(kv);
acc.incrementAndGet();
}
@Override
public void postFullSync(Replicator replicator, long checksum) {
Jedis jedis = null;
try {
jedis = new Jedis("127.0.0.1", 6379);
jedis.del("ssl3");
} finally {
jedis.close();
}
try {
replicator.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
replicator.addCloseListener(new CloseListener() {
@Override
public void handle(Replicator replicator) {
System.out.println("close testSsl3");
}
});
try {
replicator.open();
fail();
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testSsl4() throws Exception {
setJvmTrustStore("src/test/resources/keystore/truststore.jceks", "jceks");
Replicator replicator = new RedisReplicator("127.0.0.1", 56379,
Configuration.defaultSetting().setSsl(true)
.setHostnameVerifier(new BasicHostnameVerifier())
.setSslParameters(new SSLParameters())
.setSslSocketFactory(createTrustStoreSslSocketFactory()));
final AtomicInteger acc = new AtomicInteger(0);
Jedis jedis = null;
try {
jedis = new Jedis("127.0.0.1", 6379);
jedis.set("ssl4", "true");
} finally {
jedis.close();
}
replicator.addRdbFilter(new RdbFilter() {
@Override
public boolean accept(KeyValuePair<?> kv) {
return kv.getKey().equals("ssl4");
}
});
replicator.addRdbListener(new RdbListener() {
@Override
public void preFullSync(Replicator replicator) {
}
@Override
public void handle(Replicator replicator, KeyValuePair<?> kv) {
acc.incrementAndGet();
}
@Override
public void postFullSync(Replicator replicator, long checksum) {
Jedis jedis = null;
try {
jedis = new Jedis("127.0.0.1", 6379);
jedis.del("ssl4");
} finally {
jedis.close();
}
try {
replicator.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
replicator.addCloseListener(new CloseListener() {
@Override
public void handle(Replicator replicator) {
System.out.println("close testSsl4");
assertEquals(0, acc.get());
}
});
replicator.open();
}
private static SSLSocketFactory createTrustStoreSslSocketFactory() throws Exception {
KeyStore trustStore = KeyStore.getInstance("jceks");
InputStream inputStream = null;
try {
inputStream = new FileInputStream("src/test/resources/keystore/truststore.jceks");
trustStore.load(inputStream, null);
} finally {
inputStream.close();
}
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("PKIX");
trustManagerFactory.init(trustStore);
TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustManagers, new SecureRandom());
return sslContext.getSocketFactory();
}
private static SSLSocketFactory createTrustNoOneSslSocketFactory() throws Exception {
TrustManager[] unTrustManagers = new TrustManager[]{
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkClientTrusted(X509Certificate[] chain, String authType) {
throw new RuntimeException(new InvalidAlgorithmParameterException());
}
public void checkServerTrusted(X509Certificate[] chain, String authType) {
throw new RuntimeException(new InvalidAlgorithmParameterException());
}
}
};
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, unTrustManagers, new SecureRandom());
return sslContext.getSocketFactory();
}
private static class BasicHostnameVerifier implements HostnameVerifier {
private static final String COMMON_NAME_RDN_PREFIX = "CN=";
@Override
public boolean verify(String hostname, SSLSession session) {
X509Certificate peerCertificate;
try {
peerCertificate = (X509Certificate) session.getPeerCertificates()[0];
} catch (SSLPeerUnverifiedException e) {
throw new IllegalStateException("The session does not contain a peer X.509 certificate.");
}
String peerCertificateCN = getCommonName(peerCertificate);
return hostname.equals(peerCertificateCN);
}
private String getCommonName(X509Certificate peerCertificate) {
String subjectDN = peerCertificate.getSubjectDN().getName();
String[] dnComponents = subjectDN.split(",");
for (String dnComponent : dnComponents) {
if (dnComponent.startsWith(COMMON_NAME_RDN_PREFIX)) {
return dnComponent.substring(COMMON_NAME_RDN_PREFIX.length());
}
}
throw new IllegalArgumentException("The certificate has no common name.");
}
}
}
|
package com.treasure_data.bulk_import.upload_parts;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.spy;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.Random;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import com.treasure_data.client.ClientException;
import com.treasure_data.client.TreasureDataClient;
import com.treasure_data.client.bulkimport.BulkImportClient;
public class TestUnploadProcessor {
@Test @Ignore
public void test01() throws Exception {
Properties props = System.getProperties();
props.load(this.getClass().getClassLoader().getResourceAsStream("treasure-data.properties"));
TreasureDataClient tdclient = new TreasureDataClient(props);
BulkImportClient client = new BulkImportClient(tdclient);
UploadConfig conf = new UploadConfig();
conf.configure(props);
UploadProcessor proc = new UploadProcessor(client, conf);
byte[] bytes = "muga".getBytes();
String sessName = "mugasess";
String fileName = "file01";
long size = bytes.length;
UploadProcessor.Task task = new UploadProcessor.Task(sessName, fileName, size);
task = spy(task);
doReturn(new ByteArrayInputStream(bytes)).when(task).createInputStream();
proc.execute(task);
}
private Properties props;
private UploadConfig conf;
private UploadProcessor proc;
private UploadProcessor.Task task;
private UploadProcessor.ErrorInfo err;
Random rand = new Random(new Random().nextInt());
private int numTasks;
@Before
public void createResources() throws Exception {
props = System.getProperties();
// create upload config
conf = new UploadConfig();
conf.configure(props);
// create upload processor
proc = new UploadProcessor(null, conf);
numTasks = rand.nextInt(100);
}
@After
public void destroyResources() throws Exception {
}
@Test
public void returnNonErrorWhenExecuteMethodWorksNormally() throws Exception {
// configure mock
proc = spy(proc);
doNothing().when(proc).executeUpload(any(UploadProcessor.Task.class));
// test
for (int i = 0; i < numTasks; i++) {
task = UploadProcessorTestUtil.createTask(i);
UploadProcessorTestUtil.executeTaskNormally(proc, task, proc.execute(task));
}
}
@Test
public void returnIOErrorWhenExecuteMethodThrowsIOError() throws Exception {
// configure mock
proc = spy(proc);
doThrow(new IOException("dummy")).when(proc).executeUpload(any(UploadProcessor.Task.class));
// test
for (int i = 0; i < numTasks; i++) {
task = UploadProcessorTestUtil.createTask(i);
UploadProcessorTestUtil.failTask(proc, task, proc.execute(task));
}
}
@Test
public void returnIOErrorWhenExecuteMethodThrowsClientError() throws Exception {
// configure mock
proc = spy(proc);
doThrow(new ClientException("dummy")).when(proc).executeUpload(any(UploadProcessor.Task.class));
// test
int count = 1;
for (int i = 0; i < count; i++) {
task = UploadProcessorTestUtil.createTask(i);
UploadProcessorTestUtil.failTask(proc, task, proc.execute(task));
}
}
@Test
public void equalsFinishTasks() {
assertTrue(UploadProcessor.Task.FINISH_TASK.equals(UploadProcessor.Task.FINISH_TASK));
}
}
|
package org.datacite.mds.web.api.controller;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.datacite.mds.domain.Allocator;
import org.datacite.mds.domain.Datacentre;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/META-INF/spring/applicationContext.xml")
@Transactional
public class DatacentreApiControllerTest {
DatacentreApiController datacentreApiController = new DatacentreApiController();
String allocatorSymbol = "TEST";
String allocatorSymbol2 = "XYZ";
String datacentreSymbol = allocatorSymbol+".TEST";
String datacentreSymbol2 = allocatorSymbol+".NEWTEST";
Allocator allocator;
Datacentre datacentre;
Datacentre datacentre2;
@After
public void tearDown() {
datacentre.remove();
allocator.remove();
}
@Before
public void setUp() throws Exception {
allocator = new Allocator();
allocator.setSymbol("TEST");
allocator.setPassword("12345678");
allocator.setContactEmail("aaa@aaa.com");
allocator.setContactName("aaaaaaaaaaaaaa");
allocator.setDoiQuotaAllowed(-1);
allocator.setDoiQuotaUsed(0);
allocator.setIsActive(true);
allocator.setName("aaaaaaaaaa");
allocator.setRoleName("ROLE_ALLOCATOR");
allocator.persist();
datacentre = new Datacentre();
datacentre.setSymbol(datacentreSymbol);
datacentre.setAllocator(allocator);
datacentre.setContactEmail("aaa@aaa.com");
datacentre.setContactName("aaaa");
datacentre.setDoiQuotaAllowed(-1);
datacentre.setDoiQuotaUsed(0);
datacentre.setDomains("bl.uk");
datacentre.setIsActive(true);
datacentre.setName("aaaaaaaaaa");
datacentre.setRoleName("ROLE_DATACENTRE");
datacentre.persist();
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken(allocator.getSymbol(), allocator.getPassword()));
}
@Test
public void testGet() {
ResponseEntity<? extends Object> result = datacentreApiController.get(datacentreSymbol);
assertEquals(HttpStatus.OK, result.getStatusCode());
}
@Test
public void testGet404() {
ResponseEntity<? extends Object> result = datacentreApiController.get(allocatorSymbol);
assertEquals(HttpStatus.NOT_FOUND, result.getStatusCode());
}
@Test
public void testGet403NotLoggedIn() {
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken(null, null));
ResponseEntity<? extends Object> result = datacentreApiController.get(datacentreSymbol);
assertEquals(HttpStatus.FORBIDDEN, result.getStatusCode());
}
@Test
public void testGet403WrongUser() {
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken(allocatorSymbol2, null));
ResponseEntity<? extends Object> result = datacentreApiController.get(datacentreSymbol);
assertEquals(HttpStatus.FORBIDDEN, result.getStatusCode());
}
@Test
public void testUpdate() {
String newName = "qwrfgqwergv";
datacentre.setName(newName);
ResponseEntity<? extends Object> result = datacentreApiController.createOrUpdate(datacentre, false);
assertEquals(HttpStatus.OK, result.getStatusCode());
Datacentre updatedDatacentre = (Datacentre) result.getBody();
assertEquals(newName, updatedDatacentre.getName());
}
@Test
public void testUpdateTestMode() {
String newName = "qwrfgqwergv";
datacentre.setName(newName);
ResponseEntity<? extends Object> result = datacentreApiController.createOrUpdate(datacentre, true);
assertEquals(HttpStatus.OK, result.getStatusCode());
Datacentre updatedDatacentre = (Datacentre) result.getBody();
assertEquals(newName, updatedDatacentre.getName());
}
@Test
public void testUpdateTestModeNull() {
String newName = "qwrfgqwergv";
datacentre.setName(newName);
ResponseEntity<? extends Object> result = datacentreApiController.createOrUpdate(datacentre, null);
assertEquals(HttpStatus.OK, result.getStatusCode());
Datacentre updatedDatacentre = (Datacentre) result.getBody();
assertEquals(newName, updatedDatacentre.getName());
}
@Test
public void testUpdate403NotLoggedIn() {
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken(null, null));
String newName = "qwrfgqwergv";
datacentre.setName(newName);
ResponseEntity<? extends Object> result = datacentreApiController.createOrUpdate(datacentre, false);
assertEquals(HttpStatus.FORBIDDEN, result.getStatusCode());
}
@Test
public void testUpdate403AnotherOwner() {
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken(allocatorSymbol2, null));
String newName = "qwrfgqwergv";
datacentre.setName(newName);
ResponseEntity<? extends Object> result = datacentreApiController.createOrUpdate(datacentre, false);
assertEquals(HttpStatus.FORBIDDEN, result.getStatusCode());
}
@Test
@Rollback
public void testCreate() {
datacentre2 = new Datacentre();
datacentre2.setSymbol(datacentreSymbol2);
datacentre2.setAllocator(allocator);
datacentre2.setContactEmail("aaa@aaa.com");
datacentre2.setContactName("aaaa");
datacentre2.setDoiQuotaAllowed(-1);
datacentre2.setDoiQuotaUsed(0);
datacentre2.setDomains("bl.uk");
datacentre2.setIsActive(true);
datacentre2.setName("aaaaaaaaaa");
datacentre2.setRoleName("ROLE_DATACENTRE");
ResponseEntity<? extends Object> result = datacentreApiController.createOrUpdate(datacentre2, false);
assertEquals(HttpStatus.CREATED, result.getStatusCode());
}
@Test
public void testCreateTestMode() {
datacentre2 = new Datacentre();
datacentre2.setSymbol(datacentreSymbol2);
datacentre2.setAllocator(allocator);
datacentre2.setContactEmail("aaa@aaa.com");
datacentre2.setContactName("aaaa");
datacentre2.setDoiQuotaAllowed(-1);
datacentre2.setDoiQuotaUsed(0);
datacentre2.setDomains("bl.uk");
datacentre2.setIsActive(true);
datacentre2.setName("aaaaaaaaaa");
datacentre2.setRoleName("ROLE_DATACENTRE");
ResponseEntity<? extends Object> result = datacentreApiController.createOrUpdate(datacentre2, true);
assertEquals(HttpStatus.CREATED, result.getStatusCode());
}
}
|
package uk.co.eluinhost.ultrahardcore.features.deathmessages;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.event.EventHandler;
import org.bukkit.event.entity.PlayerDeathEvent;
import uk.co.eluinhost.configuration.ConfigManager;
import uk.co.eluinhost.ultrahardcore.features.UHCFeature;
/**
* DeathMessagesFeature
* Handles changes to death messages on death
*
* @author ghowden
*/
public class DeathMessagesFeature extends UHCFeature {
public static final String BASE_MESSAGES = BASE_PERMISSION + "death_messages.";
public static final String DEATH_MESSAGE_SUPPRESSED = BASE_MESSAGES + "remove";
public static final String DEATH_MESSAGE_AFFIXES = BASE_MESSAGES + "affixes";
public static final String SUPRESSED_NODE = "remove";
public static final String FORMAT_NODE = "message";
/**
* Change the format of death messages
*/
public DeathMessagesFeature() {
super("DeathMessages","Adds a prefix/suffix to all player deaths");
}
/**
* Whenver a player dies
* @param pde the death event
*/
@EventHandler
public void onPlayerDeath(PlayerDeathEvent pde) {
if (isEnabled()) {
//if death message suppression is on
if (ConfigManager.getInstance().getConfig().getBoolean(getBaseConfig()+SUPRESSED_NODE)) {
//and the players death messages are suppressed
if (pde.getEntity().hasPermission(DEATH_MESSAGE_SUPPRESSED)) {
//set to nothing
pde.setDeathMessage("");
}
return;
}
//if there is an affix for the player
if (pde.getEntity().hasPermission(DEATH_MESSAGE_AFFIXES)) {
//grab format from config file
String format = ChatColor.translateAlternateColorCodes('&', ConfigManager.getInstance().getConfig().getString(getBaseConfig()+FORMAT_NODE));
//replace vars
format = format.replaceAll("%message", pde.getDeathMessage());
format = format.replaceAll("%player", pde.getEntity().getName());
Location loc = pde.getEntity().getLocation();
format = format.replaceAll("%coords", locationString(loc));
//set the new message
pde.setDeathMessage(format);
}
}
}
/**
* Returns string in the format x:X y:Y z:Z
* @param loc Location
* @return String
*/
private static String locationString(Location loc) {
return "x:" + loc.getBlockX() + " y:" + loc.getBlockY() + " z:" + loc.getBlockZ();
}
}
|
package bisq.asset.coins;
import bisq.asset.Coin;
import bisq.asset.RegexAddressValidator;
// Not an ICO token (see https://github.com/bisq-network/proposals/issues/57#issuecomment-441671418)
public class Dragonglass extends Coin {
public Dragonglass() {
super("Dragonglass", "DRGL", new RegexAddressValidator("^(dRGL)[1-9A-HJ-NP-Za-km-z]{94}$"));
}
}
|
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import javax.xml.parsers.*;
import javax.xml.xpath.*;
public class GradingHelper {
String rootDirectory;
String hwName;
ProgramInfo[] programs;
File reportFile;
PrintWriter reportFileWriter;
ArrayList<AssignmentResults> results;
public GradingHelper(String s)
{
rootDirectory = s;
programs = null;
reportFile = null;
results = new ArrayList<AssignmentResults>();
}
/**
* Examine each subdirectory of the given directory, and
* find all the Java files in the directory. Compile the
* files and report whether the compilation succeeded.
*/
public void processDirectory() throws IOException, InterruptedException
{
/* Preprocessing: Organize files from BlackBoard assignment download. */
File rootDir = new File(rootDirectory);
if (!rootDir.isDirectory())
{
throw new IllegalArgumentException(rootDirectory + " is not a directory");
}
AssignmentResults.organizeBlackBoardFiles(rootDir);
for (File e : rootDir.listFiles())
{
if (e.isDirectory())
{
AssignmentResults ar = new AssignmentResults(e.getName(), e);
results.add(ar);
ar.findFiles(e);
ar.findSubmissionDate();
ar.copyJavaFilesToUser();
ar.showRequestedJavaFiles(programs);
ar.stripPackageFromJavaFiles();
if (ar.checkRequiredJavaFiles(programs))
{
if (ar.compileJavaFiles(e))
{
ar.runJavaPrograms(programs, e);
}
}
}
}
Collections.sort(results);
}
/**
* Read properties from the configuration file.
* Properties:
* grading.programs: list of programs expected
* grading.javaFiles: comma-separated list of input files for each program
* @param dir - Directory expected to contain the config file
* @throws IOException
*/
public void readConfiguration() throws IOException, ParserConfigurationException, SAXException, XPathExpressionException
{
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true); // never forget this!
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse(rootDirectory + File.separator + "grading.xml");
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
Node n = (Node)xpath.evaluate("/homework/name", doc, XPathConstants.NODE);
hwName = n.getTextContent();
NodeList nl = (NodeList)xpath.evaluate("/homework/program", doc, XPathConstants.NODESET);
programs = new ProgramInfo[nl.getLength()];
for (int i = 0; i < nl.getLength(); i++)
{
programs[i] = new ProgramInfo(nl.item(i));
}
}
/**
* Create a file in the given root directory to hold the
* report for the student submissions.
* @throws IOException if any I/O problems occur
*/
public void openReportFile() throws IOException
{
File rootDir = new File(rootDirectory);
if (!rootDir.isDirectory())
{
throw new IOException(rootDirectory + " is not a directory");
}
reportFile = File.createTempFile("GradingReport", ".txt", rootDir);
reportFileWriter = new PrintWriter(reportFile);
}
/**
* Close the student submission report file and
* display the name of the report file.
* @throws IOException
*/
public void closeReportFile() throws IOException
{
System.out.println("Submission results are in " + reportFile.getName());
reportFileWriter.close();
reportFileWriter = null;
}
/**
* Generate the report of the student's submissions.
*/
public void reportResults()
{
for (AssignmentResults ar : results)
{
reportFileWriter.println(ar.toString());
reportFileWriter.print('\f');
}
reportFileWriter.flush();
}
/**
* @param args - Directory to analyze for student submissions
*/
public static void main(String[] args)
{
if (args.length == 0) {
System.err.println("Usage: GradingHelper directory-name");
System.exit(1);
}
GradingHelper gh = new GradingHelper(args[0]);
try
{
gh.readConfiguration();
gh.openReportFile();
gh.processDirectory();
gh.reportResults();
gh.closeReportFile();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (ParserConfigurationException e)
{
System.err.println(e.getMessage());
}
catch (XPathExpressionException e)
{
System.err.println(e.getMessage());
}
catch (SAXException e)
{
System.err.println(e.getMessage());
}
catch (InterruptedException e)
{
System.err.println(e.getMessage());
}
}
}
|
package at.aau.game.screens;
import at.aau.game.GameConstants;
import at.aau.game.PixieSmack;
import at.aau.game.ScreenManager;
import at.aau.game.SoundManager;
import at.aau.game.Mechanics.World;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.ScreenAdapter;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector3;
public class MenuScreen extends ScreenAdapter {
private final SpriteBatch batch;
private final OrthographicCamera cam;
private PixieSmack parentGame;
Texture backgroundImage;
BitmapFont menuFont;
Music menuMusic;
String[] menuStrings = { GameConstants.NEW_GAME, GameConstants.RESUME_GAME, "Highscore", "Credits", "Exit" };
int currentMenuItem = 0;
float offsetLeft = PixieSmack.MENU_GAME_WIDTH / 8, offsetTop = PixieSmack.MENU_GAME_WIDTH / 8, offsetY = PixieSmack.MENU_GAME_HEIGHT / 8;
public MenuScreen(PixieSmack game) {
this.parentGame = game;
backgroundImage = parentGame.getAssetManager().get("menu/menu_background.jpg");
menuFont = parentGame.getAssetManager().get("menu/Ravie_72.fnt");
menuFont.getRegion().getTexture().setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
// Create camera that projects the desktop onto the actual screen size.
cam = new OrthographicCamera(PixieSmack.MENU_GAME_WIDTH, PixieSmack.MENU_GAME_HEIGHT);
cam.position.set(cam.viewportWidth / 2f, cam.viewportHeight / 2f, 0);
cam.update();
batch = new SpriteBatch();
menuMusic = Gdx.audio.newMusic(Gdx.files.internal("sfx/introMusic.wav"));
menuMusic.setLooping(true);
menuMusic.play();
}
@Override
public void render(float delta) {
handleInput();
// camera:
cam.update();
batch.setProjectionMatrix(cam.combined);
Gdx.gl.glClearColor(0.3f, 0.3f, 0.3f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
// draw bgImage ...
batch.draw(backgroundImage, 0, 0, PixieSmack.MENU_GAME_WIDTH, PixieSmack.MENU_GAME_HEIGHT);
// draw Strings ...
int offsetFactor = 0;
for (int i = 0; i < menuStrings.length; i++) {
if (i == currentMenuItem)
menuFont.setColor(0.2f, 1f, 0.2f, 1f);
else
menuFont.setColor(0.2f, 0.2f, 1f, 1f);
if (menuStrings[i].equals(GameConstants.RESUME_GAME) && !this.parentGame.alreadyIngame) {
menuFont.setColor(0.3f, 0.3f, 0.3f, 1f);
menuFont.draw(batch, menuStrings[i], offsetLeft, PixieSmack.MENU_GAME_HEIGHT - offsetTop - offsetFactor * offsetY);
offsetFactor++;
}
else if (menuStrings[i].equals(GameConstants.RESUME_GAME) && this.parentGame.alreadyIngame) {
menuFont.draw(batch, menuStrings[i], offsetLeft, PixieSmack.MENU_GAME_HEIGHT - offsetTop - offsetFactor * offsetY);
offsetFactor++;
}
else if (!menuStrings[i].equals(GameConstants.RESUME_GAME)) {
menuFont.draw(batch, menuStrings[i], offsetLeft, PixieSmack.MENU_GAME_HEIGHT - offsetTop - offsetFactor * offsetY);
offsetFactor++;
}
}
batch.end();
}
private void handleInput() {
// keys ...
if (Gdx.input.isKeyJustPressed(Input.Keys.ESCAPE) && this.parentGame.alreadyIngame) { // JUST
this.parentGame.getScreenManager().setCurrentState(ScreenManager.ScreenState.ResumeGame);
parentGame.getSoundManager().playEvent("blip");
} else if (Gdx.input.isKeyJustPressed(Input.Keys.DOWN)) {
currentMenuItem = (currentMenuItem + 1) % menuStrings.length;
if (currentMenuItem == 1 && !this.parentGame.alreadyIngame) {
currentMenuItem++;
}
parentGame.getSoundManager().playEvent("blip");
} else if (Gdx.input.isKeyJustPressed(Input.Keys.UP)) {
currentMenuItem = (currentMenuItem - 1) % menuStrings.length;
if (currentMenuItem == 1 && !this.parentGame.alreadyIngame) {
currentMenuItem
}
if (currentMenuItem < 0) {
currentMenuItem = 0;
} else {
parentGame.getSoundManager().playEvent("blip");
}
} else if (Gdx.input.isKeyJustPressed(Input.Keys.ENTER)) {
if (menuStrings[currentMenuItem].equals("Exit")) {
Gdx.app.exit();
parentGame.getSoundManager().playEvent("explode");
} else if (menuStrings[currentMenuItem].equals("Credits")) {
menuMusic.stop();
parentGame.getScreenManager().setCurrentState(ScreenManager.ScreenState.Credits);
} else if (menuStrings[currentMenuItem].equals(GameConstants.NEW_GAME)) {
parentGame.getScreenManager().setCurrentState(ScreenManager.ScreenState.NewGame);
menuMusic.stop();
} else if (menuStrings[currentMenuItem].equals(GameConstants.RESUME_GAME) && this.parentGame.alreadyIngame) {
parentGame.getScreenManager().setCurrentState(ScreenManager.ScreenState.ResumeGame);
menuMusic.stop();
} else if (menuStrings[currentMenuItem].equals("Highscore")) {
parentGame.getScreenManager().setCurrentState(ScreenManager.ScreenState.Highscore);
}
}
// touch
if (Gdx.input.justTouched()) {
Vector3 touchWorldCoords = cam.unproject(new Vector3(Gdx.input.getX(), Gdx.input.getY(), 1));
// find the menu item ..
for (int i = 0; i < menuStrings.length; i++) {
if (touchWorldCoords.x > offsetLeft) {
float pos = PixieSmack.MENU_GAME_HEIGHT - offsetTop - i * offsetY;
if (touchWorldCoords.y < pos && touchWorldCoords.y > pos - menuFont.getLineHeight()) {
// it's there
if (menuStrings[i].equals("Exit")) {
Gdx.app.exit();
} else if (menuStrings[i].equals(GameConstants.NEW_GAME)) {
menuMusic.stop();
parentGame.getScreenManager().setCurrentState(ScreenManager.ScreenState.NewGame);
} else if (menuStrings[i].equals(GameConstants.RESUME_GAME) && this.parentGame.alreadyIngame) {
parentGame.getScreenManager().setCurrentState(ScreenManager.ScreenState.ResumeGame);
} else if (menuStrings[i].equals("Credits")) {
menuMusic.stop();
parentGame.getScreenManager().setCurrentState(ScreenManager.ScreenState.Credits);
} else if (menuStrings[i].equals("Highscore")) {
menuMusic.stop();
parentGame.getScreenManager().setCurrentState(ScreenManager.ScreenState.Highscore);
}
}
}
}
}
}
}
|
package com.ray3k.stripe;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.*;
import com.badlogic.gdx.scenes.scene2d.ui.*;
import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton.TextButtonStyle;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener.ChangeEvent;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.scenes.scene2d.utils.Drawable;
import com.badlogic.gdx.utils.Align;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.IntSet;
import com.badlogic.gdx.utils.IntSet.IntSetIterator;
import com.ray3k.stripe.PopTable.PopTableStyle;
public class StripeMenuBar extends Table implements StripeMenu {
private final TextButtonStyle itemStyle;
private final TextButtonStyle submenuStyle;
private final PopTableStyle popTableStyle;
private final LabelStyle shortcutLabelStyle;
private final Array<StripeMenuValue> stripeMenuValues = new Array<>();
private final Stage stage;
private final WidgetGroup modalGroup;
private boolean menuActivated;
private final Array<KeyboardShortcutListener> keyboardShortcutListeners = new Array<>();
private StripeMenuBarStyle style;
private static final Vector2 temp = new Vector2();
public StripeMenuBar(Stage stage, Skin skin) {
this(stage, skin, "default");
}
public StripeMenuBar(Stage stage, Skin skin, String style) {
this(stage, skin.get(style, StripeMenuBarStyle.class));
}
public StripeMenuBar(Stage stage, StripeMenuBarStyle style) {
this.style = style;
itemStyle = new TextButtonStyle();
itemStyle.up = style.itemUp;
itemStyle.down = style.itemDown;
itemStyle.over = style.itemOver;
itemStyle.checked = style.itemOpen;
itemStyle.disabled = style.itemDisabled;
itemStyle.font = style.itemFont;
itemStyle.fontColor = style.itemFontColor;
itemStyle.overFontColor = style.itemOverFontColor;
itemStyle.downFontColor = style.itemDownFontColor;
itemStyle.checkedFontColor = style.itemOpenFontColor;
itemStyle.disabledFontColor = style.itemDisabledFontColor;
submenuStyle = new TextButtonStyle();
submenuStyle.up = style.submenuUp == null ? style.itemUp : style.submenuUp;
submenuStyle.down = style.submenuDown == null ? style.itemDown : style.submenuDown;
submenuStyle.over = style.submenuOver == null ? style.itemOver : style.submenuOver;
submenuStyle.checked = style.submenuOpen;
submenuStyle.disabled = style.submenuDisabled;
submenuStyle.font = style.itemFont;
submenuStyle.fontColor = style.itemFontColor;
submenuStyle.overFontColor = style.itemOverFontColor;
submenuStyle.downFontColor = style.itemDownFontColor;
submenuStyle.checkedFontColor = style.itemOpenFontColor;
submenuStyle.disabledFontColor = style.itemDisabledFontColor;
popTableStyle = new PopTableStyle();
popTableStyle.background = style.submenuBackground;
shortcutLabelStyle = new LabelStyle();
shortcutLabelStyle.font = style.shortcutFont == null ? style.itemFont : style.shortcutFont;
setBackground(style.menuBar);
this.stage = stage;
align(Align.left);
modalGroup = new WidgetGroup() {
@Override
public Actor hit(float x, float y, boolean touchable) {
temp.set(x,y);
localToStageCoordinates(temp);
StripeMenuBar.this.stageToLocalCoordinates(temp);
Actor actor = StripeMenuBar.this.hit(temp.x, temp.y, true);
return actor == null ? this : actor;
}
};
modalGroup.setFillParent(true);
modalGroup.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
hideEverything();
}
});
}
private static void hideRecursive(Array<StripeMenuValue> items) {
for (StripeMenuValue item : items) {
hideRecursive(item.stripeMenuValues);
item.hide();
}
}
private void hideEverything() {
hideRecursive(stripeMenuValues);
modalGroup.remove();
menuActivated = false;
for (StripeMenuValue value : stripeMenuValues) {
value.getParentButton().setChecked(false);
}
}
@Override
public StripeMenu menu(String name) {
StripeMenuValue returnValue = createMenu(name, this, stripeMenuValues, Align.bottomLeft, Align.bottomRight, true);
add(returnValue.textButton);
return returnValue;
}
@Override
public StripeMenu item(String name, EventListener... listeners) {
return item(name, null, listeners);
}
@Override
public StripeMenu item(String name, KeyboardShortcut keyboardShortcut, EventListener... listeners) {
add(createItem(name, stripeMenuValues, keyboardShortcut, listeners));
return this;
}
@Override
public StripeMenu parent() {
return null;
}
@Override
public TextButton getParentButton() {
return null;
}
public class StripeMenuValue extends PopTable implements StripeMenu {
private StripeMenu parent;
private TextButton textButton;
private final Array<StripeMenuValue> stripeMenuValues = new Array<>();
public StripeMenuValue(StripeMenu parent) {
super(popTableStyle);
StripeMenuValue.this.parent = parent;
align(Align.top);
}
@Override
public StripeMenu menu(String name) {
StripeMenu returnValue = createMenu(name, this, stripeMenuValues, Align.topRight, Align.bottomRight, false);
add(returnValue.getParentButton());
row();
return returnValue;
}
@Override
public StripeMenu item(String name, EventListener... listeners) {
return item(name, null, listeners);
}
@Override
public StripeMenu item(String name, KeyboardShortcut keyboardShortcut, EventListener... listeners) {
add(createItem(name, stripeMenuValues, keyboardShortcut, listeners));
row();
return this;
}
@Override
public StripeMenu parent() {
return parent;
}
@Override
public TextButton getParentButton() {
return textButton;
}
@Override
public TextButton findButton(String name) {
for (Actor actor : getChildren()) {
if (actor instanceof TextButton) {
TextButton textButton = (TextButton) actor;
if (textButton.getText().toString().equals(name)) {
return textButton;
}
}
}
return null;
}
@Override
public StripeMenu findMenu(String name) {
for (StripeMenuValue value : stripeMenuValues) {
if (value.textButton.getText().toString().equals(name)) return value;
}
return null;
}
}
private StripeMenuValue createMenu(String name, StripeMenu parent, Array<StripeMenuValue> stripeMenuValues, int edge, int align, boolean modal) {
TextButton textButton = new TextButton(name, itemStyle);
textButton.getLabel().setAlignment(Align.left);
StripeMenuValue menu = new StripeMenuValue(parent);
menu.defaults().growX();
menu.attachToActor(textButton, edge, align);
menu.textButton = textButton;
stripeMenuValues.add(menu);
ItemHoverListener listener = new ItemHoverListener(menu, stripeMenuValues);
listener.modal = modal;
listener.clickMode = modal;
textButton.addListener(listener);
return menu;
}
private TextButton createItem(String name, Array<StripeMenuValue> stripeMenuValues, KeyboardShortcut keyboardShortcut, EventListener... listeners) {
TextButton textButton = new TextButton(name, itemStyle);
textButton.setProgrammaticChangeEvents(false);
textButton.getLabel().setAlignment(Align.left);
for (EventListener listener : listeners) {
textButton.addListener(listener);
}
textButton.addListener(new ChangeListener() {
@Override
public void changed(ChangeEvent event, Actor actor) {
textButton.setChecked(false);
fire(new MenuBarEvent(textButton, textButton.getText().toString()));
}
});
textButton.addListener(new ItemHoverListener(null, stripeMenuValues));
if (keyboardShortcut != null) {
Label label = new Label(keyboardShortcut.name, shortcutLabelStyle) {
@Override
public void draw(Batch batch, float parentAlpha) {
if (textButton.isDisabled()) {
shortcutLabelStyle.fontColor = style.shortcutDisabledFontColor == null ? style.itemDisabledFontColor : style.shortcutDisabledFontColor;
} else if (textButton.isPressed()) {
shortcutLabelStyle.fontColor = style.shortcutDownFontColor == null ? style.itemDownFontColor : style.shortcutDownFontColor;
} else if (textButton.isChecked()) {
shortcutLabelStyle.fontColor = style.shortcutOpenFontColor == null ? style.itemOpenFontColor : style.shortcutOpenFontColor;
} else if (textButton.isOver()) {
shortcutLabelStyle.fontColor = style.shortcutOverFontColor == null ? style.itemOverFontColor : style.shortcutOverFontColor;
} else {
shortcutLabelStyle.fontColor = style.shortcutFontColor == null ? style.itemFontColor : style.shortcutFontColor;
}
super.draw(batch, parentAlpha);
}
};
textButton.add(label).space(style.shortcutSpace);
KeyboardShortcutListener keyboardShortcutListener = new KeyboardShortcutListener(keyboardShortcut, textButton);
stage.addListener(keyboardShortcutListener);
keyboardShortcutListeners.add(keyboardShortcutListener);
}
return textButton;
}
public StripeMenuBarStyle getStyle() {
return style;
}
@Override
public TextButton findButton(String name) {
for (Actor actor : getChildren()) {
if (actor instanceof TextButton) {
TextButton textButton = (TextButton) actor;
if (textButton.getText().toString().equals(name)) {
return textButton;
}
}
}
return null;
}
@Override
public StripeMenu findMenu(String name) {
for (StripeMenuValue value : stripeMenuValues) {
if (value.textButton.getText().toString().equals(name)) return value;
}
return null;
}
public static class KeyboardShortcut {
public String name;
public int key;
public final IntSet modifiers = new IntSet();
public KeyboardShortcut(String name, int key, int... modifiers) {
this.name = name;
this.key = key;
this.modifiers.addAll(modifiers,0, modifiers.length);
}
}
public static class MenuBarEvent extends Event {
public TextButton textButton;
public String name;
public MenuBarEvent(TextButton textButton, String name) {
this.textButton = textButton;
this.name = name;
}
}
public static abstract class MenuBarListener implements EventListener {
@Override
public boolean handle(Event event) {
if (event instanceof MenuBarEvent) {
MenuBarEvent menuBarEvent = (MenuBarEvent) event;
itemClicked(menuBarEvent.name, menuBarEvent.textButton, menuBarEvent);
return true;
}
return false;
}
public abstract void itemClicked(String name, TextButton textButton, MenuBarEvent event);
}
private class KeyboardShortcutListener extends InputListener {
private KeyboardShortcut keyboardShortcut;
private TextButton textButton;
public KeyboardShortcutListener(KeyboardShortcut keyboardShortcut, TextButton textButton) {
this.keyboardShortcut = keyboardShortcut;
this.textButton = textButton;
}
@Override
public boolean keyDown(InputEvent event, int keycode) {
if (getParent() != null && !textButton.isDisabled() && keycode == keyboardShortcut.key) {
IntSetIterator iter = keyboardShortcut.modifiers.iterator();
while (iter.hasNext) {
int modifier = iter.next();
if (!Gdx.input.isKeyPressed(modifier)) return false;
}
textButton.fire(new ChangeEvent());
fire(new MenuBarEvent(textButton, textButton.getText().toString()));
hideRecursive(stripeMenuValues);
return true;
}
return false;
}
}
private class ItemHoverListener extends ClickListener {
private final Array<StripeMenuValue> stripeMenuValues;
private final StripeMenuValue stripeMenuValue;
private boolean modal;
private boolean clickMode;
public ItemHoverListener(StripeMenuValue stripeMenuValue, Array<StripeMenuValue> stripeMenuValues) {
this.stripeMenuValue = stripeMenuValue;
this.stripeMenuValues = stripeMenuValues;
}
@Override
public void clicked(InputEvent event, float x, float y) {
if (stripeMenuValue == null) {
hideEverything();
}
if (clickMode) {
if (!menuActivated) {
menuActivated = true;
hide();
show();
} else {
hideEverything();
}
}
}
@Override
public void enter(InputEvent event, float x, float y, int pointer, Actor fromActor) {
super.enter(event, x, y, pointer, fromActor);
if (menuActivated) {
hide();
show();
}
}
private void hide() {
for (StripeMenuValue stripeMenuValue : stripeMenuValues) {
if (stripeMenuValue != this.stripeMenuValue) {
hideRecursive(stripeMenuValue.stripeMenuValues);
stripeMenuValue.hide();
stripeMenuValue.setTouchable(Touchable.disabled);
if (stripeMenuValue.textButton != null) stripeMenuValue.textButton.setChecked(false);
}
}
}
private void show() {
if (stripeMenuValue != null && stripeMenuValue.isHidden()) {
if (modal) stage.addActor(modalGroup);
stripeMenuValue.show(stage);
stripeMenuValue.attachToActor();
stripeMenuValue.setTouchable(Touchable.enabled);
if (stripeMenuValue.textButton != null) stripeMenuValue.textButton.setChecked(true);
}
}
}
public static class StripeMenuBarStyle {
public BitmapFont itemFont;
/*Optional*/
public Drawable menuBar, submenuBackground, itemUp, itemOver, itemDown, itemOpen, itemDisabled, submenuUp, submenuOver, submenuDown, submenuOpen, submenuDisabled;
public BitmapFont shortcutFont;
public Color itemFontColor, itemOverFontColor, itemDownFontColor, itemOpenFontColor, itemDisabledFontColor, shortcutFontColor, shortcutOverFontColor, shortcutDownFontColor, shortcutOpenFontColor, shortcutDisabledFontColor;
public float shortcutSpace;
public StripeMenuBarStyle() {
}
public StripeMenuBarStyle(StripeMenuBarStyle style) {
itemFont = style.itemFont;
menuBar = style.menuBar;
submenuBackground = style.submenuBackground;
itemUp = style.itemUp;
itemOver = style.itemOver;
itemDown = style.itemDown;
itemOpen = style.itemOpen;
itemDisabled = style.itemDisabled;
submenuUp = style.submenuUp;
submenuOver = style.submenuOver;
submenuDown = style.submenuDown;
submenuOpen = style.submenuOpen;
submenuDisabled = style.submenuDisabled;
shortcutFont = style.shortcutFont;
itemFontColor = style.itemFontColor;
itemOverFontColor = style.itemOverFontColor;
itemDownFontColor = style.itemDownFontColor;
itemOpenFontColor = style.itemOpenFontColor;
itemDisabledFontColor = style.itemDisabledFontColor;
shortcutOverFontColor = style.shortcutOverFontColor;
shortcutDownFontColor = style.shortcutDownFontColor;
shortcutOpenFontColor = style.shortcutOpenFontColor;
shortcutDisabledFontColor = style.shortcutDisabledFontColor;
shortcutFontColor = style.shortcutFontColor;
shortcutSpace = style.shortcutSpace;
}
}
}
|
package org.biojava.bio.structure.align.ce;
import org.biojava.bio.structure.Atom;
import org.biojava.bio.structure.TmpAtomCache;
import org.biojava.bio.structure.align.StructureAlignment;
import org.biojava.bio.structure.align.StructureAlignmentFactory;
import org.biojava.bio.structure.align.model.AFPChain;
import org.biojava.bio.structure.align.xml.AFPChainXMLConverter;
import org.biojava.bio.structure.align.xml.AFPChainXMLParser;
import junit.framework.TestCase;
public class TestSmallAlignment extends TestCase{
public void test1a4w(){
String name1 = "1a4w.I";
String name2 = "1a4w.H";
try {
Atom[] ca1 = TmpAtomCache.cache.getAtoms(name1);
Atom[] ca2 = TmpAtomCache.cache.getAtoms(name2);
StructureAlignment ce =StructureAlignmentFactory.getAlgorithm(CeMain.algorithmName);
AFPChain afpChain = ce.align(ca1, ca2);
assertTrue(afpChain != null);
assertTrue(afpChain.getNrEQR() ==0 );
String xml = AFPChainXMLConverter.toXML(afpChain,ca1,ca2);
AFPChain newChain = AFPChainXMLParser.fromXML(xml, ca1, ca2);
assertTrue(newChain != null);
String xml2 = AFPChainXMLConverter.toXML(newChain,ca1,ca2);
assertEquals(xml,xml2);
} catch (Exception e){
e.printStackTrace();
fail(e.getMessage());
}
}
}
|
package de.bwaldvogel.mongo.backend;
import static de.bwaldvogel.mongo.backend.TestUtils.json;
import static de.bwaldvogel.mongo.backend.TestUtils.jsonList;
import static de.bwaldvogel.mongo.backend.TestUtils.toArray;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.junit.Test;
import com.mongodb.MongoCommandException;
import com.mongodb.client.MongoCollection;
public abstract class AbstractAggregationTest extends AbstractTest {
@Test
public void testUnrecognizedAggregatePipelineStage() throws Exception {
List<Document> pipeline = jsonList("$unknown: {}");
assertThatExceptionOfType(MongoCommandException.class)
.isThrownBy(() -> collection.aggregate(pipeline).first())
.withMessageContaining("Command failed with error 40324 (Location40324): 'Unrecognized pipeline stage name: '$unknown'");
}
@Test
public void testIllegalAggregatePipelineStage() throws Exception {
List<Document> pipeline = jsonList("$unknown: {}, bar: 1");
assertThatExceptionOfType(MongoCommandException.class)
.isThrownBy(() -> collection.aggregate(pipeline).first())
.withMessageContaining("Command failed with error 40323 (Location40323): 'A pipeline stage specification object must contain exactly one field.'");
}
@Test
public void testAggregateWithMissingCursor() throws Exception {
assertThatExceptionOfType(MongoCommandException.class)
.isThrownBy(() -> db.runCommand(json("aggregate: 'collection', pipeline: [{$match: {}}]")))
.withMessageContaining("Command failed with error 9 (FailedToParse): 'The 'cursor' option is required, except for aggregate with the explain argument'");
}
@Test
public void testAggregateWithComplexGroupBySumPipeline() throws Exception {
Document query = json("_id: null, n: {$sum: 1}, sumOfA: {$sum: '$a'}, sumOfB: {$sum: '$b.value'}");
List<Document> pipeline = Collections.singletonList(new Document("$group", query));
assertThat(toArray(collection.aggregate(pipeline))).isEmpty();
collection.insertOne(json("_id: 1, a:30, b: {value: 20}"));
collection.insertOne(json("_id: 2, a:15, b: {value: 10.5}"));
collection.insertOne(json("_id: 3, b: {value: 1}"));
collection.insertOne(json("_id: 4, a: {value: 5}"));
assertThat(toArray(collection.aggregate(pipeline)))
.containsExactly(json("_id: null, n:4, sumOfA: 45, sumOfB: 31.5"));
}
@Test
public void testAggregateWithGroupByMinAndMax() throws Exception {
Document query = json("_id: null, minA: {$min: '$a'}, maxB: {$max: '$b.value'}, maxC: {$max: '$c'}, minC: {$min: '$c'}");
List<Document> pipeline = Collections.singletonList(new Document("$group", query));
assertThat(toArray(collection.aggregate(pipeline))).isEmpty();
collection.insertOne(json("_id: 1, a:30, b: {value: 20}, c: 1.0"));
collection.insertOne(json("_id: 2, a:15, b: {value: 10}, c: 2"));
collection.insertOne(json("_id: 3, c: 'zzz'"));
collection.insertOne(json("_id: 4, c: 'aaa'"));
assertThat(toArray(collection.aggregate(pipeline)))
.containsExactly(json("_id: null, minA: 15, maxB: 20, minC: 1.0, maxC: 'zzz'"));
}
@Test
public void testAggregateWithGroupByNonExistingMinAndMax() throws Exception {
Document query = json("_id: null, minOfA: {$min: '$doesNotExist'}, maxOfB: {$max: '$doesNotExist'}");
List<Document> pipeline = Collections.singletonList(new Document("$group", query));
assertThat(toArray(collection.aggregate(pipeline))).isEmpty();
collection.insertOne(json("_id: 1, a: 30, b: {value: 20}"));
collection.insertOne(json("_id: 2, a: 15, b: {value: 10}"));
assertThat(toArray(collection.aggregate(pipeline)))
.containsExactly(json("_id: null, minOfA: null, maxOfB: null"));
}
@Test
public void testAggregateWithUnknownGroupOperator() throws Exception {
Document query = json("_id: null, n: {$foo: 1}");
List<Document> pipeline = Collections.singletonList(new Document("$group", query));
assertThatExceptionOfType(MongoCommandException.class)
.isThrownBy(() -> collection.aggregate(pipeline).first())
.withMessageContaining("Command failed with error 15952 (Location15952): 'unknown group operator '$foo''");
}
@Test
public void testAggregateWithTooManyGroupOperators() throws Exception {
Document query = json("_id: null, n: {$sum: 1, $max: 1}");
List<Document> pipeline = Collections.singletonList(new Document("$group", query));
assertThatExceptionOfType(MongoCommandException.class)
.isThrownBy(() -> collection.aggregate(pipeline).first())
.withMessageContaining("Command failed with error 40238 (Location40238): 'The field 'n' must specify one accumulator'");
}
@Test
public void testAggregateWithEmptyPipeline() throws Exception {
assertThat(toArray(collection.aggregate(Collections.emptyList()))).isEmpty();
collection.insertOne(json("_id: 1"));
collection.insertOne(json("_id: 2"));
assertThat(toArray(collection.aggregate(Collections.emptyList())))
.containsExactly(json("_id: 1"), json("_id: 2"));
}
@Test
public void testAggregateWithMissingIdInGroupSpecification() throws Exception {
List<Document> pipeline = Collections.singletonList(new Document("$group", json("n: {$sum: 1}")));
assertThatExceptionOfType(MongoCommandException.class)
.isThrownBy(() -> toArray(collection.aggregate(pipeline)))
.withMessageContaining("Command failed with error 15955 (Location15955): 'a group specification must include an _id'");
}
@Test
public void testAggregateWithGroupBySumPipeline() throws Exception {
Document query = json("_id: null, n: {$sum: 1}");
List<Document> pipeline = Collections.singletonList(new Document("$group", query));
assertThat(toArray(collection.aggregate(pipeline))).isEmpty();
collection.insertOne(json("_id: 1"));
collection.insertOne(json("_id: 2"));
assertThat(toArray(collection.aggregate(pipeline)))
.containsExactly(json("_id: null, n: 2"));
query.putAll(json("n: {$sum: 'abc'}"));
assertThat(toArray(collection.aggregate(pipeline)))
.containsExactly(json("_id: null, n: 0"));
query.putAll(json("n: {$sum: 2}"));
assertThat(toArray(collection.aggregate(pipeline)))
.containsExactly(json("_id: null, n: 4"));
query.putAll(json("n: {$sum: 1.75}"));
assertThat(toArray(collection.aggregate(pipeline)))
.containsExactly(json("_id: null, n: 3.5"));
query.putAll(new Document("n", new Document("$sum", 10000000000L)));
assertThat(toArray(collection.aggregate(pipeline)))
.containsExactly(json("_id: null, n: 20000000000"));
query.putAll(new Document("n", new Document("$sum", -2.5F)));
assertThat(toArray(collection.aggregate(pipeline)))
.containsExactly(json("_id: null, n: -5.0"));
}
@Test
public void testAggregateWithGroupByAvg() throws Exception {
Document query = json("_id: null, avg: {$avg: 1}");
List<Document> pipeline = Collections.singletonList(new Document("$group", query));
assertThat(toArray(collection.aggregate(pipeline))).isEmpty();
collection.insertOne(json("_id: 1, a: 6.0, b: 'zzz'"));
collection.insertOne(json("_id: 2, a: 3.0, b: 'aaa'"));
assertThat(toArray(collection.aggregate(pipeline)))
.containsExactly(json("_id: null, avg: 1.0"));
query.putAll(json("avg: {$avg: '$a'}, avgB: {$avg: '$b'}"));
assertThat(toArray(collection.aggregate(pipeline)))
.containsExactly(json("_id: null, avg: 4.5, avgB: null"));
}
@Test
public void testAggregateWithGroupByKey() throws Exception {
List<Document> pipeline = jsonList("$group: {_id: '$a', count: {$sum: 1}, avg: {$avg: '$b'}}");
assertThat(toArray(collection.aggregate(pipeline))).isEmpty();
collection.insertOne(json("_id: 1, a: 1"));
collection.insertOne(json("_id: 2, a: 1"));
collection.insertOne(json("_id: 3, a: 2, b: 3"));
collection.insertOne(json("_id: 4, a: 2, b: 4"));
collection.insertOne(json("_id: 5, a: 5, b: 10"));
collection.insertOne(json("_id: 6, a: 7, c: 'a'"));
collection.insertOne(json("_id: 7"));
assertThat(toArray(collection.aggregate(pipeline)))
.containsExactlyInAnyOrder(
json("_id: 1, count: 2, avg: null"),
json("_id: 2, count: 2, avg: 3.5"),
json("_id: 5, count: 1, avg: 10.0"),
json("_id: 7, count: 1, avg: null"),
json("_id: null, count: 1, avg: null")
);
}
@Test
public void testAggregateWithGroupByNumberEdgeCases() throws Exception {
String groupBy = "$group: {_id: '$a', count: {$sum: 1}, avg: {$avg: '$a'}, min: {$min: '$a'}, max: {$max: '$a'}}";
List<Document> pipeline = jsonList(groupBy);
assertThat(toArray(collection.aggregate(pipeline))).isEmpty();
collection.insertOne(json("_id: 1, a: 1.0"));
collection.insertOne(json("_id: 2, a: 1"));
collection.insertOne(json("_id: 3, a: -0.0"));
collection.insertOne(json("_id: 4, a: 0.0"));
collection.insertOne(json("_id: 5, a: 0"));
collection.insertOne(json("_id: 6, a: 1.5"));
collection.insertOne(json("_id: 7, a: null"));
assertThat(toArray(collection.aggregate(pipeline)))
.containsExactlyInAnyOrder(
json("_id: -0.0, count: 3, avg: 0.0, min: -0.0, max: -0.0"),
json("_id: 1.0, count: 2, avg: 1.0, min: 1.0, max: 1.0"),
json("_id: 1.5, count: 1, avg: 1.5, min: 1.5, max: 1.5"),
json("_id: null, count: 1, avg: null, min: null, max: null")
);
}
@Test
public void testAggregateWithGroupByDocuments() throws Exception {
String groupBy = "$group: {_id: '$a', count: {$sum: 1}}";
String sort = "$sort: {_id: 1}";
List<Document> pipeline = Arrays.asList(json(groupBy), json(sort));
assertThat(toArray(collection.aggregate(pipeline))).isEmpty();
collection.insertOne(json("_id: 1, a: 1.0"));
collection.insertOne(json("_id: 2, a: {b: 1}"));
collection.insertOne(json("_id: 3, a: {b: 1.0}"));
collection.insertOne(json("_id: 4, a: {b: 1, c: 1}"));
collection.insertOne(json("_id: 5, a: {b: {c: 1}}"));
collection.insertOne(json("_id: 6, a: {b: {c: 1.0}}"));
collection.insertOne(json("_id: 7, a: {b: {c: 1.0, d: 1}}"));
collection.insertOne(json("_id: 8, a: {b: {d: 1, c: 1.0}}"));
collection.insertOne(json("_id: 9, a: {c: 1, b: 1}"));
collection.insertOne(json("_id: 10, a: null"));
collection.insertOne(json("_id: 11, a: {b: 1, c: 1}"));
assertThat(toArray(collection.aggregate(pipeline)))
.containsExactly(
json("_id: null, count: 1"),
json("_id: 1.0, count: 1"),
json("_id: {b: 1}, count: 2"),
json("_id: {b: 1, c: 1}, count: 2"),
json("_id: {c: 1, b: 1}, count: 1"),
json("_id: {b: {c: 1}}, count: 2"),
json("_id: {b: {c: 1.0, d: 1}}, count: 1"),
json("_id: {b: {d: 1, c: 1.0}}, count: 1")
);
}
@Test
public void testAggregateWithGroupByIllegalKey() throws Exception {
collection.insertOne(json("_id: 1, a: 1"));
assertThatExceptionOfType(MongoCommandException.class)
.isThrownBy(() -> collection.aggregate(jsonList("$group: {_id: '$a.'}")).first())
.withMessageContaining("Command failed with error 40353 (Location40353): 'FieldPath must not end with a '.'.'");
assertThatExceptionOfType(MongoCommandException.class)
.isThrownBy(() -> collection.aggregate(jsonList("$group: {_id: '$a..1'}")).first())
.withMessageContaining("Command failed with error 15998 (Location15998): 'FieldPath field names may not be empty strings.'");
}
@Test
public void testAggregateWithSimpleExpressions() throws Exception {
List<Document> pipeline = jsonList("$group: {_id: {$abs: '$value'}, count: {$sum: 1}}");
assertThat(toArray(collection.aggregate(pipeline))).isEmpty();
collection.insertOne(json("_id: 1, value: 1"));
collection.insertOne(json("_id: -2, value: -1"));
collection.insertOne(json("_id: 3, value: 2"));
collection.insertOne(json("_id: 4, value: 2"));
collection.insertOne(json("_id: 5, value: -2.5"));
assertThat(toArray(collection.aggregate(pipeline)))
.containsExactlyInAnyOrder(
json("_id: 1, count: 2"),
json("_id: 2, count: 2"),
json("_id: 2.5, count: 1")
);
}
@Test
public void testAggregateWithMultipleExpressionsInKey() throws Exception {
List<Document> pipeline = jsonList("$group: {_id: {abs: {$abs: '$value'}, sum: {$subtract: ['$end', '$start']}}, count: {$sum: 1}}");
assertThat(toArray(collection.aggregate(pipeline))).isEmpty();
collection.insertOne(json("_id: 1, value: NaN"));
collection.insertOne(json("_id: 2, value: 1, start: 5, end: 8"));
collection.insertOne(json("_id: 3, value: -1, start: 4, end: 4"));
collection.insertOne(json("_id: 4, value: 2, start: 9, end: 7"));
collection.insertOne(json("_id: 5, value: 2, start: 6, end: 7"));
assertThat(toArray(collection.aggregate(pipeline)))
.containsExactlyInAnyOrder(
json("_id: {abs: NaN, sum: null}, count: 1"),
json("_id: {abs: 1, sum: 3}, count: 1"),
json("_id: {abs: 1, sum: 0}, count: 1"),
json("_id: {abs: 2, sum: -2}, count: 1"),
json("_id: {abs: 2, sum: 1}, count: 1")
);
}
@Test
public void testAggregateWithAddToSet() throws Exception {
List<Document> pipeline = jsonList("$group: {_id: { day: { $dayOfYear: '$date'}, year: { $year: '$date' } }, itemsSold: { $addToSet: '$item' }}");
assertThat(toArray(collection.aggregate(pipeline))).isEmpty();
collection.insertOne(json("_id: 1, item: 'zzz', price: 5, quantity: 10").append("date", TestUtils.date("2014-02-15T09:12:00Z")));
collection.insertOne(json("_id: 2, item: 'abc', price: 10, quantity: 2").append("date", TestUtils.date("2014-01-01T08:00:00Z")));
collection.insertOne(json("_id: 3, item: 'jkl', price: 20, quantity: 1").append("date", TestUtils.date("2014-02-03T09:00:00Z")));
collection.insertOne(json("_id: 4, item: 'xyz', price: 5, quantity: 5").append("date", TestUtils.date("2014-02-03T09:05:00Z")));
collection.insertOne(json("_id: 5, item: 'abc', price: 10, quantity: 10").append("date", TestUtils.date("2014-02-15T08:00:00Z")));
collection.insertOne(json("_id: 6, item: 'xyz', price: 5, quantity: 10").append("date", TestUtils.date("2014-02-15T09:12:00Z")));
assertThat(toArray(collection.aggregate(pipeline)))
.containsExactlyInAnyOrder(
json("_id: { day: 1, year: 2014 }, itemsSold: [ 'abc' ]"),
json("_id: { day: 34, year: 2014 }, itemsSold: [ 'xyz', 'jkl' ]"),
json("_id: { day: 46, year: 2014 }, itemsSold: [ 'xyz', 'abc', 'zzz' ]")
);
}
@Test
public void testAggregateWithEmptyAddToSet() throws Exception {
List<Document> pipeline = jsonList("$group: {_id: 1, set: { $addToSet: '$foo' }}");
assertThat(toArray(collection.aggregate(pipeline))).isEmpty();
collection.insertOne(json("_id: 1"));
collection.insertOne(json("_id: 2"));
collection.insertOne(json("_id: 3"));
assertThat(toArray(collection.aggregate(pipeline)))
.containsExactly(json("_id: 1, set: [ ]"));
}
@Test
public void testAggregateWithAdd() throws Exception {
List<Document> pipeline = jsonList("$project: { item: 1, total: { $add: [ '$price', '$fee' ] } }");
assertThat(toArray(collection.aggregate(pipeline))).isEmpty();
collection.insertOne(json("_id: 1, item: 'abc', price: 10, fee: 2"));
collection.insertOne(json("_id: 2, item: 'jkl', price: 20, fee: 1"));
collection.insertOne(json("_id: 3, item: 'xyz', price: 5, fee: 0"));
assertThat(toArray(collection.aggregate(pipeline)))
.containsExactly(
json("_id: 1, item: 'abc', total: 12"),
json("_id: 2, item: 'jkl', total: 21"),
json("_id: 3, item: 'xyz', total: 5 ")
);
}
@Test
public void testAggregateWithSort() throws Exception {
List<Document> pipeline = jsonList("$sort: { price: -1, fee: 1 }");
assertThat(toArray(collection.aggregate(pipeline))).isEmpty();
collection.insertOne(json("_id: 1, price: 10, fee: 1"));
collection.insertOne(json("_id: 2, price: 20, fee: 0"));
collection.insertOne(json("_id: 3, price: 10, fee: 0"));
assertThat(toArray(collection.aggregate(pipeline)))
.containsExactly(
json("_id: 2, price: 20, fee: 0"),
json("_id: 3, price: 10, fee: 0"),
json("_id: 1, price: 10, fee: 1")
);
}
@Test
public void testAggregateWithProjection() throws Exception {
List<Document> pipeline = jsonList("$project: {_id: 1, value: '$x', n: '$foo.bar', other: null}");
assertThat(toArray(collection.aggregate(pipeline))).isEmpty();
collection.insertOne(json("_id: 1, x: 10, foo: 'abc'"));
collection.insertOne(json("_id: 2, x: 20"));
collection.insertOne(json("_id: 3, x: 30, foo: {bar: 7.3}"));
assertThat(toArray(collection.aggregate(pipeline)))
.containsExactly(
json("_id: 1, value: 10, other: null"),
json("_id: 2, value: 20, other: null"),
json("_id: 3, value: 30, n: 7.3, other: null")
);
}
@Test
public void testAggregateWithProjection_IllegalFieldPath() throws Exception {
collection.insertOne(json("_id: 1, x: 10"));
assertThatExceptionOfType(MongoCommandException.class)
.isThrownBy(() -> collection.aggregate(jsonList("$project: {_id: 0, v: '$x.1.'}")).first())
.withMessageContaining("Command failed with error 40353 (Location40353): 'FieldPath must not end with a '.'.'");
assertThatExceptionOfType(MongoCommandException.class)
.isThrownBy(() -> collection.aggregate(jsonList("$project: {_id: 0, v: '$x..1'}")).first())
.withMessageContaining("Command failed with error 15998 (Location15998): 'FieldPath field names may not be empty strings.'");
}
@Test
public void testAggregateWithExpressionProjection() throws Exception {
List<Document> pipeline = jsonList("$project: {_id: 0, idHex: {$toString: '$_id'}}");
assertThat(toArray(collection.aggregate(pipeline))).isEmpty();
collection.insertOne(new Document("_id", new ObjectId("abcd01234567890123456789")));
assertThat(toArray(collection.aggregate(pipeline)))
.containsExactly(json("idHex: 'abcd01234567890123456789'"));
}
@Test
public void testAggregateWithAddFields() throws Exception {
List<Document> pipeline = jsonList("$addFields: {value: '$x'}");
assertThat(toArray(collection.aggregate(pipeline))).isEmpty();
collection.insertOne(json("_id: 1, x: 10"));
collection.insertOne(json("_id: 2"));
collection.insertOne(json("_id: 3, value: 123"));
assertThat(toArray(collection.aggregate(pipeline)))
.containsExactly(
json("_id: 1, x: 10, value: 10"),
json("_id: 2"),
json("_id: 3")
);
}
@Test
public void testAggregateWithMultipleMatches() throws Exception {
Document match1 = json("$match: {price: {$lt: 100}}");
Document match2 = json("$match: {quality: {$gt: 10}}");
List<Document> pipeline = Arrays.asList(match1, match2);
assertThat(toArray(collection.aggregate(pipeline))).isEmpty();
collection.insertOne(json("_id: 1, price: 10, quality: 50"));
collection.insertOne(json("_id: 2, price: 150, quality: 500"));
collection.insertOne(json("_id: 3, price: 50, quality: 150"));
collection.insertOne(json("_id: 4, price: 10, quality: 5"));
assertThat(toArray(collection.aggregate(pipeline)))
.containsExactly(
json("_id: 1, price: 10, quality: 50"),
json("_id: 3, price: 50, quality: 150")
);
}
@Test
public void testAggregateWithCeil() throws Exception {
List<Document> pipeline = jsonList("$project: {a: 1, ceil: {$ceil: '$a'}}");
assertThat(toArray(collection.aggregate(pipeline))).isEmpty();
collection.insertOne(json("_id: 1, a: 9.25"));
collection.insertOne(json("_id: 2, a: 8.73"));
collection.insertOne(json("_id: 3, a: 4.32"));
collection.insertOne(json("_id: 4, a: -5.34"));
assertThat(toArray(collection.aggregate(pipeline)))
.containsExactlyInAnyOrder(
json("_id: 1, a: 9.25, ceil: 10.0"),
json("_id: 2, a: 8.73, ceil: 9.0"),
json("_id: 3, a: 4.32, ceil: 5.0"),
json("_id: 4, a: -5.34, ceil: -5.0")
);
}
@Test
public void testAggregateWithNumericOperators() throws Exception {
List<Document> pipeline = jsonList("$project: {a: 1, exp: {$exp: '$a'}, ln: {$ln: '$a'}, log10: {$log10: '$a'}, sqrt: {$sqrt: '$a'}}");
assertThat(toArray(collection.aggregate(pipeline))).isEmpty();
collection.insertOne(json("_id: 1, a: 1"));
assertThat(toArray(collection.aggregate(pipeline)))
.containsExactly(json("_id: 1, a: 1, exp: 2.718281828459045, ln: 0.0, log10: 0.0, sqrt: 1.0"));
}
@Test
public void testAggregateWithCount() throws Exception {
Document match = json("$match: {score: {$gt: 80}}");
Document count = json("$count: 'passing_scores'");
List<Document> pipeline = Arrays.asList(match, count);
assertThat(toArray(collection.aggregate(pipeline))).isEmpty();
collection.insertOne(json("_id: 1, subject: 'History', score: 88"));
collection.insertOne(json("_id: 2, subject: 'History', score: 92"));
collection.insertOne(json("_id: 3, subject: 'History', score: 97"));
collection.insertOne(json("_id: 4, subject: 'History', score: 71"));
collection.insertOne(json("_id: 5, subject: 'History', score: 79"));
collection.insertOne(json("_id: 6, subject: 'History', score: 83"));
assertThat(toArray(collection.aggregate(pipeline))).containsExactly(json("passing_scores: 4"));
}
@Test
public void testAggregateWithFirstAndLast() throws Exception {
Document sort = json("$sort: { item: 1, date: 1 }");
Document group = json("$group: {_id: '$item', firstSale: { $first: '$date' }, lastSale: { $last: '$date'} }");
List<Document> pipeline = Arrays.asList(sort, group);
assertThat(toArray(collection.aggregate(pipeline))).isEmpty();
collection.insertOne(json("_id: 1, item: 'abc', price: 10, quantity: 2").append("date", TestUtils.date("2014-01-01T08:00:00Z")));
collection.insertOne(json("_id: 2, item: 'jkl', price: 20, quantity: 1").append("date", TestUtils.date("2014-02-03T09:00:00Z")));
collection.insertOne(json("_id: 3, item: 'xyz', price: 5, quantity: 5").append("date", TestUtils.date("2014-02-03T09:05:00Z")));
collection.insertOne(json("_id: 4, item: 'abc', price: 10, quantity: 10").append("date", TestUtils.date("2014-02-15T08:00:00Z")));
collection.insertOne(json("_id: 5, item: 'xyz', price: 5, quantity: 10").append("date", TestUtils.date("2014-02-15T09:12:00Z")));
assertThat(toArray(collection.aggregate(pipeline)))
.containsExactlyInAnyOrder(
json("_id: 'abc'").append("firstSale", TestUtils.date("2014-01-01T08:00:00Z")).append("lastSale", TestUtils.date("2014-02-15T08:00:00Z")),
json("_id: 'jkl'").append("firstSale", TestUtils.date("2014-02-03T09:00:00Z")).append("lastSale", TestUtils.date("2014-02-03T09:00:00Z")),
json("_id: 'xyz'").append("firstSale", TestUtils.date("2014-02-03T09:05:00Z")).append("lastSale", TestUtils.date("2014-02-15T09:12:00Z"))
);
}
@Test
public void testAggregateWithPush() throws Exception {
List<Document> pipeline = jsonList("$group: {_id: null, a: {$push: '$a'}, b: {$push: {v: '$b'}}, c: {$push: '$c'}}");
assertThat(toArray(collection.aggregate(pipeline))).isEmpty();
collection.insertOne(json("_id: 1, a: 10, b: 0.1"));
collection.insertOne(json("_id: 2, a: 20, b: 0.2"));
assertThat(toArray(collection.aggregate(pipeline)))
.containsExactly(json("_id: null, a: [10, 20], b: [{v: 0.1}, {v: 0.2}], c: []"));
}
@Test
public void testAggregateWithUndefinedVariable() throws Exception {
List<Document> pipeline = jsonList("$project: {result: '$$UNDEFINED'}");
collection.insertOne(json("_id: 1"));
assertThatExceptionOfType(MongoCommandException.class)
.isThrownBy(() -> collection.aggregate(pipeline).first())
.withMessageContaining("Command failed with error 17276 (Location17276): 'Use of undefined variable: UNDEFINED'");
}
@Test
public void testAggregateWithRootVariable() throws Exception {
List<Document> pipeline = jsonList("$project: {_id: 0, doc: '$$ROOT', a: '$$ROOT.a', a_v: '$$ROOT.a.v'}");
assertThat(toArray(collection.aggregate(pipeline))).isEmpty();
collection.insertOne(json("_id: 1, a: {v: 10}"));
assertThat(toArray(collection.aggregate(pipeline)))
.containsExactly(json("doc: {_id: 1, a: {v: 10}}, a: {v: 10}, a_v: 10"));
}
@Test
public void testAggregateWithRootVariable_IllegalFieldPath() throws Exception {
collection.insertOne(json("_id: 1, x: 10"));
assertThatExceptionOfType(MongoCommandException.class)
.isThrownBy(() -> collection.aggregate(jsonList("$project: {_id: '$$ROOT.a.'}")).first())
.withMessageContaining("Command failed with error 40353 (Location40353): 'FieldPath must not end with a '.'.'");
assertThatExceptionOfType(MongoCommandException.class)
.isThrownBy(() -> collection.aggregate(jsonList("$project: {_id: '$$ROOT.a..1'}")).first())
.withMessageContaining("Command failed with error 15998 (Location15998): 'FieldPath field names may not be empty strings.'");
}
@Test
public void testAggregateWithSetOperations() throws Exception {
List<Document> pipeline = jsonList("$project: {union: {$setUnion: ['$a', '$b']}, diff: {$setDifference: ['$a', '$b']}, intersection: {$setIntersection: ['$a', '$b']}}");
assertThat(toArray(collection.aggregate(pipeline))).isEmpty();
collection.insertOne(json("_id: 1, a: [3, 2, 1]"));
collection.insertOne(json("_id: 2, a: [1.0, -0.0], b: [3, 2, 0]"));
collection.insertOne(json("_id: 3, a: [{a: 0}, {a: 1}], b: [{a: 0.0}, {a: 0.5}]"));
assertThat(toArray(collection.aggregate(pipeline)))
.containsExactlyInAnyOrder(
json("_id: 1, diff: null, intersection: null, union: null"),
json("_id: 2, diff: [1.0], intersection: [-0.0], union: [-0.0, 1.0, 2, 3]"),
json("_id: 3, diff: [{a: 1}], intersection: [{a: 0}], union: [{a: 0}, {a: 0.5}, {a: 1}]")
);
}
@Test
public void testAggregateWithComparisonOperations() throws Exception {
collection.insertOne(json("_id: 1, v: 'abc'"));
collection.insertOne(json("_id: 2, v: null"));
collection.insertOne(json("_id: 3, v: 10"));
collection.insertOne(json("_id: 4, v: [10, 20, 30]"));
collection.insertOne(json("_id: 5, v: ['abc']"));
collection.insertOne(json("_id: 6, v: [30, 40]"));
collection.insertOne(json("_id: 7, v: [5]"));
List<Document> pipeline = jsonList("$project: {cmp1: {$cmp: ['$v', 10]}, cmp2: {$cmp: ['$v', [10]]}}");
Document project;
assertThat(toArray(collection.aggregate(pipeline)))
.containsExactlyInAnyOrder(
json("_id: 1, cmp1: 1, cmp2: -1"),
json("_id: 2, cmp1: -1, cmp2: -1"),
json("_id: 3, cmp1: 0, cmp2: -1"),
json("_id: 4, cmp1: 1, cmp2: 1"),
json("_id: 5, cmp1: 1, cmp2: 1"),
json("_id: 6, cmp1: 1, cmp2: 1"),
json("_id: 7, cmp1: 1, cmp2: -1")
);
project = json("$project: {gt1: {$gt: ['$v', 10]}, gt2: {$gt: ['$v', [10]]}}");
pipeline = Collections.singletonList(project);
assertThat(toArray(collection.aggregate(pipeline)))
.containsExactlyInAnyOrder(
json("_id: 1, gt1: true, gt2: false"),
json("_id: 2, gt1: false, gt2: false"),
json("_id: 3, gt1: false, gt2: false"),
json("_id: 4, gt1: true, gt2: true"),
json("_id: 5, gt1: true, gt2: true"),
json("_id: 6, gt1: true, gt2: true"),
json("_id: 7, gt1: true, gt2: false")
);
project = json("$project: {lt1: {$lt: ['$v', 10]}, lt2: {$lt: ['$v', [10]]}}");
pipeline = Collections.singletonList(project);
assertThat(toArray(collection.aggregate(pipeline)))
.containsExactlyInAnyOrder(
json("_id: 1, lt1: false, lt2: true"),
json("_id: 2, lt1: true, lt2: true"),
json("_id: 3, lt1: false, lt2: true"),
json("_id: 4, lt1: false, lt2: false"),
json("_id: 5, lt1: false, lt2: false"),
json("_id: 6, lt1: false, lt2: false"),
json("_id: 7, lt1: false, lt2: true")
);
}
@Test
public void testAggregateWithSlice() throws Exception {
List<Document> pipeline = jsonList("$project: {name: 1, threeFavorites: {$slice: ['$favorites', 3]}}");
assertThat(toArray(collection.aggregate(pipeline))).isEmpty();
collection.insertOne(json("_id: 1, name: 'dave123', favorites: ['chocolate', 'cake', 'butter', 'apples']"));
collection.insertOne(json("_id: 2, name: 'li', favorites: ['apples', 'pudding', 'pie']"));
collection.insertOne(json("_id: 3, name: 'ahn', favorites: ['pears', 'pecans', 'chocolate', 'cherries']"));
collection.insertOne(json("_id: 4, name: 'ty', favorites: ['ice cream']"));
assertThat(toArray(collection.aggregate(pipeline)))
.containsExactly(
json("_id: 1, name: 'dave123', threeFavorites: ['chocolate', 'cake', 'butter']"),
json("_id: 2, name: 'li', threeFavorites: ['apples', 'pudding', 'pie']"),
json("_id: 3, name: 'ahn', threeFavorites: ['pears', 'pecans', 'chocolate']"),
json("_id: 4, name: 'ty', threeFavorites: ['ice cream']")
);
}
@Test
public void testAggregateWithSplit() throws Exception {
List<Document> pipeline = jsonList("$project: {_id: 1, names: {$split: ['$name', ' ']}}");
assertThat(toArray(collection.aggregate(pipeline))).isEmpty();
collection.insertOne(json("_id: 1, name: 'first document'"));
collection.insertOne(json("_id: 2, name: 'second document'"));
assertThat(toArray(collection.aggregate(pipeline)))
.containsExactly(
json("_id: 1, names: ['first', 'document']"),
json("_id: 2, names: ['second', 'document']")
);
}
@Test
public void testAggregateWithUnwind() throws Exception {
testAggregateWithUnwind(json("$unwind: '$sizes'"));
}
@Test
public void testAggregateWithUnwind_Path() throws Exception {
testAggregateWithUnwind(json("$unwind: {path: '$sizes'}"));
}
private void testAggregateWithUnwind(Document unwind) throws Exception {
List<Document> pipeline = Collections.singletonList(unwind);
assertThat(toArray(collection.aggregate(pipeline))).isEmpty();
collection.insertOne(json("_id: 1, item: 'ABC', sizes: ['S', 'M', 'L']"));
collection.insertOne(json("_id: 2, item: 'EFG', sizes: []"));
collection.insertOne(json("_id: 3, item: 'IJK', sizes: 'M'"));
collection.insertOne(json("_id: 4, item: 'LMN'"));
collection.insertOne(json("_id: 5, item: 'XYZ', sizes: null"));
assertThat(toArray(collection.aggregate(pipeline)))
.containsExactly(
json("_id: 1, item: 'ABC', sizes: 'S'"),
json("_id: 1, item: 'ABC', sizes: 'M'"),
json("_id: 1, item: 'ABC', sizes: 'L'"),
json("_id: 3, item: 'IJK', sizes: 'M'")
);
}
@Test
public void testAggregateWithUnwind_preserveNullAndEmptyArrays() throws Exception {
List<Document> pipeline = jsonList("$unwind: {path: '$sizes', preserveNullAndEmptyArrays: true}");
assertThat(toArray(collection.aggregate(pipeline))).isEmpty();
collection.insertOne(json("_id: 1, item: 'ABC', sizes: ['S', 'M', 'L']"));
collection.insertOne(json("_id: 2, item: 'EFG', sizes: []"));
collection.insertOne(json("_id: 3, item: 'IJK', sizes: 'M'"));
collection.insertOne(json("_id: 4, item: 'LMN'"));
collection.insertOne(json("_id: 5, item: 'XYZ', sizes: null"));
assertThat(toArray(collection.aggregate(pipeline)))
.containsExactly(
json("_id: 1, item: 'ABC', sizes: 'S'"),
json("_id: 1, item: 'ABC', sizes: 'M'"),
json("_id: 1, item: 'ABC', sizes: 'L'"),
json("_id: 2, item: 'EFG'"),
json("_id: 3, item: 'IJK', sizes: 'M'"),
json("_id: 4, item: 'LMN'"),
json("_id: 5, item: 'XYZ', sizes: null")
);
}
@Test
public void testAggregateWithUnwind_IncludeArrayIndex() throws Exception {
List<Document> pipeline = jsonList("$unwind: {path: '$sizes', includeArrayIndex: 'idx'}");
assertThat(toArray(collection.aggregate(pipeline))).isEmpty();
collection.insertOne(json("_id: 1, item: 'ABC', sizes: ['S', 'M', 'L']"));
collection.insertOne(json("_id: 2, item: 'EFG', sizes: []"));
collection.insertOne(json("_id: 3, item: 'IJK', sizes: 'M'"));
collection.insertOne(json("_id: 4, item: 'LMN'"));
collection.insertOne(json("_id: 5, item: 'XYZ', sizes: null"));
assertThat(toArray(collection.aggregate(pipeline)))
.containsExactly(
json("_id: 1, item: 'ABC', sizes: 'S'").append("idx", 0L),
json("_id: 1, item: 'ABC', sizes: 'M'").append("idx", 1L),
json("_id: 1, item: 'ABC', sizes: 'L'").append("idx", 2L),
json("_id: 3, item: 'IJK', sizes: 'M'").append("idx", null)
);
}
@Test
public void testAggregateWithUnwind_IncludeArrayIndex_OverwriteExistingField() throws Exception {
List<Document> pipeline = jsonList("$unwind: {path: '$sizes', includeArrayIndex: 'item'}");
assertThat(toArray(collection.aggregate(pipeline))).isEmpty();
collection.insertOne(json("_id: 1, item: 'ABC', sizes: ['S', 'M', 'L']"));
collection.insertOne(json("_id: 2, item: 'EFG', sizes: []"));
collection.insertOne(json("_id: 3, item: 'IJK', sizes: 'M'"));
collection.insertOne(json("_id: 4, item: 'LMN'"));
collection.insertOne(json("_id: 5, item: 'XYZ', sizes: null"));
assertThat(toArray(collection.aggregate(pipeline)))
.containsExactly(
json("_id: 1, sizes: 'S'").append("item", 0L),
json("_id: 1, sizes: 'M'").append("item", 1L),
json("_id: 1, sizes: 'L'").append("item", 2L),
json("_id: 3, sizes: 'M'").append("item", null)
);
}
@Test
public void testAggregateWithUnwind_IncludeArrayIndex_NestedIndexField() throws Exception {
List<Document> pipeline = jsonList("$unwind: {path: '$sizes', includeArrayIndex: 'item.idx'}");
assertThat(toArray(collection.aggregate(pipeline))).isEmpty();
collection.insertOne(json("_id: 1, item: {value: 'ABC'}, sizes: ['S', 'M', 'L']"));
collection.insertOne(json("_id: 2, item: {value: 'EFG'}, sizes: []"));
collection.insertOne(json("_id: 3, item: {value: 'IJK'}, sizes: 'M'"));
collection.insertOne(json("_id: 4, item: {value: 'LMN'}"));
collection.insertOne(json("_id: 5, item: {value: 'XYZ'}, sizes: null"));
assertThat(toArray(collection.aggregate(pipeline)))
.containsExactly(
json("_id: 1, sizes: 'S'").append("item", json("value: 'ABC'").append("idx", 0L)),
json("_id: 1, sizes: 'M'").append("item", json("value: 'ABC'").append("idx", 1L)),
json("_id: 1, sizes: 'L'").append("item", json("value: 'ABC'").append("idx", 2L)),
json("_id: 3, sizes: 'M'").append("item", json("value: 'IJK'").append("idx", null))
);
}
@Test
public void testAggregateWithUnwind_preserveNullAndEmptyArraysAndIncludeArrayIndex() throws Exception {
List<Document> pipeline = jsonList("$unwind: {path: '$sizes', preserveNullAndEmptyArrays: true, includeArrayIndex: 'idx'}");
assertThat(toArray(collection.aggregate(pipeline))).isEmpty();
collection.insertOne(json("_id: 1, item: 'ABC', sizes: ['S', 'M', 'L']"));
collection.insertOne(json("_id: 2, item: 'EFG', sizes: []"));
collection.insertOne(json("_id: 3, item: 'IJK', sizes: 'M'"));
collection.insertOne(json("_id: 4, item: 'LMN'"));
collection.insertOne(json("_id: 5, item: 'XYZ', sizes: null"));
assertThat(toArray(collection.aggregate(pipeline)))
.containsExactly(
json("_id: 1, item: 'ABC', sizes: 'S'").append("idx", 0L),
json("_id: 1, item: 'ABC', sizes: 'M'").append("idx", 1L),
json("_id: 1, item: 'ABC', sizes: 'L'").append("idx", 2L),
json("_id: 2, item: 'EFG'").append("idx", null),
json("_id: 3, item: 'IJK', sizes: 'M'").append("idx", null),
json("_id: 4, item: 'LMN'").append("idx", null),
json("_id: 5, item: 'XYZ', sizes: null").append("idx", null)
);
}
@Test
public void testAggregateWithLookup() {
MongoCollection<Document> authorsCollection = db.getCollection("authors");
authorsCollection.insertOne(json("_id: 1, name: 'Uncle Bob'"));
authorsCollection.insertOne(json("_id: 2, name: 'Martin Fowler'"));
authorsCollection.insertOne(json("_id: null, name: 'Null Author'"));
List<Document> pipeline = jsonList("$lookup: {from: 'authors', localField: 'authorId', foreignField: '_id', as: 'author'}");
assertThat(collection.aggregate(pipeline)).isEmpty();
collection.insertOne(json("_id: 1, title: 'Refactoring', authorId: 2"));
collection.insertOne(json("_id: 2, title: 'Clean Code', authorId: 1"));
collection.insertOne(json("_id: 3, title: 'Clean Coder', authorId: 1"));
collection.insertOne(json("_id: 4, title: 'Unknown author', authorId: 3"));
collection.insertOne(json("_id: 5, title: 'No author', authorId: null"));
collection.insertOne(json("_id: 6, title: 'Missing author'"));
assertThat(toArray(collection.aggregate(pipeline)))
.containsExactly(
json("_id: 1, title: 'Refactoring', authorId: 2, author: [{_id: 2, name: 'Martin Fowler'}]"),
json("_id: 2, title: 'Clean Code', authorId: 1, author: [{_id: 1, name: 'Uncle Bob'}]"),
json("_id: 3, title: 'Clean Coder', authorId: 1, author: [{_id: 1, name: 'Uncle Bob'}]"),
json("_id: 4, title: 'Unknown author', authorId: 3, author: []"),
json("_id: 5, title: 'No author', authorId: null, author: [{_id: null, name: 'Null Author'}]"),
json("_id: 6, title: 'Missing author', author: [{_id: null, name: 'Null Author'}]")
);
}
@Test
public void testAggregateWithReplaceRoot() {
List<Document> pipeline = jsonList("$replaceRoot: { newRoot: '$a.b' }");
assertThat(collection.aggregate(pipeline)).isEmpty();
collection.insertOne(json("_id: 1, a: { b: { c: 10 } }"));
assertThat(toArray(collection.aggregate(pipeline)))
.containsExactly(json("c: 10"));
}
@Test
public void testAggregateWithIllegalReplaceRoot() {
List<Document> pipeline = jsonList("$replaceRoot: { newRoot: '$a.b' }");
collection.insertOne(json("_id: 1, a: { b: 10 }, c: 123"));
assertThatExceptionOfType(MongoCommandException.class)
.isThrownBy(() -> collection.aggregate(pipeline).first())
.withMessageContaining("Command failed with error 40228 (Location40228): " +
"''newRoot' expression must evaluate to an object, but resulting value was: 10." +
" Type of resulting value: 'int'.")
.withMessageContaining("a: {b: 10}");
}
@Test
public void testAggregateWithProjectingReplaceRoot() {
List<Document> pipeline = jsonList("$replaceRoot: { newRoot: { x: '$a.b' } }");
assertThat(collection.aggregate(pipeline)).isEmpty();
collection.insertOne(json("_id: 1, a: { b: { c: 10 } }"));
assertThat(toArray(collection.aggregate(pipeline)))
.containsExactly(json("x: { c: 10 }"));
}
@Test
public void testAggregateWithMergeObjects() throws Exception {
MongoCollection<Document> orders = db.getCollection("orders");
orders.insertOne(json("_id: 1, item: 'abc', 'price': 12, ordered: 2"));
orders.insertOne(json("_id: 2, item: 'jkl', 'price': 20, ordered: 1"));
MongoCollection<Document> items = db.getCollection("items");
items.insertOne(json("_id: 1, item: 'abc', description: 'product 1', instock: 120"));
items.insertOne(json("_id: 2, item: 'def', description: 'product 2', instock: 80"));
items.insertOne(json("_id: 3, item: 'jkl', description: 'product 3', instock: 60"));
List<Document> pipeline = jsonList(
"$lookup: {from: 'items', localField: 'item', foreignField: 'item', as: 'fromItems'}",
"$replaceRoot: {newRoot: {$mergeObjects: [{$arrayElemAt: ['$fromItems', 0 ]}, '$$ROOT']}}",
"$project: { fromItems: 0 }"
);
assertThat(toArray(orders.aggregate(pipeline)))
.containsExactly(
json("_id: 1, description: 'product 1', instock: 120, item: 'abc', ordered: 2, price: 12"),
json("_id: 2, description: 'product 3', instock: 60, item: 'jkl', ordered: 1, price: 20")
);
}
@Test
public void testAggregateWithSortByCount() throws Exception {
collection.insertOne(json("_id: 1, item: 'abc', 'price': 12, ordered: 2"));
collection.insertOne(json("_id: 2, item: 'jkl', 'price': 20, ordered: 1"));
collection.insertOne(json("_id: 3, item: 'jkl', 'price': 20, ordered: 7"));
collection.insertOne(json("_id: 4, item: 'jkl', 'price': 40, ordered: 3"));
collection.insertOne(json("_id: 5, item: 'abc', 'price': 90, ordered: 5"));
collection.insertOne(json("_id: 6, item: 'zzz'"));
collection.insertOne(json("_id: 7"));
collection.insertOne(json("_id: 8, item: null"));
List<Document> pipeline = jsonList("$sortByCount: '$item'");
assertThat(toArray(collection.aggregate(pipeline)))
.containsExactly(
json("_id: 'jkl', count: 3"),
json("_id: null, count: 2"),
json("_id: 'abc', count: 2"),
json("_id: 'zzz', count: 1")
);
}
@Test
public void testObjectToArrayExpression() throws Exception {
List<Document> pipeline = jsonList("$project: {_id: 1, a: {$objectToArray: '$value'}}");
assertThat(toArray(collection.aggregate(pipeline))).isEmpty();
collection.insertOne(json("_id: 1, value: 1"));
assertThatExceptionOfType(MongoCommandException.class)
.isThrownBy(() -> collection.aggregate(pipeline).first())
.withMessageContaining("Command failed with error 40390 (Location40390): '$objectToArray requires a document input, found: int'");
collection.replaceOne(json("_id: 1"), json("_id: 1, value: {a: 1, b: 'foo', c: {x: 10}}"));
assertThat(toArray(collection.aggregate(pipeline)))
.containsExactly(
json("_id: 1, a: [{k: 'a', v: 1}, {k: 'b', v: 'foo'}, {k: 'c', v: {x: 10}}]")
);
Document illegalQuery = json("$project: {_id: 1, a: {$objectToArray: ['$value', 1]}}");
assertThatExceptionOfType(MongoCommandException.class)
.isThrownBy(() -> collection.aggregate(Collections.singletonList(illegalQuery)).first())
.withMessageContaining("Command failed with error 16020 (Location16020): 'Expression $objectToArray takes exactly 1 arguments. 2 were passed in.'");
}
@Test
public void testArrayToObjectExpression() throws Exception {
collection.insertOne(TestUtils.json("_id: 1, a: 1, b: 'xyz', kv: [['a', 'b'], ['c', 'd']]"));
assertThat(toArray(collection.aggregate(jsonList("$project: {_id: 1, x: {$arrayToObject: {$literal: [['a', 'foo']]}}}"))))
.containsExactly(json("_id: 1, x: {a: 'foo'}"));
assertThat(toArray(collection.aggregate(jsonList("$project: {_id: 1, x: {$arrayToObject: '$kv'}}"))))
.containsExactly(json("_id: 1, x: {a: 'b', c: 'd'}"));
assertThat(toArray(collection.aggregate(jsonList("$project: {_id: 1, x: {$arrayToObject: {$literal: [{k: 'k1', v: 'v1'}, {k: 'k2', v: 'v2'}]}}}"))))
.containsExactly(json("_id: 1, x: {k1: 'v1', k2: 'v2'}"));
assertThat(toArray(collection.aggregate(jsonList("$project: {_id: 1, x: {$arrayToObject: {$literal: [{k: 'k1', v: 'v1'}, {k: 'k1', v: 'v2'}]}}}"))))
.containsExactly(json("_id: 1, x: {k1: 'v2'}"));
assertThatExceptionOfType(MongoCommandException.class)
.isThrownBy(() -> collection.aggregate(jsonList("$project: {_id: 1, x: {$arrayToObject: 'illegal-type'}}")).first())
.withMessageContaining("Command failed with error 40386 (Location40386): '$arrayToObject requires an array input, found: string'");
assertThatExceptionOfType(MongoCommandException.class)
.isThrownBy(() -> collection.aggregate(jsonList("$project: {_id: 1, x: {$arrayToObject: []}}")).first())
.withMessageContaining("Command failed with error 16020 (Location16020): 'Expression $arrayToObject takes exactly 1 arguments. 0 were passed in.'");
assertThatExceptionOfType(MongoCommandException.class)
.isThrownBy(() -> collection.aggregate(jsonList("$project: {_id: 1, x: {$arrayToObject: {$literal: [['foo']]}}}}")).first())
.withMessageContaining("Command failed with error 40397 (Location40397): '$arrayToObject requires an array of size 2 arrays,found array of size: 1'");
assertThatExceptionOfType(MongoCommandException.class)
.isThrownBy(() -> collection.aggregate(jsonList("$project: {_id: 1, x: {$arrayToObject: {$literal: [123, 456]}}}}")).first())
.withMessageContaining("Command failed with error 40398 (Location40398): 'Unrecognised input type format for $arrayToObject: int'");
assertThatExceptionOfType(MongoCommandException.class)
.isThrownBy(() -> collection.aggregate(jsonList("$project: {_id: 1, x: {$arrayToObject: {$literal: [[123, 456]]}}}}")).first())
.withMessageContaining("Command failed with error 40395 (Location40395): '$arrayToObject requires an array of key-value pairs, where the key must be of type string. Found key type: int'");
assertThatExceptionOfType(MongoCommandException.class)
.isThrownBy(() -> collection.aggregate(jsonList("$project: {_id: 1, x: {$arrayToObject: {$literal: [{}]}}}}")).first())
.withMessageContaining("Command failed with error 40392 (Location40392): '$arrayToObject requires an object keys of 'k' and 'v'. Found incorrect number of keys:0'");
assertThatExceptionOfType(MongoCommandException.class)
.isThrownBy(() -> collection.aggregate(jsonList("$project: {_id: 1, x: {$arrayToObject: {$literal: [{k: 123, v: 'value'}]}}}}")).first())
.withMessageContaining("Command failed with error 40394 (Location40394): '$arrayToObject requires an object with keys 'k' and 'v', where the value of 'k' must be of type string. Found type: int'");
assertThatExceptionOfType(MongoCommandException.class)
.isThrownBy(() -> collection.aggregate(jsonList("$project: {_id: 1, x: {$arrayToObject: {$literal: [{k: 'key', z: 'value'}]}}}}")).first())
.withMessageContaining("Command failed with error 40393 (Location40393): '$arrayToObject requires an object with keys 'k' and 'v'. Missing either or both keys from: {k: \"key\", z: \"value\"}'");
}
}
|
package com.cognifide.aet.executor.model;
import org.junit.Test;
import java.util.Collections;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
public class TestSuiteRunTest {
@Test
public void constructor_whenOverridingNameAndDomain_expectUpdatedValues() {
String company = "company";
String project = "project";
String name = "abcd";
String domain = "ijkl";
TestSuiteRun baseSuiteRun = new TestSuiteRun(name, company, project, domain, Collections.emptyList());
String newName = "efgh";
String newDomain = "mnop";
TestSuiteRun updatedSuiteRun = new TestSuiteRun(baseSuiteRun, newName, newDomain, Collections.emptyList());
String correlationRegex = String.format("^%s-%s-%s-[0-9]*$", company, project, newName);
assertThat(updatedSuiteRun.getName(), equalTo(newName));
assertThat(updatedSuiteRun.getDomain(), equalTo(newDomain));
assertThat(updatedSuiteRun.getCorrelationId(), updatedSuiteRun.getCorrelationId().matches(correlationRegex));
}
}
|
package org.openlmis.pageobjects;
import com.thoughtworks.selenium.SeleneseTestNgHelper;
import org.openlmis.UiUtils.TestWebDriver;
import org.openqa.selenium.ElementNotVisibleException;
import org.openqa.selenium.Keys;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.pagefactory.AjaxElementLocatorFactory;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import static com.thoughtworks.selenium.SeleneseTestBase.assertFalse;
import static com.thoughtworks.selenium.SeleneseTestBase.assertTrue;
import static com.thoughtworks.selenium.SeleneseTestNgHelper.assertEquals;
public class UserPage extends Page {
@FindBy(how = How.ID, using = "user-add-new")
private static WebElement addNewButton = null;
@FindBy(how = How.ID, using = "userName")
private static WebElement userNameField = null;
@FindBy(how = How.ID, using = "email")
private static WebElement emailField = null;
@FindBy(how = How.ID, using = "firstName")
private static WebElement firstNameField = null;
@FindBy(how = How.ID, using = "lastName")
private static WebElement lastNameField = null;
@FindBy(how = How.XPATH, using = "//input[1][@class='btn btn-primary save-button']")
private static WebElement saveButton = null;
@FindBy(how = How.XPATH, using = "//input[2][@class='btn btn-cancel cancel-button']")
private static WebElement cancelButton = null;
@FindBy(how = How.XPATH, using = "//input[@class='btn btn-danger delete-button']")
private static WebElement disableButton = null;
@FindBy(how = How.XPATH, using = "//input[@class='btn btn-primary enable-button']")
private static WebElement enableButton = null;
@FindBy(how = How.ID, using = "searchUser")
private static WebElement searchUserTextField = null;
@FindBy(how = How.XPATH, using = "//ul[@id='userList']/li/div[@class='user-actions']/a[2]")
private static WebElement selectFirstResetPassword = null;
@FindBy(how = How.ID, using = "password1")
private static WebElement newPasswordField = null;
@FindBy(how = How.ID, using = "password2")
private static WebElement confirmPasswordField = null;
@FindBy(how = How.XPATH, using = "//div[@id='changePassword']/div/input[1]")
private static WebElement resetPasswordDone = null;
@FindBy(how = How.LINK_TEXT, using = "OK")
private static WebElement okButton = null;
@FindBy(how = How.ID, using = "user0")
private static WebElement firstUserLink = null;
@FindBy(how = How.XPATH, using = "//a[@ng-click='editUser(user.id)']")
private static WebElement selectFirstEditUser = null;
@FindBy(how = How.XPATH, using = "//h2[contains(text(),'Edit User')]")
private static WebElement editUserHeader = null;
@FindBy(how = How.ID, using = "searchFacility")
private static WebElement searchFacility = null;
@FindBy(how = How.XPATH, using = "//a[@ng-click='setSelectedFacility(facility)']")
private static WebElement selectFacility = null;
@FindBy(how = How.XPATH, using = "//form[@id='create-user']/div/div[1]/div[7]/div/ng-switch/span")
private static WebElement verifiedLabel = null;
@FindBy(how = How.XPATH, using = "//div[1][@class='pull-right control-accordion']/a[1]")
private static WebElement expandAllOption = null;
@FindBy(how = How.XPATH, using = "//div[1][@class='pull-right control-accordion']/a[2]")
private static WebElement collapseAllOption = null;
@FindBy(how = How.XPATH, using = "//a[contains(text(),'Home Facility Roles')]")
private static WebElement homeFacilityRolesAccordion = null;
@FindBy(how = How.XPATH, using = "//select[@ng-model='programSelected']")
private static WebElement homeFacilityPrograms = null;
@FindBy(how = How.XPATH, using = "(//input[@type='text'])[12]")
private static WebElement roleInputFieldHomeFacility = null;
@FindBy(how = How.XPATH, using = "//div[@class='select2-result-label']/span")
private static WebElement rolesSelectFieldHomeFacility = null;
@FindBy(how = How.XPATH, using = "//input[@ng-click='addHomeFacilityRole()']")
private static WebElement addHomeFacilityRolesButton = null;
@FindBy(how = How.XPATH, using = "//a[contains(text(),'Supervisory Roles')]")
private static WebElement supervisoryRolesAccordion = null;
@FindBy(how = How.XPATH, using = "//select[@ng-model='selectedProgramIdToSupervise']")
private static WebElement programsToSupervise = null;
@FindBy(how = How.XPATH, using = "//select[@ng-model='selectedSupervisoryNodeIdToSupervise']")
private static WebElement supervisoryNodeToSupervise = null;
@FindBy(how = How.XPATH, using = "(//input[@type='text'])[14]")
private static WebElement rolesInputFieldSupervisoryRole = null;
@FindBy(how = How.XPATH, using = "//div[@class='select2-result-label']/span")
private static WebElement rolesSelectFieldSupervisoryRole = null;
@FindBy(how = How.XPATH, using = "//input[@ng-click='addSupervisoryRole()']")
private static WebElement addSupervisoryRoleButton = null;
@FindBy(how = How.XPATH, using = "//a[contains(text(),'Warehouse Roles')]")
private static WebElement warehouseRolesAccordion = null;
@FindBy(how = How.XPATH, using = "(//input[@type='text'])[16]")
private static WebElement rolesInputFieldWarehouse = null;
@FindBy(how = How.XPATH, using = "//div[@class='select2-result-label']/span")
private static WebElement rolesSelectFieldWarehouse = null;
@FindBy(how = How.XPATH, using = "//select[@ng-model='warehouseRole.facilityId']")
private static WebElement warehouseToSelect = null;
@FindBy(how = How.XPATH, using = "//input[@ng-click='addFulfillmentRole()']")
private static WebElement addWarehouseRoleButton = null;
@FindBy(how = How.XPATH, using = "//a[contains(text(),'Delivery zones')]")
private static WebElement deliveryZonesAccordion = null;
@FindBy(how = How.XPATH, using = "//select[@name='selectDeliveryZone']")
private static WebElement zoneToDelivery = null;
@FindBy(how = How.XPATH, using = "//select[@name='selectDeliveryZoneProgram']")
private static WebElement programToDeliver = null;
@FindBy(how = How.XPATH, using = "(//input[@type='text'])[18]")
private static WebElement rolesInputFieldMDeliveryZone = null;
@FindBy(how = How.XPATH, using = "(//input[@type='text'])[15]")
private static WebElement rolesInputFieldDeliveryZone = null;
@FindBy(how = How.XPATH, using = "//input[@ng-click='addAllocationRole()']")
private static WebElement addDeliveryZoneRoleButton = null;
@FindBy(how = How.XPATH, using = "//a[contains(text(),'Admin and General Operations Roles')]")
private static WebElement adminAndGeneralOperationsRolesAccordion = null;
@FindBy(how = How.XPATH, using = "(//input[@type='text'])[17]")
private static WebElement adminRolesInputField = null;
@FindBy(how = How.LINK_TEXT, using = "View Here")
private static WebElement viewHereLink = null;
@FindBy(how = How.XPATH, using = "//div[@id='saveSuccessMsgDiv']")
private static WebElement userUpdateSuccessMessage = null;
@FindBy(how = How.XPATH, using = "//div[@id='saveSuccessMsgDiv']")
private static WebElement successMessage = null;
@FindBy(how = How.XPATH, using = "//input[contains(text(),'Remove')]")
private static WebElement removeButton = null;
@FindBy(how = How.XPATH, using = "//div[6]/div[2]/ng-include/div/div[1]/div[2]/div[1]/div/label[@class='ng-binding']")
private static WebElement addedDeliveryZoneLabel = null;
@FindBy(how = How.XPATH, using = "//a[contains(text(),'No matches found for')]")
private static WebElement noMatchFoundLink = null;
@FindBy(how = How.XPATH, using = "//div[@class='form-field radio-group']/input[1]")
private static WebElement restrictLoginYesOption = null;
@FindBy(how = How.XPATH, using = "//div[@class='form-field radio-group']/input[2]")
private static WebElement restrictLoginNoOption = null;
@FindBy(how = How.ID, using = "resetPasswordOk")
private static WebElement resetPasswordOkButton = null;
public UserPage(TestWebDriver driver) throws IOException {
super(driver);
PageFactory.initElements(new AjaxElementLocatorFactory(TestWebDriver.getDriver(), 1), this);
testWebDriver.setImplicitWait(1);
}
public void searchUser(String user) {
testWebDriver.waitForElementToAppear(searchUserTextField);
sendKeys(searchUserTextField, user);
}
public void clickUserList() {
testWebDriver.waitForElementToAppear(firstUserLink);
firstUserLink.click();
testWebDriver.waitForElementToAppear(userNameField);
}
public void focusOnFirstUserLink() {
testWebDriver.waitForElementToAppear(firstUserLink);
testWebDriver.moveToElement(firstUserLink);
testWebDriver.waitForElementToAppear(selectFirstEditUser);
}
public void clickEditUser() {
testWebDriver.waitForElementToAppear(selectFirstEditUser);
selectFirstEditUser.click();
}
public void verifyUserOnList(String userString) {
testWebDriver.waitForElementToAppear(firstUserLink);
assertTrue("User not available in list.", firstUserLink.getText().contains(userString));
}
public void verifyDisabledResetPassword() {
testWebDriver.waitForElementToAppear(firstUserLink);
assertTrue("Reset password link not disabled.", selectFirstResetPassword.getAttribute("class").contains("disabled"));
}
public void resetPassword(String newPassword, String confirmPassword) {
firstUserLink.sendKeys(Keys.TAB);
selectFirstEditUser.sendKeys(Keys.TAB);
testWebDriver.waitForElementToBeEnabled(selectFirstResetPassword);
selectFirstResetPassword.click();
testWebDriver.waitForElementToAppear(newPasswordField);
newPasswordField.sendKeys(newPassword);
confirmPasswordField.sendKeys(confirmPassword);
testWebDriver.waitForElementToBeEnabled(resetPasswordDone);
resetPasswordDone.click();
testWebDriver.waitForElementToBeEnabled(resetPasswordOkButton);
resetPasswordOkButton.click();
}
public void enterUserDetails(String userName, String email, String firstName, String lastName)
throws IOException, SQLException {
testWebDriver.waitForElementToAppear(addNewButton);
addNewButton.click();
testWebDriver.waitForElementToAppear(userNameField);
userNameField.clear();
userNameField.sendKeys(userName);
testWebDriver.waitForElementToAppear(emailField);
emailField.clear();
emailField.sendKeys(email);
testWebDriver.waitForElementToAppear(firstNameField);
firstNameField.clear();
firstNameField.sendKeys(firstName);
testWebDriver.waitForElementToAppear(lastNameField);
lastNameField.clear();
lastNameField.sendKeys(lastName);
testWebDriver.handleScroll();
clickRestrictLoginNo();
testWebDriver.waitForElementToAppear(saveButton);
saveButton.click();
testWebDriver.waitForElementToAppear(viewHereLink);
}
public void verifyUserCreated(String firstName, String lastName)
throws IOException, SQLException {
testWebDriver.waitForElementToAppear(successMessage);
String expectedMessage = String.format("User \"%s %s\" has been successfully created," +
" password link has been sent on registered Email address. View Here", firstName, lastName);
assertEquals(expectedMessage, successMessage.getText());
}
public void enterUserHomeFacility(String facilityCode) {
searchFacility.clear();
testWebDriver.handleScrollByPixels(0, 5000);
searchFacility.sendKeys(facilityCode);
for (int i = 0; i < facilityCode.length(); i++) {
searchFacility.sendKeys(Keys.ARROW_LEFT);
searchFacility.sendKeys(Keys.DELETE);
}
searchFacility.sendKeys(facilityCode);
}
public void verifyNoMatchedFoundMessage() {
SeleneseTestNgHelper.assertTrue("No match found link should show up", noMatchFoundLink.isDisplayed());
}
public void ExpandAll() {
testWebDriver.waitForElementToBeEnabled(expandAllOption);
expandAllOption.click();
}
public void collapseAll() {
testWebDriver.waitForElementToBeEnabled(collapseAllOption);
collapseAllOption.click();
}
public void clickRestrictLoginYes() {
testWebDriver.waitForElementToBeEnabled(restrictLoginYesOption);
restrictLoginYesOption.click();
}
public void clickRestrictLoginNo() {
testWebDriver.waitForElementToBeEnabled(restrictLoginNoOption);
restrictLoginNoOption.click();
}
public void verifyExpandAll() {
assertTrue(programsToSupervise.isDisplayed());
assertTrue(programToDeliver.isDisplayed());
}
public void verifyCollapseAll() {
assertFalse(programsToSupervise.isDisplayed());
assertFalse(programToDeliver.isDisplayed());
assertFalse(warehouseToSelect.isDisplayed());
}
public void enterMyFacilityAndMySupervisedFacilityData(String facilityCode, String program1, String node, String role, String roleType) {
testWebDriver.waitForElementToAppear(searchFacility);
if (!roleType.equals("ADMIN")) {
enterUserHomeFacility(facilityCode);
testWebDriver.waitForElementToBeEnabled(selectFacility);
selectFacility.click();
testWebDriver.waitForElementToBeEnabled(homeFacilityRolesAccordion);
homeFacilityRolesAccordion.click();
testWebDriver.selectByVisibleText(homeFacilityPrograms, program1);
testWebDriver.waitForElementToAppear(roleInputFieldHomeFacility);
roleInputFieldHomeFacility.click();
roleInputFieldHomeFacility.clear();
roleInputFieldHomeFacility.sendKeys(role);
testWebDriver.waitForElementToAppear(rolesSelectFieldHomeFacility);
rolesSelectFieldHomeFacility.click();
addHomeFacilityRolesButton.click();
testWebDriver.waitForElementToAppear(supervisoryRolesAccordion);
supervisoryRolesAccordion.click();
testWebDriver.waitForElementToAppear(programsToSupervise);
testWebDriver.selectByVisibleText(programsToSupervise, program1);
testWebDriver.waitForElementToAppear(supervisoryNodeToSupervise);
testWebDriver.selectByVisibleText(supervisoryNodeToSupervise, node);
testWebDriver.sleep(1000);
testWebDriver.handleScroll();
testWebDriver.waitForElementToBeEnabled(rolesInputFieldSupervisoryRole);
rolesInputFieldSupervisoryRole.click();
rolesInputFieldSupervisoryRole.clear();
rolesInputFieldSupervisoryRole.sendKeys(role);
testWebDriver.waitForElementToAppear(rolesSelectFieldSupervisoryRole);
rolesSelectFieldSupervisoryRole.click();
assertEquals(testWebDriver.getFirstSelectedOption(supervisoryNodeToSupervise).getText(), node);
assertEquals(testWebDriver.getFirstSelectedOption(programsToSupervise).getText(), program1);
testWebDriver.waitForElementToBeEnabled(addSupervisoryRoleButton);
addSupervisoryRoleButton.click();
} else {
testWebDriver.handleScroll();
testWebDriver.waitForElementToBeEnabled(adminAndGeneralOperationsRolesAccordion);
adminAndGeneralOperationsRolesAccordion.click();
testWebDriver.waitForElementToBeEnabled(adminRolesInputField);
adminRolesInputField.click();
adminRolesInputField.clear();
adminRolesInputField.sendKeys(role);
testWebDriver.waitForElementToAppear(rolesSelectFieldSupervisoryRole);
rolesSelectFieldSupervisoryRole.click();
}
}
public void saveUser() {
testWebDriver.waitForElementToBeEnabled(saveButton);
saveButton.click();
}
public void verifyUserUpdated(String firstName, String lastName) {
testWebDriver.sleep(1000);
assertTrue("User '" + firstName + " " + lastName + "' has been successfully updated message is not getting displayed",
successMessage.isDisplayed());
}
public void assignWarehouse(String warehouse, String role) {
testWebDriver.waitForElementToBeEnabled(warehouseRolesAccordion);
warehouseRolesAccordion.click();
testWebDriver.waitForElementToAppear(warehouseToSelect);
testWebDriver.selectByVisibleText(warehouseToSelect, warehouse);
testWebDriver.waitForElementToAppear(rolesInputFieldWarehouse);
rolesInputFieldWarehouse.click();
rolesInputFieldWarehouse.clear();
rolesInputFieldWarehouse.sendKeys(role);
testWebDriver.waitForElementToAppear(rolesSelectFieldWarehouse);
rolesSelectFieldSupervisoryRole.click();
assertEquals(testWebDriver.getFirstSelectedOption(warehouseToSelect).getText(), warehouse);
testWebDriver.waitForElementToBeEnabled(addWarehouseRoleButton);
addWarehouseRoleButton.click();
testWebDriver.sleep(1000);
verifyWarehouseSelectedNotAvailable(warehouse);
testWebDriver.waitForElementToBeEnabled(warehouseRolesAccordion);
warehouseRolesAccordion.click();
}
public void verifyMessage(String message) {
testWebDriver.waitForElementToAppear(userUpdateSuccessMessage);
assertEquals(userUpdateSuccessMessage.getText(), message);
}
public void enterDeliveryZoneData(String deliveryZoneCode, String program, String role) {
testWebDriver.handleScroll();
testWebDriver.getElementByXpath("//a[contains(text(),'Delivery zones')]").click();
testWebDriver.waitForElementToAppear(zoneToDelivery);
testWebDriver.selectByVisibleText(zoneToDelivery, deliveryZoneCode);
testWebDriver.waitForElementToAppear(programToDeliver);
testWebDriver.selectByVisibleText(programToDeliver, program);
testWebDriver.waitForElementToBeEnabled(rolesInputFieldMDeliveryZone);
rolesInputFieldMDeliveryZone.click();
rolesInputFieldMDeliveryZone.clear();
rolesInputFieldMDeliveryZone.sendKeys(role);
rolesInputFieldMDeliveryZone.sendKeys(Keys.RETURN);
addDeliveryZoneRoleButton.click();
}
public void enterDeliveryZoneDataWithoutHomeAndSupervisoryRolesAssigned(String deliveryZoneCode, String program, String role) {
testWebDriver.handleScroll();
deliveryZonesAccordion.click();
testWebDriver.waitForElementToAppear(zoneToDelivery);
testWebDriver.selectByVisibleText(zoneToDelivery, deliveryZoneCode);
testWebDriver.waitForElementToAppear(programToDeliver);
testWebDriver.selectByVisibleText(programToDeliver, program);
testWebDriver.waitForElementToAppear(rolesInputFieldDeliveryZone);
rolesInputFieldDeliveryZone.click();
rolesInputFieldDeliveryZone.clear();
rolesInputFieldDeliveryZone.sendKeys(role);
rolesInputFieldDeliveryZone.sendKeys(Keys.RETURN);
testWebDriver.waitForElementToBeEnabled(addDeliveryZoneRoleButton);
addDeliveryZoneRoleButton.click();
}
public void removeRole(int indexOfCancelIcon, boolean adminRole) {
int counter = 1;
List<WebElement> closeButtons = testWebDriver.getElementsByXpath("//a[@class='select2-search-choice-close']");
for (WebElement closeButton : closeButtons) {
if (counter == indexOfCancelIcon) {
closeButton.click();
if (adminRole)
clickOk();
testWebDriver.sleep(100);
counter++;
}
}
}
public void clickCancelButton() {
testWebDriver.waitForElementToAppear(cancelButton);
cancelButton.click();
}
public void clickSaveButton() {
testWebDriver.waitForElementToAppear(saveButton);
saveButton.click();
}
public void clickDisableButton() {
testWebDriver.waitForElementToAppear(disableButton);
disableButton.click();
clickOk();
}
public void clickEnableButton() {
testWebDriver.waitForElementToAppear(enableButton);
enableButton.click();
clickOk();
}
public void verifyRolePresent(String roleName) {
testWebDriver.sleep(500);
WebElement roleElement = testWebDriver.getElementByXpath("//div[contains(text(),'" + roleName + "')]");
assertTrue(roleName + " should be displayed", roleElement.isDisplayed());
}
public void verifyRoleNotPresent(String roleName) {
boolean rolePresent;
try {
testWebDriver.sleep(500);
WebElement element = testWebDriver.getElementByXpath("//div[contains(text(),'" + roleName + "')]");
rolePresent = element.isDisplayed();
} catch (ElementNotVisibleException e) {
rolePresent = false;
} catch (NoSuchElementException e) {
rolePresent = false;
}
assertFalse(rolePresent);
}
public String getAllProgramsToSupervise() {
testWebDriver.waitForElementToAppear(programsToSupervise);
return programsToSupervise.getText();
}
public String getAllProgramsHomeFacility() {
testWebDriver.waitForElementToAppear(homeFacilityPrograms);
return homeFacilityPrograms.getText();
}
public String getAllWarehouseToSelect() {
testWebDriver.waitForElementToAppear(warehouseToSelect);
return warehouseToSelect.getText();
}
public void clickViewHere() {
testWebDriver.waitForElementToAppear(viewHereLink);
viewHereLink.click();
testWebDriver.waitForElementToAppear(editUserHeader);
}
public void clickOk() {
testWebDriver.waitForElementToAppear(okButton);
okButton.click();
}
public void verifyRemoveNotPresent() {
boolean removePresent;
try {
testWebDriver.sleep(500);
removeButton.isDisplayed();
removePresent = true;
} catch (ElementNotVisibleException e) {
removePresent = false;
} catch (NoSuchElementException e) {
removePresent = false;
}
assertFalse(removePresent);
}
public void clickRemoveButtonWithOk(int removeButtonNumber) {
testWebDriver.sleep(500);
testWebDriver.getElementByXpath("(//input[@value='Remove'])[" + removeButtonNumber + "]").click();
clickOk();
}
public String getAddedDeliveryZoneLabel() {
testWebDriver.waitForElementToAppear(addedDeliveryZoneLabel);
return addedDeliveryZoneLabel.getText();
}
public String getVerifiedLabel() {
testWebDriver.waitForElementToAppear(verifiedLabel);
return verifiedLabel.getText();
}
public void clickWarehouseRolesAccordion() {
testWebDriver.waitForElementToAppear(warehouseRolesAccordion);
warehouseRolesAccordion.click();
}
public void clickHomeFacilityRolesAccordion() {
testWebDriver.waitForElementToAppear(homeFacilityRolesAccordion);
homeFacilityRolesAccordion.click();
}
public void clickSupervisoryRolesAccordion() {
testWebDriver.waitForElementToAppear(supervisoryRolesAccordion);
supervisoryRolesAccordion.click();
}
public void clickDeliveryZonesAccordion() {
testWebDriver.waitForElementToAppear(deliveryZonesAccordion);
deliveryZonesAccordion.click();
}
private void verifyWarehouseSelectedNotAvailable(String warehouse1) {
assertFalse(getAllWarehouseToSelect().contains(warehouse1));
}
public void clickEditUserButton() {
focusOnFirstUserLink();
testWebDriver.waitForElementToAppear(selectFirstEditUser);
selectFirstEditUser.click();
}
}
|
package com.psddev.dari.db;
import org.slf4j.Logger;
import com.psddev.dari.util.ObjectUtils;
import com.psddev.dari.util.Settings;
import com.psddev.dari.util.SettingsException;
/** Represents an application. */
@Record.Abstract
public class Application extends Record {
/** Specifies the class name used to determine the main application. */
public static final String MAIN_CLASS_SETTING = "dari/mainApplicationClass";
@Indexed
private String name;
private String url;
/** Returns the name. */
public String getName() {
return name;
}
/** Sets the name. */
public void setName(String name) {
this.name = name;
}
/** Returns the URL. */
public String getUrl() {
return url;
}
/** Sets the URL. */
public void setUrl(String url) {
this.url = url;
}
/**
* Initializes the application, and writes any messages to the given
* {@code logger}. By default, this method does nothing, so the
* subclasses are expected to override it to provide the desired behavior.
*/
public void initialize(Logger logger) throws Exception {
}
/** {@linkplain Application Application} utility methods. */
public final static class Static {
private Static() {
}
/**
* Returns the singleton application object matching the given
* {@code applicationClass} within the given {@code database}.
*/
@SuppressWarnings("unchecked")
public static <T extends Application> T getInstanceUsing(
Class<T> applicationClass,
Database database) {
ObjectType type = database.getEnvironment().getTypeByClass(applicationClass);
Query<T> query = Query.from(applicationClass).where("_type = ?", type.getId()).using(database);
query.as(CachingDatabase.QueryOptions.class).setDisabled(true);
T app = query.first();
if (app == null) {
DistributedLock lock = DistributedLock.Static.getInstance(database, applicationClass.getName());
lock.lock();
try {
app = query.first();
if (app == null) {
app = (T) type.createObject(null);
app.setName(type.getDisplayName());
app.saveImmediately();
return app;
}
} finally {
lock.unlock();
}
}
String oldName = app.getName();
String newName = type.getDisplayName();
if (!ObjectUtils.equals(oldName, newName)) {
app.setName(newName);
app.save();
}
return app;
}
/**
* Returns the singleton application object matching the given
* {@code applicationClass} within the {@linkplain
* Database.Static#getDefault default database}.
*/
public static <T extends Application> T getInstance(Class<T> applicationClass) {
return getInstanceUsing(applicationClass, Database.Static.getDefault());
}
/**
* Returns the main application object as determined by the
* {@value com.psddev.dari.db.Application#MAIN_CLASS_SETTING}
* {@linkplain Settings#get setting} within the given
* {@code database}.
*
* @return May be {@code null} if the setting is not set.
* @throws SettingsException If the class name in the setting is not valid.
*/
public static Application getMainUsing(Database database) {
String appClassName = Settings.get(String.class, MAIN_CLASS_SETTING);
if (ObjectUtils.isBlank(appClassName)) {
return null;
}
Class<?> objectClass = ObjectUtils.getClassByName(appClassName);
if (objectClass == null) {
throw new SettingsException(MAIN_CLASS_SETTING, String.format(
"[%s] is not a valid class name!", appClassName));
}
if (Application.class.isAssignableFrom(objectClass)) {
@SuppressWarnings("unchecked")
Class<? extends Application> appClass = (Class<? extends Application>) objectClass;
return getInstanceUsing(appClass, database);
} else {
throw new SettingsException(MAIN_CLASS_SETTING, String.format(
"[%s] is not a [%s] class!", appClassName,
Application.class.getName()));
}
}
/**
* Returns the main application object as determined by the
* {@value com.psddev.dari.db.Application#MAIN_CLASS_SETTING}
* {@linkplain Settings#get setting} within the
* {@linkplain Database.Static#getDefault default database}.
*
* @return May be {@code null} if the setting is not set.
* @throws SettingsException If the class name in the setting is not valid.
*/
public static Application getMain() {
return getMainUsing(Database.Static.getDefault());
}
}
}
|
package ru.job4j.calculator;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Test.
*
* @author Aleksey Kosolapov.
* @since 12.03.17.
* @version 0.1.
*/
public class CalculatorTest {
/**
* Test add.
*/
@Test
public void whenAddOnePlusOneThenTwo() {
Calculator calc = new Calculator();
calc.add(1D, 1D);
double result = calc.getResult();
double expected = 2D;
assertThat(result, is(expected));
}
/**
* Test substruct.
*/
@Test
public void whenSubstructNeneMinusTwoThenSeven() {
Calculator calc = new Calculator();
calc.substruct(9D, 2D);
double result = calc.getResult();
double expected = 7D;
assertThat(result, is(expected));
}
/**
* Test div.
*/
@Test
public void whenDivEightDivideTwoThenFour() {
Calculator calc = new Calculator();
calc.div(8D, 2D);
double result = calc.getResult();
double expected = 4D;
assertThat(result, is(expected));
}
/**
* Test multiple.
*/
@Test
public void whenMultipleThreeMultiplyFourThenTwelve() {
Calculator calc = new Calculator();
calc.multiple(3D, 4D);
double result = calc.getResult();
double expected = 12D;
assertThat(result, is(expected));
}
}
|
package hudson;
import hudson.model.*;
import hudson.util.Service;
import java.util.Enumeration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.FileItem;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.QueryParameter;
/**
* Manages {@link PluginWrapper}s.
*
* @author Kohsuke Kawaguchi
*/
public final class PluginManager extends AbstractModelObject {
/**
* All discovered plugins.
*/
private final List<PluginWrapper> plugins = new ArrayList<PluginWrapper>();
/**
* All active plugins.
*/
private final List<PluginWrapper> activePlugins = new ArrayList<PluginWrapper>();
private final List<FailedPlugin> failedPlugins = new ArrayList<FailedPlugin>();
/**
* Plug-in root directory.
*/
public final File rootDir;
public final ServletContext context;
/**
* {@link ClassLoader} that can load all the publicly visible classes from plugins
* (and including the classloader that loads Hudson itself.)
*
*/
// and load plugin-contributed classes.
public final ClassLoader uberClassLoader = new UberClassLoader();
/**
* Once plugin is uploaded, this flag becomes true.
* This is used to report a message that Hudson needs to be restarted
* for new plugins to take effect.
*/
public volatile boolean pluginUploaded =false;
public PluginManager(ServletContext context) {
this.context = context;
rootDir = new File(Hudson.getInstance().getRootDir(),"plugins");
if(!rootDir.exists())
rootDir.mkdirs();
File[] archives = rootDir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".hpi") // plugin jar file
|| name.endsWith(".hpl"); // linked plugin. for debugging.
}
});
if(archives==null) {
LOGGER.severe("Hudson is unable to create "+rootDir+"\nPerhaps its security privilege is insufficient");
return;
}
for( File arc : archives ) {
try {
PluginWrapper p = new PluginWrapper(this,arc);
plugins.add(p);
if(p.isActive())
activePlugins.add(p);
} catch (IOException e) {
failedPlugins.add(new FailedPlugin(arc.getName(),e));
LOGGER.log(Level.SEVERE, "Failed to load a plug-in " + arc, e);
}
}
for (PluginWrapper p : activePlugins.toArray(new PluginWrapper[0]))
try {
p.load(this);
} catch (IOException e) {
failedPlugins.add(new FailedPlugin(p.getShortName(),e));
LOGGER.log(Level.SEVERE, "Failed to load a plug-in " + p.getShortName(), e);
activePlugins.remove(p);
plugins.remove(p);
}
}
/**
* Retrurns true if any new plugin was added, which means a restart is required for the change to take effect.
*/
public boolean isPluginUploaded() {
return pluginUploaded;
}
public List<PluginWrapper> getPlugins() {
return plugins;
}
public List<FailedPlugin> getFailedPlugins() {
return failedPlugins;
}
public PluginWrapper getPlugin(String shortName) {
for (PluginWrapper p : plugins) {
if(p.getShortName().equals(shortName))
return p;
}
return null;
}
public String getDisplayName() {
return "Plugin Manager";
}
public String getSearchUrl() {
return "pluginManager";
}
/**
* Discover all the service provider implementations of the given class,
* via <tt>META-INF/services</tt>.
*/
public <T> Collection<Class<? extends T>> discover( Class<T> spi ) {
Set<Class<? extends T>> result = new HashSet<Class<? extends T>>();
for (PluginWrapper p : activePlugins) {
Service.load(spi, p.classLoader, result);
}
return result;
}
/**
* Orderly terminates all the plugins.
*/
public void stop() {
for (PluginWrapper p : activePlugins) {
p.stop();
}
// Work around a bug in commons-logging.
LogFactory.release(uberClassLoader);
}
/**
* Performs the installation of the plugins.
*/
public void doInstall(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
Enumeration<String> en = req.getParameterNames();
while (en.hasMoreElements()) {
String n = en.nextElement();
if(n.startsWith("plugin.")) {
n = n.substring(7);
UpdateCenter.Plugin p = Hudson.getInstance().getUpdateCenter().getPlugin(n);
if(p==null) {
sendError("No such plugin: "+n,req,rsp);
return;
}
p.install();
}
}
rsp.sendRedirect("../updateCenter/");
}
public void doProxyConfigure(@QueryParameter("proxy.server") String server, @QueryParameter("proxy.port") String port, StaplerResponse rsp) throws IOException {
setProp("http.proxyHost", Util.fixEmptyAndTrim(server));
setProp("http.proxyPort",Util.fixEmptyAndTrim(port));
setProp("https.proxyHost", Util.fixEmptyAndTrim(server));
setProp("https.proxyPort",Util.fixEmptyAndTrim(port));
rsp.sendRedirect("./advanced");
}
private void setProp(String key, String value) {
// System.setProperty causes NPE if t he value is null.
if(value==null) System.getProperties().remove(key);
else System.setProperty(key,value);
}
/**
* Uploads a plugin.
*/
public void doUploadPlugin( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
try {
Hudson.getInstance().checkPermission(Hudson.ADMINISTER);
ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
// Parse the request
FileItem fileItem = (FileItem) upload.parseRequest(req).get(0);
String fileName = Util.getFileName(fileItem.getName());
if(!fileName.endsWith(".hpi")) {
sendError(hudson.model.Messages.Hudson_NotAPlugin(fileName),req,rsp);
return;
}
fileItem.write(new File(rootDir, fileName));
fileItem.delete();
pluginUploaded=true;
rsp.sendRedirect2(".");
} catch (IOException e) {
throw e;
} catch (Exception e) {// grrr. fileItem.write throws this
throw new ServletException(e);
}
}
private final class UberClassLoader extends ClassLoader {
public UberClassLoader() {
super(PluginManager.class.getClassLoader());
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
// first, use the context classloader so that plugins that are loading
// can use its own classloader first.
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if(cl!=null && cl!=this)
try {
return cl.loadClass(name);
} catch(ClassNotFoundException e) {
// not found. try next
}
for (PluginWrapper p : activePlugins) {
try {
return p.classLoader.loadClass(name);
} catch (ClassNotFoundException e) {
//not found. try next
}
}
// not found in any of the classloader. delegate.
throw new ClassNotFoundException(name);
}
@Override
protected URL findResource(String name) {
for (PluginWrapper p : activePlugins) {
URL url = p.classLoader.getResource(name);
if(url!=null)
return url;
}
return null;
}
@Override
protected Enumeration<URL> findResources(String name) throws IOException {
List<URL> resources = new ArrayList<URL>();
for (PluginWrapper p : activePlugins) {
resources.addAll(Collections.list(p.classLoader.getResources(name)));
}
return Collections.enumeration(resources);
}
}
private static final Logger LOGGER = Logger.getLogger(PluginManager.class.getName());
/**
* Remembers why a plugin failed to deploy.
*/
public static final class FailedPlugin {
public final String name;
public final IOException cause;
public FailedPlugin(String name, IOException cause) {
this.name = name;
this.cause = cause;
}
public String getExceptionString() {
return Functions.printThrowable(cause);
}
}
}
|
package hudson.search;
import hudson.util.EditDistance;
import org.kohsuke.stapler.Ancestor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import org.kohsuke.stapler.export.Flavor;
import org.kohsuke.stapler.export.DataWriter;
import javax.servlet.ServletException;
import java.io.IOException;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Web-bound object that serves QuickSilver-like search requests.
*
* @author Kohsuke Kawaguchi
*/
public class Search {
public void doIndex(StaplerRequest req, StaplerResponse rsp) throws IOException {
List<Ancestor> l = req.getAncestors();
for( int i=l.size()-1; i>=0; i
Ancestor a = l.get(i);
if (a.getObject() instanceof SearchableModelObject) {
SearchableModelObject smo = (SearchableModelObject) a.getObject();
SearchIndex index = smo.getSearchIndex();
String query = req.getParameter("q");
SuggestedItem target = find(index, query);
if(target!=null) {
// found
rsp.sendRedirect2(a.getUrl()+target.getUrl());
return;
}
}
}
// TODO: go to suggestion page
throw new UnsupportedOperationException();
}
public void doSuggestOpenSearch(StaplerRequest req, StaplerResponse rsp, @QueryParameter("q")String query) throws IOException, ServletException {
DataWriter w = Flavor.JSON.createDataWriter(null, rsp);
w.startArray();
w.value(query);
w.startArray();
Set<String> paths = new HashSet<String>(); // paths already added, to control duplicates
for (SuggestedItem item : suggest(makeSuggestIndex(req), query)) {
if(paths.size()>20) break;
String p = item.getPath();
if(paths.add(p))
w.value(p);
}
w.endArray();
w.endArray();
}
/**
* Used by search box auto-completion. Returns JSON array.
*/
public void doSuggest(StaplerRequest req, StaplerResponse rsp, @QueryParameter("query")String query) throws IOException, ServletException {
Result r = new Result();
Set<String> paths = new HashSet<String>(); // paths already added, to control duplicates
for (SuggestedItem item : suggest(makeSuggestIndex(req), query)) {
if(paths.size()>20) break;
String p = item.getPath();
if(paths.add(p))
r.suggestions.add(new Item(p));
}
rsp.serveExposedBean(req,r,Flavor.JSON);
}
/**
* Creates merged search index for suggestion.
*/
private SearchIndex makeSuggestIndex(StaplerRequest req) {
SearchIndexBuilder builder = new SearchIndexBuilder();
for (Ancestor a : req.getAncestors()) {
if (a.getObject() instanceof SearchableModelObject) {
SearchableModelObject smo = (SearchableModelObject) a.getObject();
builder.add(smo.getSearchIndex());
}
}
return builder.make();
}
@ExportedBean
public static class Result {
@Exported
public List<Item> suggestions = new ArrayList<Item>();
}
@ExportedBean(defaultVisibility=999)
public static class Item {
@Exported
public String name;
public Item(String name) {
this.name = name;
}
}
private enum Mode {
FIND {
void find(SearchIndex index, String token, List<SearchItem> result) {
index.find(token, result);
}
},
SUGGEST {
void find(SearchIndex index, String token, List<SearchItem> result) {
index.suggest(token, result);
}
};
abstract void find(SearchIndex index, String token, List<SearchItem> result);
}
/**
* Performs a search and returns the match, or null if no match was found.
*/
public static SuggestedItem find(SearchIndex index, String query) {
List<SuggestedItem> r = find(Mode.FIND, index, query);
if(r.isEmpty()) return null;
else return r.get(0);
}
public static List<SuggestedItem> suggest(SearchIndex index, final String tokenList) {
class Tag implements Comparable<Tag>{
SuggestedItem item;
int distance;
Tag(SuggestedItem i) {
this.item = i;
distance = EditDistance.editDistance(i.getPath(),tokenList);
}
public int compareTo(Tag that) {
return this.distance-that.distance;
}
}
List<Tag> buf = new ArrayList<Tag>();
List<SuggestedItem> items = find(Mode.SUGGEST, index, tokenList);
// sort them
for( SuggestedItem i : items)
buf.add(new Tag(i));
Collections.sort(buf);
items.clear();
for (Tag t : buf)
items.add(t.item);
return items;
}
static final class TokenList {
private final String[] tokens;
public TokenList(String tokenList) {
tokens = tokenList.split("(?<=\\s)(?=\\S)");
}
public int length() { return tokens.length; }
/**
* Returns {@link List} such that its <tt>get(end)</tt>
* returns the concatanation of [token_start,...,token_end]
* (both end inclusive.)
*/
public List<String> subSequence(final int start) {
return new AbstractList<String>() {
public String get(int index) {
StringBuilder buf = new StringBuilder();
for(int i=start; i<=start+index; i++ )
buf.append(tokens[i]);
return buf.toString().trim();
}
public int size() {
return tokens.length-start;
}
};
}
}
private static List<SuggestedItem> find(Mode m, SearchIndex index, String tokenList) {
TokenList tokens = new TokenList(tokenList);
if(tokens.length()==0) return Collections.emptyList(); // no tokens given
List<SuggestedItem>[] paths = new List[tokens.length()+1]; // we won't use [0].
for(int i=1;i<=tokens.length();i++)
paths[i] = new ArrayList<SuggestedItem>();
List<SearchItem> items = new ArrayList<SearchItem>(); // items found in 1 step
// first token
int w=1; // width of token
for (String token : tokens.subSequence(0)) {
items.clear();
m.find(index,token,items);
for (SearchItem si : items)
paths[w].add(new SuggestedItem(si));
w++;
}
// successive tokens
for (int j=1; j<tokens.length(); j++) {
// for each length
w=1;
for (String token : tokens.subSequence(j)) {
// for each candidate
for (SuggestedItem r : paths[j]) {
items.clear();
m.find(r.item.getSearchIndex(),token,items);
for (SearchItem i : items)
paths[j+w].add(new SuggestedItem(r,i));
}
w++;
}
}
return paths[tokens.length()];
}
}
|
package txnIdSelfCheck.procedures;
import org.voltdb.SQLStmt;
import org.voltdb.VoltProcedure;
public class PoisonBaseProc extends VoltProcedure {
final SQLStmt insert = new SQLStmt("insert into bigp values (?,?,?);");
public static int SYSTEMDOTEXIT = 0;
public static int NAVELGAZE = 1;
public long run() {
return 0; // never called in base procedure
}
protected long poisonTheWell(int toxinType)
{
// make sure it gets logged to the command log
try {
Thread.sleep(10 * 1000);
} catch (InterruptedException ignoreIt) {}
if (toxinType == SYSTEMDOTEXIT) {
System.exit(37);
}
else if (toxinType == NAVELGAZE) {
while (true) {}
}
return 0; // NOT REACHED
}
}
|
package org.jbehave.scenario.parser;
import static java.util.regex.Pattern.DOTALL;
import static java.util.regex.Pattern.compile;
import static org.jbehave.scenario.definition.Blurb.EMPTY;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jbehave.scenario.Configuration;
import org.jbehave.scenario.PropertyBasedConfiguration;
import org.jbehave.scenario.definition.Blurb;
import org.jbehave.scenario.definition.KeyWords;
import org.jbehave.scenario.definition.ScenarioDefinition;
import org.jbehave.scenario.definition.StoryDefinition;
/**
* Pattern-based scenario parser, which uses the configured keywords to find the
* steps in the text scenarios.
*/
public class PatternScenarioParser implements ScenarioParser {
private final Configuration configuration;
public PatternScenarioParser() {
this(new PropertyBasedConfiguration());
}
public PatternScenarioParser(Configuration configuration) {
this.configuration = configuration;
}
public StoryDefinition defineStoryFrom(String wholeStoryAsString) {
Blurb blurb = parseBlurbFrom(wholeStoryAsString);
List<ScenarioDefinition> scenarioDefinitions = parseScenariosFrom(wholeStoryAsString);
return new StoryDefinition(blurb, scenarioDefinitions);
}
private List<ScenarioDefinition> parseScenariosFrom(
String wholeStoryAsString) {
List<ScenarioDefinition> scenarioDefinitions = new ArrayList<ScenarioDefinition>();
List<String> scenarios = splitScenarios(wholeStoryAsString);
for (String scenario : scenarios) {
Matcher findingTitle = patternToPullScenarioTitlesIntoGroupOne()
.matcher(scenario);
scenarioDefinitions.add(new ScenarioDefinition(
findingTitle.find() ? findingTitle.group(1).trim() : "",
findSteps(scenario)));
}
return scenarioDefinitions;
}
private List<String> findSteps(String scenarioAsString) {
Matcher matcher = patternToPullOutSteps().matcher(scenarioAsString);
List<String> steps = new ArrayList<String>();
int startAt = 0;
while (matcher.find(startAt)) {
steps.add(matcher.group(1));
startAt = matcher.start(4);
}
return steps;
}
private Blurb parseBlurbFrom(String wholeStoryAsString) {
String scenario = configuration.keywords().scenario();
Pattern findStoryBlurb = compile("(.*?)(" + scenario + ").*", DOTALL);
Matcher matcher = findStoryBlurb.matcher(wholeStoryAsString);
if (matcher.find()) {
return new Blurb(matcher.group(1).trim());
} else {
return EMPTY;
}
}
private List<String> splitScenarios(String allScenariosInFile) {
Pattern scenarioSplitter = patternToPullScenariosIntoGroupFour();
Matcher matcher = scenarioSplitter.matcher(allScenariosInFile);
int startAt = 0;
List<String> scenarios = new ArrayList<String>();
if (matcher.matches()) {
while (matcher.find(startAt)) {
scenarios.add(matcher.group(1));
startAt = matcher.start(4);
}
} else {
String loneScenario = allScenariosInFile;
scenarios.add(loneScenario);
}
return scenarios;
}
private Pattern patternToPullScenariosIntoGroupFour() {
String scenario = configuration.keywords().scenario();
return compile(".*?((" + scenario + ") (.|\\s)*?)\\s*(\\Z|" + scenario
+ ").*", DOTALL);
}
private Pattern patternToPullScenarioTitlesIntoGroupOne() {
KeyWords keywords = configuration.keywords();
String concatenatedKeywords = concatenateWithOr(keywords.given(),
keywords.when(), keywords.then(), keywords.others());
String scenario = keywords.scenario();
return compile(scenario + "(.*?)\\s*(" + concatenatedKeywords + ").*");
}
private String concatenateWithOr(String given, String when, String then,
String[] others) {
return concatenateWithOr(false, given, when, then, others);
}
private String concatenateWithSpaceOr(String given, String when,
String then, String[] others) {
return concatenateWithOr(true, given, when, then, others);
}
private String concatenateWithOr(boolean usingSpace, String given,
String when, String then, String[] others) {
StringBuilder builder = new StringBuilder();
builder.append(given).append(usingSpace ? "\\s|" : "|");
builder.append(when).append(usingSpace ? "\\s|" : "|");
builder.append(then).append(usingSpace ? "\\s|" : "|");
builder.append(usingSpace ? concatenateWithSpaceOr(others)
: concatenateWithOr(others));
return builder.toString();
}
private String concatenateWithOr(String... keywords) {
return concatenateWithOr(false, new StringBuilder(), keywords);
}
private String concatenateWithSpaceOr(String... keywords) {
return concatenateWithOr(true, new StringBuilder(), keywords);
}
private String concatenateWithOr(boolean usingSpace, StringBuilder builder,
String[] keywords) {
for (String other : keywords) {
builder.append(other).append(usingSpace ? "\\s|" : "|");
}
String result = builder.toString();
return result.substring(0, result.length() - 1); // chop off the last |
}
private Pattern patternToPullOutSteps() {
KeyWords keywords = configuration.keywords();
String givenWhenThen = concatenateWithOr(keywords.given(), keywords
.when(), keywords.then(), keywords.others());
String givenWhenThenSpaced = concatenateWithSpaceOr(keywords.given(),
keywords.when(), keywords.then(), keywords.others());
String scenario = keywords.scenario();
return compile("((" + givenWhenThen + ") (.|\\s)*?)\\s*(\\Z|"
+ givenWhenThenSpaced + "|" + scenario + ")");
}
}
|
/*
NOTE TO ANY READERS:
Check out "Rogue - Atlantic". It's a pretty sweet song though I must say that Flo Rida has some pretty good songs too.
Either way, I'd recommend some music if you're considering reading through this hell. Honestly, I feel like even my
not-so-messy code is extremely messy just because of how I work. I mean, I try to make the code readable but people
always tell me that it's virtually unreadable and it doesn't help that it's difficult to explain to them what the code
does without them losing interest. Also, in case you are actually, seriously going to read this crap, do yourself a
favour and pour yourself some nice Jack Daniels. You deserve it if you're going to read through this.
Do not Read Past this point... This is a human health advisory. Anyone reading past this point will risk his or her life.
If you get sick reading, we will not claim responsibility on your health. Please Stay Clear of the Code.
*/
package Launcher;
import Launcher.net.Updater;
import com.tofvesson.async.Async;
import com.tofvesson.joe.Localization;
import com.tofvesson.reflection.SafeReflection;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Rectangle;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.util.Duration;
import javafx.util.StringConverter;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/*
Do not go further. you risk your life. Read guideline above. Anyone reading past this point is no longer under our responsibility.
Beware the crocodiles on line 100!
*/
public class Main extends Application {
// Semantic versioning system data
public static final String semVerDevState = "PreDev"; // Development stage
public static final int semVerMajor = 0; // Major version
public static final int semVerMinor = 2; // Minor version
public static final int semVerPatch = 6; // Patch version
double xOffset = 0, yOffset = 0; // Offsets for dragging
private static String[] args;
Button exit, min, Home_btn, Modpack_btn, Settings_btn, Instance_btn, Default_theme, Dark_theme, Light_theme, Login_minecraft; // Define buttons
private ImageView icon;
private TextField Search_modpacks, Username_minecraft;
private Image appIcon;
private Rectangle dragBar; // Draggable top bar
Pane root, tab, dragbar_1;
private PasswordField Password_minecraft;
Node activeTab, settings_activeTab;
private Label dialog_changer;
Async stringUpdater;
@Override
public void start(Stage primaryStage) throws Exception{
primaryStage.initStyle(StageStyle.UNDECORATED);
if(args.length<2 || !args[1].equals("false")){
Stage d = new Stage();
Timeline t = new Timeline();
t.getKeyFrames().add(new KeyFrame(Duration.millis(1), event ->{ d.close(); primaryStage.show(); }));
d.initStyle(StageStyle.UNDECORATED);
Pane n = (Pane) Tabs.load("dialog_update");
d.setScene(new Scene(n));
d.getIcons().add(appIcon = new Image(getClass().getResourceAsStream("/assets/icons/app.png")));
d.show();
Thread t1 = new Thread(()->{
try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }
Updater.getInstance(t);
});
t1.setDaemon(true);
t1.start();
} else primaryStage.show(); // Remove ugly trash
root = (Pane) Tabs.load("main"); // Load via layout loader
((Label)root.lookup("#version")).setText(((Label) root.lookup("#version")) // Dynamically set version label
.getText().replace("$v", semVerDevState+" "+semVerMajor+"."+semVerMinor+"."+semVerPatch)); // Use variables to define version
primaryStage.setTitle("Team-Avion Launcher");
primaryStage.setScene(new Scene(root, 900, 500));
primaryStage.getIcons().clear();
primaryStage.getIcons().add(appIcon = new Image(getClass().getResourceAsStream("/assets/icons/app.png")));
// Field initialization
exit = (Button) root.lookup("#exit");
min = (Button) root.lookup("#min");
dragBar = (Rectangle) root.lookup("#rectangle");
Home_btn = (Button) root.lookup("#Home-btn");
Modpack_btn = (Button) root.lookup("#Modpacks-btn");
Settings_btn = (Button) root.lookup("#Settings-btn");
Instance_btn = (Button) root.lookup("#Instance-btn");
Default_theme = (Button) root.lookup("#default-theme");
Light_theme = (Button) root.lookup("#light-theme");
Dark_theme = (Button) root.lookup("#dark-theme");
Login_minecraft = (Button) root.lookup("#minecraft-login-btn");
dialog_changer = (Label) root.lookup("#dialog-changer");
tab = (Pane) root.lookup("#tab");
icon = (ImageView) root.lookup("#icon");
Search_modpacks = (TextField) root.lookup("#search-modpacks");
Username_minecraft = (TextField) root.lookup("#minecraftuser");
Password_minecraft = (PasswordField) root.lookup("#minecraftpass");
// Infrastructural navigation
exit.setOnMouseClicked(event -> primaryStage.close()); // Closes the program if exit button is clicked
min.setOnMouseClicked(event -> primaryStage.setIconified(true)); // Minimizes the program if minimize button is clicked
Home_btn.setOnMouseClicked(event ->{
if(!activeTab.equals(Home_btn)){
updateTabSelection(Home_btn, TabType.MAIN);
Tabs.switchTab("home", tab);
}
}); // Sets the active tab to the home tab unless it's already active
Modpack_btn.setOnMouseClicked(event ->{
if(!activeTab.equals(Modpack_btn)){
updateTabSelection(Modpack_btn, TabType.MAIN);
Tabs.switchTab("modpacks", tab);
if(stringUpdater!=null && stringUpdater.isAlive()) stringUpdater.cancel();
stringUpdater = new Async(SafeReflection.getFirstMethod(Main.class, "detectStringUpdate"), Tabs.load("modpacks").lookup("#search-modpacks"));
Tabs.load("modpacks").lookup("#download-modpack").setOnMouseClicked(event1 -> {
System.out.println("Downloading Modpack");
});
Tabs.load("modpacks").lookup("#view-modpack").setOnMouseClicked(event1 -> {
System.out.println("Viewing Modpack");
});
Tabs.load("modpacks").lookup("#download-modpack-a").setOnMouseClicked(event1 -> {
System.out.println("Downloading Modpack-a");
});
Tabs.load("modpacks").lookup("#view-modpack-a").setOnMouseClicked(event1 -> {
System.out.println("Viewing Modpack-a");
});
}
});
Instance_btn.setOnMouseClicked(event -> {
if(!activeTab.equals(Instance_btn)){
updateTabSelection(Instance_btn, TabType.MAIN);
Tabs.switchTab("instance", tab);
Tabs.load("instance").lookup("#Launch-VM").setOnMouseClicked(event1 -> {
System.out.println("Launching Minecraft");
});
}
});
Settings_btn.setOnMouseClicked((MouseEvent event) ->{
if(!activeTab.equals(Settings_btn)){
updateTabSelection(Settings_btn, TabType.MAIN);
Node n = Tabs.switchTab("settings", tab), tmp; // Sets the active tab to the settings tab unless it's already active
if(settings_activeTab==null) settings_activeTab = n.lookup("#Settings-Gen-btn"); // First time stuff
n.lookup("#Settings-Gen-btn").setOnMouseClicked(event1 -> {
// Generic Settings Sub-tab
if(!settings_activeTab.getId().equals(n.lookup("#Settings-Gen-btn").getId())){ // Use id to identify layouts
updateTabSelection(n.lookup("#Settings-Gen-btn"), TabType.SETTINGS);
Node genericLayout = Tabs.switchTab("settings_generic", (Pane) n.lookup("#Settings-Pane"));
}
});
n.lookup("#Settings-Mine-btn").setOnMouseClicked(event1 -> {
// Minecraft Settings Sub-tab
if(!settings_activeTab.getId().equals(n.lookup("#Settings-Mine-btn").getId())){ // Use id to identify layouts
updateTabSelection(n.lookup("#Settings-Mine-btn"), TabType.SETTINGS);
Node minecraftLayout = Tabs.switchTab("settings_minecraft", (Pane) n.lookup("#Settings-Pane"));
Tabs.load("settings_minecraft").lookup("#minecraft-login-btn").setOnMouseClicked(event3 ->{
System.out.println("Logging into minecraft");
Stage login = new Stage();
login.initModality(Modality.APPLICATION_MODAL);
login.initStyle(StageStyle.UNDECORATED);
Pane minecraftlogin = (Pane) Tabs.load("instance_userinfo");
login.setScene(new Scene(minecraftlogin, 300, 308));
login.show();
login.setResizable(false);
login.setTitle("Minecraft Login");
dragbar_1 = (Pane) Tabs.load("instance_userinfo").lookup("#dragbar-1");
dragbar_1.setOnMousePressed(event4 -> {
xOffset = event4.getSceneX();
yOffset = event4.getSceneY();
});
dragbar_1.setOnMouseDragged(event4 -> {
login.setX(event4.getScreenX() - xOffset);
login.setY(event4.getScreenY() - yOffset);
});
minecraftlogin.lookup("#close-minecraft-login-window").setOnMouseClicked(event4 ->{
System.out.println("Closing window");
login.close();
});
minecraftlogin.lookup("#minecraft-login").setOnMouseClicked(event4 ->{
System.out.println("Logging in ....");
});
});
}
});
Tabs.switchTab(settings_activeTab.getId().equals("Settings-Gen-btn") ? "settings_generic" : "settings_minecraft", (Pane) n.lookup("#Settings-Pane"));
if((tmp=Tabs.load("settings_generic").lookup("#default-theme")).getOnMouseClicked()==null) {
tmp.setOnMouseClicked(event2 -> {
Theme.Default.switchTo(root);
System.out.println("Changing Theme to Default");
});
Tabs.load("settings_generic").lookup("#light-theme").setOnMouseClicked(event2 -> {
Theme.Light.switchTo(root);
System.out.println("Changing Theme to Light");
});
Tabs.load("settings_generic").lookup("#dark-theme").setOnMouseClicked(event1 -> {
Theme.Dark.switchTo(root);
System.out.println("Changing Theme to Dark");
});
}
}
});
// Drag
dragBar.setOnMousePressed(event -> {
xOffset = event.getSceneX();
yOffset = event.getSceneY();
});
dragBar.setOnMouseDragged(event -> {
primaryStage.setX(event.getScreenX() - xOffset);
primaryStage.setY(event.getScreenY() - yOffset);
});
// Set up default layout
activeTab = Home_btn; // Update selected tab
Tabs.switchTab("home", tab);
icon.setImage(appIcon);
}
public static void main(String[] args) throws Exception{
// TODO: Try and fix this code please, It still doesn't work on my PC.
/* Localization l = new Localization(new File(Main.class.getResource("../assets/lang/").getFile())); // Create a localization with aggressive loading
System.out.println(Arrays.toString(l.getLanguageNames()));
System.out.println("Success: "+l.get("du_label")); */
Main.args = args;
if (args.length > 0) {
File f = new File(args[0]);
if (f.isFile()) while(!f.delete()) Thread.sleep(50); // Delete previous jar
}
launch(args);
}
/**
* Search for packs with an 80% match compared to detected string.
* @param toRead TextField to read from.
*/
public static void detectStringUpdate(TextField toRead){
String s = "";
while(true) if(!s.equals(toRead.getText())) System.out.println(s = toRead.getText());
}
void updateTabSelection(Node newTab, TabType t){
Node n = t==TabType.MAIN?activeTab:settings_activeTab;
n.getStyleClass().remove("selected");
n.getStyleClass().add("tab");
if(t==TabType.MAIN) activeTab = newTab;
else settings_activeTab = newTab;
newTab.getStyleClass().remove("tab");
newTab.getStyleClass().add("selected");
}
public static List<Node> getFlatRepresentation(Parent root){
List<Node> l = new ArrayList<>();
l.add(root);
for(Node n : root.getChildrenUnmodifiable()){
if(n instanceof Parent)
l.addAll(getFlatRepresentation((Parent)n));
else l.add(n);
}
return l;
}
public void processStyleData(Node n){
}
enum TabType{
SETTINGS, MAIN
}
enum Theme{
Default(""), Dark(Main.class.getResource("/assets/style/dark-theme.css").toExternalForm()), Light(Main.class.getResource("/assets/style/light-theme.css").toExternalForm());
public final String style;
Theme(String style){ this.style = style; }
public void switchTo(Pane root){
ObservableList<String> l = root.getStylesheets();
if(l.contains(Light.style)) l.remove(Light.style);
if(l.contains(Dark.style)) l.remove(Dark.style);
if(this!=Default) l.add(style);
}
}
}
|
package org.apache.uima.aae.controller;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.uima.UIMAFramework;
import org.apache.uima.aae.UIMAEE_Constants;
import org.apache.uima.flow.FinalStep;
import org.apache.uima.util.Level;
public class LocalCache extends ConcurrentHashMap<String, LocalCache.CasStateEntry> {
private static final long serialVersionUID = 1L;
private static final Class CLASS_NAME = LocalCache.class;
private AnalysisEngineController controller;
public LocalCache(AnalysisEngineController aController) {
controller = aController;
}
public CasStateEntry createCasStateEntry( String aCasReferenceId ) {
CasStateEntry entry = new CasStateEntry( aCasReferenceId );
super.put( aCasReferenceId, entry);
return entry;
}
public CasStateEntry lookupEntry( String aCasReferenceId ) {
if ( super.containsKey(aCasReferenceId)) {
return super.get(aCasReferenceId);
}
return null;
}
public String lookupInputCasReferenceId(String aCasReferenceId) {
String parentCasReferenceId=null;
if ( this.containsKey(aCasReferenceId)) {
CasStateEntry entry = (CasStateEntry)get(aCasReferenceId);
if ( entry.isSubordinate()) {
// recursively call each parent until we get to the top of the
// Cas hierarchy
parentCasReferenceId = lookupInputCasReferenceId(entry.getInputCasReferenceId());
} else {
return aCasReferenceId;
}
}
return parentCasReferenceId;
}
public String lookupInputCasReferenceId(CasStateEntry entry) {
String parentCasReferenceId=null;
if ( entry.isSubordinate()) {
// recursively call each parent until we get to the top of the
// Cas hierarchy
parentCasReferenceId =
lookupInputCasReferenceId((CasStateEntry)get(entry.getInputCasReferenceId()));
} else {
return entry.getCasReferenceId();
}
return parentCasReferenceId;
}
public synchronized void dumpContents() {
int count=0;
if ( UIMAFramework.getLogger().isLoggable(Level.FINEST) )
{
Iterator it = keySet().iterator();
StringBuffer sb = new StringBuffer("\n");
while( it.hasNext() )
{
String key = (String) it.next();
CasStateEntry entry = (CasStateEntry)get(key);
count++;
if ( entry.isSubordinate())
{
sb.append(key+ " Number Of Child CASes In Play:"+entry.getSubordinateCasInPlayCount()+" Parent CAS id:"+entry.getInputCasReferenceId());
}
else
{
sb.append(key+ " *** Input CAS. Number Of Child CASes In Play:"+entry.getSubordinateCasInPlayCount());
}
if ( entry.isWaitingForRelease() )
{
sb.append(" <<< Reached Final State in Controller:"+controller.getComponentName());
}
sb.append("\n");
}
UIMAFramework.getLogger(CLASS_NAME).logrb(Level.FINEST, CLASS_NAME.getName(),
"dumpContents", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_show_cache_entry_key__FINEST",
new Object[] { controller.getComponentName(), count, sb.toString() });
sb.setLength(0);
}
else if ( UIMAFramework.getLogger().isLoggable(Level.FINE) )
{
Iterator it = keySet().iterator();
StringBuffer sb = new StringBuffer("\n");
int inFinalState=0;
while( it.hasNext() )
{
String key = (String) it.next();
CasStateEntry entry = (CasStateEntry)get(key);
count++;
if ( entry.isWaitingForRelease() )
{
inFinalState++;
}
}
UIMAFramework.getLogger(CLASS_NAME).logrb(Level.FINE, CLASS_NAME.getName(),
"dumpContents", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_show_abbrev_cache_stats___FINE",
new Object[] { controller.getComponentName(), count, inFinalState });
}
}
public synchronized void remove(String aCasReferenceId)
{
if (aCasReferenceId != null && containsKey(aCasReferenceId))
{
if (UIMAFramework.getLogger(CLASS_NAME).isLoggable(Level.FINE)) {
UIMAFramework.getLogger(CLASS_NAME).logrb(Level.FINE, getClass().getName(), "remove", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_remove_cache_entry_for_cas__FINE", new Object[] { aCasReferenceId });
}
super.remove(aCasReferenceId);
this.notifyAll();
}
else if ( aCasReferenceId == null )
{
if (UIMAFramework.getLogger(CLASS_NAME).isLoggable(Level.FINE)) {
UIMAFramework.getLogger(CLASS_NAME).logrb(Level.FINE, getClass().getName(), "remove", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_cas_is_null_remove_from_cache_failed__FINE");
}
}
else
{
if (UIMAFramework.getLogger(CLASS_NAME).isLoggable(Level.FINE)) {
UIMAFramework.getLogger(CLASS_NAME).logrb(Level.FINE, getClass().getName(), "remove", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_cas_is_invalid_remove_from_cache_failed__FINE", new Object[] { aCasReferenceId });
}
}
}
public class CasStateEntry {
private String casReferenceId;
private volatile boolean waitingForRealease;
private volatile boolean pendingReply;
private volatile boolean subordinateCAS;
private volatile boolean replyReceived;
private FinalStep step;
private int state;
private int subordinateCasInPlayCount;
private Object childCountMux = new Object();
private String inputCasReferenceId;
private int numberOfParallelDelegates = 1;
private int howManyDelegatesResponded = 0;
private Endpoint freeCasNotificationEndpoint;
public Endpoint getFreeCasNotificationEndpoint() {
return freeCasNotificationEndpoint;
}
public void setFreeCasNotificationEndpoint(Endpoint freeCasNotificationEndpoint) {
this.freeCasNotificationEndpoint = freeCasNotificationEndpoint;
}
public CasStateEntry( String aCasReferenceId ) {
casReferenceId = aCasReferenceId;
}
public String getCasReferenceId() {
return casReferenceId;
}
public String getInputCasReferenceId() {
return inputCasReferenceId;
}
public void setInputCasReferenceId(String anInputCasReferenceId) {
inputCasReferenceId = anInputCasReferenceId;
subordinateCAS = true;
}
public void setWaitingForRelease(boolean flag) {
waitingForRealease = flag;
}
public boolean isWaitingForRelease() {
return waitingForRealease;
}
public void setFinalStep( FinalStep step ) {
this.step = step;
}
public FinalStep getFinalStep() {
return step;
}
public int getState() {
return state;
}
public void setState( int aState ) {
state = aState;
}
public boolean isSubordinate() {
return subordinateCAS;
}
public int getSubordinateCasInPlayCount() {
synchronized( childCountMux ) {
return subordinateCasInPlayCount;
}
}
public void incrementSubordinateCasInPlayCount() {
synchronized( childCountMux ) {
subordinateCasInPlayCount++;
}
}
public int decrementSubordinateCasInPlayCount() {
synchronized( childCountMux ) {
if ( subordinateCasInPlayCount > 0) {
subordinateCasInPlayCount
}
return subordinateCasInPlayCount;
}
}
public boolean isPendingReply() {
return pendingReply;
}
public void setPendingReply(boolean pendingReply) {
this.pendingReply = pendingReply;
}
public void setReplyReceived() {
replyReceived = true;
}
public boolean isReplyReceived() {
return replyReceived;
}
public synchronized void incrementHowManyDelegatesResponded(){
if ( howManyDelegatesResponded < numberOfParallelDelegates) {
howManyDelegatesResponded++;
}
}
public synchronized int howManyDelegatesResponded(){
return howManyDelegatesResponded;
}
public synchronized void resetDelegateResponded(){
howManyDelegatesResponded = 0;
}
public void setNumberOfParallelDelegates( int aNumberOfParallelDelegates ) {
numberOfParallelDelegates = aNumberOfParallelDelegates;
}
public int getNumberOfParallelDelegates() {
return numberOfParallelDelegates;
}
}
}
|
import java.util.ArrayList;
import java.util.List;
public class ListaTecnicos extends Tecnico{
private List<Tecnico> listaDeTecnicos;
public ListaTecnicos(){
super();
listaDeTecnicos = new ArrayList<Tecnico>();
}
public void inserir(Tecnico tecnico){
int elemento=listaDeTecnicos.indexOf(tecnico);
if (elemento!=-1)
System.out.println("Tecnico jah estah presente na lista");
else{
listaDeTecnicos.add(tecnico);
}
}
public void consultar (Tecnico Tecnico){
int elemento=listaDeTecnicos.indexOf(Tecnico);
if (elemento==-1)
System.out.println("Tecnico nao estah presente na lista");
else{
System.out.println("nome: " + listaDeTecnicos.get(elemento).getNome() +
"matricula: " + listaDeTecnicos.get(elemento).getMatricula() ) ;
}
}
public void remover(Tecnico Tecnico){
int elemento=listaDeTecnicos.indexOf(Tecnico);
if (elemento==-1)
System.out.println("Tecnico nao estah presente na lista");
else {
listaDeTecnicos.remove(Tecnico);
}
}
public void consultarTecnicos(){
for (int i=0;i<listaDeTecnicos.size();i++){
consultar(listaDeTecnicos.get(i));
}
}
public boolean existeTecnico(Tecnico Tecnico){
int elemento=listaDeTecnicos.indexOf(Tecnico);
if (elemento==-1)
return false;
return true;
}
}
|
package org.jasig.portal;
/**
* Contains version information about the current release.
* @author Ken Weiner, kweiner@unicon.net
* @version $Revision$
*/
public class Version {
// Update these strings appropriately for each release.
// Use empty strings rather than null when value is not desired.
private static String product = "uPortal";
private static String major = "2";
private static String minor = "5";
private static String patch = "0";
private static String extra = "RC1";
private static String releaseTag;
private static String version;
static {
// Construct version
releaseTag = "rel-" + major + "-" + minor;
if (patch != null && patch.length() > 0) {
releaseTag += "-" + patch;
}
releaseTag += extra;
// Construct version for display
version = major + "." + minor;
if (patch != null && patch.length() > 0) {
version += "." + patch;
}
version += extra;
}
/**
* Returns the product name.
* For example, this would return <code>uPortal</code> for uPortal 2.3.4.
* @return the product name
*/
public static String getProduct() {
return product;
}
/**
* Returns the major version.
* For example, this would return <code>2</code> for uPortal 2.3.4.
* @return the major version
*/
public static String getMajor() {
return major;
}
/**
* Returns the minor version.
* For example, this would return <code>3</code> for uPortal 2.3.4.
* @return the minor version
*/
public static String getMinor() {
return minor;
}
/**
* Returns the patch version.
* For example, this would return <code>4</code> for uPortal 2.3.4.
* This method may return an empty String.
* @return the patch version
*/
public static String getPatch() {
return patch;
}
/**
* Returns any extra string used to construct this version.
* For example, this would return <code>+</code> for uPortal 2.3.4+.
* A plus sign is used to denote that the code is between releases,
* the head of a branch in CVS. This method may return an empty String.
* @return the extra string, if any
*/
public static String getExtra() {
return extra;
}
/**
* Returns the release tag in the CVS repository
* corresponding to the current code.
* For example, <code>rel-2-3-4</code>.
* @return the release tag matching the running code
*/
public static String getReleaseTag() {
return releaseTag;
}
/**
* Returns the version of the current code.
* For example, <code>2.3.4</code>.
* @return the current version of the running code
*/
public static String getVersion() {
return version;
}
/**
* Returns a display-friendly string representing the
* current product and version.
* For example, <code>uPortal 2.3.4</code>.
* @return a verison string suitable for display
*/
public static String getProductAndVersion() {
return product + " " + version;
}
}
|
import java.util.Arrays;
import java.util.Random;
public class MazeGenerator {
private static Random random = new Random();
private MazeGenerator(){
}
public static byte[][] generateRecursiveBacktrackerMaze(int width, int height){
// Initialize variables
byte[][] mazeArray = new byte[width * 2 + 1][height * 2 + 1];
int[] cursorPos = new int[]{
random.nextInt(width),
random.nextInt(height)
};
// Fill Array
for(int i = 0; i < mazeArray.length; i ++){
for(int j = 0; j < mazeArray[0].length; j ++){
mazeArray[i][j] = ((i % 2 == 1) && (j % 2 == 1)) ? (byte) 1 : (byte) 0;
}
}
backtrack(mazeArray, cursorPos[0], cursorPos[1], cursorPos[0], cursorPos[1], width, height);
return mazeArray;
}
private static void backtrack(byte[][] array, int pos_x, int pos_y, int pos_prevx, int pos_prevy, int mazeWidth, int mazeHeight){
writeBetween(array, pos_x, pos_y, pos_prevx, pos_prevy, (byte) 2);
writeToMazeRarray(array, pos_x, pos_y, (byte) 2);
while(!isSurrounded(array, pos_x, pos_y)){
int direction = random.nextInt(4);
int[] newCheckPos = new int[2];
switch(direction){
case 0:
newCheckPos[0] = pos_x - 1;
newCheckPos[1] = pos_y;
break;
case 1:
newCheckPos[0] = pos_x + 1;
newCheckPos[1] = pos_y;
break;
case 2:
newCheckPos[0] = pos_x;
newCheckPos[1] = pos_y - 1;
break;
case 3:
newCheckPos[0] = pos_x;
newCheckPos[1] = pos_y + 1;
break;
}
if((newCheckPos[0] < 0) || (newCheckPos[0] > mazeWidth - 1) || (newCheckPos[1] < 0) || (newCheckPos[1] > mazeHeight - 1)) continue;
if(getArrayValue(array, newCheckPos[0], newCheckPos[1]) != 2){
backtrack(array, newCheckPos[0], newCheckPos[1], pos_x, pos_y, mazeWidth, mazeHeight);
}
}
}
public static void printMazeArray(byte[][] maze){
for(int h = 0; h < maze[0].length; h ++){
for(int w = 0; w < maze.length; w ++){
switch (maze[w][h]) {
case 0:
System.out.print("
break;
case 1:
System.out.print(".");
break;
case 2:
System.out.print(" ");
break;
}
System.out.print(" ");
}
System.out.println();
}
}
private static void writeToMazeRarray(byte[][] maze, int w, int h, byte val){
maze[w * 2 + 1][h * 2 + 1] = val;
}
private static void writeBetween(byte[][] maze, int w1, int h1, int w2, int h2, byte val){
maze[((w1 * 2 + 1) + (w2 * 2 + 1)) / 2][((h1 * 2 + 1) + (h2 * 2 + 1)) / 2] = val;
}
private static byte getArrayValue(byte[][] maze, int w, int h){
if((w < 0) || (w > ((maze.length - 1) / 2) - 1) || (h < 0) || (h > ((maze[0].length - 1) / 2) - 1)) return - 1;
return maze[w * 2 + 1][h * 2 + 1];
}
private static boolean isSurrounded(byte[][] maze, int w, int h){
if((getArrayValue(maze, w - 1, h) == 2 || getArrayValue(maze, w - 1, h) == -1) && (getArrayValue(maze, w + 1, h) == 2 || getArrayValue(maze, w + 1, h) == -1) && (getArrayValue(maze, w, h - 1) == 2 || getArrayValue(maze, w, h - 1) == -1) && (getArrayValue(maze, w, h + 1) == 2 || getArrayValue(maze, w, h + 1) == -1)) return true;
return false;
}
public static void main(String[] args) {
}
}
|
/**
@author Andrew McCallum <a href="mailto:mccallum@cs.umass.edu">mccallum@cs.umass.edu</a>
*/
package mstparser;
import java.util.ArrayList;
import java.io.*;
import java.util.Iterator;
public class Alphabet implements Serializable
{
gnu.trove.TObjectIntHashMap map;
int numEntries;
boolean growthStopped = false;
public Alphabet (int capacity)
{
this.map = new gnu.trove.TObjectIntHashMap (capacity);
//this.map.setDefaultValue(-1);
numEntries = 0;
}
public Alphabet ()
{
this (10000);
}
/** Return -1 if entry isn't present. */
public int lookupIndex (Object entry)
{
if (entry == null) {
throw new IllegalArgumentException ("Can't lookup \"null\" in an Alphabet.");
}
int ret = map.get(entry);
if (ret == -1 && !growthStopped) {
ret = numEntries;
map.put (entry, ret);
numEntries++;
}
//System.out.println(entry + " :: " + ret);
return ret;
}
public Object[] toArray () {
return map.keys();
}
public boolean contains (Object entry)
{
return map.contains (entry);
}
public int size ()
{
return numEntries;
}
public void stopGrowth ()
{
growthStopped = true;
map.compact();
}
public void allowGrowth ()
{
growthStopped = false;
}
public boolean growthStopped ()
{
return growthStopped;
}
// Serialization
private static final long serialVersionUID = 1;
private static final int CURRENT_SERIAL_VERSION = 0;
private void writeObject (ObjectOutputStream out) throws IOException {
out.writeInt (CURRENT_SERIAL_VERSION);
out.writeInt (numEntries);
out.writeObject(map);
out.writeBoolean (growthStopped);
}
private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException {
int version = in.readInt ();
numEntries = in.readInt();
map = (gnu.trove.TObjectIntHashMap)in.readObject();
growthStopped = in.readBoolean();
}
}
|
package service;
import android.app.IntentService;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.text.format.Time;
import android.util.Log;
import android.widget.ArrayAdapter;
import com.example.android.sunshine.app.BuildConfig;
import com.example.android.sunshine.app.data.WeatherContract;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Vector;
public class SunshineService extends IntentService {
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
* @param name Used to name the worker thread, important only for debugging.
*/
private ArrayAdapter<String> mForecastAdapter;
public static final String LOCATION_QUERY_EXTRA = "lqe";
private final String LOG_TAG = SunshineService.class.getSimpleName();
public SunshineService() {
super("Sunshine");
}
/**
* This method is invoked on the worker thread with a request to process.
* Only one Intent is processed at a time, but the processing happens on a
* worker thread that runs independently from other application logic.
* So, if this code takes a long time, it will hold up other requests to
* the same IntentService, but it will not hold up anything else.
* When all requests have been handled, the IntentService stops itself,
* so you should not call {@link #stopSelf}.
*
* @param intent The value passed to {@link
* Context#startService(Intent)}.
*/
@Override
protected void onHandleIntent(Intent intent) {
String locationQuery = intent.getStringExtra(LOCATION_QUERY_EXTRA);;
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String forecastJsonStr = null;
String format = "json";
String units = "metric";
int numDays = 14;
try {
// Construct the URL for the OpenWeatherMap query
// Possible parameters are avaiable at OWM's forecast API page, at
// http://openweathermap.org/API#forecast
final String FORECAST_BASE_URL =
"http://api.openweathermap.org/data/2.5/forecast/daily?";
final String QUERY_PARAM = "q";
final String FORMAT_PARAM = "mode";
final String UNITS_PARAM = "units";
final String DAYS_PARAM = "cnt";
final String APPID_PARAM = "APPID";
Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon()
.appendQueryParameter(QUERY_PARAM,locationQuery)
.appendQueryParameter(FORMAT_PARAM, format)
.appendQueryParameter(UNITS_PARAM, units)
.appendQueryParameter(DAYS_PARAM, Integer.toString(numDays))
.appendQueryParameter(APPID_PARAM, BuildConfig.OPEN_WEATHER_MAP_API_KEY)
.build();
URL url = new URL(builtUri.toString());
// Create the request to OpenWeatherMap, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return;
}
forecastJsonStr = buffer.toString();
getWeatherDataFromJson(forecastJsonStr, locationQuery);
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
}
long addLocation(String locationSetting, String cityName, double lat, double lon) {
// Students: First, check if the location with this city name exists in the db
// If it exists, return the current ID
Cursor locationCursor=this.getContentResolver().query(WeatherContract.LocationEntry.CONTENT_URI,
new String[] {WeatherContract.LocationEntry._ID},
WeatherContract.LocationEntry.COLUMN_CITY_NAME+"=?",
new String[] {cityName},
null);
if(locationCursor.moveToFirst()) {
return locationCursor.getLong(locationCursor.getColumnIndex(WeatherContract.LocationEntry._ID));
}
// Otherwise, insert it using the content resolver and the base URI
else{
ContentValues locationValues=new ContentValues();
locationValues.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING,locationSetting);
locationValues.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME,cityName);
locationValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT,lat);
locationValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG,lon);
Uri insertedRowUri=this.getContentResolver().insert(WeatherContract.LocationEntry.CONTENT_URI, locationValues);
return ContentUris.parseId(insertedRowUri);
}
}
/**
* Take the String representing the complete forecast in JSON Format and
* pull out the data we need to construct the Strings needed for the wireframes.
*
* Fortunately parsing is easy: constructor takes the JSON string and converts it
* into an Object hierarchy for us.
*/
private void getWeatherDataFromJson(String forecastJsonStr,
String locationSetting)
throws JSONException {
// Now we have a String representing the complete forecast in JSON Format.
// Fortunately parsing is easy: constructor takes the JSON string and converts it
// into an Object hierarchy for us.
// These are the names of the JSON objects that need to be extracted.
// Location information
final String OWM_CITY = "city";
final String OWM_CITY_NAME = "name";
final String OWM_COORD = "coord";
// Location coordinate
final String OWM_LATITUDE = "lat";
final String OWM_LONGITUDE = "lon";
// Weather information. Each day's forecast info is an element of the "list" array.
final String OWM_LIST = "list";
final String OWM_PRESSURE = "pressure";
final String OWM_HUMIDITY = "humidity";
final String OWM_WINDSPEED = "speed";
final String OWM_WIND_DIRECTION = "deg";
// All temperatures are children of the "temp" object.
final String OWM_TEMPERATURE = "temp";
final String OWM_MAX = "max";
final String OWM_MIN = "min";
final String OWM_WEATHER = "weather";
final String OWM_DESCRIPTION = "main";
final String OWM_WEATHER_ID = "id";
try {
JSONObject forecastJson = new JSONObject(forecastJsonStr);
JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);
JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY);
String cityName = cityJson.getString(OWM_CITY_NAME);
JSONObject cityCoord = cityJson.getJSONObject(OWM_COORD);
double cityLatitude = cityCoord.getDouble(OWM_LATITUDE);
double cityLongitude = cityCoord.getDouble(OWM_LONGITUDE);
long locationId = addLocation(locationSetting, cityName, cityLatitude, cityLongitude);
// Insert the new weather information into the database
Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length());
// OWM returns daily forecasts based upon the local time of the city that is being
// asked for, which means that we need to know the GMT offset to translate this data
// properly.
// Since this data is also sent in-order and the first day is always the
// current day, we're going to take advantage of that to get a nice
// normalized UTC date for all of our weather.
Time dayTime = new Time();
dayTime.setToNow();
// we start at the day returned by local time. Otherwise this is a mess.
int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff);
// now we work exclusively in UTC
dayTime = new Time();
for(int i = 0; i < weatherArray.length(); i++) {
// These are the values that will be collected.
long dateTime;
double pressure;
int humidity;
double windSpeed;
double windDirection;
double high;
double low;
String description;
int weatherId;
// Get the JSON object representing the day
JSONObject dayForecast = weatherArray.getJSONObject(i);
// Cheating to convert this to UTC time, which is what we want anyhow
dateTime = dayTime.setJulianDay(julianStartDay+i);
pressure = dayForecast.getDouble(OWM_PRESSURE);
humidity = dayForecast.getInt(OWM_HUMIDITY);
windSpeed = dayForecast.getDouble(OWM_WINDSPEED);
windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION);
// Description is in a child array called "weather", which is 1 element long.
// That element also contains a weather code.
JSONObject weatherObject =
dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
description = weatherObject.getString(OWM_DESCRIPTION);
weatherId = weatherObject.getInt(OWM_WEATHER_ID);
// Temperatures are in a child object called "temp". Try not to name variables
// "temp" when working with temperature. It confuses everybody.
JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
high = temperatureObject.getDouble(OWM_MAX);
low = temperatureObject.getDouble(OWM_MIN);
ContentValues weatherValues = new ContentValues();
weatherValues.put(WeatherContract.WeatherEntry.COLUMN_LOC_KEY, locationId);
weatherValues.put(WeatherContract.WeatherEntry.COLUMN_DATE, dateTime);
weatherValues.put(WeatherContract.WeatherEntry.COLUMN_HUMIDITY, humidity);
weatherValues.put(WeatherContract.WeatherEntry.COLUMN_PRESSURE, pressure);
weatherValues.put(WeatherContract.WeatherEntry.COLUMN_WIND_SPEED, windSpeed);
weatherValues.put(WeatherContract.WeatherEntry.COLUMN_DEGREES, windDirection);
weatherValues.put(WeatherContract.WeatherEntry.COLUMN_MAX_TEMP, high);
weatherValues.put(WeatherContract.WeatherEntry.COLUMN_MIN_TEMP, low);
weatherValues.put(WeatherContract.WeatherEntry.COLUMN_SHORT_DESC, description);
weatherValues.put(WeatherContract.WeatherEntry.COLUMN_WEATHER_ID, weatherId);
cVVector.add(weatherValues);
}
int inserted = 0;
// add to database
if ( cVVector.size() > 0 ) {
// Student: call bulkInsert to add the weatherEntries to the database here
ContentValues[] cVArray=new ContentValues[cVVector.size()];
cVVector.toArray(cVArray);
inserted=this.getContentResolver().bulkInsert(WeatherContract.WeatherEntry.CONTENT_URI,cVArray);
}
Log.d(LOG_TAG, "FetchWeatherTask Complete. " + inserted + " Inserted");
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
}
}
|
package edu.cornell.mannlib.vitro.webapp.auth.identifier.common;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.Identifier;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.IdentifierBundle;
/**
* The current user is a root user.
*/
public class IsRootUser extends AbstractCommonIdentifier implements Identifier {
public static final IsRootUser INSTANCE = new IsRootUser();
public static boolean isRootUser(IdentifierBundle ids) {
return !getIdentifiersForClass(ids, IsRootUser.class).isEmpty();
}
/** Enforce the singleton pattern. */
private IsRootUser() {
// Nothing to initialize.
}
@Override
public String toString() {
return "IsRootUser";
}
}
|
package nom.tam.image.comp;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import nom.tam.fits.BasicHDU;
import nom.tam.fits.BinaryTable;
import nom.tam.fits.BinaryTableHDU;
import nom.tam.fits.Data;
import nom.tam.fits.Fits;
import nom.tam.fits.FitsException;
import nom.tam.fits.FitsFactory;
import nom.tam.fits.Header;
import nom.tam.fits.HeaderCard;
import nom.tam.fits.ImageHDU;
import nom.tam.image.ImageTiler;
import nom.tam.image.TileDescriptor;
import nom.tam.image.TileLooper;
import nom.tam.util.ArrayFuncs;
import nom.tam.util.BufferedDataInputStream;
import nom.tam.util.BufferedFile;
import nom.tam.util.Cursor;
/**
* This class represents a FITS image that has rendered using the tiled
* compression convention.
*
* @author tmcglynn
*/
public class TiledImageHDU extends BinaryTableHDU {
Header hdr;
// These keywords will not be copied from the original
// image into the copy.
private static String[] reserved = {
"SIMPLE", "XTENSION", "BITPIX",
"NAXIS", "NAXIS1", "NAXIS2", "NAXIS3", "NAXIS4", "NAXIS5",
"BLOCKED", "EXTEND", "PCOUNT", "GCOUNT", "ZHECKSUM", "ZDATASUM", "END",
"ZSIMPLE", "ZEXTENSION", "ZEXTEND", "ZBLOCKED", "ZPCOUNT", "ZGCOUNT",
"ZHECKSUM", "ZDATASUM",
"ZTILE1", "ZTILE2", "ZTILE3", "ZTILE4", "ZTILE5",
"ZBITPIX", "ZXTENSION", "ZNAXIS",
"ZNAXIS1", "ZNAXIS2", "ZNAXIS3", "ZNAXIS4", "ZNAXIS5",
"ZNAME1", "ZNAME2", "ZNAME3", "ZNAME4", "ZNAME5",
"ZVAR1", "ZVAR2", "ZVAR3", "ZVAR4", "ZVAR5",
"ZMASKCMP", "ZQUANTIZ", "ZSCALE", "ZZERO"
};
private static Set<String> reservedKeys = new HashSet<String>();
private Quantizer quant;
private CompressionScheme cs;
private Class baseClass;
/**
* The tile widths in each dimension
*/
private int[] tileSize;
/**
* Dimensionality
*/
private int naxis;
/**
* Image dimensions
*/
private int[] imageSize;
/**
* Image BITPIX
*/
private int zbitpix;
static {
for (String res : reserved) {
reservedKeys.add(res);
}
}
private static Map<Integer, Class> bitpixClasses = new HashMap<Integer, Class>();
static {
bitpixClasses.put(8, byte.class);
bitpixClasses.put(16, short.class);
bitpixClasses.put(32, int.class);
bitpixClasses.put(64, long.class);
bitpixClasses.put(-32, float.class);
bitpixClasses.put(-64, double.class);
}
private String kernelClass;
/**
* See if an existing binary table can be treated at a TiledImageHDU.
*
* @param input A binary table that has been created/read in that may be a
* tiled image.
* @throws FitsException if the input cannot be treated as a TiledImageHDU.
*/
public TiledImageHDU(BinaryTableHDU input) throws FitsException {
super(input.getHeader(), input.getData());
hdr = input.getHeader();
if (!hdr.getBooleanValue("ZIMAGE", false)
|| hdr.getStringValue("ZCMPTYPE") == null
|| hdr.getIntValue("ZBITPIX", -1) == -1
|| hdr.getIntValue("ZNAXIS", -1) == -1) {
throw new FitsException("Required keywords not found for TiledImageHDU");
}
naxis = hdr.getIntValue("ZNAXIS");
tileSize = new int[naxis];
imageSize = new int[naxis];
for (int i = 0; i < naxis; i += 1) {
String axis = "ZNAXIS" + (i + 1);
imageSize[i] = hdr.getIntValue(axis, -1);
if (imageSize[i] == -1) {
throw new FitsException("Missing " + axis + " keyword for TileImageHDU");
}
String tile = "ZTILE" + (i + 1);
tileSize[i] = hdr.getIntValue(tile, -1);
// Default tiling is row by row.
if (tileSize[i] == -1) {
if (i == 0) {
tileSize[i] = imageSize[i];
} else {
tileSize[i] = 1;
}
}
}
zbitpix = hdr.getIntValue("ZBITPIX");
baseClass = bitpixClasses.get(zbitpix);
cs = getCompression(hdr.getStringValue("ZCMPTYPE"));
if (hdr.containsKey("ZQUANTIZ")) {
if (hdr.getStringValue("ZQUANTIZ").toUpperCase().equals("SUBTRACTIVE_DITHER_1")) {
double scale = hdr.getDoubleValue("ZSCALE");
double offset = hdr.getDoubleValue("ZZERO");
quant = new Quantizer(scale, offset);
}
}
Map<String, String> params = cs.getParameters(hdr);
cs.initialize(params);
}
/**
* Create a tiled image HDU from an existing Image HDU.
*/
public TiledImageHDU(ImageHDU input, Map<String, String> parameters) throws FitsException,
IOException {
super(coreHeader(), nilData());
hdr = getHeader(); // Get a local reference to the Header.
String comp = parameters.get("compression");
imageSize = input.getAxes();
naxis = imageSize.length;
if (naxis == 0 || imageSize[0] == 0) {
throw new FitsException("Cannot compress nil image");
}
String tiling = parameters.get("tiling");
if (tiling == null) {
tiling = imageSize[0] + "";
for (int i = 1; i < imageSize.length; i += 1) {
tiling += ",1";
}
}
String[] fields = tiling.split(",");
if (fields.length != imageSize.length) {
throw new FitsException("Tile dimensionality (" + fields.length + ") must match image (" + imageSize.length + ")");
}
tileSize = new int[imageSize.length];
for (int i = 0; i < imageSize.length; i += 1) {
tileSize[i] = Integer.parseInt(fields[i].trim());
}
Header old = input.getHeader();
// Position the insertion pointer after the TFORM1.
hdr.getStringValue("TFORM1");
cs = getCompression(comp);
insertTileKeywords(old, cs, parameters, imageSize, tileSize);
Object kern = input.getKernel();
int bitpix = old.getIntValue("BITPIX");
zbitpix = bitpix;
if (bitpix < 0) {
RealStats rs = new RealStats(kern);
double offset = rs.min;
double scale = rs.noise3 / 16;
double bits = Math.log((rs.max - rs.min) / scale) / Math.log(2);
insertQuantizerKeywords(offset, scale);
if (bits > 30) {
throw new IllegalStateException("Cannot quantize image, noise too large");
}
quant = new Quantizer(scale, offset);
}
Cursor newPointer = hdr.iterator();
newPointer.setKey("END");
Cursor oldPointer = old.iterator();
oldPointer.setKey("BITPIX");
copyOldKeywords(oldPointer, newPointer);
TileLooper tl = new TileLooper(imageSize, tileSize);
cs.initialize(parameters);
populateData(kern, bitpix, tl, cs);
}
private void insertQuantizerKeywords(double offset, double scale)
throws FitsException {
hdr.addValue("ZZERO", offset, " Quantizer offset value");
hdr.addValue("ZSCALE", scale, " Quantizer scaling");
hdr.addValue("ZQUANTIZ", "SUBTRACTIVE_DITHER_1", " Quantizing scheme");
}
private void populateData(Object kern, int bitpix, TileLooper tl, CompressionScheme cs)
throws FitsException, IOException {
// Get rid of the dummy rows we initialized with.
BinaryTable bt = (BinaryTable) this.getData();
this.deleteRows(0, 2);
int tileCount = 0;
Iterator<TileDescriptor> ti = tl.iterator();
kernelClass = kern.getClass().getName();
BinaryTable table = (BinaryTable) getData();
while (ti.hasNext()) {
TileDescriptor td = ti.next();
int sz = 1;
for (int i = 0; i < td.size.length; i += 1) {
sz *= td.size[i];
}
byte[] data;
if (quant == null) {
data = getTileData(td, kern, bitpix);
} else {
data = quant.quantize(kern, td, tileCount);
}
data = cs.compress(data);
this.addRow(new Object[]{data});
}
}
private void insertTileKeywords(Header old, CompressionScheme comp,
Map<String, String> parameters,
int[] axes, int[] tiles)
throws FitsException {
hdr.insertComment(" ");
hdr.insertComment(" Tile compression keywords ");
hdr.insertComment(" ");
// Update the header.
hdr.addValue("ZIMAGE", true, "This is a tile compressed image");
hdr.addValue("ZCMPTYPE", comp.name(), "The compression algorithm used");
hdr.addValue("ZBITPIX", old.getIntValue("BITPIX"), "The original bitpix value");
hdr.addValue("ZNAXIS", axes.length, "The original NAXIS");
for (int i = 0; i < axes.length; i += 1) {
String d = (i + 1) + "";
hdr.addValue("ZNAXIS" + d, axes[i], "The original NAXIS" + d);
hdr.addValue("ZTILE" + d, tiles[i], "The tile size along this axis");
}
if (old.containsKey("SIMPLE")) {
hdr.addValue("ZSIMPLE", old.getBooleanValue("SIMPLE"), "Was primary array");
}
if (old.containsKey("BLOCKED")) {
hdr.addValue("ZBLOCKED", old.getIntValue("BLOCKED"), "Old BLOCKED value");
}
if (old.containsKey("EXTEND")) {
hdr.addValue("ZEXTEND", old.getBooleanValue("EXTEND"), "Old EXTEND value");
}
if (old.containsKey("PCOUNT")) {
hdr.addValue("ZPCOUNT", old.getIntValue("PCOUNT"), "Old PCOUNT value");
}
if (old.containsKey("GCOUNT")) {
hdr.addValue("ZGCOUNT", old.getIntValue("GCOUNT"), "Old GCOUNT value");
}
if (old.containsKey("CHECKSUM")) {
hdr.addValue("ZHECKSUM", old.getStringValue("CHECKSUM"), "Old CHECKSUM value");
}
if (old.containsKey("DATASUM")) {
hdr.addValue("DATASUM", old.getStringValue("DATASUM"), "Old DATASUM value");
}
comp.updateForWrite(hdr, parameters);
}
private void copyOldKeywords(Cursor oldPointer, Cursor newPointer) {
newPointer.add(new HeaderCard("COMMENT"));
newPointer.add(new HeaderCard("COMMENT Header info copied from original image"));
newPointer.add(new HeaderCard("COMMENT"));
while (oldPointer.hasNext()) {
HeaderCard card = (HeaderCard) oldPointer.next();
String key = card.getKey();
if (key.equals("END")) {
break;
}
if (!reservedKeys.contains(key)) {
newPointer.add(card);
}
}
}
private CompressionScheme getCompression(String comp) {
if (comp == null) {
comp = "rice_1";
}
comp = comp.toLowerCase();
CompressionScheme cs;
if (comp.equals("rice_1") || comp.equals("rice")) {
cs = new Rice();
} else if (comp.equals("gzip_1") || comp.equals("gzip")) {
cs = new Gzip();
} else {
throw new IllegalArgumentException("Unsupported compression:" + comp);
}
return cs;
}
private byte[] getTileData(TileDescriptor td, Object kern, int bitpix) {
int sz = Math.abs(bitpix) / 8;
for (int i = 0; i < td.size.length; i += 1) {
sz *= td.size[i];
}
int[] size = td.size;
int[] corn = td.corner;
ByteArrayOutputStream bo = new ByteArrayOutputStream(sz);
DataOutputStream output = new DataOutputStream(bo);
int[] pixel = new int[size.length];
try {
while (true) {
writeArray(output, kern, pixel, corn, size, 0);
// We'll handle the first index in writeArray so we
// start at 1. Note that this indices are in FITS order,
// the opposite of Java's.
boolean incremented = false;
for (int i = 1; i < size.length; i += 1) {
if (pixel[i] < size[i] - 1) {
pixel[i] += 1;
incremented = true;
}
}
if (!incremented) {
break;
}
}
output.close();
return bo.toByteArray();
} catch (IOException e) {
System.err.println("Unexpected IOException transferring data");
throw new RuntimeException("Unexpected exception", e);
}
}
private void writeArray(DataOutputStream output, Object data,
int[] pixel, int[] corner, int[] size, int level)
throws IOException {
char c = kernelClass.charAt(level + 1);
// The indices are in FITS order, so we access them inverted.
int zind = size.length - level - 1;
int pix = corner[zind] + pixel[zind];
int sz = size[zind];
switch (c) {
// Recurse to the next level, but pick out the appropriate sub-array.
case '[':
writeArray(output, ((Object[]) data)[pix], pixel, corner, size, level + 1);
break;
case 'B': {
byte[] temp = (byte[]) data;
for (int i = pix; i < pix + sz; i += 1) {
output.writeByte(temp[i]);
}
break;
}
case 'S': {
short[] temp = (short[]) data;
for (int i = pix; i < pix + sz; i += 1) {
output.writeShort(temp[i]);
}
break;
}
case 'I': {
int[] temp = (int[]) data;
for (int i = pix; i < pix + sz; i += 1) {
output.writeInt(temp[i]);
}
break;
}
case 'L': {
long[] temp = (long[]) data;
for (int i = pix; i < pix + sz; i += 1) {
output.writeLong(temp[i]);
}
break;
}
case 'F': {
float[] temp = (float[]) data;
for (int i = pix; i < pix + sz; i += 1) {
output.writeFloat(temp[i]);
}
break;
}
case 'D': {
double[] temp = (double[]) data;
for (int i = pix; i < pix + sz; i += 1) {
output.writeDouble(temp[i]);
}
break;
}
default:
throw new IOException("Invalid type rendering tiled image:" + kernelClass);
}
}
/**
* Create the basic header for a TiledImage.
*/
private static Header coreHeader() throws FitsException {
Header hdr = BinaryTableHDU.manufactureHeader(nilData());
hdr.addValue("TTYPE1", "COMPRESSED_DATA", "Compressed data for a single tile");
return hdr;
}
/**
* Create a nil data segment for a basic tiled image.
*
* @return A nil data segment
*/
private static Data nilData() throws FitsException {
// We start with two rows so that we can ensure
// that it is seen as a variable length column.
// Need to delete these before adding the real data.
byte[][] testData = new byte[2][];
testData[0] = new byte[0];
testData[1] = new byte[1];
return BinaryTableHDU.encapsulate(new Object[]{testData});
}
/**
* Find the size and tile information in the header
*/
private void getDimens(int[] axes, int[] tiles) throws FitsException {
boolean tilesFound = true;
// First look for the ZTILEn keywords.
for (int i = 0; i < axes.length; i += 1) {
axes[i] = hdr.getIntValue("ZNAXIS" + (i + 1), -1);
if (axes[i] == -1) {
throw new FitsException("Required ZNAXISn not found");
}
if (tilesFound) {
tiles[i] = hdr.getIntValue("ZTILE" + (i + 1), -1);
if (tiles[i] == -1) {
tilesFound = false;
}
}
}
if (!tilesFound) {
tiles[0] = axes[0];
for (int i = 1; i < tiles.length; i += 1) {
tiles[i] = 1;
}
}
}
private Map<String, String> getParameters() {
Map<String, String> params = new HashMap<String, String>();
int i = 1;
while (hdr.containsKey("ZNAME" + i)) {
String name = hdr.getStringValue("ZNAME" + i);
String val = hdr.getStringValue("ZVAL" + i);
params.put(name, val);
}
return params;
}
/**
* Convert the tiled image into a regular ImageHDU.
*
* @return The converted HDU.
*/
public ImageHDU getImageHDU() throws FitsException, IOException {
System.out.println("In getImage!!!");
int[] axes = new int[hdr.getIntValue("ZNAXIS")];
int bitpix = hdr.getIntValue("ZBITPIX");
int[] tiles = new int[axes.length];
boolean found = true;
getDimens(axes, tiles);
Object data = ArrayFuncs.newInstance(baseClass, ArrayFuncs.reverseIndices(axes));
int[] dataCorner = new int[naxis];
TileLooper tl = new TileLooper(axes, tiles);
Iterator<TileDescriptor> ti = tl.iterator();
Object[] rows = (Object[]) getColumn("COMPRESSED_DATA");
int nTile = 0;
String className = data.getClass().getName();
for (TileDescriptor td: tl) {
byte[] tileData = (byte[]) rows[td.count];
Object tile = getTile(td, tileData);
insertTile(tile, td.corner, td.size, data, dataCorner, imageSize, className, 0);
}
System.out.println("Finished the loop");
BasicHDU bhdu = FitsFactory.HDUFactory(data);
//importKeywords(bhdu);
return (ImageHDU) bhdu;
}
private Object getTile(TileDescriptor td, byte[] tileData) throws IOException {
int tileLen = 1;
int[] tsize = td.size;
for (int j = 0; j < tsize.length; j += 1) {
tileLen *= tsize[j];
}
tileData = cs.decompress(tileData, tileLen);
Object tile = ArrayFuncs.newInstance(baseClass, ArrayFuncs.reverseIndices(td.size));
if (quant == null) {
BufferedDataInputStream bds = new BufferedDataInputStream(
new ByteArrayInputStream(tileData));
bds.readLArray(tile);
} else {
quant.fill(tileData, tile, td);
}
return tile;
}
/**
* Return the data from the specified tile in the native format.
*/
private Object getTile(TileDescriptor td) throws FitsException, IOException {
byte[] buf = (byte[]) getElement(td.count, this.findColumn("COMPRESSED_DATA"));
System.out.println(" "+td.count+" "+buf[0]+" "+buf[1]+
" "+buf[2]+" "+buf[3]+
" "+buf[4]+" "+buf[5]+
" "+buf[6]+" "+buf[7]);
return getTile(td, buf);
}
private void importKeywords(BasicHDU hdu) {
Header newHdr = hdu.getHeader();
Header oldHdr = getHeader();
Cursor newC = newHdr.iterator();
newC.setKey("END");
Cursor oldC = oldHdr.iterator();
oldC.setKey("NAXIS");
while (oldC.hasNext()) {
HeaderCard old = (HeaderCard) (oldC.next());
String key = old.getKey();
if (!reservedKeys.contains(key)) {
newC.add(old);
}
}
}
/**
* Fill in a single tile's worth of data in the subset. Note that we are
* using FITS ordering of indices.
*
* @param tileArray The input stream containing the tile data.
* @param cutoutArray The cutout array
* @param tileCorners The current tile descriptor.
* @param corners The corners of the cutout array within the full image
* @param lengths The lengths of the cutout array
* @throws IOException
*/
private void insertTile(
Object tileData, int[] tileCorners, int tileSize[],
Object cutoutData, int[] cutoutCorners, int cutoutSize[],
String className,
int level) {
// Recall that our arrays are describing the cutout in
// the same order as FITS uses (x,y,z)
int x = tileCorners.length - level - 1; // Inverted index
int txStart = 0;
int cxStart = 0;
// Does the tile start before the cutout?
if (tileCorners[x] < cutoutCorners[x]) {
txStart = cutoutCorners[x] - tileCorners[x];
} else {
cxStart = tileCorners[x] - cutoutCorners[x];
}
int txCnt = tileSize[x];
if (tileCorners[x] + tileSize[x] > cutoutCorners[x] + cutoutSize[x]) {
txCnt = (cutoutCorners[x] + cutoutSize[x] - tileCorners[x] - txStart);
}
if (className.charAt(level + 1) == '[') {
// We are going to recurse to the next level.
// Note that the arrays are in FITS order, so
// we need to reverse them.
Object[] t = (Object[]) tileData;
Object[] c = (Object[]) cutoutData;
for (int i = 0; i < txCnt; i += 1) {
insertTile(t[txStart + i], tileCorners, tileSize,
c[cxStart + i], cutoutCorners, cutoutSize,
className, level + 1);
}
} else {
// Just copy the data into the cutout.
System.arraycopy(tileData, txStart, cutoutData, cxStart, txCnt);
}
}
public static void main(String[] args) throws Exception {
Fits f = new Fits(args[0]);
ImageHDU im = (ImageHDU) f.readHDU();
Fits g = new Fits();
Map<String, String> params = new HashMap<String, String>();
params.put("compression", "RICE_1");
TiledImageHDU tHdu = new TiledImageHDU(im, params);
g.addHDU(tHdu);
BufferedFile bf = new BufferedFile(args[1], "rw");
g.write(bf);
bf.close();
ImageHDU reconv = tHdu.getImageHDU();
bf = new BufferedFile(args[2], "rw");
f = new Fits();
f.addHDU(reconv);
f.write(bf);
bf.close();
}
public ImageTiler getImageTiler() {
return new TiledTiler();
}
class TiledTiler implements ImageTiler {
public Object getTile(int[] corners, int[] lengths) throws IOException {
Object array = ArrayFuncs.newInstance(baseClass, ArrayFuncs.reverseIndices(lengths));
getTile(array, corners, lengths);
return array;
}
/**
* Fill a subset from the tiles
*/
public void getTile(Object array, int[] corners, int[] lengths) throws IOException {
// First compute the tiles that we are going to loop over.
int[] tFirst = new int[naxis];
int[] tCount = new int[naxis];
for (int i = 0; i < naxis; i += 1) {
if (corners[i] < 0 || corners[i] >= imageSize[i]
|| (lengths[i] <= 0 || (corners[i] + lengths[i]) > imageSize[i])) {
throw new IllegalArgumentException("Invalid tile request");
}
tFirst[i] = corners[i] / tileSize[i];
tCount[i] = (corners[i] + lengths[i] - 1) / tileSize[i] - tFirst[i] + 1;
}
// Create a tile looper that goes over the tiles we want.
TileLooper tl = new TileLooper(imageSize, tileSize, tFirst, tCount);
String cName = array.getClass().getName();
Class base = ArrayFuncs.getBaseClass(array);
for (TileDescriptor td : tl) {
try {
Object tileData = TiledImageHDU.this.getTile(td);
insertTile(tileData, td.corner, td.size, array, corners, lengths, cName, 0);
} catch (FitsException e) {
throw new IOException("FITS error reading tile", e);
}
}
}
public Object getCompleteImage() throws IOException {
Object array = ArrayFuncs.newInstance(baseClass, ArrayFuncs.reverseIndices(imageSize));
int[] corner = new int[imageSize.length]; // Filled with 0's
getTile(array, corner, imageSize);
return array;
}
}
}
|
package com.renomad.capsaicin;
import java.nio.ByteBuffer;
import java.util.UUID;
import com.renomad.capsaicin.Logger;
/**
* Control message for data flow to server. Needs to
* be encrypted and secure. We want our communication
* to be opaque, but fast.
* see comments in code for capsaicin_server.c to better
* understand the protocol. -BK 1/19/2014
* @author Byron Katz
*/
public final class CtlMsg {
private final CtlAct action;
private final int sid;
private final UUID vid;
private final UUID uid;
private final long offset;
private final short sbytes;
//TODO - BK - make sure that the following adheres to best
//practices for thread safety
//TODO - BK - set up a way to send encoded messages back and forth.
//openssl?
/**
* Constructor method to creat a thread-safe object
* for control messages to server.
* actions are set by the CtlAct static object.
* @param sid The session id, for tracking our conversation.
* @param action CtlAct.send or CtlAct.receive, etc.
* @param vid the video (or whatever) we want, as a 16 byte UUID.
* @param uid the user we are, as a 16 byte UUID.
* @param origin location within the file to start the file pull.
* @param sbytes an integer to say how much to
* pull down. (probably make this a constant - should be
* less than 1500 bytes, from the best reading I've
* done on the subject. - BK 1/19/2014
* TODO - BK 1/19/2014 - make sure this is totally thread safe.
* for example, does it need to be synchronized?
* ////TODO - BK - WIP - FINISH THIS PART!
*/
public CtlMsg (int sid, CtlAct action, UUID vid, UUID uid,
long offset, short sbytes) {
this.sid = sid;
this.action = action;
this.vid = vid;
this.uid = uid;
this.offset = offset;
this.sbytes = sbytes;
}
/**
* Thread safe message object
* @return a throw-away byte array
*/
public byte[] getMessage() {
ByteBuffer mbuf = ByteBuffer.allocate(47); //current size
mbuf.putInt(sid)
.put(action.getValue())
.putLong(vid.getMostSignificantBits())
.putLong(vid.getLeastSignificantBits())
.putLong(uid.getMostSignificantBits())
.putLong(uid.getLeastSignificantBits())
.putLong(offset)
.putShort(sbytes);
return mbuf.array();
}
@Override
public String toString() {
return "action: " + action + " sid: " + sid + " vid: " + vid +
"uid: " + uid + " offset: " + offset + " sbytes: " + sbytes;
}
}
|
package com.nityankhanna.androidutils.system.io;
import android.content.Context;
import android.os.Environment;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.channels.FileChannel;
/**
* A utility class for file operations.
*/
public class FileManager {
private static FileManager sharedInstance;
private FileManager() {
}
public static FileManager getInstance() {
synchronized (FileManager.class) {
if (sharedInstance == null) {
sharedInstance = new FileManager();
}
}
return sharedInstance;
}
/**
* Determines if the there is the ability to write to external storage.
*
* @return Returns true if there is the ability to write to external storage.
*/
public boolean canWriteToExternalStorage() {
return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
}
/**
* Copies one file to another.
*
* @param source The source file.
* @param destination The destination file.
*
* @return Returns the destination file with the copied contents.
*
* @throws IOException
*/
public File copyFile(File source, File destination) throws IOException {
FileInputStream inputStream = new FileInputStream(source);
FileOutputStream outputStream = new FileOutputStream(destination);
FileChannel inChannel = inputStream.getChannel();
FileChannel outChannel = outputStream.getChannel();
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} finally {
if (inChannel != null) {
inChannel.close();
}
if (outChannel != null) {
outChannel.close();
}
inputStream.close();
outputStream.close();
}
return destination;
}
/**
* Logs an exception to a file.
*
* @param context The application context.
* @param exception The exception to log to the file.
*/
public void logException(Context context, Exception exception) {
logException(context, exception, null);
}
/**
* Logs an exception to a file.
*
* @param context The application context.
* @param exception The exception to log to the file.
* @param fileName The name of the file.
*/
public void logException(Context context, Exception exception, String fileName) {
ObjectOutputStream outputStream = null;
FileOutputStream fileOutputStream = null;
try {
if (fileName == null) {
fileOutputStream = context.openFileOutput(context.getPackageName() + "-exceptions", Context.MODE_PRIVATE);
} else {
fileOutputStream = context.openFileOutput(fileName, Context.MODE_PRIVATE);
}
fileOutputStream = context.openFileOutput(fileName, Context.MODE_PRIVATE);
outputStream = new ObjectOutputStream(fileOutputStream);
outputStream.writeObject(exception);
fileOutputStream.getFD().sync();
} catch (IOException ex) {
ex.printStackTrace();
throw new FileWriteException(ex.getMessage());
} finally {
try {
if (outputStream != null) {
outputStream.close();
}
if (fileOutputStream != null) {
fileOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* * Reads an Object from a file.
*
* @param context The application context.
* @param fileName The name of the file to read from.
*
* @return Returns the object from the file.
*/
public Object readObjectFromFile(Context context, String fileName) {
ObjectInputStream inputStream = null;
Object object = null;
try {
FileInputStream fileIn = context.openFileInput(fileName);
inputStream = new ObjectInputStream(fileIn);
object = inputStream.readObject();
} catch (IOException ex) {
ex.printStackTrace();
throw new FileReadException(ex.getMessage());
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return object;
}
/**
* Reads a raw text file from the android resources.
*
* @param context The application context.
* @param resourceId The id of the resource to find.
*
* @return Returns a string containing the text from the file.
*/
public String readTextFileFromResources(Context context, int resourceId) {
InputStream inputStream = null;
BufferedReader bufferedReader = null;
try {
inputStream = context.getResources().openRawResource(resourceId);
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuilder text = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
text.append(line);
text.append('\n');
}
return text.toString();
} catch (IOException ex) {
ex.printStackTrace();
throw new FileReadException(ex.getMessage());
} finally {
try {
if (bufferedReader != null) {
bufferedReader.close();
}
if (inputStream != null) {
inputStream.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
/**
* Writes an object to a file.
*
* @param context The application context.
* @param object The object to write to the file.
* @param filename The The name of the file to write to.
* @param mode The mode in which to write the file.
*/
public void writeObjectToFile(Context context, Object object, String filename, FileMode mode) {
ObjectOutputStream outputStream = null;
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = context.openFileOutput(filename, mode.getValue());
outputStream = new ObjectOutputStream(fileOutputStream);
outputStream.writeObject(object);
fileOutputStream.getFD().sync();
} catch (IOException ex) {
ex.printStackTrace();
throw new FileWriteException(ex.getMessage());
} finally {
try {
if (outputStream != null) {
outputStream.close();
}
if (fileOutputStream != null) {
fileOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
|
package ca.ualberta.cs.cmput301t02project;
import java.util.ArrayList;
import ca.ualberta.cs.cmput301t02project.model.CommentModel;
import ca.ualberta.cs.cmput301t02project.model.LocationModel;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class CreateCommentActivity extends Activity {
// TODO: Refactor with new classes
// private CommentsListController commentsListController;
// private MyCommentsController myCommentsListController;
private Location currentLocation;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_comment);
Button post = (Button) findViewById(R.id.create_post);
String loc = "No location yet";
currentLocation = new Location(loc);
// Retrieve location manager
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Requests location from provider
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
post.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EditText inputComment = (EditText) findViewById(R.id.create_text);
String receivedCoor = "No Location Avaliable";
if (currentLocation != null) { // for testing only, remove later -KW
double lat = currentLocation.getLatitude();
String strLat = String.valueOf(lat);
double lon = currentLocation.getLongitude();
String strLon = String.valueOf(lon);
receivedCoor = strLat.toString()+strLon.toString();
}
// Refactor into MVC?
// Username is temporarily in front of the comment. Can redesign
// later -SB
CommentModel comment = new CommentModel(receivedCoor + ": "
+ inputComment.getText().toString(), null, CurrentUser
.getName().toString());// added a
// testVariable(receivedCoor)
// here, delete after -KW
ArrayList<CommentModel> commentList = ProjectApplication
.getCurrentCommentList();
commentList.add(comment);
finish();
}
});
}
// Retrieve location updates through LocationListener interface
private final LocationListener locationListener = new LocationListener() {
// TODO: override the four methods.
@Override
public void onLocationChanged(Location location) {
if (location != null) {
currentLocation = location;
} else {
// do something later here
}
}
@Override
public void onProviderDisabled(String provider) {
// TODO
}
@Override
public void onProviderEnabled(String provider) {
// TODO
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.create_comment, menu);
return true;
}
}
|
package app.web;
import app.web.interceptor.Protected;
import core.framework.api.http.ContentType;
import core.framework.api.web.Request;
import core.framework.api.web.Response;
import core.framework.api.web.site.Message;
import javax.inject.Inject;
/**
* @author neo
*/
public class IndexController {
@Inject
Message message;
@Inject
LanguageManager languageManager;
@Protected(operation = "index")
public Response index(Request request) {
IndexPage model = new IndexPage();
model.name = message.get("key.name", languageManager.language()).orElse("world not found");
model.imageURL = "https://image.com/image123.jpg";
// Session session = request.session();
//// Optional<String> hello = session.get("hello");
// session.set("hello", "world");
Response response = Response.html("/template/index.html", model, languageManager.language());
response.cookie(Cookies.TEST, "1+2");
response.cookie(Cookies.TEST1, "hello \"\" cookies");
return response;
}
public Response submit(Request request) {
return Response.text("hello " + request.formParam("name").orElse("nobody"), ContentType.TEXT_PLAIN);
}
public Response logout(Request request) {
request.session().invalidate();
return Response.text("logout", ContentType.TEXT_PLAIN);
}
}
|
package jade.imtp.leap.JICP;
//#MIDP_EXCLUDE_FILE
import jade.core.Profile;
import jade.core.IMTPManager;
import jade.mtp.TransportAddress;
import jade.imtp.leap.*;
import jade.util.Logger;
import jade.util.leap.Properties;
import java.io.*;
import java.net.*;
import java.util.Hashtable;
import java.util.Enumeration;
import java.util.StringTokenizer;
/**
* Class declaration
* @author Giovanni Caire - TILAB
* @author Ronnie Taib - Motorola
* @author Nicolas Lhuillier - Motorola
* @author Steffen Rusitschka - Siemens
*/
public class JICPServer extends Thread implements PDPContextManager.Listener {
public static final String LEAP_PROPERTY_FILE = "leap-property-file";
private static final String LEAP_PROPERTY_FILE_DEFAULT = "leap.properties";
private static final String PDP_CONTEXT_MANAGER_CLASS = "pdp-context-manager";
private static final int LISTENING = 0;
private static final int TERMINATING = 1;
private int state = LISTENING;
private String host;
private ServerSocket server;
private ICP.Listener cmdListener;
private int mediatorCnt = 1;
private Hashtable mediators = new Hashtable();
private Properties leapProps = new Properties();
private PDPContextManager myPDPContextManager;
private int handlersCnt = 0;
private int maxHandlers;
private ConnectionFactory connFactory;
private Logger myLogger;
/**
* Constructor declaration
*/
public JICPServer(Profile p, JICPPeer myPeer, ICP.Listener l, ConnectionFactory f, int max) throws ICPException {
cmdListener = l;
connFactory = f;
maxHandlers = max;
myLogger = Logger.getMyLogger(getClass().getName());
StringBuffer sb = null;
int idLength;
String peerID = myPeer.getID();
if (peerID != null) {
sb = new StringBuffer(peerID);
sb.append('-');
idLength = sb.length();
}
else {
sb = new StringBuffer();
idLength = 0;
}
// Local host
sb.append(JICPProtocol.LOCAL_HOST_KEY);
host = p.getParameter(sb.toString(), null);
if (host == null) {
// Local host not specified --> try to get it using JICP GET_ADDRESS
sb.setLength(idLength);
sb.append(JICPProtocol.REMOTE_URL_KEY);
String remoteURL = p.getParameter(sb.toString(), null);
if (remoteURL != null) {
host = myPeer.getAddress(remoteURL);
}
else {
// Retrieve local host automatically
host = Profile.getDefaultNetworkName();
}
}
// Local port: a peripheral container can change it if busy...
int port = JICPProtocol.DEFAULT_PORT;
boolean changePortIfBusy = !p.getBooleanProperty(Profile.MAIN, true);
sb.setLength(idLength);
sb.append(JICPProtocol.LOCAL_PORT_KEY);
String strPort = p.getParameter(sb.toString(), null);
try {
port = Integer.parseInt(strPort);
}
catch (Exception e) {
// Try to use the Peer-ID as the port number
try {
port = Integer.parseInt(peerID);
}
catch (Exception e1) {
// Keep default
}
}
// Read the LEAP configuration properties
String fileName = p.getParameter(LEAP_PROPERTY_FILE, LEAP_PROPERTY_FILE_DEFAULT);
try {
leapProps.load(fileName);
}
catch (Exception e) {
myLogger.log(Logger.FINE, "Can't read LEAP property file "+fileName+". "+e);
// Ignore: no back end properties specified
}
// Initialize the PDPContextManager if specified
String pdpContextManagerClass = leapProps.getProperty(PDP_CONTEXT_MANAGER_CLASS);
if (pdpContextManagerClass != null) {
try {
myPDPContextManager = (PDPContextManager) Class.forName(pdpContextManagerClass).newInstance();
myPDPContextManager.init(leapProps);
myPDPContextManager.registerListener(this);
}
catch (Throwable t) {
t.printStackTrace();
myPDPContextManager = null;
}
}
// Create the ServerSocket
server = myPeer.getServerSocket(host, port, changePortIfBusy);
setDaemon(true);
setName("JICPServer-"+getLocalPort());
}
public int getLocalPort() {
return server.getLocalPort();
}
public String getLocalHost() {
return host;
}
/**
Shut down this JICP server
*/
public synchronized void shutdown() {
if(myLogger.isLoggable(Logger.FINE))
myLogger.log(Logger.FINE,"Shutting down JICPServer...");
state = TERMINATING;
try {
// Force the listening thread (this) to exit from the accept()
// Calling this.interrupt(); should be the right way, but it seems
// not to work...so do that by closing the server socket.
server.close();
// Wait for the listening thread to complete
this.join();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
catch (InterruptedException ie) {
ie.printStackTrace();
}
}
/**
* JICPServer thread entry point. Accept incoming connections
* and for each of them start a ConnectionHandler that handles it.
*/
public void run() {
while (state != TERMINATING) {
try {
// Accept connection
Socket s = server.accept();
InetAddress addr = s.getInetAddress();
int port = s.getPort();
if(myLogger.isLoggable(Logger.FINEST))
myLogger.log(Logger.FINEST,"Incoming connection from "+addr+":"+port);
Connection c = connFactory.createConnection(s);
new ConnectionHandler(c, addr, port).start(); // start a handler and go back to listening
}
catch (InterruptedIOException e) {
// These can be generated by socket timeout (just ignore
// the exception) or by a call to the shutdown()
// method (the state has been set to TERMINATING and the
// server will exit).
}
catch (Exception e) {
if (state == LISTENING) {
if(myLogger.isLoggable(Logger.WARNING))
myLogger.log(Logger.WARNING,"Problems accepting a new connection");
e.printStackTrace();
// Stop listening
state = TERMINATING;
}
}
} // END of while(listen)
if(myLogger.isLoggable(Logger.FINE))
myLogger.log(Logger.FINE,"JICPServer terminated");
// release socket
try {
server.close();
}
catch (IOException io) {
if(myLogger.isLoggable(Logger.WARNING))
myLogger.log(Logger.WARNING,"I/O error closing the server socket");
io.printStackTrace();
}
server = null;
// Close all mediators
Enumeration e = mediators.elements();
while (e.hasMoreElements()) {
JICPMediator m = (JICPMediator) e.nextElement();
m.kill();
}
mediators.clear();
}
/**
* Called by a Mediator to notify that it is no longer active
*/
public void deregisterMediator(String id) {
myLogger.log(Logger.FINE, "Deregistering mediator "+id);
mediators.remove(id);
}
/**
Called by the JICPPeer ticker at each tick
*/
public void tick(long currentTime) {
synchronized (mediators) {
Enumeration e = mediators.elements();
while (e.hasMoreElements()) {
JICPMediator m = (JICPMediator) e.nextElement();
m.tick(currentTime);
}
}
}
/**
Called by the PDPContextManager (if any)
*/
public void handlePDPContextClosed(String id) {
// FIXME: to be implemented
}
/**
Inner class ConnectionHandler.
Handle a connection accepted by this JICPServer
*/
class ConnectionHandler extends Thread {
private Connection c;
private InetAddress addr;
private int port;
/**
* Constructor declaration
* @param s
*/
public ConnectionHandler(Connection c, InetAddress addr, int port) {
this.c = c;
this.addr = addr;
this.port = port;
}
/**
* Thread entry point
*/
public void run() {
handlersCnt++;
if(myLogger.isLoggable(Logger.FINEST))
myLogger.log(Logger.FINEST,"CommandHandler started");
boolean closeConnection = true;
int status = 0;
byte type = (byte) 0;
try {
boolean loop = false;
do {
// Read the incoming JICPPacket
JICPPacket pkt = c.readPacket();
JICPPacket reply = null;
status = 1;
type = pkt.getType();
switch (type) {
case JICPProtocol.COMMAND_TYPE:
case JICPProtocol.RESPONSE_TYPE:
// Get the right recipient and let it process the command.
String recipientID = pkt.getRecipientID();
if(myLogger.isLoggable(Logger.FINEST))
myLogger.log(Logger.FINEST,"Recipient: "+recipientID);
if (recipientID != null) {
// The recipient is one of the mediators
JICPMediator m = (JICPMediator) mediators.get(recipientID);
if (m != null) {
if(myLogger.isLoggable(Logger.FINEST))
myLogger.log(Logger.FINEST,"Passing incoming packet to mediator "+recipientID);
reply = m.handleJICPPacket(pkt, addr, port);
}
else {
// If the packet is a response we don't need to reply
if (type == JICPProtocol.COMMAND_TYPE) {
reply = new JICPPacket("Unknown recipient "+recipientID, null);
}
}
}
else {
// The recipient is my ICP.Listener (the local CommandDispatcher)
loop = true;
if (type == JICPProtocol.COMMAND_TYPE) {
if(myLogger.isLoggable(Logger.FINEST))
myLogger.log(Logger.FINEST,"Passing incoming COMMAND to local listener");
byte[] rsp = cmdListener.handleCommand(pkt.getData());
byte dataInfo = JICPProtocol.DEFAULT_INFO;
if (handlersCnt >= maxHandlers) {
// Too many connections open --> close the connection as soon as the command has been served
dataInfo |= JICPProtocol.TERMINATED_INFO;
loop = false;
}
reply = new JICPPacket(JICPProtocol.RESPONSE_TYPE, dataInfo, rsp);
}
if ((pkt.getInfo() & JICPProtocol.TERMINATED_INFO) != 0) {
loop = false;
}
}
break;
case JICPProtocol.GET_ADDRESS_TYPE:
// Respond sending back the caller address
if(myLogger.isLoggable(Logger.INFO))
myLogger.log(Logger.INFO,"Received a GET_ADDRESS request from "+addr+":"+port);
reply = new JICPPacket(JICPProtocol.GET_ADDRESS_TYPE, JICPProtocol.DEFAULT_INFO, addr.getHostAddress().getBytes());
break;
//#PJAVA_EXCLUDE_BEGIN
case JICPProtocol.CREATE_MEDIATOR_TYPE:
// Starts a new Mediator and sends back its ID
String s = new String(pkt.getData());
Properties p = parseProperties(s);
// If there is a PDPContextManager add the PDP context properties
if (myPDPContextManager != null) {
Properties pdpContextInfo = myPDPContextManager.getPDPContextInfo(addr);
if (pdpContextInfo != null) {
mergeProperties(p, pdpContextInfo);
}
else {
if(myLogger.isLoggable(Logger.WARNING))
myLogger.log(Logger.WARNING,"CREATE_MEDIATOR request from non authorized address: "+addr);
reply = new JICPPacket("Not authorized", null);
break;
}
}
// Get mediator ID from the passed properties (if present)
String id = p.getProperty(JICPProtocol.MEDIATOR_ID_KEY);
String msisdn = p.getProperty(PDPContextManager.MSISDN);
if(id != null) {
if (msisdn != null && !msisdn.equals(id)) {
// Security attack: Someone is pretending to be someone other
if(myLogger.isLoggable(Logger.WARNING))
myLogger.log(Logger.WARNING,"CREATE_MEDIATOR request with mediator-id != MSISDN. Address is: "+addr);
reply = new JICPPacket("Not authorized", null);
break;
}
// An existing front-end whose back-end was lost. The BackEnd must resynch
p.setProperty(jade.core.BackEndContainer.RESYNCH, "true");
}
else {
// Use the MSISDN (if present)
id = msisdn;
if (id == null) {
// Construct a default id using the string representation of the server's TCP endpoint
id = "BE-"+getLocalHost() + ':' + getLocalPort() + '-' + String.valueOf(mediatorCnt++);
}
}
// If last connection from the same device aborted, the old
// BackEnd may still exist as a zombie. In case ids are assigned
// using the MSISDN the new name is equals to the old one.
if (id.equals(msisdn)) {
JICPMediator old = (JICPMediator) mediators.get(id);
if (old != null) {
// This is a zombie mediator --> kill it
myLogger.log(Logger.INFO, "Replacing old mediator "+id);
old.kill();
// Be sure the zombie container has been removed
waitABit(1000);
}
}
if(myLogger.isLoggable(Logger.INFO))
myLogger.log(Logger.INFO,"Received a CREATE_MEDIATOR request from "+ addr + ":" + port + ". ID is [" + id + "]");
// Start the mediator
JICPMediator m = startMediator(id, p);
m.handleIncomingConnection(c, pkt, addr, port);
if(myLogger.isLoggable(Logger.FINE))
myLogger.log(Logger.FINE, "Reregistering mediator "+id);
mediators.put(id, m);
// Create an ad-hoc reply including the assigned mediator-id and the IP address
String replyMsg = id+'#'+addr.getHostAddress();
reply = new JICPPacket(JICPProtocol.RESPONSE_TYPE, JICPProtocol.DEFAULT_INFO, replyMsg.getBytes());
closeConnection = false;
break;
case JICPProtocol.CONNECT_MEDIATOR_TYPE:
// A mediated container is (re)connecting to its mediator
recipientID = pkt.getRecipientID();
// FIXME: If there is a PDPContextManager check that the recipientID is the MSISDN
if(myLogger.isLoggable(Logger.INFO))
myLogger.log(Logger.INFO,"Received a CONNECT_MEDIATOR request from "+addr+":"+port+". Mediator ID is "+recipientID);
m = (JICPMediator) mediators.get(recipientID);
if (m != null) {
// Don't close the connection, but pass it to the proper
// mediator.
m.handleIncomingConnection(c, pkt, addr, port);
closeConnection = false;
reply = new JICPPacket(JICPProtocol.RESPONSE_TYPE, JICPProtocol.DEFAULT_INFO, addr.getHostAddress().getBytes());
}
else {
if(myLogger.isLoggable(Logger.INFO))
myLogger.log(Logger.INFO,"Mediator "+recipientID+" not found");
reply = new JICPPacket("Mediator "+recipientID+" not found", null);
}
break;
//#PJAVA_EXCLUDE_END
default:
// Send back an error response
if(myLogger.isLoggable(Logger.WARNING))
myLogger.log(Logger.WARNING,"Uncorrect JICP data type: "+pkt.getType());
reply = new JICPPacket("Uncorrect JICP data type: "+pkt.getType(), null);
}
status = 2;
// Send the actual response data
if (reply != null) {
//reply.writeTo(out);
c.writePacket(reply);
}
status = 3;
} while (loop);
}
catch (Exception e) {
switch (status) {
case 0:{
if(myLogger.isLoggable(Logger.SEVERE))
myLogger.log(Logger.SEVERE,"Communication error reading incoming packet from "+addr+":"+port);
e.printStackTrace();
}
break;
case 1:
if(myLogger.isLoggable(Logger.SEVERE))
myLogger.log(Logger.SEVERE,"Error handling incoming packet");
e.printStackTrace();
// If the incoming packet was a command, try
// to send back a generic error response
if (type == JICPProtocol.COMMAND_TYPE && c != null) {
try {
c.writePacket(new JICPPacket("Unexpected error", e));
}
catch (IOException ioe) {
// Just print a warning
if(myLogger.isLoggable(Logger.WARNING))
myLogger.log(Logger.WARNING,"Can't send back error indication "+ioe);
}
}
break;
case 2:
if(myLogger.isLoggable(Logger.SEVERE))
myLogger.log(Logger.SEVERE,"Communication error writing return packet to "+addr+":"+port+" ["+e.toString()+"]");
break;
case 3:
// This is a re-used connection waiting for the next incoming packet
if (e instanceof EOFException) {
if(myLogger.isLoggable(Logger.FINE))
myLogger.log(Logger.FINE,"Client "+addr+":"+port+" has closed the connection.");
}
else {
if(myLogger.isLoggable(Logger.FINE))
myLogger.log(Logger.FINE,"Unexpected client "+addr+":"+port+" termination. "+e.toString());
}
}
}
finally {
try {
if (closeConnection) {
// Close connection
if(myLogger.isLoggable(Logger.FINEST))
myLogger.log(Logger.FINEST,"Closing connection with "+addr+":"+port);
c.close();
}
}
catch (IOException io) {
if(myLogger.isLoggable(Logger.INFO))
myLogger.log(Logger.INFO,"I/O error while closing the connection");
io.printStackTrace();
}
handlersCnt
}
}
} // END of inner class ConnectionHandler
private Properties parseProperties(String s) throws ICPException {
StringTokenizer st = new StringTokenizer(s, "=
Properties p = new Properties();
while (st.hasMoreTokens()) {
String key = st.nextToken();
if (!st.hasMoreTokens()) {
throw new ICPException("Wrong initialization properties format.");
}
p.setProperty(key, st.nextToken());
}
return p;
}
private void mergeProperties(Properties p1, Properties p2) {
Enumeration e = p2.propertyNames();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
p1.setProperty(key, p2.getProperty(key));
}
}
private JICPMediator startMediator(String id, Properties p) throws Exception {
String className = p.getProperty(JICPProtocol.MEDIATOR_CLASS_KEY);
if (className != null) {
JICPMediator m = (JICPMediator) Class.forName(className).newInstance();
mergeProperties(p, leapProps);
myLogger.log(Logger.FINE, "Initializing mediator "+id+" with properties "+p);
m.init(this, id, p);
return m;
}
else {
throw new ICPException("No JICPMediator class specified.");
}
}
private void waitABit(long t) {
try {
Thread.sleep(t);
}
catch (InterruptedException ie) {
}
}
}
|
package jade.imtp.leap;
import jade.core.*;
import jade.lang.acl.ACLMessage;
import jade.mtp.TransportAddress;
import jade.util.leap.*;
import jade.imtp.leap.JICP.JICPProtocol;
import jade.imtp.leap.JICP.Connection;
import jade.util.Logger;
import java.io.IOException;
/**
* @author Giovanni Caire - Telecom Italia Lab
*/
public class LEAPIMTPManager implements IMTPManager {
/**
* Profile keys for LEAP-IMTP specific parameters
*/
static final String MAIN_URL = "main-url";
private static final String ICPS = "icps";
private static final String ROUTER_URL = "router-url";
/**
* Local pointer to the singleton command dispatcher in this JVM
*/
private CommandDispatcher theDispatcher = null;
/**
* The Profile holding the configuration for this IMTPManager
*/
private Profile theProfile = null;
private String masterPMAddr;
private String localAddr;
private NodeLEAP localNode;
Logger logger = Logger.getMyLogger(this.getClass().getName());
/**
* Default constructor used to dynamically instantiate a new
* LEAPIMTPManager object
*/
public LEAPIMTPManager() {
}
// IMTPManager Interface
/**
* Initialize the support for intra-platform communication
*/
public void initialize(Profile p) throws IMTPException {
theProfile = p;
// Get the singleton CommandDispatcher
theDispatcher = CommandDispatcher.getDispatcher();
// Add to the CommandDispatcher the ICPs specified in the Profile
try {
// Set defaults if not explicitly set.
setDefaults();
List l = theProfile.getSpecifiers(ICPS);
Iterator it = l.iterator();
while (it.hasNext()) {
Specifier s = (Specifier) it.next();
try {
ICP peer = (ICP) Class.forName(s.getClassName()).newInstance();
String id = (s.getArgs() != null ? (String) (s.getArgs()[0]) : null);
theDispatcher.addICP(peer, id, theProfile);
}
catch (Exception e) {
if(logger.isLoggable(Logger.SEVERE))
logger.log(Logger.SEVERE,"Error adding ICP. "+e);
}
}
// Initialize the local node
localNode = new NodeLEAP("No-Name", theProfile.getBooleanProperty(Profile.MAIN, true));
Skeleton skel = new NodeSkel(localNode);
theDispatcher.registerSkeleton(skel, localNode);
}
catch (ProfileException pe) {
// Just print a warning
if(logger.isLoggable(Logger.SEVERE))
logger.log(Logger.SEVERE,"Profile error. "+pe.getMessage());
}
// Now check that some ICP is active. Note that, as a CommandDispatcher
// can serve multiple IMTPManagers, some ICPs could be already active.
List URLs = theDispatcher.getLocalURLs();
if (URLs.size() == 0) {
throw new IMTPException("No ICP active");
}
else {
localAddr = (String) URLs.get(0);
Iterator it = URLs.iterator();
logger.log(Logger.ALL,"Listening for intra-platform commands on address:");
StringBuffer sb = new StringBuffer("Listening for intra-platform commands on address:\n");
while (it.hasNext()) {
sb.append("- "+(String) it.next()+"\n");
}
logger.log(Logger.INFO,sb.toString());
}
// Be sure the mainURL uses the host address. Note that this must
// be done after ICP installation
adjustMainURL();
// Get the address of the master PlatformManager (if this is a backup main)
if (theProfile.getBooleanProperty(Profile.MAIN, true)) {
if (theProfile.getBooleanProperty(Profile.LOCAL_SERVICE_MANAGER, false)) {
// This node hosts a real PlatformManager that is NOT the master PlatformManager
// --> MAIN_URL points to the master PlatformManager
masterPMAddr = theProfile.getParameter(MAIN_URL, null);
}
}
// Finally, if a URL for the default router is specified in the
// Profile, set it in the CommandDispatcher
theDispatcher.setRouterAddress(theProfile.getParameter(ROUTER_URL, null));
}
private void adjustMainURL() {
//#MIDP_EXCLUDE_BEGIN
try {
String mainURL = theProfile.getParameter(MAIN_URL, null);
TransportAddress ta = theDispatcher.stringToAddr(mainURL);
java.net.InetAddress ad = java.net.InetAddress.getByName(ta.getHost());
TransportProtocol tp = theDispatcher.getProtocol(ta.getProto());
String hostAddr = ad.getHostAddress();
if (hostAddr.equals("127.0.0.1")) {
hostAddr = ad.getHostName();
}
ta = tp.buildAddress(hostAddr, ta.getPort(), ta.getFile(), ta.getAnchor());
// DEBUG
//System.out.println("MAIN URL set to "+tp.addrToString(ta));
theProfile.setParameter(MAIN_URL, tp.addrToString(ta));
}
catch (Exception e) {
// Ignore it
}
//#MIDP_EXCLUDE_END
}
public Node getLocalNode() throws IMTPException {
return localNode;
}
//#MIDP_EXCLUDE_BEGIN
public void exportPlatformManager(PlatformManager mgr) throws IMTPException {
Skeleton skel = new PlatformManagerSkel(mgr, this);
mgr.setLocalAddress(localAddr);
theDispatcher.registerSkeleton(skel, mgr);
// Attach to the original Platform manager, if any
if (masterPMAddr != null) {
PlatformManager masterPM = theDispatcher.getPlatformManagerStub(masterPMAddr);
try {
((PlatformManagerImpl) mgr).setPlatformName(masterPM.getPlatformName());
mgr.addReplica(masterPMAddr, true); // Do as if it was a propagated info
masterPM.addReplica(localAddr, false);
}
catch (ServiceException se) {
throw new IMTPException("Cannot attach to the original PlatformManager.", se);
}
}
}
public void unexportPlatformManager(PlatformManager pm) throws IMTPException {
theDispatcher.deregisterSkeleton(pm);
}
//#MIDP_EXCLUDE_END
public PlatformManager getPlatformManagerProxy() throws IMTPException {
return theDispatcher.getPlatformManagerProxy(theProfile);
}
public PlatformManager getPlatformManagerProxy(String addr) throws IMTPException {
return theDispatcher.getPlatformManagerStub(addr);
}
public void reconnected(PlatformManager pm) {
theDispatcher.setPlatformManagerProxy(pm);
}
// FIXME: this is not IMTP-dependent --> Should be moved elsewhere
public Service.Slice createSliceProxy(String serviceName, Class itf, Node where) throws IMTPException {
try {
Class proxyClass = Class.forName(serviceName + "Proxy");
Service.SliceProxy proxy = (Service.SliceProxy)proxyClass.newInstance();
proxy.setNode(where);
return proxy;
}
catch(Exception e) {
throw new IMTPException("Error creating a slice proxy", e);
}
}
/**
* Release all resources of this LEAPIMTPManager
*/
public void shutDown() {
try {
localNode.exit();
theDispatcher.deregisterSkeleton(localNode);
}
catch (IMTPException imtpe) {
// Should never happen since this is a local call
imtpe.printStackTrace();
}
}
public List getLocalAddresses() {
return theDispatcher.getLocalTAs();
}
// PRIVATE METHODS
/**
In the Profile ICPS can be specified as follows.
1) If there is only one ICP -->
icps = <icp-class-name>
<param-key> = <param-value>
....
2) In general (typically used when there are 2 or more ICPs)
icps = <icp1-class-name>(<icp1-id>);<icp2-class-name>(<icp2-id>)...
<icp1-id>-<param-key> = <param-value>
....
<icp2-id>-<param-key> = <param-value>
....
If there is no ICP indication set it as follows.
a) Peripheral container / J2SE
- There is at least 1 ICP already active --> Nothing
- There are no ICPs already active --> JICPPeer
b) Peripheral container / PJAVA or MIDP --> JICPBMPeer
c) Main container / J2SE or PJAVA --> JICPPeer
*/
private void setDefaults() throws ProfileException {
// - MAIN URL (Useful for peripheral containers and backup main. Ignored otherwise
String mainURL = theProfile.getParameter(MAIN_URL, null);
if (mainURL == null) {
String mainHost = getMainHost();
if (mainHost != null) {
String mainProto = theProfile.getParameter(Profile.MAIN_PROTO, "jicp");
String mainPort = theProfile.getParameter(Profile.MAIN_PORT, null);
mainPort = (mainPort != null) ? (":" + mainPort) : (":" + JICPProtocol.DEFAULT_PORT);
mainURL = new String(mainProto + "://" + mainHost + mainPort);
theProfile.setParameter(MAIN_URL, mainURL);
}
}
if (!theProfile.getBooleanProperty(Profile.MAIN, true)) {
// ICPS for a "Peripheral Container"
if (theProfile.getParameter(ICPS, null) == null) {
String jvm = theProfile.getParameter(Profile.JVM, null);
if (Profile.J2SE.equals(jvm)) {
// Set default ICPS for J2SE
if (theDispatcher.getLocalURLs().size() == 0) {
theProfile.setParameter(ICPS, "jade.imtp.leap.JICP.JICPPeer");
}
}
else {
// Set default ICPS for PJAVA and MIDP (same)
theProfile.setParameter(ICPS, "jade.imtp.leap.JICP.JICPBMPeer");
if (theProfile.getParameter(JICPProtocol.REMOTE_URL_KEY, null) == null) {
theProfile.setParameter(JICPProtocol.REMOTE_URL_KEY, mainURL);
}
}
}
}
else {
// ICPS for a Main Container
if (theProfile.getParameter(ICPS, null) == null) {
theProfile.setParameter(ICPS, "jade.imtp.leap.JICP.JICPPeer");
}
}
}
private String getMainHost() {
String host = theProfile.getParameter(Profile.MAIN_HOST, null);
//#MIDP_EXCLUDE_BEGIN
if (host == null) {
host = Profile.getDefaultNetworkName();
}
//#MIDP_EXCLUDE_END
return host;
}
}
|
package com.newsblur.activity;
import android.content.Intent;
import android.os.Bundle;
import android.app.FragmentManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;
import com.newsblur.R;
import com.newsblur.fragment.DefaultFeedViewDialogFragment;
import com.newsblur.fragment.ItemListFragment;
import com.newsblur.fragment.ReadFilterDialogFragment;
import com.newsblur.fragment.StoryOrderDialogFragment;
import com.newsblur.service.NBSyncService;
import com.newsblur.util.AppConstants;
import com.newsblur.util.DefaultFeedView;
import com.newsblur.util.DefaultFeedViewChangedListener;
import com.newsblur.util.FeedSet;
import com.newsblur.util.FeedUtils;
import com.newsblur.util.ReadFilter;
import com.newsblur.util.ReadFilterChangedListener;
import com.newsblur.util.StateFilter;
import com.newsblur.util.StoryOrder;
import com.newsblur.util.StoryOrderChangedListener;
import com.newsblur.view.StateToggleButton.StateChangedListener;
public abstract class ItemsList extends NbActivity implements StateChangedListener, StoryOrderChangedListener, ReadFilterChangedListener, DefaultFeedViewChangedListener {
public static final String EXTRA_STATE = "currentIntelligenceState";
private static final String STORY_ORDER = "storyOrder";
private static final String READ_FILTER = "readFilter";
private static final String DEFAULT_FEED_VIEW = "defaultFeedView";
public static final String BUNDLE_FEED_IDS = "feedIds";
protected ItemListFragment itemListFragment;
protected FragmentManager fragmentManager;
private TextView overlayStatusText;
protected StateFilter currentState;
private FeedSet fs;
protected boolean stopLoading = false;
@Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
overridePendingTransition(R.anim.slide_in_from_right, R.anim.slide_out_to_left);
// our intel state is entirely determined by the state of the Main view
currentState = (StateFilter) getIntent().getSerializableExtra(EXTRA_STATE);
this.fs = createFeedSet();
requestWindowFeature(Window.FEATURE_PROGRESS);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_itemslist);
fragmentManager = getFragmentManager();
getActionBar().setDisplayHomeAsUpEnabled(true);
this.overlayStatusText = (TextView) findViewById(R.id.itemlist_sync_status);
}
protected abstract FeedSet createFeedSet();
public FeedSet getFeedSet() {
return this.fs;
}
@Override
protected void onResume() {
super.onResume();
updateStatusIndicators();
stopLoading = false;
// this view shows stories, it is not safe to perform cleanup
NBSyncService.holdStories(true);
// Reading activities almost certainly changed the read/unread state of some stories. Ensure
// we reflect those changes promptly.
itemListFragment.hasUpdated();
}
private void getFirstStories() {
stopLoading = false;
triggerRefresh(AppConstants.READING_STORY_PRELOAD, 0);
}
@Override
protected void onPause() {
stopLoading = true;
NBSyncService.holdStories(false);
super.onPause();
}
public void triggerRefresh(int desiredStoryCount, int totalSeen) {
if (!stopLoading) {
boolean gotSome = NBSyncService.requestMoreForFeed(fs, desiredStoryCount, totalSeen);
if (gotSome) triggerSync();
updateStatusIndicators();
}
}
public void markItemListAsRead() {
FeedUtils.markFeedsRead(fs, null, null, this);
Toast.makeText(this, R.string.toast_marked_stories_as_read, Toast.LENGTH_SHORT).show();
setResult(RESULT_OK);
finish();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
return true;
} else if (item.getItemId() == R.id.menu_mark_all_as_read) {
markItemListAsRead();
return true;
} else if (item.getItemId() == R.id.menu_story_order) {
StoryOrder currentValue = getStoryOrder();
StoryOrderDialogFragment storyOrder = StoryOrderDialogFragment.newInstance(currentValue);
storyOrder.show(getFragmentManager(), STORY_ORDER);
return true;
} else if (item.getItemId() == R.id.menu_read_filter) {
ReadFilter currentValue = getReadFilter();
ReadFilterDialogFragment readFilter = ReadFilterDialogFragment.newInstance(currentValue);
readFilter.show(getFragmentManager(), READ_FILTER);
return true;
} else if (item.getItemId() == R.id.menu_default_view) {
DefaultFeedView currentValue = getDefaultFeedView();
DefaultFeedViewDialogFragment readFilter = DefaultFeedViewDialogFragment.newInstance(currentValue);
readFilter.show(getFragmentManager(), DEFAULT_FEED_VIEW);
return true;
}
return false;
}
// TODO: can all of these be replaced with PrefsUtils queries via FeedSet?
protected abstract StoryOrder getStoryOrder();
protected abstract ReadFilter getReadFilter();
protected abstract DefaultFeedView getDefaultFeedView();
@Override
public void handleUpdate() {
updateStatusIndicators();
if (itemListFragment != null) {
itemListFragment.hasUpdated();
}
}
private void updateStatusIndicators() {
boolean isLoading = NBSyncService.isFeedSetSyncing(this.fs);
setProgressBarIndeterminateVisibility(isLoading);
if (itemListFragment != null) {
itemListFragment.setLoading(isLoading);
}
if (overlayStatusText != null) {
String syncStatus = NBSyncService.getSyncStatusMessage();
if (syncStatus != null) {
overlayStatusText.setText(syncStatus);
overlayStatusText.setVisibility(View.VISIBLE);
} else {
overlayStatusText.setVisibility(View.GONE);
}
}
}
@Override
public void changedState(StateFilter state) {
itemListFragment.changeState(state);
}
@Override
public void storyOrderChanged(StoryOrder newValue) {
updateStoryOrderPreference(newValue);
FeedUtils.clearReadingSession();
itemListFragment.resetEmptyState();
itemListFragment.hasUpdated();
itemListFragment.scrollToTop();
getFirstStories();
}
public abstract void updateStoryOrderPreference(StoryOrder newValue);
@Override
public void readFilterChanged(ReadFilter newValue) {
updateReadFilterPreference(newValue);
FeedUtils.clearReadingSession();
itemListFragment.resetEmptyState();
itemListFragment.hasUpdated();
itemListFragment.scrollToTop();
getFirstStories();
}
protected abstract void updateReadFilterPreference(ReadFilter newValue);
@Override
public void finish() {
super.finish();
/*
* Animate out the list by sliding it to the right and the Main activity in from
* the left. Do this when going back to Main as a subtle hint to the swipe gesture,
* to make the gesture feel more natural, and to override the really ugly transition
* used in some of the newer platforms.
*/
overridePendingTransition(R.anim.slide_in_from_left, R.anim.slide_out_to_right);
}
}
|
package com.newsblur.network;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.newsblur.domain.Classifier;
import com.newsblur.domain.Feed;
import com.newsblur.domain.FeedResult;
import com.newsblur.domain.Story;
import com.newsblur.domain.ValueMultimap;
import com.newsblur.network.domain.FeedFolderResponse;
import com.newsblur.network.domain.NewsBlurResponse;
import com.newsblur.network.domain.ProfileResponse;
import com.newsblur.network.domain.RegisterResponse;
import com.newsblur.network.domain.StoriesResponse;
import com.newsblur.network.domain.StoryTextResponse;
import com.newsblur.network.domain.UnreadCountResponse;
import com.newsblur.network.domain.UnreadStoryHashesResponse;
import com.newsblur.serialization.BooleanTypeAdapter;
import com.newsblur.serialization.ClassifierMapTypeAdapter;
import com.newsblur.serialization.DateStringTypeAdapter;
import com.newsblur.serialization.FeedListTypeAdapter;
import com.newsblur.serialization.StoryTypeAdapter;
import com.newsblur.util.AppConstants;
import com.newsblur.util.FeedSet;
import com.newsblur.util.NetworkUtils;
import com.newsblur.util.PrefConstants;
import com.newsblur.util.PrefsUtils;
import com.newsblur.util.ReadFilter;
import com.newsblur.util.StoryOrder;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import org.apache.http.HttpStatus;
public class APIManager {
private Context context;
private Gson gson;
private String customUserAgent;
private OkHttpClient httpClient;
public APIManager(final Context context) {
this.context = context;
this.gson = new GsonBuilder()
.registerTypeAdapter(Date.class, new DateStringTypeAdapter())
.registerTypeAdapter(Boolean.class, new BooleanTypeAdapter())
.registerTypeAdapter(boolean.class, new BooleanTypeAdapter())
.registerTypeAdapter(Story.class, new StoryTypeAdapter())
.registerTypeAdapter(new TypeToken<List<Feed>>(){}.getType(), new FeedListTypeAdapter())
.registerTypeAdapter(new TypeToken<Map<String,Classifier>>(){}.getType(), new ClassifierMapTypeAdapter())
.create();
String appVersion = context.getSharedPreferences(PrefConstants.PREFERENCES, 0).getString(AppConstants.LAST_APP_VERSION, "unknown_version");
this.customUserAgent = "NewsBlur Android app" +
" (" + Build.MANUFACTURER + " " +
Build.MODEL + " " +
Build.VERSION.RELEASE + " " +
appVersion + ")";
this.httpClient = new OkHttpClient();
}
public NewsBlurResponse login(final String username, final String password) {
// This call should be pretty rare, but is expensive on the server side. Log it
// at an above-debug level so it will be noticed if it ever gets called too often.
Log.i(this.getClass().getName(), "calling login API");
final ContentValues values = new ContentValues();
values.put(APIConstants.PARAMETER_USERNAME, username);
values.put(APIConstants.PARAMETER_PASSWORD, password);
final APIResponse response = post(APIConstants.URL_LOGIN, values);
NewsBlurResponse loginResponse = response.getResponse(gson);
if (!response.isError()) {
PrefsUtils.saveLogin(context, username, response.getCookie());
}
return loginResponse;
}
public boolean loginAs(String username) {
ContentValues values = new ContentValues();
values.put(APIConstants.PARAMETER_USER, username);
String urlString = APIConstants.URL_LOGINAS + "?" + builderGetParametersString(values);
Log.i(this.getClass().getName(), "doing superuser swap: " + urlString);
// This API returns a redirect that means the call worked, but we do not want to follow it. To
// just get the cookie from the 302 and stop, we directly use a one-off OkHttpClient.
Request.Builder requestBuilder = new Request.Builder().url(urlString);
addCookieHeader(requestBuilder);
OkHttpClient noredirHttpClient = new OkHttpClient();
noredirHttpClient.setFollowRedirects(false);
try {
Response response = noredirHttpClient.newCall(requestBuilder.build()).execute();
if (!response.isRedirect()) return false;
String newCookie = response.header("Set-Cookie");
PrefsUtils.saveLogin(context, username, newCookie);
} catch (IOException ioe) {
return false;
}
return true;
}
public boolean setAutoFollow(boolean autofollow) {
ContentValues values = new ContentValues();
values.put("autofollow_friends", autofollow ? "true" : "false");
final APIResponse response = post(APIConstants.URL_AUTOFOLLOW_PREF, values);
return (!response.isError());
}
public NewsBlurResponse markFeedsAsRead(FeedSet fs, Long includeOlder, Long includeNewer) {
ValueMultimap values = new ValueMultimap();
if (fs.getSingleFeed() != null) {
values.put(APIConstants.PARAMETER_FEEDID, fs.getSingleFeed());
} else if (fs.getMultipleFeeds() != null) {
for (String feedId : fs.getMultipleFeeds()) values.put(APIConstants.PARAMETER_FEEDID, feedId);
} else if (fs.getSingleSocialFeed() != null) {
values.put(APIConstants.PARAMETER_FEEDID, APIConstants.VALUE_PREFIX_SOCIAL + fs.getSingleSocialFeed().getKey());
} else if (fs.getMultipleSocialFeeds() != null) {
for (Map.Entry<String,String> entry : fs.getMultipleSocialFeeds().entrySet()) {
values.put(APIConstants.PARAMETER_FEEDID, APIConstants.VALUE_PREFIX_SOCIAL + entry.getKey());
}
} else if (fs.isAllNormal()) {
// all stories uses a special API call
return markAllAsRead();
} else if (fs.isAllSocial()) {
values.put(APIConstants.PARAMETER_FEEDID, APIConstants.VALUE_ALLSOCIAL);
} else {
throw new IllegalStateException("Asked to get stories for FeedSet of unknown type.");
}
if (includeOlder != null) {
// the app uses milliseconds but the API wants seconds
long cut = includeOlder.longValue();
values.put(APIConstants.PARAMETER_CUTOFF_TIME, Long.toString(cut/1000L));
values.put(APIConstants.PARAMETER_DIRECTION, APIConstants.VALUE_OLDER);
}
if (includeNewer != null) {
// the app uses milliseconds but the API wants seconds
long cut = includeNewer.longValue();
values.put(APIConstants.PARAMETER_CUTOFF_TIME, Long.toString(cut/1000L));
values.put(APIConstants.PARAMETER_DIRECTION, APIConstants.VALUE_NEWER);
}
APIResponse response = post(APIConstants.URL_MARK_FEED_AS_READ, values);
// TODO: these calls use a different return format than others: the errors field is an array, not an object
//return response.getResponse(gson, NewsBlurResponse.class);
NewsBlurResponse nbr = new NewsBlurResponse();
if (response.isError()) nbr.message = "err";
return nbr;
}
private NewsBlurResponse markAllAsRead() {
ValueMultimap values = new ValueMultimap();
values.put(APIConstants.PARAMETER_DAYS, "0");
APIResponse response = post(APIConstants.URL_MARK_ALL_AS_READ, values);
// TODO: these calls use a different return format than others: the errors field is an array, not an object
//return response.getResponse(gson, NewsBlurResponse.class);
NewsBlurResponse nbr = new NewsBlurResponse();
if (response.isError()) nbr.message = "err";
return nbr;
}
public NewsBlurResponse markStoryAsRead(String storyHash) {
ValueMultimap values = new ValueMultimap();
values.put(APIConstants.PARAMETER_STORY_HASH, storyHash);
APIResponse response = post(APIConstants.URL_MARK_STORIES_READ, values);
return response.getResponse(gson, NewsBlurResponse.class);
}
public NewsBlurResponse markStoryAsStarred(String storyHash) {
ValueMultimap values = new ValueMultimap();
values.put(APIConstants.PARAMETER_STORY_HASH, storyHash);
APIResponse response = post(APIConstants.URL_MARK_STORY_AS_STARRED, values);
return response.getResponse(gson, NewsBlurResponse.class);
}
public NewsBlurResponse markStoryAsUnstarred(String storyHash) {
ValueMultimap values = new ValueMultimap();
values.put(APIConstants.PARAMETER_STORY_HASH, storyHash);
APIResponse response = post(APIConstants.URL_MARK_STORY_AS_UNSTARRED, values);
return response.getResponse(gson, NewsBlurResponse.class);
}
public NewsBlurResponse markStoryHashUnread(String hash) {
final ValueMultimap values = new ValueMultimap();
values.put(APIConstants.PARAMETER_STORY_HASH, hash);
APIResponse response = post(APIConstants.URL_MARK_STORY_HASH_UNREAD, values);
return response.getResponse(gson, NewsBlurResponse.class);
}
public RegisterResponse signup(final String username, final String password, final String email) {
final ContentValues values = new ContentValues();
values.put(APIConstants.PARAMETER_USERNAME, username);
values.put(APIConstants.PARAMETER_PASSWORD, password);
values.put(APIConstants.PARAMETER_EMAIL, email);
final APIResponse response = post(APIConstants.URL_SIGNUP, values);
RegisterResponse registerResponse = ((RegisterResponse) response.getResponse(gson, RegisterResponse.class));
if (!response.isError()) {
PrefsUtils.saveLogin(context, username, response.getCookie());
CookieSyncManager.createInstance(context.getApplicationContext());
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setCookie(APIConstants.COOKIE_DOMAIN, response.getCookie());
CookieSyncManager.getInstance().sync();
}
return registerResponse;
}
public ProfileResponse updateUserProfile() {
final APIResponse response = get(APIConstants.URL_MY_PROFILE);
if (!response.isError()) {
ProfileResponse profileResponse = (ProfileResponse) response.getResponse(gson, ProfileResponse.class);
PrefsUtils.saveUserDetails(context, profileResponse.user);
return profileResponse;
} else {
return null;
}
}
public UnreadCountResponse getFeedUnreadCounts(Set<String> apiIds) {
ValueMultimap values = new ValueMultimap();
for (String id : apiIds) {
values.put(APIConstants.PARAMETER_FEEDID, id);
}
APIResponse response = get(APIConstants.URL_FEED_UNREAD_COUNT, values);
return (UnreadCountResponse) response.getResponse(gson, UnreadCountResponse.class);
}
public UnreadStoryHashesResponse getUnreadStoryHashes() {
ValueMultimap values = new ValueMultimap();
values.put(APIConstants.PARAMETER_INCLUDE_TIMESTAMPS, "1");
APIResponse response = get(APIConstants.URL_UNREAD_HASHES, values);
return (UnreadStoryHashesResponse) response.getResponse(gson, UnreadStoryHashesResponse.class);
}
public StoriesResponse getStoriesByHash(List<String> storyHashes) {
ValueMultimap values = new ValueMultimap();
for (String hash : storyHashes) {
values.put(APIConstants.PARAMETER_H, hash);
}
values.put(APIConstants.PARAMETER_INCLUDE_HIDDEN, APIConstants.VALUE_TRUE);
APIResponse response = get(APIConstants.URL_RIVER_STORIES, values);
return (StoriesResponse) response.getResponse(gson, StoriesResponse.class);
}
/**
* Fetches stories for the given FeedSet, choosing the correct API and the right
* request parameters as needed.
*/
public StoriesResponse getStories(FeedSet fs, int pageNumber, StoryOrder order, ReadFilter filter) {
Uri uri = null;
ValueMultimap values = new ValueMultimap();
// create the URI and populate request params depending on what kind of stories we want
if (fs.getSingleFeed() != null) {
uri = Uri.parse(APIConstants.URL_FEED_STORIES).buildUpon().appendPath(fs.getSingleFeed()).build();
values.put(APIConstants.PARAMETER_FEEDS, fs.getSingleFeed());
values.put(APIConstants.PARAMETER_INCLUDE_HIDDEN, APIConstants.VALUE_TRUE);
} else if (fs.getMultipleFeeds() != null) {
uri = Uri.parse(APIConstants.URL_RIVER_STORIES);
for (String feedId : fs.getMultipleFeeds()) values.put(APIConstants.PARAMETER_FEEDS, feedId);
values.put(APIConstants.PARAMETER_INCLUDE_HIDDEN, APIConstants.VALUE_TRUE);
} else if (fs.getSingleSocialFeed() != null) {
String feedId = fs.getSingleSocialFeed().getKey();
String username = fs.getSingleSocialFeed().getValue();
uri = Uri.parse(APIConstants.URL_SOCIALFEED_STORIES).buildUpon().appendPath(feedId).appendPath(username).build();
values.put(APIConstants.PARAMETER_USER_ID, feedId);
values.put(APIConstants.PARAMETER_USERNAME, username);
} else if (fs.getMultipleSocialFeeds() != null) {
uri = Uri.parse(APIConstants.URL_SHARED_RIVER_STORIES);
for (Map.Entry<String,String> entry : fs.getMultipleSocialFeeds().entrySet()) {
values.put(APIConstants.PARAMETER_FEEDS, entry.getKey());
}
} else if (fs.isAllNormal()) {
uri = Uri.parse(APIConstants.URL_RIVER_STORIES);
values.put(APIConstants.PARAMETER_INCLUDE_HIDDEN, APIConstants.VALUE_TRUE);
} else if (fs.isAllSocial()) {
uri = Uri.parse(APIConstants.URL_SHARED_RIVER_STORIES);
} else if (fs.isAllRead()) {
uri = Uri.parse(APIConstants.URL_READ_STORIES);
} else if (fs.isAllSaved()) {
uri = Uri.parse(APIConstants.URL_STARRED_STORIES);
} else if (fs.isGlobalShared()) {
uri = Uri.parse(APIConstants.URL_SHARED_RIVER_STORIES);
values.put(APIConstants.PARAMETER_GLOBAL_FEED, Boolean.TRUE.toString());
} else {
throw new IllegalStateException("Asked to get stories for FeedSet of unknown type.");
}
// request params common to most story sets
values.put(APIConstants.PARAMETER_PAGE_NUMBER, Integer.toString(pageNumber));
if ( !(fs.isAllRead() || fs.isAllSaved())) {
values.put(APIConstants.PARAMETER_ORDER, order.getParameterValue());
values.put(APIConstants.PARAMETER_READ_FILTER, filter.getParameterValue());
}
APIResponse response = get(uri.toString(), values);
return (StoriesResponse) response.getResponse(gson, StoriesResponse.class);
}
public boolean followUser(final String userId) {
final ContentValues values = new ContentValues();
values.put(APIConstants.PARAMETER_USERID, userId);
final APIResponse response = post(APIConstants.URL_FOLLOW, values);
if (!response.isError()) {
return true;
} else {
return false;
}
}
public boolean unfollowUser(final String userId) {
final ContentValues values = new ContentValues();
values.put(APIConstants.PARAMETER_USERID, userId);
final APIResponse response = post(APIConstants.URL_UNFOLLOW, values);
if (!response.isError()) {
return true;
} else {
return false;
}
}
public NewsBlurResponse shareStory(final String storyId, final String feedId, final String comment, final String sourceUserId) {
final ContentValues values = new ContentValues();
if (!TextUtils.isEmpty(comment)) {
values.put(APIConstants.PARAMETER_SHARE_COMMENT, comment);
}
if (!TextUtils.isEmpty(sourceUserId)) {
values.put(APIConstants.PARAMETER_SHARE_SOURCEID, sourceUserId);
}
values.put(APIConstants.PARAMETER_FEEDID, feedId);
values.put(APIConstants.PARAMETER_STORYID, storyId);
APIResponse response = post(APIConstants.URL_SHARE_STORY, values);
return response.getResponse(gson, NewsBlurResponse.class);
}
/**
* Fetch the list of feeds/folders/socials from the backend.
*
* @param doUpdateCounts forces a refresh of unread counts. This has a high latency
* cost and should not be set if the call is being used to display the UI for
* the first time, in which case it is more appropriate to make a separate,
* additional call to refreshFeedCounts().
*/
public FeedFolderResponse getFolderFeedMapping(boolean doUpdateCounts) {
ContentValues params = new ContentValues();
params.put(APIConstants.PARAMETER_UPDATE_COUNTS, (doUpdateCounts ? "true" : "false"));
APIResponse response = get(APIConstants.URL_FEEDS, params);
if (response.isError()) {
Log.e(this.getClass().getName(), "Error fetching feeds: " + response.getErrorMessage());
return null;
}
// note: this response is complex enough, we have to do a custom parse in the FFR
FeedFolderResponse result = new FeedFolderResponse(response.getResponseBody(), gson);
// bind a litle extra instrumentation to this response, since it powers the feedback link
result.connTime = response.connectTime;
result.readTime = response.readTime;
return result;
}
public NewsBlurResponse trainClassifier(String feedId, String key, int type, int action) {
String typeText = null;
String actionText = null;
switch (type) {
case Classifier.AUTHOR:
typeText = "author";
break;
case Classifier.TAG:
typeText = "tag";
break;
case Classifier.TITLE:
typeText = "title";
break;
case Classifier.FEED:
typeText = "feed";
break;
}
switch (action) {
case Classifier.CLEAR_LIKE:
actionText = "remove_like_";
break;
case Classifier.CLEAR_DISLIKE:
actionText = "remove_dislike_";
break;
case Classifier.LIKE:
actionText = "like_";
break;
case Classifier.DISLIKE:
actionText = "dislike_";
break;
}
StringBuilder builder = new StringBuilder();;
builder.append(actionText);
builder.append(typeText);
ContentValues values = new ContentValues();
if (type == Classifier.FEED) {
values.put(builder.toString(), feedId);
} else {
values.put(builder.toString(), key);
}
values.put(APIConstants.PARAMETER_FEEDID, feedId);
final APIResponse response = post(APIConstants.URL_CLASSIFIER_SAVE, values);
return response.getResponse(gson, NewsBlurResponse.class);
}
public ProfileResponse getUser(String userId) {
final ContentValues values = new ContentValues();
values.put(APIConstants.PARAMETER_USER_ID, userId);
final APIResponse response = get(APIConstants.URL_USER_PROFILE, values);
if (!response.isError()) {
ProfileResponse profileResponse = (ProfileResponse) response.getResponse(gson, ProfileResponse.class);
return profileResponse;
} else {
return null;
}
}
public StoryTextResponse getStoryText(String feedId, String storyId) {
final ContentValues values = new ContentValues();
values.put(APIConstants.PARAMETER_FEEDID, feedId);
values.put(APIConstants.PARAMETER_STORYID, storyId);
final APIResponse response = get(APIConstants.URL_STORY_TEXT, values);
if (!response.isError()) {
StoryTextResponse storyTextResponse = (StoryTextResponse) response.getResponse(gson, StoryTextResponse.class);
return storyTextResponse;
} else {
return null;
}
}
public NewsBlurResponse favouriteComment(String storyId, String commentUserId, String feedId) {
ContentValues values = new ContentValues();
values.put(APIConstants.PARAMETER_STORYID, storyId);
values.put(APIConstants.PARAMETER_STORY_FEEDID, feedId);
values.put(APIConstants.PARAMETER_COMMENT_USERID, commentUserId);
APIResponse response = post(APIConstants.URL_LIKE_COMMENT, values);
return response.getResponse(gson, NewsBlurResponse.class);
}
public NewsBlurResponse unFavouriteComment(String storyId, String commentUserId, String feedId) {
ContentValues values = new ContentValues();
values.put(APIConstants.PARAMETER_STORYID, storyId);
values.put(APIConstants.PARAMETER_STORY_FEEDID, feedId);
values.put(APIConstants.PARAMETER_COMMENT_USERID, commentUserId);
APIResponse response = post(APIConstants.URL_UNLIKE_COMMENT, values);
return response.getResponse(gson, NewsBlurResponse.class);
}
public NewsBlurResponse replyToComment(String storyId, String storyFeedId, String commentUserId, String reply) {
ContentValues values = new ContentValues();
values.put(APIConstants.PARAMETER_STORYID, storyId);
values.put(APIConstants.PARAMETER_STORY_FEEDID, storyFeedId);
values.put(APIConstants.PARAMETER_COMMENT_USERID, commentUserId);
values.put(APIConstants.PARAMETER_REPLY_TEXT, reply);
APIResponse response = post(APIConstants.URL_REPLY_TO, values);
return response.getResponse(gson, NewsBlurResponse.class);
}
public boolean addFeed(String feedUrl, String folderName) {
ContentValues values = new ContentValues();
values.put(APIConstants.PARAMETER_URL, feedUrl);
if (!TextUtils.isEmpty(folderName)) {
values.put(APIConstants.PARAMETER_FOLDER, folderName);
}
final APIResponse response = post(APIConstants.URL_ADD_FEED, values);
return (!response.isError());
}
public FeedResult[] searchForFeed(String searchTerm) {
ContentValues values = new ContentValues();
values.put(APIConstants.PARAMETER_FEED_SEARCH_TERM, searchTerm);
final APIResponse response = get(APIConstants.URL_FEED_AUTOCOMPLETE, values);
if (!response.isError()) {
return gson.fromJson(response.getResponseBody(), FeedResult[].class);
} else {
return null;
}
}
public NewsBlurResponse deleteFeed(String feedId, String folderName) {
ContentValues values = new ContentValues();
values.put(APIConstants.PARAMETER_FEEDID, feedId);
if ((!TextUtils.isEmpty(folderName)) && (!folderName.equals(AppConstants.ROOT_FOLDER))) {
values.put(APIConstants.PARAMETER_IN_FOLDER, folderName);
}
APIResponse response = post(APIConstants.URL_DELETE_FEED, values);
return response.getResponse(gson, NewsBlurResponse.class);
}
/* HTTP METHODS */
private APIResponse get(final String urlString) {
APIResponse response;
int tryCount = 0;
do {
backoffSleep(tryCount++);
response = get_single(urlString, HttpStatus.SC_OK);
} while ((response.isError()) && (tryCount < AppConstants.MAX_API_TRIES));
return response;
}
private APIResponse get_single(final String urlString, int expectedReturnCode) {
if (!NetworkUtils.isOnline(context)) {
return new APIResponse(context);
}
if (AppConstants.VERBOSE_LOG) {
Log.d(this.getClass().getName(), "API GET " + urlString);
}
Request.Builder requestBuilder = new Request.Builder().url(urlString);
addCookieHeader(requestBuilder);
requestBuilder.header("User-Agent", this.customUserAgent);
return new APIResponse(context, httpClient, requestBuilder.build(), expectedReturnCode);
}
private void addCookieHeader(Request.Builder requestBuilder) {
SharedPreferences preferences = context.getSharedPreferences(PrefConstants.PREFERENCES, 0);
String cookie = preferences.getString(PrefConstants.PREF_COOKIE, null);
if (cookie != null) {
requestBuilder.header("Cookie", cookie);
}
}
private APIResponse get(final String urlString, final ContentValues values) {
return this.get(urlString + "?" + builderGetParametersString(values));
}
private String builderGetParametersString(ContentValues values) {
List<String> parameters = new ArrayList<String>();
for (Entry<String, Object> entry : values.valueSet()) {
StringBuilder builder = new StringBuilder();
builder.append((String) entry.getKey());
builder.append("=");
builder.append(URLEncoder.encode((String) entry.getValue()));
parameters.add(builder.toString());
}
return TextUtils.join("&", parameters);
}
private APIResponse get(final String urlString, final ValueMultimap valueMap) {
return this.get(urlString + "?" + valueMap.getParameterString());
}
private APIResponse post(String urlString, RequestBody formBody) {
APIResponse response;
int tryCount = 0;
do {
backoffSleep(tryCount++);
response = post_single(urlString, formBody);
} while ((response.isError()) && (tryCount < AppConstants.MAX_API_TRIES));
return response;
}
private APIResponse post_single(String urlString, RequestBody formBody) {
if (!NetworkUtils.isOnline(context)) {
return new APIResponse(context);
}
if (AppConstants.VERBOSE_LOG) {
Log.d(this.getClass().getName(), "API POST " + urlString);
Log.d(this.getClass().getName(), "post body: " + formBody.toString());
}
Request.Builder requestBuilder = new Request.Builder().url(urlString);
addCookieHeader(requestBuilder);
requestBuilder.post(formBody);
return new APIResponse(context, httpClient, requestBuilder.build());
}
private APIResponse post(final String urlString, final ContentValues values) {
FormEncodingBuilder formEncodingBuilder = new FormEncodingBuilder();
for (Entry<String, Object> entry : values.valueSet()) {
formEncodingBuilder.add(entry.getKey(), (String)entry.getValue());
}
return this.post(urlString, formEncodingBuilder.build());
}
private APIResponse post(final String urlString, final ValueMultimap valueMap) {
return this.post(urlString, valueMap.asFormEncodedRequestBody());
}
/**
* Pause for the sake of exponential retry-backoff as apropriate before the Nth call as counted
* by the zero-indexed tryCount.
*/
private void backoffSleep(int tryCount) {
if (tryCount == 0) return;
Log.i(this.getClass().getName(), "API call failed, pausing before retry number " + tryCount);
try {
// simply double the base sleep time for each subsequent try
long factor = Math.round(Math.pow(2.0d, tryCount));
Thread.sleep(AppConstants.API_BACKOFF_BASE_MILLIS * factor);
} catch (InterruptedException ie) {
Log.w(this.getClass().getName(), "Abandoning API backoff due to interrupt.");
}
}
}
|
//this utility adds (modified) inchis as comments to Chemkin files
/**
*
* @author gmagoon
*/
import java.util.*;
import java.io.*;
import jing.chem.*;
import jing.chemParser.*;
import jing.chemUtil.*;
//arg[0]=dictionary file
//arg[1]=original chemkin file
//arg[2]=new chemkin file
public class InchifyCHEMKINusingDictionary {
public static void main(String[] args) {
RMG.globalInitializeSystemProperties();
//1. read the Dictionary file, converting to modified inchis along the way and adding them into inchiDict HashMap
HashMap inchiDict = new HashMap();
try {
FileReader in = new FileReader(args[0]);
BufferedReader data = new BufferedReader(in);
String line = ChemParser.readMeaningfulLine(data, true);
// While more species
while (line != null) {
System.out.println(line);//print the name of the molecule
Graph g = ChemParser.readChemGraph(data);
System.out.println(g);
ChemGraph chemgraph = ChemGraph.make(g);
//get the inchi
String inchiString = chemgraph.getModifiedInChIAnew();
String name = line.split("\\s+")[0];//split on whitespace and take the first part of the name (in case the second part happens to be a pre-existing InChI
inchiDict.put(name, inchiString);//add the chemkin name as key, and InChI as value
line = ChemParser.readMeaningfulLine(data, true);
}
in.close();
}
catch (FileNotFoundException e) {
System.err.println("File was not found!\n");
}
catch(IOException e){
System.err.println("Something wrong with ChemParser.readChemGraph");
}
catch(ForbiddenStructureException e){
System.err.println("Something wrong with ChemGraph.make");
}
//2. read the CHEMKIN file, while simultaneously writing a CHEMKIN output file with InChI comments, where available
try {
FileReader chemkinOld = new FileReader(args[1]);
FileWriter chemkinNew = new FileWriter(args[2]);
BufferedReader chemkinReader = new BufferedReader(chemkinOld);
BufferedWriter chemkinWriter = new BufferedWriter(chemkinNew);
String line = chemkinReader.readLine();
// While more InChIs remain
while (line != null) {
String[] spl = line.split(" "); //split on space
int len= spl.length;
//if the last "word" is a 1 and the first word can be found in the dictionary, write a comment line before copying the line; otherwise, just copy the line
if (spl[len-1].equals("1")){
if (inchiDict.containsKey(spl[0])){
chemkinWriter.write("! [_ SMILES=\""+inchiDict.get(spl[0])+"\" _]\n");
}
else{
System.out.println("Warning: Could not find InChI corresponding to CHEMKIN file species "+ spl[0]);
}
}
chemkinWriter.write(line+"\n");
line = chemkinReader.readLine();
}
chemkinOld.close();
chemkinWriter.flush();
chemkinWriter.close();
chemkinNew.close();
}
catch (FileNotFoundException e) {
System.err.println("File was not found!\n");
}
catch (IOException eIO) {
System.err.println("IO Exception!\n");
}
}
}
|
package com.twelvemonkeys.io;
import com.twelvemonkeys.lang.StringUtil;
import com.twelvemonkeys.lang.Validate;
import com.twelvemonkeys.util.Visitor;
import java.io.*;
import java.net.URL;
import java.text.NumberFormat;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.UndeclaredThrowableException;
public final class FileUtil {
// TODO: Be more cosequent using resolve() all places where File objects are involved
// TODO: Exception handling
/**
* The size of the buffer used for copying
*/
public final static int BUF_SIZE = 1024;
private static String TEMP_DIR = null;
private final static FileSystem FS = FileSystem.get();
public static void main(String[] pArgs) throws IOException {
File file;
if (pArgs[0].startsWith("file:")) {
file = toFile(new URL(pArgs[0]));
System.out.println(file);
}
else {
file = new File(pArgs[0]);
System.out.println(file.toURL());
}
System.out.println("Free space: " + getFreeSpace(file) + "/" + getTotalSpace(file) + " bytes");
}
//*/
/**
* Copies the fromFile to the toFile location. If toFile is a directory, a
* new file is created in that directory, with the name of the fromFile.
* If the toFile exists, the file will not be copied, unless owerWrite is
* true.
*
* @param pFromFileName The name of the file to copy from
* @param pToFileName The name of the file to copy to
* @return true if the file was copied successfully,
* false if the output file exists. In all other cases, an
* IOException is thrown, and the method does not return a value.
* @throws IOException if an i/o error occurs during copy
*/
public static boolean copy(String pFromFileName, String pToFileName) throws IOException {
return copy(new File(pFromFileName), new File(pToFileName), false);
}
/**
* Copies the fromFile to the toFile location. If toFile is a directory, a
* new file is created in that directory, with the name of the fromFile.
* If the toFile exists, the file will not be copied, unless owerWrite is
* true.
*
* @param pFromFileName The name of the file to copy from
* @param pToFileName The name of the file to copy to
* @param pOverWrite Specifies if the toFile should be overwritten, if it
* exists.
* @return true if the file was copied successfully,
* false if the output file exists, and the owerWrite parameter is
* false. In all other cases, an
* IOException is thrown, and the method does not return a value.
* @throws IOException if an i/o error occurs during copy
*/
public static boolean copy(String pFromFileName, String pToFileName, boolean pOverWrite) throws IOException {
return copy(new File(pFromFileName), new File(pToFileName), pOverWrite);
}
/**
* Copies the fromFile to the toFile location. If toFile is a directory, a
* new file is created in that directory, with the name of the fromFile.
* If the toFile exists, the file will not be copied, unless owerWrite is
* true.
*
* @param pFromFile The file to copy from
* @param pToFile The file to copy to
* @return true if the file was copied successfully,
* false if the output file exists. In all other cases, an
* IOException is thrown, and the method does not return a value.
* @throws IOException if an i/o error occurs during copy
*/
public static boolean copy(File pFromFile, File pToFile) throws IOException {
return copy(pFromFile, pToFile, false);
}
/**
* Copies the fromFile to the toFile location. If toFile is a directory, a
* new file is created in that directory, with the name of the fromFile.
* If the toFile exists, the file will not be copied, unless owerWrite is
* true.
*
* @param pFromFile The file to copy from
* @param pToFile The file to copy to
* @param pOverWrite Specifies if the toFile should be overwritten, if it
* exists.
* @return {@code true} if the file was copied successfully,
* {@code false} if the output file exists, and the
* {@code pOwerWrite} parameter is
* {@code false}. In all other cases, an
* {@code IOExceptio}n is thrown, and the method does not return.
* @throws IOException if an i/o error occurs during copy
* @todo Test copyDir functionality!
*/
public static boolean copy(File pFromFile, File pToFile, boolean pOverWrite) throws IOException {
// Copy all directory structure
if (pFromFile.isDirectory()) {
return copyDir(pFromFile, pToFile, pOverWrite);
}
// Check if destination is a directory
if (pToFile.isDirectory()) {
// Create a new file with same name as from
pToFile = new File(pToFile, pFromFile.getName());
}
// Check if file exists, and return false if overWrite is false
if (!pOverWrite && pToFile.exists()) {
return false;
}
InputStream in = null;
OutputStream out = null;
try {
// Use buffer size two times byte array, to avoid i/o bottleneck
in = new FileInputStream(pFromFile);
out = new FileOutputStream(pToFile);
// Copy from inputStream to outputStream
copy(in, out);
}
//Just pass any IOException on up the stack
finally {
close(in);
close(out);
}
return true; // If we got here, everything is probably okay.. ;-)
}
/**
* Tries to close the given stream.
* NOTE: If the stream cannot be closed, the IOException thrown is silently
* ignored.
*
* @param pInput the stream to close
*/
public static void close(InputStream pInput) {
try {
if (pInput != null) {
pInput.close();
}
}
catch (IOException ignore) {
// Non critical error
}
}
/**
* Tries to close the given stream.
* NOTE: If the stream cannot be closed, the IOException thrown is silently
* ignored.
*
* @param pOutput the stream to close
*/
public static void close(OutputStream pOutput) {
try {
if (pOutput != null) {
pOutput.close();
}
}
catch (IOException ignore) {
// Non critical error
}
}
static void close(Reader pReader) {
try {
if (pReader != null) {
pReader.close();
}
}
catch (IOException ignore) {
// Non critical error
}
}
static void close(Writer pWriter) {
try {
if (pWriter != null) {
pWriter.close();
}
}
catch (IOException ignore) {
// Non critical error
}
}
/**
* Copies a directory recursively. If the destination folder does not exist,
* it is created
*
* @param pFrom the source directory
* @param pTo the destination directory
* @param pOverWrite {@code true} if we should allow overwrting existing files
* @return {@code true} if all files were copied sucessfully
* @throws IOException if {@code pTo} exists, and it not a directory,
* or if copying of any of the files in the folder fails
*/
private static boolean copyDir(File pFrom, File pTo, boolean pOverWrite) throws IOException {
if (pTo.exists() && !pTo.isDirectory()) {
throw new IOException("A directory may only be copied to another directory, not to a file");
}
pTo.mkdirs(); // mkdir?
boolean allOkay = true;
File[] files = pFrom.listFiles();
for (File file : files) {
if (!copy(file, new File(pTo, file.getName()), pOverWrite)) {
allOkay = false;
}
}
return allOkay;
}
public static boolean copy(InputStream pFrom, OutputStream pTo) throws IOException {
Validate.notNull(pFrom, "from");
Validate.notNull(pTo, "to");
// TODO: Consider using file channels for faster copy where possible
// Use buffer size two times byte array, to avoid i/o bottleneck
// TODO: Consider letting the client decide as this is sometimes not a good thing!
InputStream in = new BufferedInputStream(pFrom, BUF_SIZE * 2);
OutputStream out = new BufferedOutputStream(pTo, BUF_SIZE * 2);
byte[] buffer = new byte[BUF_SIZE];
int count;
while ((count = in.read(buffer)) != -1) {
out.write(buffer, 0, count);
}
// Flush out stream, to write any remaining buffered data
out.flush();
return true; // If we got here, everything is probably okay.. ;-)
}
/**
* Gets the file (type) extension of the given file.
* A file extension is the part of the filename, after the last occurence
* of a period {@code '.'}.
* If the filename contains no period, {@code null} is returned.
*
* @param pFileName the full filename with extension
* @return the extension (type) of the file, or {@code null}
*/
public static String getExtension(final String pFileName) {
return getExtension0(getFilename(pFileName));
}
/**
* Gets the file (type) extension of the given file.
* A file extension is the part of the filename, after the last occurence
* of a period {@code '.'}.
* If the filename contains no period, {@code null} is returned.
*
* @param pFile the file
* @return the extension (type) of the file, or {@code null}
*/
public static String getExtension(final File pFile) {
return getExtension0(pFile.getName());
}
// NOTE: Assumes filename and no path
private static String getExtension0(final String pFileName) {
int index = pFileName.lastIndexOf('.');
if (index >= 0) {
return pFileName.substring(index + 1);
}
// No period found
return null;
}
/**
* Gets the file name of the given file, without the extension (type).
* A file extension is the part of the filename, after the last occurence
* of a period {@code '.'}.
* If the filename contains no period, the complete file name is returned
* (same as {@code pFileName}, if the string contains no path elements).
*
* @param pFileName the full filename with extension
* @return the base name of the file
*/
public static String getBasename(final String pFileName) {
return getBasename0(getFilename(pFileName));
}
/**
* Gets the file name of the given file, without the extension (type).
* A file extension is the part of the filename, after the last occurence
* of a period {@code '.'}.
* If the filename contains no period, {@code pFile.getName()} is returned.
*
* @param pFile the file
* @return the base name of the file
*/
public static String getBasename(final File pFile) {
return getBasename0(pFile.getName());
}
// NOTE: Assumes filename and no path
public static String getBasename0(final String pFileName) {
int index = pFileName.lastIndexOf('.');
if (index >= 0) {
return pFileName.substring(0, index);
}
// No period found
return pFileName;
}
/**
* Extracts the directory path without the filename, from a complete
* filename path.
*
* @param pPath The full filename path.
* @return the path without the filename.
* @see File#getParent
* @see #getFilename
*/
public static String getDirectoryname(final String pPath) {
return getDirectoryname(pPath, File.separatorChar);
}
/**
* Extracts the directory path without the filename, from a complete
* filename path.
*
* @param pPath The full filename path.
* @param pSeparator the separator char used in {@code pPath}
* @return the path without the filename.
* @see File#getParent
* @see #getFilename
*/
public static String getDirectoryname(final String pPath, final char pSeparator) {
int index = pPath.lastIndexOf(pSeparator);
if (index < 0) {
return ""; // Assume only filename
}
return pPath.substring(0, index);
}
/**
* Extracts the filename of a complete filename path.
*
* @param pPath The full filename path.
* @return the extracted filename.
* @see File#getName
* @see #getDirectoryname
*/
public static String getFilename(final String pPath) {
return getFilename(pPath, File.separatorChar);
}
/**
* Extracts the filename of a complete filename path.
*
* @param pPath The full filename path.
* @param pSeparator The file separator.
* @return the extracted filename.
* @see File#getName
* @see #getDirectoryname
*/
public static String getFilename(final String pPath, final char pSeparator) {
int index = pPath.lastIndexOf(pSeparator);
if (index < 0) {
return pPath; // Assume only filename
}
return pPath.substring(index + 1);
}
/**
* Tests if a file or directory has no content.
* A file is empty if it has a length of 0L. A non-existing file is also
* considered empty.
* A directory is considered empty if it contains no files.
*
* @param pFile The file to test
* @return {@code true} if the file is empty, otherwise
* {@code false}.
*/
public static boolean isEmpty(File pFile) {
if (pFile.isDirectory()) {
return (pFile.list().length == 0);
}
return (pFile.length() == 0);
}
/**
* Gets the default temp directory for the system as a File.
*
* @return a {@code File}, representing the default temp directory.
* @see File#createTempFile
*/
public static File getTempDirFile() {
return new File(getTempDir());
}
/**
* Gets the default temp directory for the system.
*
* @return a {@code String}, representing the path to the default temp
* directory.
* @see File#createTempFile
*/
public static String getTempDir() {
synchronized (FileUtil.class) {
if (TEMP_DIR == null) {
// Get the 'java.io.tmpdir' property
String tmpDir = System.getProperty("java.io.tmpdir");
if (StringUtil.isEmpty(tmpDir)) {
// Stupid fallback...
// TODO: Delegate to FileSystem?
if (new File("/temp").exists()) {
tmpDir = "/temp"; // Windows
}
else {
tmpDir = "/tmp"; // Unix
}
}
TEMP_DIR = tmpDir;
}
}
return TEMP_DIR;
}
/**
* Gets the contents of the given file, as a byte array.
*
* @param pFilename the name of the file to get content from
* @return the content of the file as a byte array.
* @throws IOException if the read operation fails
*/
public static byte[] read(String pFilename) throws IOException {
return read(new File(pFilename));
}
/**
* Gets the contents of the given file, as a byte array.
*
* @param pFile the file to get content from
* @return the content of the file as a byte array.
* @throws IOException if the read operation fails
*/
public static byte[] read(File pFile) throws IOException {
// Custom implementation, as we know the size of a file
if (!pFile.exists()) {
throw new FileNotFoundException(pFile.toString());
}
byte[] bytes = new byte[(int) pFile.length()];
InputStream in = null;
try {
// Use buffer size two times byte array, to avoid i/o bottleneck
in = new BufferedInputStream(new FileInputStream(pFile), BUF_SIZE * 2);
int off = 0;
int len;
while ((len = in.read(bytes, off, in.available())) != -1 && (off < bytes.length)) {
off += len;
// System.out.println("read:" + len);
}
}
// Just pass any IOException on up the stack
finally {
close(in);
}
return bytes;
}
/**
* Reads all data from the input stream to a byte array.
*
* @param pInput The input stream to read from
* @return The content of the stream as a byte array.
* @throws IOException if an i/o error occurs during read.
*/
public static byte[] read(InputStream pInput) throws IOException {
// Create byte array
ByteArrayOutputStream bytes = new FastByteArrayOutputStream(BUF_SIZE);
// Copy from stream to byte array
copy(pInput, bytes);
return bytes.toByteArray();
}
/**
* Writes the contents from a byte array to an output stream.
*
* @param pOutput The output stream to write to
* @param pData The byte array to write
* @return {@code true}, otherwise an IOException is thrown.
* @throws IOException if an i/o error occurs during write.
*/
public static boolean write(OutputStream pOutput, byte[] pData) throws IOException {
// Write data
pOutput.write(pData);
// If we got here, all is okay
return true;
}
/**
* Writes the contents from a byte array to a file.
*
* @param pFile The file to write to
* @param pData The byte array to write
* @return {@code true}, otherwise an IOException is thrown.
* @throws IOException if an i/o error occurs during write.
*/
public static boolean write(File pFile, byte[] pData) throws IOException {
boolean success = false;
OutputStream out = null;
try {
out = new BufferedOutputStream(new FileOutputStream(pFile));
success = write(out, pData);
}
finally {
close(out);
}
return success;
}
/**
* Writes the contents from a byte array to a file.
*
* @param pFilename The name of the file to write to
* @param pData The byte array to write
* @return {@code true}, otherwise an IOException is thrown.
* @throws IOException if an i/o error occurs during write.
*/
public static boolean write(String pFilename, byte[] pData) throws IOException {
return write(new File(pFilename), pData);
}
/**
* Deletes the specified file.
*
* @param pFile The file to delete
* @param pForce Forces delete, even if the parameter is a directory, and
* is not empty. Be careful!
* @return {@code true}, if the file existed and was deleted.
* @throws IOException if an i/o error occurs during delete.
*/
public static boolean delete(final File pFile, final boolean pForce) throws IOException {
if (pForce && pFile.isDirectory()) {
return deleteDir(pFile);
}
return pFile.exists() && pFile.delete();
}
/**
* Deletes a directory recursively.
*
* @param pFile the file to delete
* @return {@code true} if the file was deleted sucessfully
* @throws IOException if an i/o error occurs during delete.
*/
private static boolean deleteDir(final File pFile) throws IOException {
// Recusively delete all files/subfolders
// Deletes the files using visitor pattern, to avoid allocating
// a file array, which may throw OutOfMemoryExceptions for
// large directories/in low memory situations
class DeleteFilesVisitor implements Visitor<File> {
private int failedCount = 0;
private IOException exception = null;
public void visit(final File pFile) {
try {
if (!delete(pFile, true)) {
failedCount++;
}
}
catch (IOException e) {
failedCount++;
if (exception == null) {
exception = e;
}
}
}
boolean succeeded() throws IOException {
if (exception != null) {
throw exception;
}
return failedCount == 0;
}
}
DeleteFilesVisitor fileDeleter = new DeleteFilesVisitor();
visitFiles(pFile, null, fileDeleter);
// If any of the deletes above failed, this will fail (or return false)
return fileDeleter.succeeded() && pFile.delete();
}
/**
* Deletes the specified file.
*
* @param pFilename The name of file to delete
* @param pForce Forces delete, even if the parameter is a directory, and
* is not empty. Careful!
* @return {@code true}, if the file existed and was deleted.
* @throws java.io.IOException if deletion fails
*/
public static boolean delete(String pFilename, boolean pForce) throws IOException {
return delete(new File(pFilename), pForce);
}
/**
* Deletes the specified file.
*
* @param pFile The file to delete
* @return {@code true}, if the file existed and was deleted.
* @throws java.io.IOException if deletion fails
*/
public static boolean delete(File pFile) throws IOException {
return delete(pFile, false);
}
/**
* Deletes the specified file.
*
* @param pFilename The name of file to delete
* @return {@code true}, if the file existed and was deleted.
* @throws java.io.IOException if deletion fails
*/
public static boolean delete(String pFilename) throws IOException {
return delete(new File(pFilename), false);
}
/**
* Renames the specified file.
* If the destination is a directory (and the source is not), the source
* file is simply moved to the destination directory.
*
* @param pFrom The file to rename
* @param pTo The new file
* @param pOverWrite Specifies if the tofile should be overwritten, if it
* exists
* @return {@code true}, if the file was renamed.
*
* @throws FileNotFoundException if {@code pFrom} does not exist.
*/
public static boolean rename(File pFrom, File pTo, boolean pOverWrite) throws IOException {
if (!pFrom.exists()) {
throw new FileNotFoundException(pFrom.getAbsolutePath());
}
if (pFrom.isFile() && pTo.isDirectory()) {
pTo = new File(pTo, pFrom.getName());
}
return (pOverWrite || !pTo.exists()) && pFrom.renameTo(pTo);
}
/**
* Renames the specified file, if the destination does not exist.
* If the destination is a directory (and the source is not), the source
* file is simply moved to the destination directory.
*
* @param pFrom The file to rename
* @param pTo The new file
* @return {@code true}, if the file was renamed.
* @throws java.io.IOException if rename fails
*/
public static boolean rename(File pFrom, File pTo) throws IOException {
return rename(pFrom, pTo, false);
}
/**
* Renames the specified file.
* If the destination is a directory (and the source is not), the source
* file is simply moved to the destination directory.
*
* @param pFrom The file to rename
* @param pTo The new name of the file
* @param pOverWrite Specifies if the tofile should be overwritten, if it
* exists
* @return {@code true}, if the file was renamed.
* @throws java.io.IOException if rename fails
*/
public static boolean rename(File pFrom, String pTo, boolean pOverWrite) throws IOException {
return rename(pFrom, new File(pTo), pOverWrite);
}
/**
* Renames the specified file, if the destination does not exist.
* If the destination is a directory (and the source is not), the source
* file is simply moved to the destination directory.
*
* @param pFrom The file to rename
* @param pTo The new name of the file
* @return {@code true}, if the file was renamed.
* @throws java.io.IOException if rename fails
*/
public static boolean rename(File pFrom, String pTo) throws IOException {
return rename(pFrom, new File(pTo), false);
}
/**
* Renames the specified file.
* If the destination is a directory (and the source is not), the source
* file is simply moved to the destination directory.
*
* @param pFrom The name of the file to rename
* @param pTo The new name of the file
* @param pOverWrite Specifies if the tofile should be overwritten, if it
* exists
* @return {@code true}, if the file was renamed.
* @throws java.io.IOException if rename fails
*/
public static boolean rename(String pFrom, String pTo, boolean pOverWrite) throws IOException {
return rename(new File(pFrom), new File(pTo), pOverWrite);
}
/**
* Renames the specified file, if the destination does not exist.
* If the destination is a directory (and the source is not), the source
* file is simply moved to the destination directory.
*
* @param pFrom The name of the file to rename
* @param pTo The new name of the file
* @return {@code true}, if the file was renamed.
* @throws java.io.IOException if rename fails
*/
public static boolean rename(String pFrom, String pTo) throws IOException {
return rename(new File(pFrom), new File(pTo), false);
}
/**
* Lists all files (and directories) in a specific folder.
*
* @param pFolder The folder to list
* @return a list of {@code java.io.File} objects.
* @throws FileNotFoundException if {@code pFolder} is not a readable file
*/
public static File[] list(final String pFolder) throws FileNotFoundException {
return list(pFolder, null);
}
/**
* Lists all files (and directories) in a specific folder which are
* embraced by the wildcard filename mask provided.
*
* @param pFolder The folder to list
* @param pFilenameMask The wildcard filename mask
* @return a list of {@code java.io.File} objects.
* @see File#listFiles(FilenameFilter)
* @throws FileNotFoundException if {@code pFolder} is not a readable file
*/
public static File[] list(final String pFolder, final String pFilenameMask) throws FileNotFoundException {
if (StringUtil.isEmpty(pFolder)) {
return null;
}
File folder = resolve(pFolder);
if (!(/*folder.exists() &&*/folder.isDirectory() && folder.canRead())) {
// NOTE: exists is implicitly called by isDirectory
throw new FileNotFoundException("\"" + pFolder + "\" is not a directory or is not readable.");
}
if (StringUtil.isEmpty(pFilenameMask)) {
return folder.listFiles();
}
// TODO: Rewrite to use regexp
FilenameFilter filter = new FilenameMaskFilter(pFilenameMask);
return folder.listFiles(filter);
}
public static File toFile(URL pURL) {
if (pURL == null) {
throw new NullPointerException("URL == null");
}
// NOTE: Precondition tests below is based on the File(URI) constructor,
// and is most likely overkill...
// NOTE: A URI is absolute iff it has a scheme component
// As the scheme has to be "file", this is implicitly tested below
// NOTE: A URI is opaque iff it is absolute and it's shceme-specific
// part does not begin with a '/', see below
if (!"file".equals(pURL.getProtocol())) {
// URL protocol => URI scheme
throw new IllegalArgumentException("URL scheme is not \"file\"");
}
if (pURL.getAuthority() != null) {
throw new IllegalArgumentException("URL has an authority component");
}
if (pURL.getRef() != null) {
// URL ref (anchor) => URI fragment
throw new IllegalArgumentException("URI has a fragment component");
}
if (pURL.getQuery() != null) {
throw new IllegalArgumentException("URL has a query component");
}
String path = pURL.getPath();
if (!path.startsWith("/")) {
// A URL should never be able to represent an opaque URI, test anyway
throw new IllegalArgumentException("URI is not hierarchical");
}
if (path.equals("")) {
throw new IllegalArgumentException("URI path component is empty");
}
// Convert separator, doesn't seem to be neccessary on Windows/Unix,
// but do it anyway to be compatible...
if (File.separatorChar != '/') {
path = path.replace('/', File.separatorChar);
}
return resolve(path);
}
public static File resolve(String pPath) {
return Win32File.wrap(new File(pPath));
}
public static File resolve(File pPath) {
return Win32File.wrap(pPath);
}
public static File resolve(File pParent, String pChild) {
return Win32File.wrap(new File(pParent, pChild));
}
public static File[] resolve(File[] pPaths) {
return Win32File.wrap(pPaths);
}
// TODO: Handle SecurityManagers in a deterministic way
// TODO: Exception handling
// TODO: What happens if the file does not exist?
public static long getFreeSpace(final File pPath) {
// NOTE: Allow null, to get space in current/system volume
File path = pPath != null ? pPath : new File(".");
Long space = getSpace16("getFreeSpace", path);
if (space != null) {
return space;
}
return FS.getFreeSpace(path);
}
public static long getUsableSpace(final File pPath) {
// NOTE: Allow null, to get space in current/system volume
File path = pPath != null ? pPath : new File(".");
Long space = getSpace16("getUsableSpace", path);
if (space != null) {
return space;
}
return getTotalSpace(path);
}
// TODO: FixMe for Windows, before making it public...
public static long getTotalSpace(final File pPath) {
// NOTE: Allow null, to get space in current/system volume
File path = pPath != null ? pPath : new File(".");
Long space = getSpace16("getTotalSpace", path);
if (space != null) {
return space;
}
return FS.getTotalSpace(path);
}
private static Long getSpace16(final String pMethodName, final File pPath) {
try {
Method freeSpace = File.class.getMethod(pMethodName);
return (Long) freeSpace.invoke(pPath);
}
catch (NoSuchMethodException ignore) {}
catch (IllegalAccessException ignore) {}
catch (InvocationTargetException e) {
Throwable throwable = e.getTargetException();
if (throwable instanceof SecurityException) {
throw (SecurityException) throwable;
}
throw new UndeclaredThrowableException(throwable);
}
return null;
}
/**
* Formats the given number to a human readable format.
* Kind of like {@code df -h}.
*
* @param pSizeInBytes the size in byte
* @return a human readable string representation
*/
public static String toHumanReadableSize(final long pSizeInBytes) {
// TODO: Rewrite to use String.format?
if (pSizeInBytes < 1024L) {
return pSizeInBytes + " Bytes";
}
else if (pSizeInBytes < (1024L << 10)) {
return getSizeFormat().format(pSizeInBytes / (double) (1024L)) + " KB";
}
else if (pSizeInBytes < (1024L << 20)) {
return getSizeFormat().format(pSizeInBytes / (double) (1024L << 10)) + " MB";
}
else if (pSizeInBytes < (1024L << 30)) {
return getSizeFormat().format(pSizeInBytes / (double) (1024L << 20)) + " GB";
}
else if (pSizeInBytes < (1024L << 40)) {
return getSizeFormat().format(pSizeInBytes / (double) (1024L << 30)) + " TB";
}
else {
return getSizeFormat().format(pSizeInBytes / (double) (1024L << 40)) + " PB";
}
}
// NumberFormat is not thread-safe, so we stick to thread-confined instances
private static ThreadLocal<NumberFormat> sNumberFormat = new ThreadLocal<NumberFormat>() {
protected NumberFormat initialValue() {
NumberFormat format = NumberFormat.getNumberInstance();
// TODO: Consider making this locale/platform specific, OR a method parameter...
// format.setMaximumFractionDigits(2);
format.setMaximumFractionDigits(0);
return format;
}
};
private static NumberFormat getSizeFormat() {
return sNumberFormat.get();
}
@SuppressWarnings({"ResultOfMethodCallIgnored"})
public static void visitFiles(final File pDirectory, final FileFilter pFilter, final Visitor<File> pVisitor) {
Validate.notNull(pDirectory, "directory");
Validate.notNull(pVisitor, "visitor");
pDirectory.listFiles(new FileFilter() {
public boolean accept(final File pFile) {
if (pFilter == null || pFilter.accept(pFile)) {
pVisitor.visit(pFile);
}
return false;
}
});
}
}
|
package org.commcare.session;
import org.commcare.suite.model.SessionDatum;
import org.commcare.suite.model.Text;
import org.javarosa.core.model.condition.EvaluationContext;
import org.javarosa.core.model.instance.TreeReference;
import org.javarosa.xpath.XPathException;
import java.util.Vector;
/**
* Performs all logic involved in polling the current CommCareSession to determine what information
* or action is needed by the session, and then sends a signal to the registered
* SessionNavigationResponder to indicate what should be done to get it (or if an error occurred)
*
* @author amstone
*/
public class SessionNavigator {
// Result codes to be interpreted by the SessionNavigationResponder
public static final int ASSERTION_FAILURE = 0;
public static final int NO_CURRENT_FORM = 1;
public static final int START_FORM_ENTRY = 2;
public static final int GET_COMMAND = 3;
public static final int START_ENTITY_SELECTION = 4;
public static final int LAUNCH_CONFIRM_DETAIL = 5;
public static final int EXCEPTION_THROWN = 6;
private SessionNavigationResponder responder;
private CommCareSession currentSession;
private EvaluationContext ec;
private TreeReference currentAutoSelectedCase;
private Exception thrownException;
public SessionNavigator(SessionNavigationResponder r) {
this.responder = r;
}
private void sendResponse(int resultCode) {
responder.processSessionResponse(resultCode);
}
public TreeReference getCurrentAutoSelection() {
return this.currentAutoSelectedCase;
}
public Exception getCurrentException() {
return this.thrownException;
}
/**
* Polls the CommCareSession to determine what information is needed in order to proceed with
* the next entry step in the session, and then executes the action to get that info, OR
* proceeds with trying to enter the form if no more info is needed
*/
public void startNextSessionStep() {
currentSession = responder.getSessionForNavigator();
ec = responder.getEvalContextForNavigator();
String needed = currentSession.getNeededData();
if (needed == null) {
readyToProceed();
} else if (needed.equals(SessionFrame.STATE_COMMAND_ID)) {
sendResponse(GET_COMMAND);
} else if (needed.equals(SessionFrame.STATE_DATUM_VAL)) {
handleGetDatum();
} else if (needed.equals(SessionFrame.STATE_DATUM_COMPUTED)) {
handleCompute();
}
}
private void readyToProceed() {
Text text = currentSession.getCurrentEntry().getAssertions().getAssertionFailure(ec);
if (text != null) {
// We failed one of our assertions
sendResponse(ASSERTION_FAILURE);
}
else if (currentSession.getForm() == null) {
sendResponse(NO_CURRENT_FORM);
} else {
sendResponse(START_FORM_ENTRY);
}
}
private void handleGetDatum() {
TreeReference autoSelection = getAutoSelectedCase();
if (autoSelection == null) {
sendResponse(START_ENTITY_SELECTION);
} else {
this.currentAutoSelectedCase = autoSelection;
handleAutoSelect();
}
}
private void handleAutoSelect() {
SessionDatum selectDatum = currentSession.getNeededDatum();
if (selectDatum.getLongDetail() == null) {
// No confirm detail defined for this entity select, so just set the case id right away
// and proceed
String autoSelectedCaseId = SessionDatum.getCaseIdFromReference(
currentAutoSelectedCase, selectDatum, ec);
currentSession.setDatum(selectDatum.getDataId(), autoSelectedCaseId);
startNextSessionStep();
} else {
sendResponse(LAUNCH_CONFIRM_DETAIL);
}
}
/**
*
* Returns the auto-selected case for the next needed datum, if there should be one.
* Returns null if auto selection is not enabled, or if there are multiple available cases
* for the datum (and therefore auto-selection should not be used).
*/
private TreeReference getAutoSelectedCase() {
SessionDatum selectDatum = currentSession.getNeededDatum();
if (selectDatum.isAutoSelectEnabled()) {
Vector<TreeReference> entityListElements = ec.expandReference(selectDatum.getNodeset());
if (entityListElements.size() == 1) {
return entityListElements.elementAt(0);
} else {
return null;
}
} else {
return null;
}
}
private void handleCompute() {
try {
currentSession.setComputedDatum(ec);
} catch (XPathException e) {
this.thrownException = e;
sendResponse(EXCEPTION_THROWN);
}
startNextSessionStep();
}
public void stepBack() {
currentSession.stepBack();
}
}
|
package org.mskcc.cbio.oncokb.util;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.mskcc.cbio.oncokb.model.*;
import java.util.*;
public class IndicatorUtils {
public static IndicatorQueryResp processQuery(Query query, String geneStatus,
Set<LevelOfEvidence> levels, String source, Boolean highestLevelOnly) {
geneStatus = geneStatus != null ? geneStatus : "complete";
highestLevelOnly = highestLevelOnly == null ? false : highestLevelOnly;
IndicatorQueryResp indicatorQuery = new IndicatorQueryResp();
indicatorQuery.setQuery(query);
Gene gene = null;
List<Alteration> relevantAlterations = new ArrayList<>();
if (query == null) {
return indicatorQuery;
}
if (query.getAlteration() != null && query.getAlteration().toLowerCase().matches("gain")) {
query.setAlteration("Amplification");
}
source = source == null ? "oncokb" : source;
// Deal with fusion without primary gene
// TODO: support entrezGeneId fusion
if (query.getHugoSymbol() != null
&& query.getAlterationType() != null &&
query.getAlterationType().equalsIgnoreCase("fusion")) {
List<String> geneStrsList = Arrays.asList(query.getHugoSymbol().split("-"));
Set<String> geneStrsSet = new HashSet<>();
if (geneStrsList != null) {
geneStrsSet = new HashSet<>(geneStrsList);
}
if (geneStrsSet.size() == 2) {
List<Gene> tmpGenes = new ArrayList<>();
for (String geneStr : geneStrsSet) {
Gene tmpGene = GeneUtils.getGeneByHugoSymbol(geneStr);
if (tmpGene != null) {
tmpGenes.add(tmpGene);
}
}
if (tmpGenes.size() > 0) {
query.setAlteration(query.getHugoSymbol() + " fusion");
for (Gene tmpGene : tmpGenes) {
Alteration alt = AlterationUtils.getAlteration(tmpGene.getHugoSymbol(), query.getAlteration(),
null, null, null, null);
AlterationUtils.annotateAlteration(alt, alt.getAlteration());
List<Alteration> tmpRelevantAlts = AlterationUtils.getRelevantAlterations(alt);
if (tmpRelevantAlts != null && tmpRelevantAlts.size() > 0) {
gene = tmpGene;
relevantAlterations = tmpRelevantAlts;
break;
}
}
// None of relevant alterations found in both genes.
if (gene == null) {
gene = tmpGenes.get(0);
}
}
}
} else {
gene = query.getEntrezGeneId() == null ? GeneUtils.getGeneByHugoSymbol(query.getHugoSymbol()) :
GeneUtils.getGeneByHugoSymbol(query.getHugoSymbol());
if (gene != null) {
Alteration alt = AlterationUtils.getAlteration(gene.getHugoSymbol(), query.getAlteration(),
null, query.getConsequence(), query.getProteinStart(), query.getProteinEnd());
AlterationUtils.annotateAlteration(alt, alt.getAlteration());
relevantAlterations = AlterationUtils.getRelevantAlterations(alt);
}
}
if (gene != null) {
query.setHugoSymbol(gene.getHugoSymbol());
query.setEntrezGeneId(gene.getEntrezGeneId());
indicatorQuery.setGeneExist(true);
// Gene summary
indicatorQuery.setGeneSummary(SummaryUtils.geneSummary(gene));
List<Alteration> nonVUSRelevantAlts = AlterationUtils.excludeVUS(relevantAlterations);
Map<String, LevelOfEvidence> highestLevels = new HashMap<>();
List<Alteration> alleles = new ArrayList<>();
List<OncoTreeType> oncoTreeTypes = new ArrayList<>();
if (relevantAlterations == null || relevantAlterations.size() == 0) {
indicatorQuery.setVariantExist(false);
Alteration alteration = AlterationUtils.getAlteration(query.getHugoSymbol(), query.getAlteration(),
null, query.getConsequence(), query.getProteinStart(), query.getProteinEnd());
if (alteration != null) {
alleles = AlterationUtils.getAlleleAlterations(alteration);
}
} else {
indicatorQuery.setVariantExist(true);
if (!relevantAlterations.isEmpty()) {
for (Alteration alteration : relevantAlterations) {
alleles.addAll(AlterationUtils.getAlleleAlterations(alteration));
}
}
}
if (query.getProteinEnd() == null || query.getProteinStart() == null) {
Alteration alteration = AlterationUtils.getAlteration(query.getHugoSymbol(), query.getAlteration(),
null, query.getConsequence(), query.getProteinStart(), query.getProteinEnd());
AlterationUtils.annotateAlteration(alteration, query.getAlteration());
indicatorQuery.setHotspot(HotspotUtils.isHotspot(gene.getHugoSymbol(), alteration.getProteinStart(), alteration.getProteinEnd()));
} else {
indicatorQuery.setHotspot(HotspotUtils.isHotspot(gene.getHugoSymbol(), query.getProteinStart(), query.getProteinEnd()));
}
if (query.getTumorType() != null) {
oncoTreeTypes = TumorTypeUtils.getMappedOncoTreeTypesBySource(query.getTumorType(), source);
// Tumor type summary
indicatorQuery.setTumorTypeSummary(SummaryUtils.tumorTypeSummary(gene, query.getAlteration(),
new ArrayList<Alteration>(relevantAlterations), query.getTumorType(),
new HashSet<OncoTreeType>(oncoTreeTypes)));
}
// Mutation summary
indicatorQuery.setVariantSummary(SummaryUtils.oncogenicSummary(gene,
new ArrayList<Alteration>(relevantAlterations), query.getAlteration(), false));
indicatorQuery.setVUS(isVUS(
EvidenceUtils.getRelevantEvidences(query, source,
geneStatus, Collections.singleton(EvidenceType.VUS), null)
));
if (alleles == null || alleles.size() == 0) {
indicatorQuery.setAlleleExist(false);
} else {
indicatorQuery.setAlleleExist(true);
}
Set<Evidence> treatmentEvidences = null;
if (nonVUSRelevantAlts.size() > 0) {
Oncogenicity oncogenicity = MainUtils.findHighestOncogenicByEvidences(
EvidenceUtils.getRelevantEvidences(query, source, geneStatus,
Collections.singleton(EvidenceType.ONCOGENIC), null)
);
indicatorQuery.setOncogenic(oncogenicity == null ? "" : oncogenicity.getOncogenic());
treatmentEvidences = EvidenceUtils.keepHighestLevelForSameTreatments(
EvidenceUtils.getRelevantEvidences(query, source, geneStatus,
MainUtils.getTreatmentEvidenceTypes(),
(levels != null ?
new HashSet<LevelOfEvidence>(CollectionUtils.intersection(levels,
LevelUtils.getPublicAndOtherIndicationLevels())) : LevelUtils.getPublicAndOtherIndicationLevels())));
} else if (indicatorQuery.getAlleleExist() || indicatorQuery.getVUS()) {
Oncogenicity oncogenicity = getAlternativeAlleleOncogenicity(alleles);
treatmentEvidences = getAlternativeAlleleTreatments(alleles, levels, oncoTreeTypes);
indicatorQuery.setOncogenic(oncogenicity == null ? "" : oncogenicity.getOncogenic());
}
if (treatmentEvidences != null) {
if (highestLevelOnly) {
Set<Evidence> filteredEvis = new HashSet<>();
// Get highest sensitive evidences
Set<Evidence> sensitiveEvidences = EvidenceUtils.getSensitiveEvidences(treatmentEvidences);
filteredEvis.addAll(EvidenceUtils.getOnlySignificantLevelsEvidences(sensitiveEvidences));
// Get highest resistance evidences
Set<Evidence> resistanceEvidences = EvidenceUtils.getResistanceEvidences(treatmentEvidences);
filteredEvis.addAll(EvidenceUtils.getOnlyHighestLevelEvidences(resistanceEvidences));
treatmentEvidences = filteredEvis;
}
if (treatmentEvidences != null) {
List<IndicatorQueryTreatment> treatments = getIndicatorQueryTreatments(treatmentEvidences);
indicatorQuery.setTreatments(treatments);
highestLevels = findHighestLevel(new HashSet<>(treatments));
indicatorQuery.setHighestSensitiveLevel(highestLevels.get("sensitive"));
indicatorQuery.setHighestResistanceLevel(highestLevels.get("resistant"));
indicatorQuery.setOtherSignificantSensitiveLevels(getOtherSignificantLevels(indicatorQuery.getHighestSensitiveLevel(), "sensitive", treatmentEvidences));
indicatorQuery.setOtherSignificantResistanceLevels(getOtherSignificantLevels(indicatorQuery.getHighestResistanceLevel(), "resistance", treatmentEvidences));
}
}
// This is special case for KRAS wildtype. May need to come up with a better plan for this.
if (gene != null && (gene.getHugoSymbol().equals("KRAS") || gene.getHugoSymbol().equals("NRAS"))
&& query.getAlteration() != null
&& StringUtils.containsIgnoreCase(query.getAlteration(), "wildtype")) {
if (oncoTreeTypes.contains(TumorTypeUtils.getOncoTreeCancerType("Colorectal Cancer"))) {
indicatorQuery.setGeneSummary("RAS (KRAS/NRAS) which is wildtype (not mutated) in this sample, encodes an upstream activator of the pro-oncogenic MAP- and PI3-kinase pathways and is mutated in approximately 40% of late stage colorectal cancers.");
indicatorQuery.setVariantSummary("The absence of a mutation in the RAS genes is clinically important because it expands approved treatments available to treat this tumor. RAS status in stage IV colorectal cancer influences patient responses to the anti-EGFR antibody therapies cetuximab and panitumumab.");
indicatorQuery.setTumorTypeSummary("These drugs are FDA-approved for the treatment of KRAS wildtype colorectal tumors together with chemotherapy or alone following progression through standard chemotherapy.");
} else {
indicatorQuery.setVariantSummary("");
indicatorQuery.setTumorTypeSummary("");
indicatorQuery.setTreatments(new ArrayList<IndicatorQueryTreatment>());
indicatorQuery.setHighestResistanceLevel(null);
indicatorQuery.setHighestSensitiveLevel(null);
}
}
} else {
indicatorQuery.setGeneExist(false);
}
indicatorQuery.setDataVersion(MainUtils.getDataVersion());
indicatorQuery.setLastUpdate(MainUtils.getDataVersionDate());
return indicatorQuery;
}
private static List<LevelOfEvidence> getOtherSignificantLevels(LevelOfEvidence highestLevel, String type, Set<Evidence> evidences) {
List<LevelOfEvidence> otherSignificantLevels = new ArrayList<>();
if (type != null && highestLevel != null && evidences != null) {
if (type.equals("sensitive")) {
if (highestLevel.equals(LevelOfEvidence.LEVEL_2B)) {
Map<LevelOfEvidence, Set<Evidence>> levels = EvidenceUtils.separateEvidencesByLevel(evidences);
if (levels.containsKey(LevelOfEvidence.LEVEL_3A)) {
otherSignificantLevels.add(LevelOfEvidence.LEVEL_3A);
}
}
} else if (type.equals("resistance")) {
}
}
return otherSignificantLevels;
}
private static List<IndicatorQueryTreatment> getIndicatorQueryTreatments(Set<Evidence> evidences) {
List<IndicatorQueryTreatment> treatments = new ArrayList<>();
if (evidences != null) {
List<Evidence> sortedEvidence = new ArrayList<>(evidences);
Collections.sort(sortedEvidence, new Comparator<Evidence>() {
public int compare(Evidence e1, Evidence e2) {
if (e1.getId() == null)
return 1;
if (e2.getId() == null)
return -1;
return e1.getId() - e2.getId();
}
});
for (Evidence evidence : sortedEvidence) {
Set<String> pmids = new HashSet<>();
Set<ArticleAbstract> abstracts = new HashSet<>();
for (Article article : evidence.getArticles()) {
if (article.getPmid() != null) {
pmids.add(article.getPmid());
}
if (article.getAbstractContent() != null) {
ArticleAbstract articleAbstract = new ArticleAbstract();
articleAbstract.setAbstractContent(article.getAbstractContent());
articleAbstract.setLink(article.getLink());
abstracts.add(articleAbstract);
}
}
for (Treatment treatment : evidence.getTreatments()) {
IndicatorQueryTreatment indicatorQueryTreatment = new IndicatorQueryTreatment();
indicatorQueryTreatment.setDrugs(treatment.getDrugs());
indicatorQueryTreatment.setApprovedIndications(treatment.getApprovedIndications());
indicatorQueryTreatment.setLevel(evidence.getLevelOfEvidence());
indicatorQueryTreatment.setPmids(pmids);
indicatorQueryTreatment.setAbstracts(abstracts);
treatments.add(indicatorQueryTreatment);
}
}
}
return treatments;
}
private static Boolean isVUS(Set<Evidence> evidenceList) {
for (Evidence evidence : evidenceList) {
if (evidence.getEvidenceType().equals(EvidenceType.VUS)) {
return true;
}
}
return false;
}
private static Map<String, LevelOfEvidence> findHighestLevel(Set<IndicatorQueryTreatment> treatments) {
int levelSIndex = -1;
int levelRIndex = -1;
Map<String, LevelOfEvidence> levels = new HashMap<>();
if (treatments != null) {
for (IndicatorQueryTreatment treatment : treatments) {
LevelOfEvidence levelOfEvidence = treatment.getLevel();
if (levelOfEvidence != null) {
int _index = -1;
if (LevelUtils.isSensitiveLevel(levelOfEvidence)) {
_index = LevelUtils.SENSITIVE_LEVELS.indexOf(levelOfEvidence);
if (_index > levelSIndex) {
levelSIndex = _index;
}
} else if (LevelUtils.isResistanceLevel(levelOfEvidence)) {
_index = LevelUtils.RESISTANCE_LEVELS.indexOf(levelOfEvidence);
if (_index > levelRIndex) {
levelRIndex = _index;
}
}
}
}
}
levels.put("sensitive", levelSIndex > -1 ? LevelUtils.SENSITIVE_LEVELS.get(levelSIndex) : null);
levels.put("resistant", levelRIndex > -1 ? LevelUtils.RESISTANCE_LEVELS.get(levelRIndex) : null);
return levels;
}
private static Oncogenicity getAlternativeAlleleOncogenicity(List<Alteration> alternativeAllele) {
Alteration oncogenicAllele = AlterationUtils.findOncogenicAllele(alternativeAllele);
List<Alteration> alleleAndRelevantAlterations = new ArrayList<>();
Set<Alteration> oncogenicMutations = null;
alleleAndRelevantAlterations.addAll(alternativeAllele);
if (oncogenicAllele != null) {
oncogenicMutations = AlterationUtils.getOncogenicMutations(oncogenicAllele);
alleleAndRelevantAlterations.addAll(oncogenicMutations);
}
Oncogenicity oncogenicity = MainUtils.setToAlleleOncogenicity(MainUtils.findHighestOncogenicByEvidences(new HashSet<>(EvidenceUtils.getEvidence(new ArrayList<>(alleleAndRelevantAlterations), Collections.singleton(EvidenceType.ONCOGENIC), null))));
return oncogenicity;
}
private static Set<Evidence> getAlternativeAlleleTreatments(List<Alteration> alternativeAlleles, Set<LevelOfEvidence> levels, List<OncoTreeType> oncoTreeTypes) {
Alteration oncogenicAllele = AlterationUtils.findOncogenicAllele(alternativeAlleles);
Set<Alteration> oncogenicMutations = AlterationUtils.getOncogenicMutations(oncogenicAllele);
Set<Evidence> treatmentEvidences = EvidenceUtils.keepHighestLevelForSameTreatments(
EvidenceUtils.convertEvidenceLevel(
EvidenceUtils.getEvidence(new ArrayList<>(alternativeAlleles),
MainUtils.getSensitiveTreatmentEvidenceTypes(),
(levels != null ?
new HashSet<>(CollectionUtils.intersection(levels,
LevelUtils.getPublicAndOtherIndicationLevels())) : LevelUtils.getPublicAndOtherIndicationLevels())), new HashSet<>(oncoTreeTypes)));
if (oncogenicMutations != null) {
treatmentEvidences.addAll(EvidenceUtils.keepHighestLevelForSameTreatments(
EvidenceUtils.convertEvidenceLevel(
EvidenceUtils.getEvidence(new ArrayList<>(oncogenicMutations),
MainUtils.getTreatmentEvidenceTypes(),
(levels != null ?
new HashSet<>(CollectionUtils.intersection(levels,
LevelUtils.getPublicAndOtherIndicationLevels())) : LevelUtils.getPublicAndOtherIndicationLevels())), new HashSet<>(oncoTreeTypes))));
}
return treatmentEvidences;
}
}
|
package Parser;
import java.security.InvalidParameterException;
import commandFactory.CommandType;
import commonClasses.Constants;
import commonClasses.SummaryReport;
public class Parser {
private ParsedResult result;
private MainCommandInterpreter mainHandler;
private OptionalCommandInterpreter optionHandler;
public Parser() {
mainHandler = new MainCommandInterpreter();
optionHandler = new OptionalCommandInterpreter();
}
public ParsedResult parseString(String input) {
result = new ParsedResult();
// Processing first command and getting command param
try {
String[] seperatedInput = input.split("-");
String commandWord = getCommandWord(seperatedInput[1]);
mainHandler.identifyAndSetCommand(commandWord.toLowerCase());
if (commandDoesNotRequireParam(mainHandler.getCommand())) {
result.setCommandType(mainHandler.getCommand());
return result;
}
String remainingInput = mainHandler.removeCommandWord(seperatedInput[1]);
//String commandParam = getParam(remainingInput);
//remainingInput = removeParam(remainingInput);
result = mainHandler.updateResults(result, remainingInput.trim());
// Processing optional commands
processOptionalCommand(seperatedInput);
if (result.getTaskDetails().getDueDate() == null) {
result.getTaskDetails().setDueDate(Constants.SOMEDAY);
}
return result;
} catch (Exception e) {
result.setValidationResult(false);
return result;
}
/*
* System.out.println(commandWord);
*
* System.out.println(commandWord); System.out.println(commandParam);
* System.out.println(ParsedResult.getTaskDetails().getDueDate()
* .toLocalDate().toString("dd/MM/yyyy"));
* System.out.println(ParsedResult.getTaskDetails().getDueDate()
* .toLocalTime().toString("HH:mm"));
*/
}
private void processOptionalCommand(String[] remainingInput) {
String commandWord;
String commandParam;
for(int i=4; i<remainingInput.length;i+=2) {
commandWord = getCommandWord(remainingInput[i]);
optionHandler.identifyAndSetCommand(commandWord.toLowerCase());
remainingInput[i] = optionHandler.removeCommandWord(remainingInput[i]);
//commandParam = getParam(remainingInput[i]);
result = optionHandler.updateResults(result, remainingInput[i].trim());
//remainingInput = removeParam(remainingInput);
}
}
private static boolean commandDoesNotRequireParam(CommandType command) {
if (command == CommandType.UNDO)
return true;
return false;
}
private static String removeParam(String remainingInput) {
int indexEndOfParam = remainingInput.indexOf(']');
// Adjust index to take substring after ']'
indexEndOfParam++;
remainingInput = remainingInput.substring(indexEndOfParam);
return remainingInput.trim();
}
private static String getCommandWord(String input) {
String[] splittedCommand = input.split(" ");
return splittedCommand[0];
}
private static String getParam(String remainingInput)
throws InvalidParameterException {
int indexStartOfParam = remainingInput.indexOf('[');
int indexEndOfParam = remainingInput.indexOf(']');
if (indexStartOfParam == -1 || indexEndOfParam == -1) {
SummaryReport
.setFeedBackMsg(Constants.MESSAGE_INVALID_PARAM_FORMATTING);
throw new InvalidParameterException();
// return remainingInput;
}
indexStartOfParam++; // adjust to get first letter of param
remainingInput = remainingInput.substring(indexStartOfParam,
indexEndOfParam);
return remainingInput.trim();
}
}
|
package processing.app;
import static processing.app.I18n._;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.logging.impl.LogFactoryImpl;
import org.apache.commons.logging.impl.NoOpLog;
import cc.arduino.packages.DiscoveryManager;
import cc.arduino.packages.Uploader;
import processing.app.debug.Compiler;
import cc.arduino.libraries.contributions.LibrariesIndexer;
import cc.arduino.packages.contributions.ContributionsIndexer;
import cc.arduino.utils.ArchiveExtractor;
import processing.app.debug.TargetBoard;
import processing.app.debug.LegacyTargetPackage;
import processing.app.debug.TargetPackage;
import processing.app.debug.TargetPlatform;
import processing.app.debug.TargetPlatformException;
import processing.app.helpers.BasicUserNotifier;
import processing.app.helpers.CommandlineParser;
import processing.app.helpers.OSUtils;
import processing.app.helpers.PreferencesMap;
import processing.app.helpers.UserNotifier;
import processing.app.helpers.filefilters.OnlyDirs;
import processing.app.helpers.filefilters.OnlyFilesWithExtension;
import processing.app.legacy.PApplet;
import processing.app.packages.LibraryList;
import processing.app.packages.UserLibrary;
public class BaseNoGui {
/** Version string to be used for build */
public static final int REVISION = 10602;
/** Extended version string displayed on GUI */
static String VERSION_NAME = "1.6.2";
static File buildFolder;
// Current directory to use for relative paths specified on the
// commandline
static String currentDirectory = System.getProperty("user.dir");
private static DiscoveryManager discoveryManager = new DiscoveryManager();
// these are static because they're used by Sketch
static private File examplesFolder;
static private File toolsFolder;
// maps #included files to their library folder
public static Map<String, UserLibrary> importToLibraryTable;
// maps library name to their library folder
static private LibraryList libraries;
// XXX: Remove this field
static private List<File> librariesFolders;
static UserNotifier notifier = new BasicUserNotifier();
static public Map<String, TargetPackage> packages;
static Platform platform;
static File portableFolder = null;
static final String portableSketchbookFolder = "sketchbook";
static ContributionsIndexer indexer;
static LibrariesIndexer librariesIndexer;
// Returns a File object for the given pathname. If the pathname
// is not absolute, it is interpreted relative to the current
// directory when starting the IDE (which is not the same as the
// current working directory!).
static public File absoluteFile(String path) {
if (path == null) return null;
File file = new File(path);
if (!file.isAbsolute()) {
file = new File(currentDirectory, path);
}
return file;
}
/**
* Get the number of lines in a file by counting the number of newline
* characters inside a String (and adding 1).
*/
static public int countLines(String what) {
int count = 1;
for (char c : what.toCharArray()) {
if (c == '\n') count++;
}
return count;
}
/**
* Get the path to the platform's temporary folder, by creating
* a temporary temporary file and getting its parent folder.
* <br/>
* Modified for revision 0094 to actually make the folder randomized
* to avoid conflicts in multi-user environments. (Bug 177)
*/
static public File createTempFolder(String name) {
try {
File folder = File.createTempFile(name, null);
//String tempPath = ignored.getParent();
//return new File(tempPath);
folder.delete();
folder.mkdirs();
return folder;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
static public String getAvrBasePath() {
String path = getHardwarePath() + File.separator + "tools" +
File.separator + "avr" + File.separator + "bin" + File.separator;
if (OSUtils.isLinux() && !(new File(path)).exists()) {
return ""; // use distribution provided avr tools if bundled tools missing
}
return path;
}
static public File getBuildFolder() {
if (buildFolder == null) {
String buildPath = PreferencesData.get("build.path");
if (buildPath != null) {
buildFolder = absoluteFile(buildPath);
if (!buildFolder.exists())
buildFolder.mkdirs();
} else {
//File folder = new File(getTempFolder(), "build");
//if (!folder.exists()) folder.mkdirs();
buildFolder = createTempFolder("build");
buildFolder.deleteOnExit();
}
}
return buildFolder;
}
static public PreferencesMap getBoardPreferences() {
TargetBoard board = getTargetBoard();
if (board == null)
return null;
String boardId = board.getId();
PreferencesMap prefs = new PreferencesMap(board.getPreferences());
String extendedName = prefs.get("name");
for (String menuId : board.getMenuIds()) {
if (!board.hasMenu(menuId))
continue;
// Get "custom_[MENU_ID]" preference (for example "custom_cpu")
String entry = PreferencesData.get("custom_" + menuId);
if (entry != null && entry.startsWith(boardId)) {
String selectionId = entry.substring(boardId.length() + 1);
prefs.putAll(board.getMenuPreferences(menuId, selectionId));
// Update the name with the extended configuration
extendedName += ", " + board.getMenuLabel(menuId, selectionId);
}
}
prefs.put("name", extendedName);
return prefs;
}
static public File getContentFile(String name) {
File path = new File(System.getProperty("user.dir"));
if (OSUtils.isMacOS()) {
if (System.getProperty("WORK_DIR") != null) {
path = new File(System.getProperty("WORK_DIR"));
} else {
try {
path = new File(BaseNoGui.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()).getParentFile();
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
}
return new File(path, name);
}
static public TargetPlatform getCurrentTargetPlatformFromPackage(String pack) {
return getTargetPlatform(pack, PreferencesData.get("target_platform"));
}
static public File getDefaultSketchbookFolder() {
if (getPortableFolder() != null)
return new File(getPortableFolder(), getPortableSketchbookFolder());
File sketchbookFolder = null;
try {
sketchbookFolder = getPlatform().getDefaultSketchbookFolder();
} catch (Exception e) { }
return sketchbookFolder;
}
public static DiscoveryManager getDiscoveryManager() {
return discoveryManager;
}
static public File getExamplesFolder() {
return examplesFolder;
}
static public String getExamplesPath() {
return examplesFolder.getAbsolutePath();
}
static public File getHardwareFolder() {
// calculate on the fly because it's needed by Preferences.init() to find
// the boards.txt and programmers.txt preferences files (which happens
// before the other folders / paths get cached).
return getContentFile("hardware");
}
static public String getHardwarePath() {
return getHardwareFolder().getAbsolutePath();
}
static public LibraryList getLibraries() {
return libraries;
}
static public List<File> getLibrariesPath() {
return librariesFolders;
}
/**
* Return an InputStream for a file inside the Processing lib folder.
*/
static public InputStream getLibStream(String filename) throws IOException {
return new FileInputStream(new File(getContentFile("lib"), filename));
}
static public Platform getPlatform() {
return platform;
}
static public File getPortableFolder() {
return portableFolder;
}
static public String getPortableSketchbookFolder() {
return portableSketchbookFolder;
}
/**
* Convenience method to get a File object for the specified filename inside
* the settings folder.
* For now, only used by Preferences to get the preferences.txt file.
* @param filename A file inside the settings folder.
* @return filename wrapped as a File object inside the settings folder
*/
static public File getSettingsFile(String filename) {
return new File(getSettingsFolder(), filename);
}
static public File getSettingsFolder() {
if (getPortableFolder() != null)
return getPortableFolder();
File settingsFolder = null;
String preferencesPath = PreferencesData.get("settings.path");
if (preferencesPath != null) {
settingsFolder = absoluteFile(preferencesPath);
} else {
try {
settingsFolder = getPlatform().getSettingsFolder();
} catch (Exception e) {
showError(_("Problem getting data folder"),
_("Error getting the Arduino data folder."), e);
}
}
// create the folder if it doesn't exist already
if (!settingsFolder.exists()) {
if (!settingsFolder.mkdirs()) {
showError(_("Settings issues"),
_("Arduino cannot run because it could not\n" +
"create a folder to store your settings."), null);
}
}
return settingsFolder;
}
static public File getSketchbookFolder() {
if (portableFolder != null)
return new File(portableFolder, PreferencesData.get("sketchbook.path"));
return absoluteFile(PreferencesData.get("sketchbook.path"));
}
static public File getSketchbookHardwareFolder() {
return new File(getSketchbookFolder(), "hardware");
}
static public File getSketchbookLibrariesFolder() {
File libdir = new File(getSketchbookFolder(), "libraries");
if (!libdir.exists()) {
try {
libdir.mkdirs();
File readme = new File(libdir, "readme.txt");
FileWriter freadme = new FileWriter(readme);
freadme.write(_("For information on installing libraries, see: " +
"http://arduino.cc/en/Guide/Libraries\n"));
freadme.close();
} catch (Exception e) {
}
}
return libdir;
}
static public String getSketchbookPath() {
// Get the sketchbook path, and make sure it's set properly
String sketchbookPath = PreferencesData.get("sketchbook.path");
// If a value is at least set, first check to see if the folder exists.
// If it doesn't, warn the user that the sketchbook folder is being reset.
if (sketchbookPath != null) {
File sketchbookFolder;
if (getPortableFolder() != null)
sketchbookFolder = new File(getPortableFolder(), sketchbookPath);
else
sketchbookFolder = absoluteFile(sketchbookPath);
if (!sketchbookFolder.exists()) {
showWarning(_("Sketchbook folder disappeared"),
_("The sketchbook folder no longer exists.\n" +
"Arduino will switch to the default sketchbook\n" +
"location, and create a new sketchbook folder if\n" +
"necessary. Arduino will then stop talking about\n" +
"himself in the third person."), null);
sketchbookPath = null;
}
}
return sketchbookPath;
}
public static TargetBoard getTargetBoard() {
TargetPlatform targetPlatform = getTargetPlatform();
if (targetPlatform == null)
return null;
String boardId = PreferencesData.get("board");
return targetPlatform.getBoard(boardId);
}
/**
* Returns a specific TargetPackage
*
* @param packageName
* @return
*/
static public TargetPackage getTargetPackage(String packageName) {
return packages.get(packageName);
}
/**
* Returns the currently selected TargetPlatform.
*
* @return
*/
static public TargetPlatform getTargetPlatform() {
String packageName = PreferencesData.get("target_package");
String platformName = PreferencesData.get("target_platform");
return getTargetPlatform(packageName, platformName);
}
/**
* Returns a specific TargetPlatform searching Package/Platform
*
* @param packageName
* @param platformName
* @return
*/
static public TargetPlatform getTargetPlatform(String packageName,
String platformName) {
TargetPackage p = packages.get(packageName);
if (p == null)
return null;
return p.get(platformName);
}
static public File getToolsFolder() {
return toolsFolder;
}
static public String getToolsPath() {
return toolsFolder.getAbsolutePath();
}
static public LibraryList getUserLibs() {
LibraryList libs = BaseNoGui.librariesIndexer.getInstalledLibraries();
return libs.filterLibrariesInSubfolder(getSketchbookFolder());
}
/**
* Given a folder, return a list of the header files in that folder (but not
* the header files in its sub-folders, as those should be included from
* within the header files at the top-level).
*/
static public String[] headerListFromIncludePath(File path) throws IOException {
String[] list = path.list(new OnlyFilesWithExtension(".h"));
if (list == null) {
throw new IOException();
}
return list;
}
static public void init(String[] args) throws Exception {
getPlatform().init();
String sketchbookPath = getSketchbookPath();
// If no path is set, get the default sketchbook folder for this platform
if (sketchbookPath == null) {
if (BaseNoGui.getPortableFolder() != null)
PreferencesData.set("sketchbook.path", getPortableSketchbookFolder());
else
showError(_("No sketchbook"), _("Sketchbook path not defined"), null);
}
BaseNoGui.initPackages();
// Setup board-dependent variables.
onBoardOrPortChange();
CommandlineParser parser = CommandlineParser.newCommandlineParser(args);
for (String path: parser.getFilenames()) {
// Correctly resolve relative paths
File file = absoluteFile(path);
// Fix a problem with systems that use a non-ASCII languages. Paths are
// being passed in with 8.3 syntax, which makes the sketch loader code
// unhappy, since the sketch folder naming doesn't match up correctly.
if (OSUtils.isWindows()) {
try {
file = file.getCanonicalFile();
} catch (IOException e) {
e.printStackTrace();
}
}
if (!parser.isVerifyOrUploadMode() && !parser.isGetPrefMode())
showError(_("Mode not supported"), _("Only --verify, --upload or --get-pref are supported"), null);
if (!parser.isForceSavePrefs())
PreferencesData.setDoSave(false);
if (!file.exists()) {
String mess = I18n.format(_("Failed to open sketch: \"{0}\""), path);
// Open failure is fatal in upload/verify mode
showError(null, mess, 2);
}
}
// Save the preferences. For GUI mode, this happens in the quit
// handler, but for other modes we should also make sure to save
// them.
PreferencesData.save();
if (parser.isVerifyOrUploadMode()) {
// Set verbosity for command line build
PreferencesData.set("build.verbose", "" + parser.isDoVerboseBuild());
PreferencesData.set("upload.verbose", "" + parser.isDoVerboseUpload());
// Make sure these verbosity preferences are only for the
// current session
PreferencesData.setDoSave(false);
if (parser.isUploadMode()) {
if (parser.getFilenames().size() != 1)
{
showError(_("Multiple files not supported"), _("The --upload option supports only one file at a time"), null);
}
List<String> warningsAccumulator = new LinkedList<String>();
boolean success = false;
try {
// Editor constructor loads the sketch with handleOpenInternal() that
// creates a new Sketch that, in trun, calls load() inside its constructor
// This translates here as:
// SketchData data = new SketchData(file);
// File tempBuildFolder = getBuildFolder();
// data.load();
SketchData data = new SketchData(absoluteFile(parser.getFilenames().get(0)));
File tempBuildFolder = getBuildFolder();
data.load();
// Sketch.exportApplet()
// - calls Sketch.prepare() that calls Sketch.ensureExistence()
// - calls Sketch.build(verbose=false) that calls Sketch.ensureExistence(), set progressListener and calls Compiler.build()
// - calls Sketch.upload() (see later...)
if (!data.getFolder().exists()) showError(_("No sketch"), _("Can't find the sketch in the specified path"), null);
String suggestedClassName = Compiler.build(data, tempBuildFolder.getAbsolutePath(), tempBuildFolder, null, parser.isDoVerboseBuild());
if (suggestedClassName == null) showError(_("Error while verifying"), _("An error occurred while verifying the sketch"), null);
showMessage(_("Done compiling"), _("Done compiling"));
// - chiama Sketch.upload() ... to be continued ...
Uploader uploader = Compiler.getUploaderByPreferences(parser.isNoUploadPort());
if (uploader.requiresAuthorization() && !PreferencesData.has(uploader.getAuthorizationKey())) showError("...", "...", null);
try {
success = Compiler.upload(data, uploader, tempBuildFolder.getAbsolutePath(), suggestedClassName, parser.isDoUseProgrammer(), parser.isNoUploadPort(), warningsAccumulator);
showMessage(_("Done uploading"), _("Done uploading"));
} finally {
if (uploader.requiresAuthorization() && !success) {
PreferencesData.remove(uploader.getAuthorizationKey());
}
}
} catch (Exception e) {
showError(_("Error while verifying/uploading"), _("An error occurred while verifying/uploading the sketch"), e);
}
for (String warning : warningsAccumulator) {
System.out.print(_("Warning"));
System.out.print(": ");
System.out.println(warning);
}
if (!success) showError(_("Error while uploading"), _("An error occurred while uploading the sketch"), null);
} else {
for (String path : parser.getFilenames())
{
try {
// Editor constructor loads sketch with handleOpenInternal() that
// creates a new Sketch that calls load() in its constructor
// This translates here as:
// SketchData data = new SketchData(file);
// File tempBuildFolder = getBuildFolder();
// data.load();
SketchData data = new SketchData(absoluteFile(path));
File tempBuildFolder = getBuildFolder();
data.load();
// Sketch.prepare() calls Sketch.ensureExistence()
// Sketch.build(verbose) calls Sketch.ensureExistence() and set progressListener and, finally, calls Compiler.build()
// This translates here as:
// if (!data.getFolder().exists()) showError(...);
// String ... = Compiler.build(data, tempBuildFolder.getAbsolutePath(), tempBuildFolder, null, verbose);
if (!data.getFolder().exists()) showError(_("No sketch"), _("Can't find the sketch in the specified path"), null);
String suggestedClassName = Compiler.build(data, tempBuildFolder.getAbsolutePath(), tempBuildFolder, null, parser.isDoVerboseBuild());
if (suggestedClassName == null) showError(_("Error while verifying"), _("An error occurred while verifying the sketch"), null);
showMessage(_("Done compiling"), _("Done compiling"));
} catch (Exception e) {
showError(_("Error while verifying"), _("An error occurred while verifying the sketch"), e);
}
}
}
// No errors exit gracefully
System.exit(0);
}
else if (parser.isGetPrefMode()) {
String value = PreferencesData.get(parser.getGetPref(), null);
if (value != null) {
System.out.println(value);
System.exit(0);
} else {
System.exit(4);
}
}
}
static public void initLogger() {
System.setProperty(LogFactoryImpl.LOG_PROPERTY, NoOpLog.class.getCanonicalName());
Logger.getLogger("javax.jmdns").setLevel(Level.OFF);
}
static public void initPackages() throws Exception {
indexer = new ContributionsIndexer(BaseNoGui.getSettingsFolder());
File indexFile = indexer.getIndexFile();
if (!indexFile.isFile()) {
try {
File distFile = getContentFile("dist/default_package.tar.bz2");
if (distFile.isFile()) {
// If present, unpack distribution file into preferences folder
ArchiveExtractor.extract(distFile, BaseNoGui.getSettingsFolder(), 1);
// TODO: The first distribution file may be removed after extraction?
} else {
// Otherwise create an empty packages index
FileOutputStream out = new FileOutputStream(indexFile);
out.write("{ \"packages\" : [ ] }".getBytes());
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
indexer.parseIndex();
indexer.syncWithFilesystem();
System.out.println(indexer);
packages = new HashMap<String, TargetPackage>();
loadHardware(getHardwareFolder());
loadHardware(getSketchbookHardwareFolder());
loadContributedHardware(indexer);
librariesIndexer = new LibrariesIndexer(BaseNoGui.getSettingsFolder());
File librariesIndexFile = librariesIndexer.getIndexFile();
if (!librariesIndexFile.isFile()) {
try {
// Otherwise create an empty packages index
FileOutputStream out = new FileOutputStream(librariesIndexFile);
out.write("{ \"libraries\" : [ ] }".getBytes());
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
librariesIndexer.parseIndex();
}
static protected void initPlatform() {
try {
Class<?> platformClass = Class.forName("processing.app.Platform");
if (OSUtils.isMacOS()) {
platformClass = Class.forName("processing.app.macosx.Platform");
} else if (OSUtils.isWindows()) {
platformClass = Class.forName("processing.app.windows.Platform");
} else if (OSUtils.isLinux()) {
platformClass = Class.forName("processing.app.linux.Platform");
}
platform = (Platform) platformClass.newInstance();
} catch (Exception e) {
showError(_("Problem Setting the Platform"),
_("An unknown error occurred while trying to load\n" +
"platform-specific code for your machine."), e);
}
}
static public void initPortableFolder() {
// Portable folder
portableFolder = getContentFile("portable");
if (!portableFolder.exists())
portableFolder = null;
}
static public void initVersion() {
// help 3rd party installers find the correct hardware path
PreferencesData.set("last.ide." + VERSION_NAME + ".hardwarepath", getHardwarePath());
PreferencesData.set("last.ide." + VERSION_NAME + ".daterun", "" + (new Date()).getTime() / 1000);
}
/**
* Return true if the name is valid for a Processing sketch.
*/
static public boolean isSanitaryName(String name) {
return sanitizeName(name).equals(name);
}
static protected void loadHardware(File folder) {
if (!folder.isDirectory()) return;
String list[] = folder.list(new OnlyDirs());
// if a bad folder or something like that, this might come back null
if (list == null) return;
// alphabetize list, since it's not always alpha order
// replaced hella slow bubble sort with this feller for 0093
Arrays.sort(list, String.CASE_INSENSITIVE_ORDER);
for (String target : list) {
// Skip reserved 'tools' folder.
if (target.equals("tools"))
continue;
File subfolder = new File(folder, target);
try {
packages.put(target, new LegacyTargetPackage(target, subfolder));
} catch (TargetPlatformException e) {
System.out.println("WARNING: Error loading hardware folder " + target);
System.out.println(" " + e.getMessage());
}
}
}
/**
* Grab the contents of a file as a string.
*/
static public String loadFile(File file) throws IOException {
String[] contents = PApplet.loadStrings(file);
if (contents == null) return null;
return PApplet.join(contents, "\n");
}
static public void main(String args[]) throws Exception {
if (args.length == 0)
showError(_("No parameters"), _("No command line parameters found"), null);
initPlatform();
initPortableFolder();
initParameters(args);
init(args);
}
static public void onBoardOrPortChange() {
examplesFolder = getContentFile("examples");
toolsFolder = getContentFile("tools");
librariesFolders = new ArrayList<File>();
// Add IDE libraries folder
librariesFolders.add(getContentFile("libraries"));
TargetPlatform targetPlatform = getTargetPlatform();
if (targetPlatform != null) {
String core = getBoardPreferences().get("build.core", "arduino");
if (core.contains(":")) {
String referencedCore = core.split(":")[0];
TargetPlatform referencedPlatform = getTargetPlatform(referencedCore, targetPlatform.getId());
if (referencedPlatform != null) {
File referencedPlatformFolder = referencedPlatform.getFolder();
// Add libraries folder for the referenced platform
File folder = new File(referencedPlatformFolder, "libraries");
librariesFolders.add(folder);
}
}
File platformFolder = targetPlatform.getFolder();
// Add libraries folder for the selected platform
File folder = new File(platformFolder, "libraries");
librariesFolders.add(folder);
}
// Add libraries folder for the sketchbook
librariesFolders.add(getSketchbookLibrariesFolder());
// Scan for libraries in each library folder.
// Libraries located in the latest folders on the list can override
// other libraries with the same name.
try {
BaseNoGui.librariesIndexer.setSketchbookLibrariesFolder(getSketchbookLibrariesFolder());
BaseNoGui.librariesIndexer.setLibrariesFolders(librariesFolders);
BaseNoGui.librariesIndexer.rescanLibraries();
} catch (IOException e) {
showWarning(_("Error"), _("Error loading libraries"), e);
}
populateImportToLibraryTable();
}
static protected void loadContributedHardware(ContributionsIndexer indexer) {
for (TargetPackage pack : indexer.createTargetPackages()) {
packages.put(pack.getId(), pack);
}
}
static public void populateImportToLibraryTable() {
// Populate importToLibraryTable
importToLibraryTable = new HashMap<String, UserLibrary>();
for (UserLibrary lib : librariesIndexer.getInstalledLibraries()) {
try {
String headers[] = headerListFromIncludePath(lib.getSrcFolder());
for (String header : headers) {
UserLibrary old = importToLibraryTable.get(header);
if (old != null) {
// This is the case where 2 libraries have a .h header
// with the same name. We must decide which library to
// use when a sketch has #include "name.h"
// When all other factors are equal, "libName" is
// used in preference to "oldName", because getLibraries()
// gives the library list in order from less specific to
// more specific locations.
// But often one library is more clearly the user's
// intention to use. Many cases are tested, always first
// for "libName", then for "oldName".
String name = header.substring(0, header.length() - 2); // name without ".h"
String oldName = old.getInstalledFolder().getName(); // just the library folder name
String libName = lib.getInstalledFolder().getName(); // just the library folder name
//System.out.println("name conflict: " + name);
//System.out.println(" old = " + oldName + " -> " + old.getFolder().getPath());
//System.out.println(" new = " + libName + " -> " + lib.getFolder().getPath());
String name_lc = name.toLowerCase();
String oldName_lc = oldName.toLowerCase();
String libName_lc = libName.toLowerCase();
// always favor a perfect name match
if (libName.equals(name)) {
} else if (oldName.equals(name)) {
continue;
// check for "-master" appended (zip file from github)
} else if (libName.equals(name+"-master")) {
} else if (oldName.equals(name+"-master")) {
continue;
// next, favor a match with other stuff appended
} else if (libName.startsWith(name)) {
} else if (oldName.startsWith(name)) {
continue;
// otherwise, favor a match with stuff prepended
} else if (libName.endsWith(name)) {
} else if (oldName.endsWith(name)) {
continue;
// as a last resort, match if stuff prepended and appended
} else if (libName.contains(name)) {
} else if (oldName.contains(name)) {
continue;
// repeat all the above tests, with case insensitive matching
} else if (libName_lc.equals(name_lc)) {
} else if (oldName_lc.equals(name_lc)) {
continue;
} else if (libName_lc.equals(name_lc+"-master")) {
} else if (oldName_lc.equals(name_lc+"-master")) {
continue;
} else if (libName_lc.startsWith(name_lc)) {
} else if (oldName_lc.startsWith(name_lc)) {
continue;
} else if (libName_lc.endsWith(name_lc)) {
} else if (oldName_lc.endsWith(name_lc)) {
continue;
} else if (libName_lc.contains(name_lc)) {
} else if (oldName_lc.contains(name_lc)) {
continue;
} else {
// none of these tests matched, so just default to "libName".
}
}
importToLibraryTable.put(header, lib);
}
} catch (IOException e) {
showWarning(_("Error"), I18n
.format("Unable to list header files in {0}", lib.getSrcFolder()), e);
}
}
}
static public void initParameters(String args[]) {
String preferencesFile = null;
// Do a first pass over the commandline arguments, the rest of them
// will be processed by the Base constructor. Note that this loop
// does not look at the last element of args, to prevent crashing
// when no parameter was specified to an option. Later, Base() will
// then show an error for these.
for (int i = 0; i < args.length - 1; i++) {
if (args[i].equals("--preferences-file")) {
++i;
preferencesFile = args[i];
continue;
}
if (args[i].equals("--curdir")) {
i++;
currentDirectory = args[i];
continue;
}
}
// run static initialization that grabs all the prefs
PreferencesData.init(absoluteFile(preferencesFile));
}
/**
* Recursively remove all files within a directory,
* used with removeDir(), or when the contents of a dir
* should be removed, but not the directory itself.
* (i.e. when cleaning temp files from lib/build)
*/
static public void removeDescendants(File dir) {
if (!dir.exists()) return;
String files[] = dir.list();
for (int i = 0; i < files.length; i++) {
if (files[i].equals(".") || files[i].equals("..")) continue;
File dead = new File(dir, files[i]);
if (!dead.isDirectory()) {
if (!PreferencesData.getBoolean("compiler.save_build_files")) {
if (!dead.delete()) {
// temporarily disabled
System.err.println(I18n.format(_("Could not delete {0}"), dead));
}
}
} else {
removeDir(dead);
//dead.delete();
}
}
}
/**
* Remove all files in a directory and the directory itself.
*/
static public void removeDir(File dir) {
if (dir.exists()) {
removeDescendants(dir);
if (!dir.delete()) {
System.err.println(I18n.format(_("Could not delete {0}"), dir));
}
}
}
/**
* Produce a sanitized name that fits our standards for likely to work.
* <p/>
* Java classes have a wider range of names that are technically allowed
* (supposedly any Unicode name) than what we support. The reason for
* going more narrow is to avoid situations with text encodings and
* converting during the process of moving files between operating
* systems, i.e. uploading from a Windows machine to a Linux server,
* or reading a FAT32 partition in OS X and using a thumb drive.
* <p/>
* This helper function replaces everything but A-Z, a-z, and 0-9 with
* underscores. Also disallows starting the sketch name with a digit.
*/
static public String sanitizeName(String origName) {
char c[] = origName.toCharArray();
StringBuffer buffer = new StringBuffer();
// can't lead with a digit, so start with an underscore
if ((c[0] >= '0') && (c[0] <= '9')) {
buffer.append('_');
}
for (int i = 0; i < c.length; i++) {
if (((c[i] >= '0') && (c[i] <= '9')) ||
((c[i] >= 'a') && (c[i] <= 'z')) ||
((c[i] >= 'A') && (c[i] <= 'Z')) ||
((i > 0) && (c[i] == '-')) ||
((i > 0) && (c[i] == '.'))) {
buffer.append(c[i]);
} else {
buffer.append('_');
}
}
// let's not be ridiculous about the length of filenames.
// in fact, Mac OS 9 can handle 255 chars, though it can't really
// deal with filenames longer than 31 chars in the Finder.
// but limiting to that for sketches would mean setting the
// upper-bound on the character limit here to 25 characters
// (to handle the base name + ".class")
if (buffer.length() > 63) {
buffer.setLength(63);
}
return buffer.toString();
}
/**
* Spew the contents of a String object out to a file.
*/
static public void saveFile(String str, File file) throws IOException {
File temp = File.createTempFile(file.getName(), null, file.getParentFile());
PApplet.saveStrings(temp, new String[] { str });
if (file.exists()) {
boolean result = file.delete();
if (!result) {
throw new IOException(
I18n.format(
_("Could not remove old version of {0}"),
file.getAbsolutePath()));
}
}
boolean result = temp.renameTo(file);
if (!result) {
throw new IOException(
I18n.format(
_("Could not replace {0}"),
file.getAbsolutePath()));
}
}
static public void selectBoard(TargetBoard targetBoard) {
TargetPlatform targetPlatform = targetBoard.getContainerPlatform();
TargetPackage targetPackage = targetPlatform.getContainerPackage();
PreferencesData.set("target_package", targetPackage.getId());
PreferencesData.set("target_platform", targetPlatform.getId());
PreferencesData.set("board", targetBoard.getId());
File platformFolder = targetPlatform.getFolder();
PreferencesData.set("runtime.platform.path", platformFolder.getAbsolutePath());
PreferencesData.set("runtime.hardware.path", platformFolder.getParentFile().getAbsolutePath());
}
public static void selectSerialPort(String port) {
PreferencesData.set("serial.port", port);
if (port.startsWith("/dev/"))
PreferencesData.set("serial.port.file", port.substring(5));
else
PreferencesData.set("serial.port.file", port);
}
public static void setBuildFolder(File newBuildFolder) {
buildFolder = newBuildFolder;
}
static public void showError(String title, String message, int exit_code) {
showError(title, message, null, exit_code);
}
static public void showError(String title, String message, Throwable e) {
notifier.showError(title, message, e, 1);
}
/**
* Show an error message that's actually fatal to the program.
* This is an error that can't be recovered. Use showWarning()
* for errors that allow P5 to continue running.
*/
static public void showError(String title, String message, Throwable e, int exit_code) {
notifier.showError(title, message, e, exit_code);
}
/**
* "No cookie for you" type messages. Nothing fatal or all that
* much of a bummer, but something to notify the user about.
*/
static public void showMessage(String title, String message) {
notifier.showMessage(title, message);
}
/**
* Non-fatal error message with optional stack trace side dish.
*/
static public void showWarning(String title, String message, Exception e) {
notifier.showWarning(title, message, e);
}
}
|
// $Id: ThreadPoolFiller.java,v 1.2 2003/03/28 08:00:29 dustin Exp $
package net.spy.pool;
import java.util.Map;
import java.util.HashMap;
import java.lang.ref.WeakReference;
import net.spy.SpyConfig;
/**
* Filler for filling thread pools.
*/
public class ThreadPoolFiller extends PoolFiller {
private int id=0;
private static Map groups=null;
/**
* Get an instance of ThreadPoolFiller.
*/
public ThreadPoolFiller(String name, SpyConfig conf) {
super(name, conf);
}
private synchronized ThreadGroup getThreadGroup() {
if(groups==null) {
groups=new HashMap();
}
// Get the reference
WeakReference wr=(WeakReference)groups.get(getName());
ThreadGroup rv=null;
// If the reference worked, try to get the object from the reference
if(wr!=null) {
rv=(ThreadGroup)wr.get();
}
// If we didn't get an object, make one.
if(rv==null) {
rv=new ThreadGroup("ThreadPool - " + getName());
groups.put(getName(), new WeakReference(rv));
}
return(rv);
}
/**
* Get a new thread poolable.
*/
public PoolAble getObject() throws PoolException {
ThreadPoolable rv=null;
// get the thread itself
WorkerThread o=new WorkerThread(getThreadGroup(), "Worker
// Get the poolable
rv=new ThreadPoolable(o,
(long)getPropertyInt("max_age", 0), getPoolHash());
// Return it
return(rv);
}
}
|
package org.epics.vtype;
import java.util.List;
import org.epics.util.array.CollectionNumbers;
import org.epics.util.array.ListInt;
import org.epics.util.array.ListNumber;
/**
* Multi dimensional array, which can be used for waveforms or more rich data.
* <p>
* The data is stored in a linear structure. The sizes array gives the dimensionality
* and size for each dimension.
*
* @author carcassi
*/
public interface Array {
/**
* Return the object containing the array data.
* <p>
* This method will either return a {@link List} or a {@link ListNumber}
* depending of the array type. A collection is returned, instead of an
* array, so that the type implementation can be immutable or can at
* least try to prevent modifications. ListNumber has also several
* advantages over the Java arrays, including the ability to iterate the list
* regardless of numeric type.
* <p>
* If a numeric array is actually needed, refer to {@link CollectionNumbers}.
*
* @return the array data
*/
Object getData();
/**
* The shape of the multidimensional array.
* <p>
* The size of the returned list will be the number of the dimension of the array.
* Each number represents the size of each dimension. The total number
* of elements in the array is therefore the product of all the
* numbers in the list returned. *
*
* @return the dimension sizes
*/
ListInt getSizes();
}
|
package etomica.modules.dcvgcmd;
import etomica.AtomType;
import etomica.Default;
import etomica.Phase;
import etomica.Simulation;
import etomica.Space;
import etomica.Species;
import etomica.SpeciesSpheresMono;
import etomica.action.activity.ActivityIntegrate;
import etomica.atom.AtomFactoryHomo;
import etomica.data.AccumulatorAverage;
import etomica.data.DataPump;
import etomica.data.DataSourceGroup;
import etomica.data.meter.MeterNMolecules;
import etomica.data.meter.MeterProfile;
import etomica.integrator.IntegratorMC;
import etomica.integrator.IntegratorVelocityVerlet;
import etomica.integrator.IntervalActionAdapter;
import etomica.lattice.LatticeCubicFcc;
import etomica.nbr.CriterionSimple;
import etomica.nbr.CriterionSpecies;
import etomica.nbr.NeighborCriterion;
import etomica.nbr.PotentialCalculationAgents;
import etomica.nbr.PotentialMasterHybrid;
import etomica.nbr.cell.PotentialMasterCell;
import etomica.nbr.list.NeighborListManager;
import etomica.potential.P2WCA;
import etomica.space.BoundaryRectangularSlit;
import etomica.space.Vector;
import etomica.space3d.Space3D;
import etomica.space3d.Vector3D;
import etomica.units.Kelvin;
/**
*
* Dual-control-volume grand-canonical molecular dynamics simulation.
*
*/
public class DCVGCMD extends Simulation {
public IntegratorDCVGCMD integratorDCV;
public P2WCA potential;
public P2WCA potential1;
public P1WCAWall potentialwall;
public P1WCAWall potentialwall1;
public P1WCAPorousWall potentialwallPorousA, potentialwallPorousA1;
public P1WCAPorousWall potentialwallPorousB, potentialwallPorousB1;
public SpeciesSpheresMono species;
public SpeciesSpheresMono species1;
public SpeciesTube speciesTube;
public Phase phase;
public DataSourceGroup fluxMeters;
public MeterFlux meterFlux0, meterFlux1, meterFlux2, meterFlux3;
public MeterTemperature thermometer;
public MeterNMolecules density1;
public MeterNMolecules density2;
public MeterProfile profile1;
public MeterProfile profile2;
public AccumulatorAverage accumulator1;
public AccumulatorAverage accumulator2;
public AccumulatorAverage fluxAccumulator;
public Vector poreCenter;
public ActivityIntegrate activityIntegrate;
//Constructor
public DCVGCMD() {
this(Space3D.getInstance());
}
private DCVGCMD(Space space) {
//Instantiate classes
super(space, true, new PotentialMasterHybrid(space));
Default.ATOM_MASS = 40.;
Default.ATOM_SIZE = 3.0;
Default.POTENTIAL_WELL = 119.8;
//Default.makeLJDefaults();
//Default.BOX_SIZE = 14.0;
species = new SpeciesSpheresMono(this);
species1 = new SpeciesSpheresMono(this);
speciesTube = new SpeciesTube(this, 20, 40);
AtomType tubetype = ((AtomFactoryHomo) speciesTube.moleculeFactory())
.childFactory().getType();
AtomType speciestype = species.moleculeFactory().getType();
AtomType speciestype1 = species1.moleculeFactory().getType();
PotentialMasterHybrid potentialMasterHybrid = (PotentialMasterHybrid) potentialMaster;
double neighborRangeFac = 1.4;
final NeighborListManager nbrManager = potentialMasterHybrid.getNeighborManager();
nbrManager.getPbcEnforcer().setApplyToMolecules(false);
int nCells = (int) (40 / (neighborRangeFac * Default.ATOM_SIZE));
potentialMasterHybrid.setNCells(nCells);
//0-0 intraspecies interaction
potential = new P2WCA(space);
NeighborCriterion nbrCriterion = new CriterionSimple(space,potential.getRange(),neighborRangeFac*potential.getRange());
CriterionSpecies criterion = new CriterionSpecies(nbrCriterion, species, species);
potential.setCriterion(criterion);
nbrManager.addCriterion(nbrCriterion,new AtomType[]{species.getFactory().getType()});
potentialMaster.setSpecies(potential, new Species[] {species, species});
//1-1 intraspecies interaction
P2WCA potential11 = new P2WCA(space);
nbrCriterion = new CriterionSimple(space,potential.getRange(),neighborRangeFac*potential11.getRange());
criterion = new CriterionSpecies(nbrCriterion, species1, species1);
potential11.setCriterion(criterion);
nbrManager.addCriterion(nbrCriterion,new AtomType[]{species1.getFactory().getType()});
potentialMaster.setSpecies(potential11, new Species[] {species1, species1});
//0-1 interspecies interaction
potential1 = new P2WCA(space);
nbrCriterion = new CriterionSimple(space,potential.getRange(),neighborRangeFac*potential1.getRange());
criterion = new CriterionSpecies(nbrCriterion, species1, species);
potential1.setCriterion(criterion);
nbrManager.addCriterion(nbrCriterion, new AtomType[]{species.getFactory().getType(),species1.getFactory().getType()});
potentialMaster.setSpecies(potential1, new Species[] { species1, species });
P2WCA potentialTubeAtom = new P2WCA(space);
potentialMaster.addPotential(potentialTubeAtom,new AtomType[] { tubetype, speciestype});
nbrCriterion = new CriterionSimple(space,potentialTubeAtom.getRange(),neighborRangeFac*potentialTubeAtom.getRange());
criterion = new CriterionSpecies(nbrCriterion, speciesTube, species);
potentialTubeAtom.setCriterion(criterion);
nbrManager.addCriterion(nbrCriterion,new AtomType[]{species.getFactory().getType(),((AtomFactoryHomo)speciesTube.getFactory()).childFactory().getType()});
P2WCA potentialTubeAtom1 = new P2WCA(space);
potentialMaster.addPotential(potentialTubeAtom1,new AtomType[] { tubetype, speciestype1});
nbrCriterion = new CriterionSimple(space,potentialTubeAtom1.getRange(),neighborRangeFac*potentialTubeAtom.getRange());
criterion = new CriterionSpecies(nbrCriterion, speciesTube, species1);
potentialTubeAtom1.setCriterion(criterion);
nbrManager.addCriterion(nbrCriterion,new AtomType[]{species1.getFactory().getType()});
potentialwall = new P1WCAWall(space);
potentialMaster.setSpecies(potentialwall, new Species[] { species });
potentialwall1 = new P1WCAWall(space);
potentialMaster.setSpecies(potentialwall1, new Species[] { species1 });
potentialwallPorousA = new P1WCAPorousWall(space);
potentialMaster.setSpecies(potentialwallPorousA, new Species[] { species });
potentialwallPorousA1 = new P1WCAPorousWall(space);
potentialMaster.setSpecies(potentialwallPorousA1, new Species[] { species1 });
potentialwallPorousB = new P1WCAPorousWall(space);
potentialMaster.setSpecies(potentialwallPorousB, new Species[] { species });
potentialwallPorousB1 = new P1WCAPorousWall(space);
potentialMaster.setSpecies(potentialwallPorousB1, new Species[] { species1 });
species.setNMolecules(20);
species1.setNMolecules(20);
phase = new Phase(this);
integratorDCV = new IntegratorDCVGCMD(potentialMaster, species,
species1);
Default.AUTO_REGISTER = false;
final IntegratorVelocityVerlet integrator = new IntegratorVelocityVerlet(
potentialMaster, space);
final IntegratorMC integratorMC = new IntegratorMC(potentialMaster);
Default.AUTO_REGISTER = true;
integratorDCV.addPhase(phase);
integratorDCV.addListener(nbrManager);
nbrManager.setRange(potential.getRange() * neighborRangeFac);
integratorMC.addMCMoveListener(potentialMasterHybrid.getNbrCellManager(phase).makeMCMoveListener());
potentialMasterHybrid.calculate(phase, new PotentialCalculationAgents(potentialMasterHybrid));
activityIntegrate = new ActivityIntegrate(
integratorDCV);
getController().addAction(activityIntegrate);
//make MC integrator next
integratorDCV.setIntegrators(integratorMC, integrator);
integratorDCV.setTemperature(Kelvin.UNIT.toSim(500.));
integrator.setIsothermal(false);
integrator.setMeterTemperature(new MeterTemperature(speciesTube));
//integrator.setSleepPeriod(1);
integrator.setTimeStep(0.01);
//integrator.setInterval(10);
activityIntegrate.setDoSleep(true);
phase.setBoundary(new BoundaryRectangularSlit(space, 2));
// phase.setBoundary(new BoundaryRectangularPeriodic(space));
phase.setDimensions(new Vector3D(40, 40, 80));
// Crystal crystal = new Crystal(new PrimitiveTetragonal(space, 20,
// 40),new BasisMonatomic(3));
double length = 0.25;
ConfigurationLatticeTube config = new ConfigurationLatticeTube(
new LatticeCubicFcc(), length, speciesTube);
config.initializeCoordinates(phase);
//position of hole in porous-wall potential
poreCenter = space.makeVector();
poreCenter.Ea1Tv1(0.5, phase.boundary().dimensions());
Vector[] poreCentersVector = new Vector[] { poreCenter };
potentialwallPorousA.setPoreCenters(poreCentersVector);
potentialwallPorousA1.setPoreCenters(poreCentersVector);
potentialwallPorousB.setPoreCenters(poreCentersVector);
potentialwallPorousB1.setPoreCenters(poreCentersVector);
//radius of hole in porous-wall potential
double poreRadius = 1.05 * ((ConformationTube) speciesTube.getFactory()
.getConformation()).tubeRadius;
potentialwallPorousA.setPoreRadius(poreRadius);
potentialwallPorousA1.setPoreRadius(poreRadius);
potentialwallPorousB.setPoreRadius(poreRadius);
potentialwallPorousB1.setPoreRadius(poreRadius);
//place porous-wall potentials; put just past the edges of the tube
double zA = (length + 0.05) * phase.boundary().dimensions().x(2);
double zB = (1.0 - length - 0.05) * phase.boundary().dimensions().x(2);
potentialwallPorousA.setZ(zA);
potentialwallPorousA1.setZ(zA);
potentialwallPorousB.setZ(zB);
potentialwallPorousB1.setZ(zB);
MyMCMove[] moves = integratorDCV.mcMoves();
meterFlux0 = new MeterFlux(moves[0], integratorDCV);
meterFlux1 = new MeterFlux(moves[1], integratorDCV);
meterFlux2 = new MeterFlux(moves[2], integratorDCV);
meterFlux3 = new MeterFlux(moves[3], integratorDCV);
meterFlux0.setPhase(phase);
meterFlux1.setPhase(phase);
meterFlux2.setPhase(phase);
meterFlux3.setPhase(phase);
fluxMeters = new DataSourceGroup(new MeterFlux[] { meterFlux0,
meterFlux1, meterFlux2, meterFlux3 });
// fluxAccumulator = new AccumulatorAverage();
// DataPump fluxPump = new DataPump(fluxMeters, fluxAccumulator);
// IntervalActionAdapter fluxInterval = new IntervalActionAdapter(
// fluxPump, integratorDCV);
thermometer = new MeterTemperature(speciesTube);
thermometer.setPhase(phase);
density1 = new MeterNMolecules();
density2 = new MeterNMolecules();
density1.setPhase(phase);
density2.setPhase(phase);
density1.setSpecies(species);
density2.setSpecies(species1);
profile1 = new MeterProfile(space);
profile2 = new MeterProfile(space);
profile1.setDataSource(density1);
profile1.setPhase(phase);
profile1.setProfileVector(new Vector3D(0.0, 0.0, 1.0));
profile2.setDataSource(density2);
profile2.setPhase(phase);
profile2.setProfileVector(new Vector3D(0.0, 0.0, 1.0));
accumulator1 = new AccumulatorAverage();
DataPump profile1pump = new DataPump(profile1, accumulator1);
new IntervalActionAdapter(profile1pump, integratorDCV);
accumulator2 = new AccumulatorAverage();
DataPump profile2pump = new DataPump(profile2, accumulator2);
new IntervalActionAdapter(profile2pump, integratorDCV);
//remove for nbrlist integrator.addIntervalListener(new PhaseImposePbc(phase));
} //End of constructor
} //End of DCVGCMD class
|
package com.leandog.gametel.driver.commands;
import java.lang.reflect.Method;
import com.jayway.android.robotium.solo.Solo;
import com.leandog.gametel.driver.TestRunInformation;
public class CommandRunner {
private Object theLastResult;
public void execute(final Command command) {
try {
final Method method = findMethodFor(command);
theLastResult = method.invoke(TestRunInformation.getSolo(), command.getArguments());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public Object theLastResult() {
return theLastResult;
}
private Method findMethodFor(final Command command) throws NoSuchMethodException {
return Solo.class.getMethod(command.getName(), argumentTypesFor(command));
}
private Class<? extends Object> typeFor(final Object argument) {
Class<? extends Object> argumentType = argument.getClass();
if( argumentType.equals(Integer.class) ) {
argumentType = int.class;
}
return argumentType;
}
private Class<?>[] argumentTypesFor(final Command command) {
Class<?>[] types = new Class<?>[command.getArguments().length];
int index = 0;
for(final Object argument : command.getArguments()) {
types[index++] = typeFor(argument);
}
return types;
}
}
|
package org.dspace.curate;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.net.URL;
import java.sql.SQLException;
import java.util.List;
import java.util.ArrayList;
import java.util.Properties;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.dspace.handle.HandleManager;
import org.dspace.app.util.DCInput;
import org.dspace.app.util.DCInputSet;
import org.dspace.app.util.DCInputsReader;
import org.dspace.app.util.DCInputsReaderException;
import org.dspace.content.DCValue;
import org.dspace.content.DSpaceObject;
import org.dspace.content.Item;
import org.dspace.content.Bundle;
import org.dspace.content.Bitstream;
import org.dspace.content.crosswalk.MetadataValidationException;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context;
import org.dspace.core.Constants;
import org.dspace.identifier.IdentifierService;
import org.dspace.identifier.IdentifierNotFoundException;
import org.dspace.identifier.IdentifierNotResolvableException;
import org.dspace.utils.DSpace;
import org.apache.log4j.Logger;
/**
* OdinsHamr helps users reconcile author metadata with metadata stored in ORCID.
*
* Input: a single DSpace item OR a collection
* Output: CSV file that maps author names in the DSpace item to author names in ORCID.
* @author Ryan Scherle
*/
@Suspendable
public class OdinsHamr extends AbstractCurationTask {
private static Logger log = Logger.getLogger(OdinsHamr.class);
private IdentifierService identifierService = null;
DocumentBuilderFactory dbf = null;
DocumentBuilder docb = null;
static long total = 0;
private Context context;
@Override
public void init(Curator curator, String taskId) throws IOException {
super.init(curator, taskId);
identifierService = new DSpace().getSingletonService(IdentifierService.class);
// init xml processing
try {
dbf = DocumentBuilderFactory.newInstance();
docb = dbf.newDocumentBuilder();
} catch (ParserConfigurationException e) {
throw new IOException("unable to initiate xml processor", e);
}
}
/**
* Perform the curation task upon passed DSO
*
* input: an item
* output: several lines of authors, can show all or only identified matches
*
* @param dso the DSpace object
* @throws IOException
*/
@Override
public int perform(DSpaceObject dso) throws IOException {
log.info("performing ODIN's Hamr task " + total++ );
String handle = "\"[no handle found]\"";
String itemDOI = "\"[no item DOI found]\"";
String articleDOI = "\"[no article DOI found]\"";
try {
context = new Context();
} catch (SQLException e) {
log.fatal("Unable to open database connection", e);
return Curator.CURATE_FAIL;
}
if (dso.getType() == Constants.COLLECTION) {
report("itemDOI, articleDOI, orcidID, orcidName, dspaceORCID, dspaceName");
} else if (dso.getType() == Constants.ITEM) {
Item item = (Item)dso;
try {
handle = item.getHandle();
log.info("handle = " + handle);
if (handle == null) {
// this item is still in workflow - no handle assigned
context.abort();
return Curator.CURATE_SKIP;
}
// item DOI
DCValue[] vals = item.getMetadata("dc.identifier");
if (vals.length == 0) {
setResult("Object has no dc.identifier available " + handle);
log.error("Skipping -- no dc.identifier available for " + handle);
context.abort();
return Curator.CURATE_SKIP;
} else {
for(int i = 0; i < vals.length; i++) {
if (vals[i].value.startsWith("doi:")) {
itemDOI = vals[i].value;
}
}
}
log.debug("itemDOI = " + itemDOI);
// article DOI
vals = item.getMetadata("dc.relation.isreferencedby");
if (vals.length == 0) {
log.debug("Object has no articleDOI (dc.relation.isreferencedby) " + handle);
} else {
articleDOI = vals[0].value;
}
log.debug("articleDOI = " + articleDOI);
// DSpace names
List<String> dspaceNames = new ArrayList<String>();
vals = item.getMetadata("dc.contributor.author");
if (vals.length == 0) {
log.error("Object has no dc.contributor.author available in DSpace" + handle);
} else {
for(int i = 0; i < vals.length; i++) {
dspaceNames.add(vals[i].value);
}
}
log.debug("DSpace names found = " + dspaceNames.size());
// ORCID names
//TODO: lookup names in ORCID
//TODO: reconcile names between DSpace and ORCID
//TODO: add processing for article DOIs, not just item DOIs
String orcidID = "[no ORCID found]";
String orcidName = "none";
String dspaceORCID = "[no ORCID in DSpace]";
for(String dspaceName:dspaceNames) {
report(itemDOI + ", " + articleDOI + ", " + orcidID + ", \"" + orcidName + "\", " +
dspaceORCID + ", \"" + dspaceName + "\"");
setResult("Last processed item = " + handle + " -- " + itemDOI);
}
log.info(handle + " done.");
} catch (Exception e) {
log.fatal("Skipping -- Exception in processing " + handle, e);
setResult("Object has a fatal error: " + handle + "\n" + e.getMessage());
report("Object has a fatal error: " + handle + "\n" + e.getMessage());
context.abort();
return Curator.CURATE_SKIP;
}
} else {
log.info("Skipping -- non-item DSpace object");
setResult("Object skipped (not an item)");
context.abort();
return Curator.CURATE_SKIP;
}
try {
context.complete();
} catch (SQLException e) {
log.fatal("Unable to close database connection", e);
}
log.info("ODIN's Hamr complete");
return Curator.CURATE_SUCCESS;
}
/**
An XML utility method that returns the text content of a node.
**/
private String getNodeText(Node aNode) {
return aNode.getChildNodes().item(0).getNodeValue();
}
private Item getDSpaceItem(String itemID) {
Item dspaceItem = null;
try {
dspaceItem = (Item)identifierService.resolve(context, itemID);
} catch (IdentifierNotFoundException e) {
log.fatal("Unable to get DSpace Item for " + itemID, e);
} catch (IdentifierNotResolvableException e) {
log.fatal("Unable to get DSpace Item for " + itemID, e);
}
return dspaceItem;
}
}
|
package org.duracloud.duradmin.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.MessageFormat;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.lang.StringUtils;
import org.duracloud.client.ContentStore;
import org.duracloud.common.constant.Constants;
import org.duracloud.common.model.AclType;
import org.duracloud.common.util.TagUtil;
import org.duracloud.common.web.EncodeUtil;
import org.duracloud.domain.Content;
import org.duracloud.duradmin.domain.Acl;
import org.duracloud.duradmin.domain.ContentItem;
import org.duracloud.duradmin.domain.ContentProperties;
import org.duracloud.duradmin.domain.Space;
import org.duracloud.duradmin.domain.SpaceProperties;
import org.duracloud.duradmin.security.RootAuthentication;
import org.duracloud.error.ContentStateException;
import org.duracloud.error.ContentStoreException;
import org.duracloud.error.NotFoundException;
import org.duracloud.security.impl.DuracloudUserDetails;
import org.duracloud.storage.domain.StorageProviderType;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
/**
* Provides utility methods for spaces.
*
* @author Bill Branan
*/
public class SpaceUtil {
public static Space populateSpace(Space space,
org.duracloud.domain.Space cloudSpace,
ContentStore contentStore,
Authentication authentication) throws ContentStoreException {
space.setSpaceId(cloudSpace.getId());
space.setProperties(getSpaceProperties(cloudSpace.getProperties()));
space.setStreamingEnabled(StringUtils.isNotBlank(space.getProperties().getStreamingHost()));
space.setExtendedProperties(cloudSpace.getProperties());
space.setContents(cloudSpace.getContentIds());
Map<String,AclType> spaceAcls = contentStore.getSpaceACLs(cloudSpace.getId());
space.setAcls(toAclList(spaceAcls));
if (isAdmin(authentication)
&& isChronopolis(contentStore)
&& isSnapshotInProgress(contentStore, space.getSpaceId())) {
space.setSnapshotInProgress(true);
}
AclType callerAcl = resolveCallerAcl(space.getSpaceId(),
contentStore,
spaceAcls,
authentication,
space.isSnapshotInProgress());
String aclName = null;
if (null != callerAcl) {
aclName = callerAcl.name();
}
space.setCallerAcl(aclName);
return space;
}
private static SpaceProperties getSpaceProperties(Map<String, String> spaceProps) {
SpaceProperties spaceProperties = new SpaceProperties();
spaceProperties.setCreated(spaceProps.remove(ContentStore.SPACE_CREATED));
spaceProperties.setCount(spaceProps.remove(ContentStore.SPACE_COUNT));
spaceProperties.setSize(spaceProps.remove(ContentStore.SPACE_SIZE));
spaceProperties.setTags(TagUtil.parseTags(spaceProps.remove(TagUtil.TAGS)));
spaceProperties.setStreamingHost(spaceProps.get(ContentStore.STREAMING_HOST));
return spaceProperties;
}
public static void populateContentItem(String duradminBaseURL,
ContentItem contentItem,
String spaceId,
String contentId,
ContentStore store,
Authentication authentication)
throws ContentStoreException {
contentItem.setSpaceId(spaceId);
contentItem.setContentId(contentId);
contentItem.setStoreId(store.getStoreId());
Map<String, String> contentProperties =
store.getContentProperties(spaceId, contentId);
ContentProperties properties = populateContentProperties(contentProperties);
contentItem.setProperties(properties);
contentItem.setExtendedProperties(contentProperties);
contentItem.setDurastoreURL(formatDurastoreURL(contentItem, store));
Map<String,AclType> acls = store.getSpaceACLs(spaceId);
contentItem.setAcls(toAclList(acls));
AclType callerAcl = resolveCallerAcl(spaceId, store, acls, authentication);
String aclName = null;
if (null != callerAcl) {
aclName = callerAcl.name();
}
contentItem.setCallerAcl(aclName);
contentItem.setImageViewerBaseURL(null);
}
private static String formatDurastoreURL(ContentItem contentItem,ContentStore store) {
String pattern = "{0}/{1}/{2}?storeID={3}";
return MessageFormat.format(pattern,
// NOTE: The https --> http swap is required by the Djatoka
// SimpleListResolver, see: http://sourceforge.net/apps/mediawiki/djatoka/index.php?title=Installation#Configure_a_Referent_Resolver
// https is not supported.
store.getBaseURL().replace("https", "http"),
contentItem.getSpaceId(),
EncodeUtil.urlEncode(contentItem.getContentId()),
store.getStoreId());
}
private static ContentProperties populateContentProperties(Map<String, String> contentProperties) {
ContentProperties properties = new ContentProperties();
properties
.setMimetype(contentProperties.remove(ContentStore.CONTENT_MIMETYPE));
properties.setSize(contentProperties.remove(ContentStore.CONTENT_SIZE));
properties
.setChecksum(contentProperties.remove(ContentStore.CONTENT_CHECKSUM));
properties
.setModified(contentProperties.remove(ContentStore.CONTENT_MODIFIED));
properties.setTags(TagUtil.parseTags(contentProperties.remove(TagUtil.TAGS)));
return properties;
}
public static void streamContent(ContentStore store, HttpServletResponse response, String spaceId, String contentId)
throws ContentStoreException, IOException {
OutputStream outStream = response.getOutputStream();
try{
Content c = store.getContent(spaceId, contentId);
Map<String,String> m = store.getContentProperties(spaceId, contentId);
response.setContentType(m.get(ContentStore.CONTENT_MIMETYPE));
String contentLength = m.get(ContentStore.CONTENT_SIZE);
if(contentLength != null){
response.setContentLength(Integer.parseInt(contentLength));
}
InputStream is = c.getStream();
byte[] buf = new byte[1024];
int read = -1;
while((read = is.read(buf)) > 0){
outStream.write(buf, 0, read);
}
response.flushBuffer();
outStream.close();
}catch (Exception ex) {
if(ex.getCause() instanceof ContentStateException){
response.reset();
response.setStatus(HttpStatus.SC_CONFLICT);
String message =
"The requested content item is currently in long-term storage" +
" with limited retrieval capability. Please contact " +
"DuraCloud support (https://wiki.duraspace.org/x/6gPNAQ) " +
"for assistance in retrieving this content item.";
//It is necessary to pad the message in order to force Internet Explorer to
//display the server sent text rather than display the browser default error message.
//If the message is less than 512 bytes, the browser will ignore the message.
message += StringUtils.repeat(" ", 512);
outStream.write(message.getBytes());
outStream.close();
} else {
throw ex;
}
}
}
public static AclType resolveCallerAcl(String spaceId,ContentStore store, Map<String,AclType> acls,
Authentication authentication)
throws ContentStoreException {
return resolveCallerAcl(spaceId, store, acls, authentication, null);
}
public static AclType resolveCallerAcl(String spaceId,ContentStore store, Map<String,AclType> acls,
Authentication authentication, Boolean snapshotInProgress)
throws ContentStoreException {
//if a snapshot is in progress, read only
// check authorities
if(isRoot(authentication)){
return AclType.WRITE;
}
if(snapshotInProgress == null){
snapshotInProgress = false;
if(isChronopolis(store)){
snapshotInProgress = isSnapshotInProgress(store,spaceId);
}
}
if(snapshotInProgress){
return AclType.READ;
}
// check authorities
if(isAdmin(authentication)){
return AclType.WRITE;
}
AclType callerAcl = null;
DuracloudUserDetails details =
(DuracloudUserDetails) authentication.getPrincipal();
List<String> userGroups = details.getGroups();
for (Map.Entry<String, AclType> e : acls.entrySet()) {
AclType value = e.getValue();
if (e.getKey().equals(details.getUsername())
|| userGroups.contains(e.getKey())) {
callerAcl = value;
if(AclType.WRITE.equals(callerAcl)){
break;
}
}
}
return callerAcl;
}
private static boolean isSnapshotInProgress(ContentStore store,
String spaceId) throws ContentStoreException {
try{
store.getContentProperties(spaceId, Constants.SNAPSHOT_ID);
return true;
}catch(NotFoundException ex){
return false;
} //do nothing - no snapshot in progress
}
protected static boolean isChronopolis(ContentStore store) {
return store.getStorageProviderType().equals(StorageProviderType.CHRON_STAGE.name());
}
public static boolean isAdmin(Authentication authentication) {
return hasRole(authentication, "ROLE_ADMIN");
}
private static boolean isRoot(Authentication authentication) {
return hasRole(authentication, "ROLE_ROOT");
}
protected static boolean hasRole(Authentication authentication, String role) {
Collection authorities = authentication.getAuthorities();
for (Object a : authorities) {
if (((GrantedAuthority)a).getAuthority().equals(role)) {
return true;
}
}
return false;
}
public static List<Acl> toAclList(Map<String, AclType> spaceACLs) {
List<Acl> acls = new LinkedList<Acl>();
if (spaceACLs != null) {
for (Map.Entry<String, AclType> entry : spaceACLs.entrySet()) {
String key = entry.getKey();
AclType value = entry.getValue();
boolean read = false, write = false;
if (value.equals(AclType.READ)) {
read = true;
} else if (value.equals(AclType.WRITE)) {
read = true;
write = true;
}
acls.add(new Acl(key, formatAclDisplayName(key), read, write));
}
}
sortAcls(acls);
return acls;
}
private static final Comparator<Acl> ACL_COMPARATOR = new Comparator<Acl>() {
private String groupPrefix = "group-";
@Override
public int compare(Acl o1, Acl o2) {
if(o1.name.equals(o2.name)){
return 0;
}
if(o1.isPublicGroup()){
return -1;
}
if(o2.isPublicGroup()){
return 1;
}
if(o1.name.startsWith(groupPrefix)){
return !o2.name.startsWith(groupPrefix) ? -1 : o1.name.compareToIgnoreCase(o2.name);
}else{
return o2.name.startsWith(groupPrefix) ? 1 : o1.name.compareToIgnoreCase(o2.name);
}
}
};
public static void sortAcls(List<Acl> acls) {
Collections.sort(acls, ACL_COMPARATOR);
}
public static String formatAclDisplayName(String key) {
String prefix = "group-";
if (key.startsWith(prefix)) {
return key.replaceFirst(prefix, "");
}
return key;
}
}
|
package org.neo4j.index.impl.lucene;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.TermQuery;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.PropertyContainer;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.index.Index;
import org.neo4j.graphdb.index.IndexHits;
import org.neo4j.helpers.collection.CombiningIterator;
import org.neo4j.helpers.collection.FilteringIterator;
import org.neo4j.helpers.collection.IteratorUtil;
import org.neo4j.index.impl.IdToEntityIterator;
import org.neo4j.index.impl.IndexHitsImpl;
import org.neo4j.index.impl.PrimitiveUtils;
import org.neo4j.kernel.impl.cache.LruCache;
import org.neo4j.kernel.impl.core.ReadOnlyDbException;
public abstract class LuceneIndex<T extends PropertyContainer> implements Index<T>
{
static final String KEY_DOC_ID = "_id_";
static final String KEY_START_NODE_ID = "_start_node_id_";
static final String KEY_END_NODE_ID = "_end_node_id_";
final LuceneIndexProvider service;
final IndexIdentifier identifier;
final IndexType type;
private volatile boolean deleted;
LuceneIndex( LuceneIndexProvider service, IndexIdentifier identifier )
{
this.service = service;
this.identifier = identifier;
this.type = service.dataSource().getType( identifier );
}
LuceneXaConnection getConnection()
{
assertNotDeleted();
if ( service.broker() == null )
{
throw new ReadOnlyDbException();
}
return service.broker().acquireResourceConnection();
}
private void assertNotDeleted()
{
if ( deleted )
{
throw new IllegalStateException( "This index (" + identifier + ") has been deleted" );
}
}
LuceneXaConnection getReadOnlyConnection()
{
assertNotDeleted();
return service.broker() == null ? null :
service.broker().acquireReadOnlyResourceConnection();
}
void markAsDeleted()
{
this.deleted = true;
}
/**
* See {@link Index#add(PropertyContainer, String, Object)} for more generic
* documentation.
*
* Adds key/value to the {@code entity} in this index. Added values are
* searchable withing the transaction, but composite {@code AND}
* queries aren't guaranteed to return added values correctly within that
* transaction. When the transaction has been committed all such queries
* are guaranteed to return correct results.
*
* @param entity the entity (i.e {@link Node} or {@link Relationship})
* to associate the key/value pair with.
* @param key the key in the key/value pair to associate with the entity.
* @param value the value in the key/value pair to associate with the
* entity.
*/
public void add( T entity, String key, Object value )
{
LuceneXaConnection connection = getConnection();
for ( Object oneValue : PrimitiveUtils.asArray( value ) )
{
connection.add( this, entity, key, oneValue );
}
}
/**
* See {@link Index#remove(PropertyContainer, String, Object)} for more
* generic documentation.
*
* Removes key/value to the {@code entity} in this index. Removed values
* are excluded withing the transaction, but composite {@code AND}
* queries aren't guaranteed to exclude removed values correctly within
* that transaction. When the transaction has been committed all such
* queries are guaranteed to return correct results.
*
* @param entity the entity (i.e {@link Node} or {@link Relationship})
* to dissociate the key/value pair from.
* @param key the key in the key/value pair to dissociate from the entity.
* @param value the value in the key/value pair to dissociate from the
* entity.
*/
public void remove( T entity, String key, Object value )
{
LuceneXaConnection connection = getConnection();
for ( Object oneValue : PrimitiveUtils.asArray( value ) )
{
connection.remove( this, entity, key, oneValue );
}
}
public void delete()
{
getConnection().deleteIndex( this );
}
public IndexHits<T> get( String key, Object value )
{
return query( type.get( key, value ), key, value, null );
}
public IndexHits<T> query( String key, Object queryOrQueryObject )
{
QueryContext context = queryOrQueryObject instanceof QueryContext ?
(QueryContext) queryOrQueryObject : null;
return query( type.query( key, context != null ?
context.queryOrQueryObject : queryOrQueryObject, context ), null, null, context );
}
/**
* {@inheritDoc}
*
* @see #query(String, Object)
*/
public IndexHits<T> query( Object queryOrQueryObject )
{
return query( null, queryOrQueryObject );
}
protected IndexHits<T> query( Query query, String keyForDirectLookup,
Object valueForDirectLookup, QueryContext additionalParametersOrNull )
{
List<Long> ids = new ArrayList<Long>();
LuceneXaConnection con = getReadOnlyConnection();
LuceneTransaction luceneTx = con != null ? con.getLuceneTx() : null;
Collection<Long> addedIds = Collections.emptySet();
Collection<Long> removedIds = Collections.emptySet();
Query excludeQuery = null;
boolean isRemoveAll = false;
if ( luceneTx != null )
{
addedIds = keyForDirectLookup != null ?
luceneTx.getAddedIds( this, keyForDirectLookup, valueForDirectLookup ) :
luceneTx.getAddedIds( this, query, additionalParametersOrNull );
ids.addAll( addedIds );
removedIds = keyForDirectLookup != null ?
luceneTx.getRemovedIds( this, keyForDirectLookup, valueForDirectLookup ) :
luceneTx.getRemovedIds( this, query );
excludeQuery = luceneTx.getExtraRemoveQuery( this );
isRemoveAll = luceneTx.isRemoveAll( this );
}
service.dataSource().getReadLock();
Iterator<Long> idIterator = null;
int idIteratorSize = -1;
IndexSearcherRef searcher = null;
boolean isLazy = false;
try
{
searcher = service.dataSource().getIndexSearcher( identifier );
if ( !isRemoveAll && searcher != null )
{
if ( excludeQuery != null )
{
removedIds = removedIds.isEmpty() ? new HashSet<Long>() : removedIds;
readNodesFromHits( new DocToIdIterator( search( searcher, excludeQuery, null ),
null, searcher ), removedIds );
}
boolean foundInCache = false;
LruCache<String, Collection<Long>> cachedIdsMap = null;
if ( keyForDirectLookup != null )
{
cachedIdsMap = service.dataSource().getFromCache(
identifier, keyForDirectLookup );
foundInCache = fillFromCache( cachedIdsMap, ids,
keyForDirectLookup, valueForDirectLookup.toString(), removedIds );
}
if ( !foundInCache )
{
DocToIdIterator searchedNodeIds = new DocToIdIterator( search( searcher,
query, additionalParametersOrNull ), removedIds, searcher );
if ( searchedNodeIds.size() >= service.lazynessThreshold )
{
// Instantiate a lazy iterator
isLazy = true;
// TODO Clear cache? why?
Collection<Iterator<Long>> iterators = new ArrayList<Iterator<Long>>();
iterators.add( ids.iterator() );
iterators.add( searchedNodeIds );
idIterator = new CombiningIterator<Long>( iterators );
idIteratorSize = ids.size() + searchedNodeIds.size();
}
else
{
// Loop through result here (and cache it if possible)
Collection<Long> readIds = readNodesFromHits( searchedNodeIds, ids );
if ( cachedIdsMap != null )
{
cachedIdsMap.put( valueForDirectLookup.toString(), readIds );
}
}
}
}
}
finally
{
// The DocToIdIterator closes the IndexSearchRef instance anyways,
// or the LazyIterator if it's a lazy one. So no need here.
service.dataSource().releaseReadLock();
}
if ( idIterator == null )
{
idIterator = ids.iterator();
idIteratorSize = ids.size();
}
idIterator = FilteringIterator.noDuplicates( idIterator );
IndexHits<T> hits = new IndexHitsImpl<T>(
IteratorUtil.asIterable( new IdToEntityIterator<T>( idIterator )
{
@Override
protected T underlyingObjectToObject( Long id )
{
return getById( id );
}
} ), idIteratorSize );
if ( isLazy )
{
hits = new LazyIndexHits<T>( hits, searcher );
}
return hits;
}
private boolean fillFromCache(
LruCache<String, Collection<Long>> cachedNodesMap,
List<Long> nodeIds, String key, String valueAsString,
Collection<Long> deletedNodes )
{
boolean found = false;
if ( cachedNodesMap != null )
{
Collection<Long> cachedNodes = cachedNodesMap.get( valueAsString );
if ( cachedNodes != null )
{
found = true;
for ( Long cachedNodeId : cachedNodes )
{
if ( deletedNodes == null ||
!deletedNodes.contains( cachedNodeId ) )
{
nodeIds.add( cachedNodeId );
}
}
}
}
return found;
}
private SearchResult search( IndexSearcherRef searcher, Query query,
QueryContext additionalParametersOrNull )
{
try
{
searcher.incRef();
Sort sorting = additionalParametersOrNull != null ?
additionalParametersOrNull.sorting : null;
Hits hits = new Hits( searcher.getSearcher(), query, null, sorting );
return new SearchResult( new HitsIterator( hits ), hits.length() );
}
catch ( IOException e )
{
throw new RuntimeException( "Unable to query " + this + " with "
+ query, e );
}
}
public void setCacheCapacity( String key, int capacity )
{
service.dataSource().setCacheCapacity( identifier, key, capacity );
}
public Integer getCacheCapacity( String key )
{
return service.dataSource().getCacheCapacity( identifier, key );
}
private Collection<Long> readNodesFromHits( DocToIdIterator searchedIds,
Collection<Long> ids )
{
ArrayList<Long> readIds = new ArrayList<Long>();
while ( searchedIds.hasNext() )
{
Long readId = searchedIds.next();
ids.add( readId );
readIds.add( readId );
}
return readIds;
}
protected abstract T getById( long id );
protected abstract long getEntityId( T entity );
protected abstract LuceneCommand newAddCommand( PropertyContainer entity,
String key, Object value );
protected abstract LuceneCommand newRemoveCommand( PropertyContainer entity,
String key, Object value );
static class NodeIndex extends LuceneIndex<Node>
{
NodeIndex( LuceneIndexProvider service,
IndexIdentifier identifier )
{
super( service, identifier );
}
@Override
protected Node getById( long id )
{
return service.graphDb().getNodeById( id );
}
@Override
protected long getEntityId( Node entity )
{
return entity.getId();
}
@Override
protected LuceneCommand newAddCommand( PropertyContainer entity, String key, Object value )
{
return new LuceneCommand.AddCommand( identifier, LuceneCommand.NODE,
((Node) entity).getId(), key, value );
}
@Override
protected LuceneCommand newRemoveCommand( PropertyContainer entity, String key, Object value )
{
return new LuceneCommand.RemoveCommand( identifier, LuceneCommand.NODE,
((Node) entity).getId(), key, value );
}
}
static class RelationshipIndex extends LuceneIndex<Relationship>
implements org.neo4j.graphdb.index.RelationshipIndex
{
RelationshipIndex( LuceneIndexProvider service,
IndexIdentifier identifier )
{
super( service, identifier );
}
@Override
protected Relationship getById( long id )
{
return service.graphDb().getRelationshipById( id );
}
@Override
protected long getEntityId( Relationship entity )
{
return entity.getId();
}
public IndexHits<Relationship> get( String key, Object valueOrNull, Node startNodeOrNull,
Node endNodeOrNull )
{
return query( (Query) null, (String) null, null, null );
}
public IndexHits<Relationship> query( String key, Object queryOrQueryObjectOrNull,
Node startNodeOrNull, Node endNodeOrNull )
{
QueryContext context = queryOrQueryObjectOrNull != null &&
queryOrQueryObjectOrNull instanceof QueryContext ?
(QueryContext) queryOrQueryObjectOrNull : null;
BooleanQuery query = new BooleanQuery();
if ( (context != null && context.queryOrQueryObject != null) ||
(context == null && queryOrQueryObjectOrNull != null ) )
{
query.add( type.query( key, context != null ?
context.queryOrQueryObject : queryOrQueryObjectOrNull, context ), Occur.MUST );
}
addIfNotNull( query, startNodeOrNull, KEY_START_NODE_ID );
addIfNotNull( query, endNodeOrNull, KEY_END_NODE_ID );
return query( query, (String) null, null, context );
}
private static void addIfNotNull( BooleanQuery query, Node nodeOrNull, String field )
{
if ( nodeOrNull != null )
{
query.add( new TermQuery( new Term( field, "" + nodeOrNull.getId() ) ),
Occur.MUST );
}
}
public IndexHits<Relationship> query( Object queryOrQueryObjectOrNull,
Node startNodeOrNull, Node endNodeOrNull )
{
return query( null, queryOrQueryObjectOrNull, startNodeOrNull, endNodeOrNull );
}
@Override
protected LuceneCommand newAddCommand( PropertyContainer entity, String key, Object value )
{
Relationship rel = (Relationship) entity;
return new LuceneCommand.AddRelationshipCommand( identifier, LuceneCommand.RELATIONSHIP,
RelationshipId.of( rel ), key, value );
}
@Override
protected LuceneCommand newRemoveCommand( PropertyContainer entity, String key, Object value )
{
Relationship rel = (Relationship) entity;
return new LuceneCommand.RemoveCommand( identifier, LuceneCommand.RELATIONSHIP,
rel.getId(), key, value );
}
}
}
|
package io.bigio.examples.helloworld;
import io.bigio.Component;
import io.bigio.Initialize;
import io.bigio.Inject;
import io.bigio.Interceptor;
import io.bigio.MessageListener;
import io.bigio.Speaker;
import io.bigio.core.Envelope;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author atrimble
*/
@Component
public class Consumer {
private static final Logger LOG = LoggerFactory.getLogger(Consumer.class);
@Inject
private Speaker speaker;
@Initialize
public void init() {
speaker.addListener("HelloWorld", (HelloWorldMessage message) -> {
LOG.info("As a lambda expression: " + message.getMessage());
});
speaker.addListener("HelloWorld", new MessageListener<HelloWorldMessage>() {
@Override
public void receive(HelloWorldMessage message) {
LOG.info("As an anonymous inner class: " + message.getMessage());
}
});
speaker.addInterceptor("HelloWorld", (Envelope envelope) -> {
LOG.info("Interceptor as a lambda expression: " + envelope.getSenderKey() + " : " + envelope.getTopic());
return envelope;
});
speaker.addInterceptor("HelloWorld", new Interceptor() {
@Override
public Envelope intercept(Envelope envelope) {
LOG.info("Interceptor as an anonymous inner class: " + envelope.getSenderKey() + " : " + envelope.getTopic());
return envelope;
}
});
}
}
|
// TODO find a good way to change symbol flags (PRIVATE, DEFERRED,
// INTERFACE). In particular find how to make sure that the
// modifications are not made too early, for example before the symbol
// is cloned.
package scalac.transformer;
import scalac.*;
import ch.epfl.lamp.util.*;
import scalac.ast.*;
import scalac.symtab.*;
import scalac.util.*;
import Tree.*;
import java.util.*;
/**
* Add, for each class, an interface with the same name, to be used
* later by mixin expansion. More specifically:
*
* - at the end of the name of every class, the string "$class" is
* added,
*
* - an interface with the original name of the class is created, and
* contains all directly bound members of the class (as abstract
* members),
*
* - the interface is added to the mixin base classes of the class.
*
* @author Michel Schinz
* @version 1.0
*/
class AddInterfaces extends Transformer {
protected AddInterfacesPhase phase;
protected Definitions defs;
public AddInterfaces(Global global, AddInterfacesPhase phase) {
super(global);
this.phase = phase;
this.defs = global.definitions;
}
protected LinkedList/*<Pair<Symbol,Symbol>>*/ ownerSubstStack =
new LinkedList();
protected Pair/*<Symbol,Symbol>*/ ownerSubst = null;
protected SymbolSubstTypeMap typeSubst = null;
protected Type.SubstThisMap thisTypeSubst = null;
protected LinkedList/*<List<Tree>>*/ bodyStack = new LinkedList();
public Tree[] transform(Tree[] trees) {
List newTrees = new ArrayList();
bodyStack.addFirst(newTrees);
for (int i = 0; i < trees.length; ++i)
newTrees.add(transform(trees[i]));
bodyStack.removeFirst();
return (Tree[]) newTrees.toArray(new Tree[newTrees.size()]);
}
public Tree transform(Tree tree) {
// Update tree type, to take into account the new (type)
// symbols of enclosing classes / methods.
Type newTp = tree.type();
if (typeSubst != null) newTp = typeSubst.apply(newTp);
if (thisTypeSubst != null) newTp = thisTypeSubst.apply(newTp);
tree.setType(newTp);
if (tree.definesSymbol() && !(tree instanceof ClassDef)) {
// Update symbol's owner, if needed.
Symbol sym = tree.symbol();
if (ownerSubst != null && ownerSubst.fst == sym.owner())
sym.setOwner((Symbol)ownerSubst.snd);
// Update symbol's type. Do that only for symbols which do
// not belong to a class, since the type of these (i.e.
// class members) has been changed during cloning
// operation.
if (! (sym.owner().isClass() || thisTypeSubst == null))
sym.updateInfo(typeSubst.apply(sym.info()));
}
switch (tree) {
case ClassDef(_,_,_,_,_,_): {
Symbol sym = tree.symbol();
if (phase.needInterface(sym)) {
ClassDef classDef = (ClassDef)tree;
Symbol ifaceSym = sym;
Symbol classSym = phase.getClassSymbol(ifaceSym);
List/*<Tree>*/ enclosingBody = (List)bodyStack.getFirst();
enclosingBody.add(makeInterface(classDef));
typeSubst = phase.getClassSubst(classSym);
Tree newTree = makeClass(classDef);
typeSubst = null;
return newTree;
} else
return super.transform(tree);
}
case DefDef(int mods,
Name name,
AbsTypeDef[] tparams,
ValDef[][] vparams,
Tree tpe,
Tree rhs): {
Symbol sym = tree.symbol();
Tree newTree;
Symbol owner;
if (sym.isConstructor())
owner = sym.constructorClass();
else
owner = sym.owner();
if (owner.isClass() && phase.needInterface(owner)) {
Symbol classOwner = phase.getClassSymbol(owner);
Map ownerMemberMap = phase.getClassMemberMap(classOwner);
Symbol newSym = (Symbol)ownerMemberMap.get(sym);
assert newSym != null
: Debug.show(sym) + " not in " + ownerMemberMap;
global.nextPhase();
typeSubst.insertSymbol(sym.typeParams(), newSym.typeParams());
if (!sym.isConstructor())
typeSubst.insertSymbol(sym.valueParams(), newSym.valueParams());
global.prevPhase();
pushOwnerSubst(sym, newSym);
newTree = gen.DefDef(newSym, transform(rhs));
popOwnerSubst();
typeSubst.removeSymbol(sym.valueParams());
typeSubst.removeSymbol(sym.typeParams());
} else
newTree = super.transform(tree);
return newTree;
}
case This(_): {
// Use class symbol for references to "this".
Symbol classThisSym = phase.getClassSymbol(tree.symbol());
return gen.This(tree.pos, classThisSym);
}
case Super(_, _): {
// Use class symbol for references to "super".
Symbol classSuperSym = phase.getClassSymbol(tree.symbol());
return gen.Super(tree.pos, classSuperSym);
}
case Select(Super(_, _), _): {
// Use class member symbols for references to "super".
Symbol sym = tree.symbol();
Symbol classOwner = phase.getClassSymbol(sym.owner());
Map ownerMemberMap = phase.getClassMemberMap(classOwner);
if (ownerMemberMap != null && ownerMemberMap.containsKey(sym)) {
Tree qualifier = transform(((Select)tree).qualifier);
Symbol newSym = (Symbol)ownerMemberMap.get(sym);
return gen.Select(tree.pos, qualifier, newSym);
} else
return super.transform(tree);
}
case Select(Tree qualifier, _): {
Symbol sym = tree.symbol();
if (sym.isConstructor()) {
// If the constructor now refers to the interface
// constructor, use the class constructor instead.
Symbol clsSym = sym.constructorClass();
if (phase.needInterface(clsSym)) {
Symbol realClsSym = phase.getClassSymbol(clsSym);
Map memMap = phase.getClassMemberMap(realClsSym);
assert memMap != null
: Debug.show(clsSym) + " " + Debug.show(realClsSym);
return gen.Select(tree.pos, qualifier, (Symbol)memMap.get(sym));
} else
return super.transform(tree);
} else {
qualifier = transform(qualifier);
Symbol owner = sym.owner();
if (owner.isClass()
&& owner.isJava() && !owner.isInterface()
&& owner != defs.ANY_CLASS
&& owner != defs.ANYREF_CLASS
&& owner != defs.JAVA_OBJECT_CLASS) {
Type qualifierType = qualifier.type().bound();
if (phase.needInterface(qualifierType.symbol())) {
Type castType = qualifierType.baseType(owner);
qualifier = gen.mkAsInstanceOf(qualifier, castType);
}
}
return copy.Select(tree, sym, qualifier);
}
}
case Ident(_): {
Symbol sym = tree.symbol();
if (sym.isConstructor()) {
// If the constructor now refers to the interface
// constructor, use the class constructor instead.
Symbol clsSym = sym.constructorClass();
if (phase.needInterface(clsSym)) {
Symbol realClsSym = phase.getClassSymbol(clsSym);
Map memMap = phase.getClassMemberMap(realClsSym);
assert memMap != null
: Debug.show(clsSym) + " " + Debug.show(realClsSym);
assert memMap.containsKey(sym)
: Debug.show(sym) + " not in " + memMap;
return gen.Ident(tree.pos, (Symbol)memMap.get(sym));
} else
return super.transform(tree);
} else if (typeSubst != null) {
Symbol newSym = (Symbol)typeSubst.lookupSymbol(tree.symbol());
if (newSym != null)
return gen.Ident(tree.pos, newSym);
else
return super.transform(tree);
} else {
return super.transform(tree);
}
}
case New(Template templ): {
Tree.New newTree = (Tree.New)super.transform(tree);
Symbol ifaceSym = newTree.type.unalias().symbol();
if (phase.needInterface(ifaceSym)) {
Map clsMap = new HashMap();
Symbol classSym = phase.getClassSymbol(ifaceSym);
clsMap.put(ifaceSym, classSym);
clsMap.put(ifaceSym.primaryConstructor(), classSym.primaryConstructor());
SymbolSubstTypeMap clsSubst =
new SymbolSubstTypeMap(clsMap, Collections.EMPTY_MAP);
newTree.setType(clsSubst.apply(newTree.type));
newTree.templ.setType(clsSubst.apply(newTree.templ.type));
Tree.Apply parent = (Tree.Apply)newTree.templ.parents[0];
parent.setType(clsSubst.apply(parent.type));
parent.fun.setType(clsSubst.apply(parent.fun.type));
}
return newTree;
}
case Template(_,_): {
Symbol sym = tree.symbol();
if (sym != Symbol.NONE) {
Symbol newDummySymbol = sym.cloneSymbol();
pushOwnerSubst(sym, newDummySymbol);
Tree newTemplate = super.transform(tree);
popOwnerSubst();
return newTemplate;
} else
return super.transform(tree);
}
default:
return super.transform(tree);
}
}
protected Tree makeInterface(ClassDef classDef) {
Template classImpl = classDef.impl;
Tree[] classBody = classImpl.body;
TreeList ifaceBody = new TreeList();
for (int i = 0; i < classBody.length; ++i) {
Tree t = classBody[i];
Symbol tSym = t.symbol();
if (!t.definesSymbol() || !phase.memberGoesInInterface(tSym))
continue;
if (tSym.isClass())
ifaceBody.append(transform(new Tree[] { t }));
else if (tSym.isType())
ifaceBody.append(t);
else if (tSym.isMethod())
ifaceBody.append(gen.DefDef(tSym, Tree.Empty));
else
throw Debug.abort("don't know what to do with this ", t);
}
return gen.ClassDef(classDef.symbol(), ifaceBody.toArray());
}
protected Tree makeClass(ClassDef classDef) {
Symbol ifaceSym = classDef.symbol();
Symbol classSym = phase.getClassSymbol(ifaceSym);
TreeList newClassBody = new TreeList();
Template classImpl = classDef.impl;
Tree[] classBody = classImpl.body;
Map classMemberMap = phase.getClassMemberMap(classSym);
assert thisTypeSubst == null;
thisTypeSubst = new Type.SubstThisMap(ifaceSym, classSym);
for (int i = 0; i < classBody.length; ++i) {
Tree t = classBody[i];
Symbol tSym = t.symbol();
if (t.definesSymbol() && !(classMemberMap.containsKey(tSym)
|| tSym.isConstructor()))
continue;
Tree newT = transform(t);
if (t.definesSymbol() && classMemberMap.containsKey(tSym))
newT.setSymbol((Symbol)classMemberMap.get(tSym));
newClassBody.append(newT);
}
thisTypeSubst = null;
Tree[] newParents = Tree.cloneArray(transform(classImpl.parents), 1);
global.nextPhase();
Type ifaceType = classSym.parents()[newParents.length - 1];
global.prevPhase();
newParents[newParents.length - 1] =
gen.mkPrimaryConstr(classDef.pos, ifaceType);
Symbol local = classDef.impl.symbol();
local.setOwner(classSym);
return gen.ClassDef(classSym, newParents, local, newClassBody.toArray());
}
protected Tree[][] extractParentArgs(Tree[] parents) {
Tree[][] pArgs = new Tree[parents.length][];
for (int i = 0; i < parents.length; ++i) {
switch(parents[i]) {
case Apply(_, Tree[] args): pArgs[i] = transform(args); break;
default: throw Debug.abort("unexpected parent constr. ", parents[i]);
}
}
return pArgs;
}
protected void pushOwnerSubst(Symbol from, Symbol to) {
ownerSubstStack.addFirst(ownerSubst);
ownerSubst = new Pair(from, to);
}
protected void popOwnerSubst() {
ownerSubst = (Pair)ownerSubstStack.removeFirst();
}
}
|
package org.jasig.portal;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Locale;
import java.util.Map;
import org.jasig.portal.car.CarResources;
import org.jasig.portal.services.LogService;
import com.oreilly.servlet.multipart.Part;
/**
* A set of runtime data accessible by a channel.
*
* @author <a href="mailto:pkharchenko@interactivebusiness.com">Peter Kharchenko</a>
* @version $Revision$
*/
public class ChannelRuntimeData extends Hashtable implements Cloneable {
private BrowserInfo binfo=null;
private Locale[] locales = null;
private UPFileSpec channelUPFile;
private String baseActionURL = null;
private String httpRequestMethod=null;
private String keywords=null;
private boolean renderingAsRoot=false;
private boolean targeted = false;
private static final String TRADITIONAL_MEDIA_BASE = "media/";
/**
* Default empty constructor
*/
public ChannelRuntimeData() {
super();
channelUPFile = new UPFileSpec();
}
/**
* Create a new instance of ourself
* Used by the CError channel
* @return crd the cloned ChannelRuntimeData object
*/
public Object clone() {
ChannelRuntimeData crd = new ChannelRuntimeData();
crd.binfo = binfo;
crd.locales = locales;
crd.channelUPFile = channelUPFile;
crd.baseActionURL = baseActionURL;
crd.httpRequestMethod = httpRequestMethod;
crd.keywords = keywords;
crd.renderingAsRoot = renderingAsRoot;
crd.targeted = targeted;
crd.putAll(this);
return crd;
}
/**
* Set a UPFileSpec which will be used to produce
* baseActionURL and workerActionURL.
* @param upfs the UPFileSpec
*/
public void setUPFile(UPFileSpec upfs) {
channelUPFile = upfs;
}
/**
* Get the UPFileSpec
* @return channelUPFile the UPFileSpec
*/
public UPFileSpec getUPFile() {
return this.channelUPFile;
}
/**
* Set the HTTP Reqeust method.
*
* @param method a <code>String</code> value
*/
public void setHttpRequestMethod(String method) {
this.httpRequestMethod=method;
}
/**
* Get HTTP request method (i.e. GET, POST)
*
* @return a <code>String</code> value
*/
public String getHttpRequestMethod() {
return this.httpRequestMethod;
}
/**
* Sets the base action URL. This was added back in for the benefit
* of web services. Not sure if it is going to stay this way.
* @param baseActionURL the base action URL
*/
public void setBaseActionURL(String baseActionURL) {
this.baseActionURL = baseActionURL;
}
/**
* Sets whether or not the channel is rendering as the root of the layout.
* @param rar <code>true</code> if channel is rendering as the root, otherwise <code>false</code>
*/
public void setRenderingAsRoot(boolean rar) {
renderingAsRoot = rar;
}
/**
* Sets whether or not the channel is currently targeted. A channel is targeted
* if an incoming request specifies the channel's subscribe ID as the targeted node ID.
* @param targeted <code>true</code> if channel is targeted, otherwise <code>false</code>
*/
public void setTargeted(boolean targeted) {
this.targeted = targeted;
}
/**
* Setter method for browser info object.
*
* @param bi a browser info associated with the current request
*/
public void setBrowserInfo(BrowserInfo bi) {
this.binfo = bi;
}
/**
* Provides information about a user-agent associated with the current request/response.
*
* @return a <code>BrowserInfo</code> object ecapsulating various user-agent information.
*/
public BrowserInfo getBrowserInfo() {
return binfo;
}
/**
* Setter method for array of locales. A channel should
* make an effort to render itself according to the
* order of the locales in this array.
* @param locales an ordered list of locales
*/
public void setLocales(Locale[] locales) {
this.locales = locales;
}
/**
* Accessor method for ordered set of locales.
* @return locales an ordered list of locales
*/
public Locale[] getLocales() {
return locales;
}
/**
* A convenience method for setting a whole set of parameters at once.
* The values in the Map must be object arrays. If (name, value[]) is in
* the Map, then a future call to getParameter(name) will return value[0].
* @param params a <code>Map</code> of parameter names to parameter value arrays.
*/
public void setParameters(Map params) {
this.putAll(params); // copy a Map
}
/**
* A convenience method for setting a whole set of parameters at once.
* The Map should contain name-value pairs. The name should be a String
* and the value should be either a String or a Part.
* If (name, value) is in the Map then a future call to getParameter(name)
* will return value.
* @param params a <code>Map</code> of parameter names to parameter value arrays.
*/
public void setParametersSingleValued(Map params) {
if (params != null) {
java.util.Iterator iter = params.keySet().iterator();
while (iter.hasNext()) {
String key = (String)iter.next();
Object value = params.get(key);
if (value instanceof String)
setParameter(key, (String)value);
else if (value instanceof Part)
setParameter(key, (Part)value);
}
}
}
/**
* Sets multi-valued parameter.
*
* @param pName parameter name
* @param values an array of parameter values
* @return an array of parameter values
*/
public String[] setParameterValues(String pName, String[] values) {
return (String[])super.put(pName, values);
}
/**
* Establish a parameter name-value pair.
*
* @param pName parameter name
* @param value parameter value
*/
public void setParameter(String pName, String value) {
String[] valueArray = new String[1];
valueArray[0] = value;
super.put(pName, valueArray);
}
public com.oreilly.servlet.multipart.Part[] setParameterValues(String pName, com.oreilly.servlet.multipart.Part[] values) {
return (com.oreilly.servlet.multipart.Part[])super.put(pName, values);
}
public synchronized void setParameter(String key, Part value) {
Part[] valueArray = new Part[1];
valueArray[0] = value;
super.put(key, valueArray);
}
/**
* Returns a baseActionURL - parameters of a request coming in on the baseActionURL
* will be placed into the ChannelRuntimeData object for channel's use.
*
* @return a value of URL to which parameter sequences should be appended.
*/
public String getBaseActionURL() {
return this.getBaseActionURL(false);
}
/**
* Returns a baseActionURL - parameters of a request coming in on the baseActionURL
* will be placed into the ChannelRuntimeData object for channel's use.
*
* @param idempotent a <code>boolean</code> value specifying if a given URL should be idepotent.
* @return a value of URL to which parameter sequences should be appended.
*/
public String getBaseActionURL(boolean idempotent) {
// If the base action URL was explicitly set, use it
// peterk: we should probably introduce idepotent version of this one as well, at some point
if (baseActionURL != null) {
return URLEncoder.encode(baseActionURL);
}
String url=null;
try {
if(idempotent) {
UPFileSpec upfs=new UPFileSpec(channelUPFile);
upfs.setTagId(PortalSessionManager.IDEMPOTENT_URL_TAG);
url=upfs.getUPFile();
} else {
url=channelUPFile.getUPFile();
}
} catch (Exception e) {
LogService.log(LogService.ERROR,"ChannelRuntimeData::getBaseActionURL() : unable to construct a base action URL!");
}
return URLEncoder.encode(url);
}
/**
* Returns the URL to invoke one of the workers specified in PortalSessionManager.
* Typically the channel that is invoked with the worker will have to implement an
* interface specific for that worker.
* @param worker - Worker string must be a UPFileSpec.xxx value.
* @return URL to invoke the worker.
*/
public String getBaseWorkerURL(String worker) {
// todo: propagate the exception
String url=null;
try {
url=getBaseWorkerURL(worker,false);
} catch (Exception e) {
LogService.log(LogService.ERROR,"ChannelRuntimeData::getBaseWorkerURL() : unable to construct a worker action URL for a worker \""+worker+"\".");
}
return url;
}
/**
Returns a media base appropriate for web-visible resources used by and
deployed with the passed in object. If the class of the passed in
object was loaded from a CAR then a URL appropriate for accessing
images in CARs is returned. Otherwise, a URL to the base media
in the web application's document root is returned.
*/
public String getBaseMediaURL( Object aChannelObject )
throws PortalException
{
return getBaseMediaURL( aChannelObject.getClass() );
}
/**
Returns a media base appropriate for web-visible resources used by and
deployed with the passed in class. If the class of the passed in
object was loaded from a CAR then a URL appropriate for accessing
images in CARs is returned. Otherwise, a URL to the base media
in the web application's document root is returned.
*/
public String getBaseMediaURL( Class aChannelClass )
throws PortalException
{
if ( aChannelClass.getClassLoader() ==
CarResources.getInstance().getClassLoader() )
return createBaseCarMediaURL();
return TRADITIONAL_MEDIA_BASE;
}
/**
Returns a media base appropriate for the resource path passed in. The
resource path is the path to the resource within its channel archive.
(See org.jasig.portal.car.CarResources class for more information.)
If the passed in resourcePath matches that of a resource loaded from
CARs then this method returns a URL appropriate to obtain CAR
deployed, web-visible resources. Otherwise it returns a URL to the
traditional media path under the uPortal web application's document
root.
*/
public String getBaseMediaURL( String resourcePath )
throws PortalException
{
if ( CarResources.getInstance().containsResource( resourcePath ) )
return createBaseCarMediaURL();
return TRADITIONAL_MEDIA_BASE;
}
/**
* Creates the CAR media base URL.
*/
private String createBaseCarMediaURL() throws PortalException {
String url = getBaseWorkerURL( CarResources.CAR_WORKER_ID, true );
return url.concat( "?" + CarResources.CAR_RESOURCE_PARM + "=" );
}
/**
* Returns the URL to invoke one of the workers specified in PortalSessionManager.
* Typically the channel that is invoked with the worker will have to implement an
* interface specific for that worker.
* @param worker - Worker string must be a UPFileSpec.xxx value.
* @param idempotent a <code>boolean</code> value sepcifying if a URL should be idempotent
* @return URL to invoke the worker.
* @exception PortalException if an error occurs
*/
public String getBaseWorkerURL(String worker, boolean idempotent) throws PortalException {
String url=null;
UPFileSpec upfs=new UPFileSpec(channelUPFile);
upfs.setMethod(UPFileSpec.WORKER_METHOD);
upfs.setMethodNodeId(worker);
if(idempotent) {
upfs.setTagId(PortalSessionManager.IDEMPOTENT_URL_TAG);
}
url=upfs.getUPFile();
return URLEncoder.encode(url);
}
/**
* Tells whether or not the channel is rendering as the root of the layout.
* @return <code>true</code> if channel is rendering as the root, otherwise <code>false</code>
*/
public boolean isRenderingAsRoot() {
return renderingAsRoot;
}
/**
* Tells whether or not the channel is currently targeted. A channel is targeted
* if an incoming request specifies the channel's subscribe ID as the targeted node ID.
* @return <code>true</code> if channel is targeted, otherwise <code>false</code>
*/
public boolean isTargeted() {
return targeted;
}
/**
* Get a parameter value. If the parameter has multiple values, only the first value is returned.
*
* @param pName parameter name
* @return parameter value
*/
public String getParameter(String pName) {
String[] value_array = this.getParameterValues(pName);
if ((value_array != null) && (value_array.length > 0))
return value_array[0];
else
return null;
}
/**
* Obtain an <code>Object</code> parameter value. If the parameter has multiple values, only the first value is returned.
*
* @param pName parameter name
* @return parameter value
*/
public Object getObjectParameter(String pName) {
Object[] value_array = this.getObjectParameterValues(pName);
if ((value_array != null) && (value_array.length > 0)) {
return value_array[0];
} else {
return null;
}
}
/**
* Obtain all values for a given parameter.
*
* @param pName parameter name
* @return an array of parameter string values
*/
public String[] getParameterValues(String pName) {
Object[] pars = (Object[])super.get(pName);
if (pars instanceof String[]) {
return (String[])pars;
} else {
return null;
}
}
/**
* Obtain all values for a given parameter as <code>Object</code>s.
*
* @param pName parameter name
* @return a vector of parameter <code>Object[]</code> values
*/
public Object[] getObjectParameterValues(String pName) {
return (Object[])super.get(pName);
}
/**
* Get an enumeration of parameter names.
*
* @return an <code>Enumeration</code> of parameter names.
*/
public Enumeration getParameterNames() {
return (Enumeration)super.keys();
}
/**
* Get the parameters as a Map
* @return a Map of parameter name-value pairs
*/
public Map getParameters() {
Map params = new java.util.HashMap(this.size());
Enumeration e = this.getParameterNames();
while (e.hasMoreElements()) {
String name = (String)e.nextElement();
String value = this.getParameter(name);
params.put(name, value);
}
return params;
}
/**
* Sets the keywords
* @param keywords a String of keywords
*/
public void setKeywords(String keywords)
{
this.keywords = keywords;
}
/**
* Returns the keywords
* @return a String of keywords, null if there were none
*/
public String getKeywords()
{
return keywords;
}
}
|
package org.jasig.portal;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Locale;
import java.util.Map;
import org.jasig.portal.car.CarResources;
import org.jasig.portal.services.LogService;
import com.oreilly.servlet.multipart.Part;
/**
* A set of runtime data accessible by a channel.
*
* @author <a href="mailto:pkharchenko@interactivebusiness.com">Peter Kharchenko</a>
* @version $Revision$
*/
public class ChannelRuntimeData extends Hashtable implements Cloneable {
private BrowserInfo binfo=null;
private Locale[] locales = null;
private UPFileSpec channelUPFile;
private String baseActionURL = null;
private String httpRequestMethod=null;
private String keywords=null;
private boolean renderingAsRoot=false;
private static final String TRADITIONAL_MEDIA_BASE = "media/";
/**
* Default empty constructor
*/
public ChannelRuntimeData() {
super();
channelUPFile = new UPFileSpec();
}
/**
* Create a new instance of ourself
* Used by the CError channel
* @return crd the cloned ChannelRuntimeData object
*/
public Object clone() {
ChannelRuntimeData crd = new ChannelRuntimeData();
crd.binfo = binfo;
crd.locales = locales;
crd.channelUPFile = channelUPFile;
crd.baseActionURL = baseActionURL;
crd.httpRequestMethod = httpRequestMethod;
crd.keywords = keywords;
crd.renderingAsRoot = renderingAsRoot;
crd.putAll(this);
return crd;
}
/**
* Set a UPFileSpec which will be used to produce
* baseActionURL and workerActionURL.
* @param upfs the UPFileSpec
*/
public void setUPFile(UPFileSpec upfs) {
channelUPFile = upfs;
}
/**
* Get the UPFileSpec
* @return channelUPFile the UPFileSpec
*/
public UPFileSpec getUPFile() {
return this.channelUPFile;
}
/**
* Set the HTTP Reqeust method.
*
* @param method a <code>String</code> value
*/
public void setHttpRequestMethod(String method) {
this.httpRequestMethod=method;
}
/**
* Get HTTP request method (i.e. GET, POST)
*
* @return a <code>String</code> value
*/
public String getHttpRequestMethod() {
return this.httpRequestMethod;
}
/**
* Sets the base action URL. This was added back in for the benefit
* of web services. Not sure if it is going to stay this way.
* @param baseActionURL the base action URL
*/
public void setBaseActionURL(String baseActionURL) {
this.baseActionURL = baseActionURL;
}
/**
* Sets whether or not the channel is rendering as the root of the layout.
* @param rar <code>true</code> if channel is rendering as the root, otherwise <code>false</code>
*/
public void setRenderingAsRoot(boolean rar) {
renderingAsRoot = rar;
}
/**
* Setter method for browser info object.
*
* @param bi a browser info associated with the current request
*/
public void setBrowserInfo(BrowserInfo bi) {
this.binfo = bi;
}
/**
* Provides information about a user-agent associated with the current request/response.
*
* @return a <code>BrowserInfo</code> object ecapsulating various user-agent information.
*/
public BrowserInfo getBrowserInfo() {
return binfo;
}
/**
* Setter method for array of locales. A channel should
* make an effort to render itself according to the
* order of the locales in this array.
* @param locales an ordered list of locales
*/
public void setLocales(Locale[] locales) {
this.locales = locales;
}
/**
* Accessor method for ordered set of locales.
* @return locales an ordered list of locales
*/
public Locale[] getLocales() {
return locales;
}
/**
* A convenience method for setting a whole set of parameters at once.
* The values in the Map must be object arrays. If (name, value[]) is in
* the Map, then a future call to getParameter(name) will return value[0].
* @param params a <code>Map</code> of parameter names to parameter value arrays.
*/
public void setParameters(Map params) {
this.putAll(params); // copy a Map
}
/**
* A convenience method for setting a whole set of parameters at once.
* The Map should contain name-value pairs. The name should be a String
* and the value should be either a String or a Part.
* If (name, value) is in the Map then a future call to getParameter(name)
* will return value.
* @param params a <code>Map</code> of parameter names to parameter value arrays.
*/
public void setParametersSingleValued(Map params) {
if (params != null) {
java.util.Iterator iter = params.keySet().iterator();
while (iter.hasNext()) {
String key = (String)iter.next();
Object value = params.get(key);
if (value instanceof String)
setParameter(key, (String)value);
else if (value instanceof Part)
setParameter(key, (Part)value);
}
}
}
/**
* Sets multi-valued parameter.
*
* @param pName parameter name
* @param values an array of parameter values
* @return an array of parameter values
*/
public String[] setParameterValues(String pName, String[] values) {
return (String[])super.put(pName, values);
}
/**
* Establish a parameter name-value pair.
*
* @param pName parameter name
* @param value parameter value
*/
public void setParameter(String pName, String value) {
String[] valueArray = new String[1];
valueArray[0] = value;
super.put(pName, valueArray);
}
public com.oreilly.servlet.multipart.Part[] setParameterValues(String pName, com.oreilly.servlet.multipart.Part[] values) {
return (com.oreilly.servlet.multipart.Part[])super.put(pName, values);
}
public synchronized void setParameter(String key, Part value) {
Part[] valueArray = new Part[1];
valueArray[0] = value;
super.put(key, valueArray);
}
/**
* Returns a baseActionURL - parameters of a request coming in on the baseActionURL
* will be placed into the ChannelRuntimeData object for channel's use.
*
* @return a value of URL to which parameter sequences should be appended.
*/
public String getBaseActionURL() {
return this.getBaseActionURL(false);
}
/**
* Returns a baseActionURL - parameters of a request coming in on the baseActionURL
* will be placed into the ChannelRuntimeData object for channel's use.
*
* @param idempotent a <code>boolean</code> value specifying if a given URL should be idepotent.
* @return a value of URL to which parameter sequences should be appended.
*/
public String getBaseActionURL(boolean idempotent) {
// If the base action URL was explicitly set, use it
// peterk: we should probably introduce idepotent version of this one as well, at some point
if (baseActionURL != null) {
return java.net.URLEncoder.encode(baseActionURL);
}
String url=null;
try {
if(idempotent) {
UPFileSpec upfs=new UPFileSpec(channelUPFile);
upfs.setTagId(PortalSessionManager.IDEMPOTENT_URL_TAG);
url=upfs.getUPFile();
} else {
url=channelUPFile.getUPFile();
}
} catch (Exception e) {
LogService.log(LogService.ERROR,"ChannelRuntimeData::getBaseActionURL() : unable to construct a base action URL!");
}
return java.net.URLEncoder.encode(url);
}
/**
* Returns the URL to invoke one of the workers specified in PortalSessionManager.
* Typically the channel that is invoked with the worker will have to implement an
* interface specific for that worker.
* @param worker - Worker string must be a UPFileSpec.xxx value.
* @return URL to invoke the worker.
*/
public String getBaseWorkerURL(String worker) {
// todo: propagate the exception
String url=null;
try {
url=getBaseWorkerURL(worker,false);
} catch (Exception e) {
LogService.log(LogService.ERROR,"ChannelRuntimeData::getBaseWorkerURL() : unable to construct a worker action URL for a worker \""+worker+"\".");
}
return java.net.URLEncoder.encode(url);
}
/**
Returns a media base appropriate for web-visible resources used by and
deployed with the passed in object. If the class of the passed in
object was loaded from a CAR then a URL appropriate for accessing
images in CARs is returned. Otherwise, a URL to the base media
in the web application's document root is returned.
*/
public String getBaseMediaURL( Object aChannelObject )
throws PortalException
{
return getBaseMediaURL( aChannelObject.getClass() );
}
/**
Returns a media base appropriate for web-visible resources used by and
deployed with the passed in class. If the class of the passed in
object was loaded from a CAR then a URL appropriate for accessing
images in CARs is returned. Otherwise, a URL to the base media
in the web application's document root is returned.
*/
public String getBaseMediaURL( Class aChannelClass )
throws PortalException
{
if ( aChannelClass.getClassLoader() ==
CarResources.getInstance().getClassLoader() )
return createBaseCarMediaURL();
return TRADITIONAL_MEDIA_BASE;
}
/**
Returns a media base appropriate for the resource path passed in. The
resource path is the path to the resource within its channel archive.
(See org.jasig.portal.car.CarResources class for more information.)
If the passed in resourcePath matches that of a resource loaded from
CARs then this method returns a URL appropriate to obtain CAR
deployed, web-visible resources. Otherwise it returns a URL to the
traditional media path under the uPortal web application's document
root.
*/
public String getBaseMediaURL( String resourcePath )
throws PortalException
{
if ( CarResources.getInstance().containsResource( resourcePath ) )
return createBaseCarMediaURL();
return TRADITIONAL_MEDIA_BASE;
}
/**
* Creates the CAR media base URL.
*/
private String createBaseCarMediaURL() throws PortalException {
String url = getBaseWorkerURL( CarResources.CAR_WORKER_ID, true );
return URLEncoder.encode(url).concat( "?" + CarResources.CAR_RESOURCE_PARM + "=" );
}
/**
* Returns the URL to invoke one of the workers specified in PortalSessionManager.
* Typically the channel that is invoked with the worker will have to implement an
* interface specific for that worker.
* @param worker - Worker string must be a UPFileSpec.xxx value.
* @param idempotent a <code>boolean</code> value sepcifying if a URL should be idempotent
* @return URL to invoke the worker.
* @exception PortalException if an error occurs
*/
public String getBaseWorkerURL(String worker, boolean idempotent) throws PortalException {
String url=null;
UPFileSpec upfs=new UPFileSpec(channelUPFile);
upfs.setMethod(UPFileSpec.WORKER_METHOD);
upfs.setMethodNodeId(worker);
if(idempotent) {
upfs.setTagId(PortalSessionManager.IDEMPOTENT_URL_TAG);
}
url=upfs.getUPFile();
return java.net.URLEncoder.encode(url);
}
/**
* Tells whether or not the channel is rendering as the root of the layout.
* @return <code>true</code> if channel is rendering as the root, otherwise <code>false</code>
*/
public boolean isRenderingAsRoot() {
return renderingAsRoot;
}
/**
* Get a parameter value. If the parameter has multiple values, only the first value is returned.
*
* @param pName parameter name
* @return parameter value
*/
public String getParameter(String pName) {
String[] value_array = this.getParameterValues(pName);
if ((value_array != null) && (value_array.length > 0))
return value_array[0];
else
return null;
}
/**
* Obtain an <code>Object</code> parameter value. If the parameter has multiple values, only the first value is returned.
*
* @param pName parameter name
* @return parameter value
*/
public Object getObjectParameter(String pName) {
Object[] value_array = this.getObjectParameterValues(pName);
if ((value_array != null) && (value_array.length > 0)) {
return value_array[0];
} else {
return null;
}
}
/**
* Obtain all values for a given parameter.
*
* @param pName parameter name
* @return an array of parameter string values
*/
public String[] getParameterValues(String pName) {
Object[] pars = (Object[])super.get(pName);
if (pars instanceof String[]) {
return (String[])pars;
} else {
return null;
}
}
/**
* Obtain all values for a given parameter as <code>Object</code>s.
*
* @param pName parameter name
* @return a vector of parameter <code>Object[]</code> values
*/
public Object[] getObjectParameterValues(String pName) {
return (Object[])super.get(pName);
}
/**
* Get an enumeration of parameter names.
*
* @return an <code>Enumeration</code> of parameter names.
*/
public Enumeration getParameterNames() {
return (Enumeration)super.keys();
}
/**
* Get the parameters as a Map
* @return a Map of parameter name-value pairs
*/
public Map getParameters() {
Map params = new java.util.HashMap(this.size());
Enumeration e = this.getParameterNames();
while (e.hasMoreElements()) {
String name = (String)e.nextElement();
String value = this.getParameter(name);
params.put(name, value);
}
return params;
}
/**
* Sets the keywords
* @param keywords a String of keywords
*/
public void setKeywords(String keywords)
{
this.keywords = keywords;
}
/**
* Returns the keywords
* @return a String of keywords, null if there were none
*/
public String getKeywords()
{
return keywords;
}
}
|
package com.gallatinsystems.framework.servlet;
import com.gallatinsystems.framework.rest.RestRequest;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.dev.LocalTaskQueue;
import com.google.appengine.api.taskqueue.dev.QueueStateInfo;
import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
import com.google.appengine.tools.development.testing.LocalTaskQueueTestConfig;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockFilterChain;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
class ExecuteRequestAsTaskFilterTests {
private final LocalServiceTestHelper helper =
new LocalServiceTestHelper(new LocalTaskQueueTestConfig());
private MockHttpServletRequest httpRequest;
private String testPrivateKey = "very private";
@BeforeEach
public void setUp() {
this.httpRequest = new MockHttpServletRequest();
httpRequest.setRequestURI("/testservletapi");
httpRequest.setMethod("POST");
httpRequest.setContentType("application/x-www-form-urlencoded");
httpRequest.addParameter("action", "saveSurveyInstance");
httpRequest.addParameter("collectionDate", "30-03-2017+10%3A05%3A57+CEST");
httpRequest.addParameter("duration", "41");
httpRequest.addParameter("questionId", "149382277%7C0%3D44.3845%257C7.5845%257C1%7Ctype%3DGEO");
httpRequest.addParameter("questionId", "151492308%7C0%3Dhttp%253A%252F%252Fwaterforpeople.s3.amazonaws.com%252Fimages%252Fdb0756e0-b2ec-49ed-bbdb-26d4478af5c3.jpg%7Ctype%3DIMAGE");
httpRequest.addParameter("questionId", "152332013%7C0%3Dfiunsc%7Ctype%3DVALUE");
httpRequest.addParameter("questionId", "149292013%7C0%3D3%7Ctype%3DVALUE");
httpRequest.addParameter("runAsTask", "1");
httpRequest.addParameter("submitter", "tony");
httpRequest.addParameter("surveyId", "15316201398");
httpRequest.addParameter("surveyInstanceId", "15337202187");
httpRequest.addParameter("ts", "2020/03/03 15:05:14");
httpRequest.addParameter("h", "CmuehPsWW6//5Q4i8O1P5AjS/8Y=");
helper.setUp();
}
@Test
void testRequestToTaskMapping() {
ExecuteRequestAsTaskFilter filter = new ExecuteRequestAsTaskFilter();
ExecuteRequestAsTaskFilter.RequestToTaskMapper requestToTaskMapper = filter.new RequestToTaskMapper(this.httpRequest);
Map<String, List<String>> taskRequestParams = requestToTaskMapper.getTaskOptions().getStringParams();
assertEquals(10, taskRequestParams.size(), "Unexpected number of params for the request");
assertEquals("/testservletapi", requestToTaskMapper.getTaskOptions().getUrl());
assertEquals("saveSurveyInstance", taskRequestParams.get("action").get(0));
assertEquals("2020/03/03 15:05:14", taskRequestParams.get("ts").get(0));
assertEquals("30-03-2017+10%3A05%3A57+CEST", taskRequestParams.get("collectionDate").get(0));
assertEquals("41", taskRequestParams.get("duration").get(0));
assertEquals("CmuehPsWW6//5Q4i8O1P5AjS/8Y=", taskRequestParams.get("h").get(0));
Map<String, List<String>> headers = requestToTaskMapper.getTaskOptions().getHeaders();
assertTrue(headers.containsKey(RestRequest.QUEUED_TASK_HEADER), "The task queued header was not added");
}
@Test
void testAddRequestToTaskQueue() throws IOException, ServletException {
ExecuteRequestAsTaskFilter filter = new ExecuteRequestAsTaskFilter();
filter.doFilter(this.httpRequest, new MockHttpServletResponse(), new MockFilterChain());
assertTrue(filter.isTaskRequest(this.httpRequest), "The request MUST have a runAsTask parameter whose value is == 1");
assertFalse(filter.isQueuedTask(this.httpRequest), "The request should not have an X-Akvo-Queued-Task header set");
LocalTaskQueue localTaskQueue = LocalTaskQueueTestConfig.getLocalTaskQueue();
QueueStateInfo queueStateInfo = localTaskQueue.getQueueStateInfo().get(QueueFactory.getDefaultQueue().getQueueName());
Assertions.assertEquals(1, queueStateInfo.getTaskInfo().size());
}
@Test
void testExecuteRequestIfQueued() throws IOException, ServletException {
// comes from queued task
this.httpRequest.addHeader(RestRequest.QUEUED_TASK_HEADER, "1");
ExecuteRequestAsTaskFilter filter = new ExecuteRequestAsTaskFilter();
filter.doFilter(this.httpRequest, new MockHttpServletResponse(), new MockFilterChain());
assertTrue(filter.isTaskRequest(this.httpRequest), "The request MUST have a runAsTask parameter whose value is == 1");
assertTrue(filter.isQueuedTask(this.httpRequest), "The request MUST have an X-Akvo-Queued-Task header set");
LocalTaskQueue localTaskQueue = LocalTaskQueueTestConfig.getLocalTaskQueue();
QueueStateInfo queueStateInfo = localTaskQueue.getQueueStateInfo().get(QueueFactory.getDefaultQueue().getQueueName());
Assertions.assertEquals(0, queueStateInfo.getTaskInfo().size());
}
@AfterEach
public void tearDown() {
helper.tearDown();
}
}
|
package de.kleppmann.maniation.maths;
import java.text.DecimalFormat;
public class Quaternion {
private double w, x, y, z, mag;
private Quaternion inverse;
private Quaternion(boolean nonsense) {}
public Quaternion() {
this.w = 1.0; this.x = 0.0; this.y = 0.0; this.z = 0.0;
this.inverse = new Quaternion(true);
inverse.w = 1.0; inverse.x = 0.0; inverse.y = 0.0; inverse.z = 0.0;
inverse.inverse = this;
}
public Quaternion(double w, double x, double y, double z) {
this.w = w;
this.x = x;
this.y = y;
this.z = z;
double m = w*w + x*x + y*y + z*z;
this.mag = Math.sqrt(m);
this.inverse = new Quaternion(true);
this.inverse.w = w/m;
this.inverse.x = -x/m;
this.inverse.y = -y/m;
this.inverse.z = -z/m;
this.inverse.mag = 1.0/this.mag;
this.inverse.inverse = this;
}
public Quaternion(Vector3D v) {
this.w = 0.0;
this.x = v.getComponent(0);
this.y = v.getComponent(1);
this.z = v.getComponent(2);
this.inverse = null;
}
public double getW() {
return w;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
public double getZ() {
return z;
}
public String toString() {
DecimalFormat format = new DecimalFormat("
return "Quaternion(w: " + format.format(w) +
", x: " + format.format(x) +
", y: " + format.format(y) +
", z: " + format.format(z) + ")";
}
public Quaternion mult(Quaternion other) {
return new Quaternion(
this.w*other.w - this.x*other.x - this.y*other.y - this.z*other.z,
this.w*other.x + this.x*other.w + this.y*other.z - this.z*other.y,
this.w*other.y + this.y*other.w + this.z*other.x - this.x*other.z,
this.w*other.z + this.z*other.w + this.x*other.y - this.y*other.x
);
}
public Quaternion add(Quaternion other) {
return new Quaternion(this.w+other.w, this.x+other.x,
this.y+other.y, this.z+other.z);
}
public Quaternion subtract(Quaternion other) {
return new Quaternion(this.w-other.w, this.x-other.x,
this.y-other.y, this.z-other.z);
}
public Quaternion quergs(Quaternion delta) {
double mag = delta.getMagnitude();
if (mag < 1e-20) return this;
long n = Math.round(mag/Math.PI - 0.5);
double d = mag - Math.PI*(n + 0.5);
if ((d < 1e-6) && (d > -1e-6)) return new Quaternion(delta.w/mag,
delta.x/mag, delta.y/mag, delta.z/mag);
double t = Math.tan(mag)/mag;
double wn = this.w + t*delta.w;
double xn = this.x + t*delta.x;
double yn = this.y + t*delta.y;
double zn = this.z + t*delta.z;
mag = Math.sqrt(wn*wn + xn*xn + yn*yn + zn*zn);
return new Quaternion(wn/mag, xn/mag, yn/mag, zn/mag);
}
public Quaternion getInverse() {
return inverse;
}
public Vector3D transform(Vector3D v) {
if (v.getDimension() != 3) throw new IllegalArgumentException();
Quaternion t = mult(new Quaternion(v)).mult(inverse);
return new Vector3D(t.x, t.y, t.z);
}
public double getMagnitude() {
return mag;
}
public Matrix33 toMatrix() {
return new Matrix33(
1.0 - 2.0*(y*y + z*z), 2.0*(x*y - w*z), 2.0*(x*z + w*y),
2.0*(x*y + w*z), 1.0 - 2.0*(x*x + z*z), 2.0*(y*z - w*x),
2.0*(x*z - w*y), 2.0*(y*z + w*x), 1.0 - 2.0*(x*x + y*y));
}
public Quaternion interpolateTo(Quaternion dest, double amount) {
double theta = Math.acos(this.x*dest.x + this.y*dest.y + this.z*dest.z + this.w*dest.w);
double sinTheta = Math.sin(theta);
double v1 = Math.sin((1.0 - amount)*theta) / sinTheta;
double v2 = Math.sin(amount*theta) / sinTheta;
return new Quaternion(
v1*this.w + v2*dest.w,
v1*this.x + v2*dest.x,
v1*this.y + v2*dest.y,
v1*this.z + v2*dest.z);
}
public EulerAngles toEuler() {
double sy = 2.0*(w*y - x*z);
double cy = Math.sqrt(1 - sy*sy);
double sx, cx, sz, cz;
if (Math.abs(cy) < 1e-6) {
sx = 2.0*(w*x - y*z);
cx = 1.0 - 2.0*(x*x + z*z);
sz = 0.0;
cz = 1.0;
} else {
sx = 2.0*(y*z + w*x)/cy;
cx = (1.0 - 2.0*(x*x + y*y))/cy;
sz = 2.0*(x*y + w*z)/cy;
cz = (1.0 - 2.0*(y*y + z*z))/cy;
}
double rotX = Math.acos(cx); if (sx < 0) rotX = 2*Math.PI - rotX;
double rotY = Math.acos(cy); if (sy < 0) rotY = 2*Math.PI - rotY;
double rotZ = Math.acos(cz); if (sz < 0) rotZ = 2*Math.PI - rotZ;
return new EulerAngles(EulerAngles.Convention.ROLL_PITCH_YAW, rotX, rotY, rotZ);
}
public static Quaternion getXRotation(double angle) {
return new Quaternion(Math.cos(angle/2.0), Math.sin(angle/2.0), 0.0, 0.0);
}
public static Quaternion getYRotation(double angle) {
return new Quaternion(Math.cos(angle/2.0), 0.0, Math.sin(angle/2.0), 0.0);
}
public static Quaternion getZRotation(double angle) {
return new Quaternion(Math.cos(angle/2.0), 0.0, 0.0, Math.sin(angle/2.0));
}
}
|
package de.jungblut.nlp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.regex.Pattern;
public class GermanNormalizer implements Normalizer {
/**
* TODO this should be configurable: <br/>
* - which stop words <br/>
* - how long tokens to remove <br/>
* - merge with follow-up <br/>
* - the tokenizer to use <br/>
* - remove punctionation
*/
private static final Pattern specialSignFilter = Pattern.compile(
"\\p{Punct}", Pattern.CASE_INSENSITIVE);
public final static HashSet<String> GERMAN_STOP_WORDS = new HashSet<String>(
Arrays.asList(new String[] { "and", "the", "of", "to", "einer", "eine",
"eines", "einem", "einen", "der", "die", "das", "dass", "da\u00DF", "du",
"er", "sie", "es", "was", "wer", "wie", "wir", "und", "oder", "ohne",
"mit", "am", "im", "in", "aus", "auf", "ist", "sein", "war", "wird",
"ihr", "ihre", "ihres", "ihnen", "ihrer", "als", "f\u00FCr", "von", "mit",
"dich", "dir", "mich", "mir", "mein", "sein", "kein", "durch",
"wegen", "wird", "sich", "bei", "beim", "noch", "den", "dem", "zu",
"zur", "zum", "auf", "ein", "auch", "werden", "an", "des", "sein",
"sind", "vor", "nicht", "sehr", "um", "unsere", "ohne", "so", "da",
"nur", "diese", "dieser", "diesem", "dieses", "nach", "\u00FCber", "mehr",
"hat", "bis", "uns", "unser", "unserer", "unserem", "unsers", "euch",
"euers", "euer", "eurem", "ihr", "ihres", "ihrer", "ihrem", "alle",
"vom" }));
@Override
public String[] tokenizeAndNormalize(String s) {
final String trim = s.toLowerCase().trim();
final String replaceAll = specialSignFilter.matcher(trim).replaceAll("");
String[] tokens = Tokenizer.whiteSpaceTokenize(replaceAll);
ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < tokens.length; i++) {
if (!tokens[i].isEmpty() && !isWhitespaceToken(tokens[i])
&& !GERMAN_STOP_WORDS.contains(tokens[i])) {
list.add(tokens[i]);
}
}
list = mergeDigitsWithFollowUpToken(list);
// remove all tokens that are longer than 20
Iterator<String> it = list.iterator();
while (it.hasNext()) {
if (it.next().length() > 20) {
it.remove();
}
}
return list.toArray(new String[0]);
}
private final ArrayList<String> mergeDigitsWithFollowUpToken(
ArrayList<String> list) {
ArrayList<String> toReturn = new ArrayList<String>();
Iterator<String> it = list.iterator();
ArrayList<String> buffer = new ArrayList<String>();
while (it.hasNext()) {
final String next = it.next();
if (isDigitToken(next)) {
buffer.add(next);
} else {
if (buffer.isEmpty()) {
toReturn.add(next);
} else {
buffer.add(next);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < buffer.size(); i++) {
sb.append(buffer.get(i));
if (i != buffer.size() - 1)
sb.append("_");
}
toReturn.add(sb.toString());
buffer.clear();
}
}
}
return toReturn;
}
protected final boolean isDigitToken(String token) {
char[] chars = token.toCharArray();
for (int i = 0; i < chars.length; i++) {
if (!Character.isDigit(chars[i]))
return false;
}
return true;
}
protected final boolean isWhitespaceToken(String token) {
char[] chars = token.toCharArray();
for (int i = 0; i < chars.length; i++) {
if (!Character.isWhitespace(chars[i]))
return false;
}
return true;
}
}
|
package org.fcrepo.utils;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.slf4j.LoggerFactory.getLogger;
import java.math.BigDecimal;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import javax.jcr.Binary;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.PropertyIterator;
import javax.jcr.PropertyType;
import javax.jcr.Repository;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.Value;
import javax.jcr.ValueFactory;
import javax.jcr.Workspace;
import javax.jcr.nodetype.NodeType;
import javax.jcr.nodetype.NodeTypeIterator;
import javax.jcr.nodetype.NodeTypeManager;
import javax.jcr.version.Version;
import javax.jcr.version.VersionHistory;
import javax.jcr.version.VersionIterator;
import javax.jcr.version.VersionManager;
import com.codahale.metrics.Counter;
import com.codahale.metrics.MetricRegistry;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedMap;
import com.hp.hpl.jena.datatypes.xsd.XSDDatatype;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.update.GraphStore;
import com.hp.hpl.jena.update.GraphStoreFactory;
import org.fcrepo.RdfLexicon;
import org.fcrepo.metrics.RegistryService;
import org.fcrepo.rdf.GraphSubjects;
import org.fcrepo.rdf.impl.DefaultGraphSubjects;
import org.fcrepo.services.LowLevelStorageService;
import org.fcrepo.services.functions.GetClusterConfiguration;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.modeshape.jcr.api.JcrConstants;
import org.modeshape.jcr.api.NamespaceRegistry;
import org.modeshape.jcr.value.BinaryKey;
import org.modeshape.jcr.value.BinaryValue;
import org.powermock.api.mockito.PowerMockito;
import com.google.common.base.Function;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.ResourceFactory;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.slf4j.Logger;
@RunWith(PowerMockRunner.class)
@PowerMockIgnore({"org.slf4j.*", "javax.xml.parsers.*", "org.apache.xerces.*"})
@PrepareForTest({FedoraTypesUtils.class, RegistryService.class})
public class JcrRdfToolsTest {
private static final Logger LOGGER = getLogger(JcrRdfToolsTest.class);
private Node mockNode;
private NamespaceRegistry mockNsRegistry;
private GraphSubjects testSubjects;
private Session mockSession;
private Repository mockRepository;
private Workspace mockWorkspace;
@Before
public void setUp() throws RepositoryException {
mockSession = mock(Session.class);
testSubjects = new DefaultGraphSubjects();
mockNode = mock(Node.class);
when(mockNode.getSession()).thenReturn(mockSession);
mockWorkspace = mock(Workspace.class);
mockRepository = mock(Repository.class);
when(mockSession.getRepository()).thenReturn(mockRepository);
when(mockSession.getWorkspace()).thenReturn(mockWorkspace);
mockNamespaceRegistry();
when(mockWorkspace.getNamespaceRegistry()).thenReturn(mockNsRegistry);
}
@Test
public void shouldMapInternalJcrNamespaceToFcrepoNamespace() {
assertEquals("info:fedora/fedora-system:def/internal#", JcrRdfTools
.getRDFNamespaceForJcrNamespace("http:
}
@Test
public void shouldMapFcrepoNamespaceToJcrNamespace() {
assertEquals(
"http:
JcrRdfTools
.getJcrNamespaceForRDFNamespace("info:fedora/fedora-system:def/internal
}
@Test
public void shouldPassThroughOtherNamespaceValues() {
assertEquals("some-namespace-uri", JcrRdfTools
.getJcrNamespaceForRDFNamespace("some-namespace-uri"));
assertEquals("some-namespace-uri", JcrRdfTools
.getRDFNamespaceForJcrNamespace("some-namespace-uri"));
}
@Test
public void shouldMapRdfPredicatesToJcrProperties()
throws RepositoryException {
final Property p =
ResourceFactory.createProperty(
"info:fedora/fedora-system:def/internal#", "uuid");
assertEquals("jcr:uuid", JcrRdfTools.getPropertyNameFromPredicate(
mockNode, p));
}
@Test
public void shouldReuseRegisteredNamespaces() throws RepositoryException {
final Property p =
ResourceFactory.createProperty("registered-uri#", "uuid");
assertEquals("some-prefix:uuid", JcrRdfTools
.getPropertyNameFromPredicate(mockNode, p));
}
@Test
public void shouldRegisterUnknownUris() throws RepositoryException {
when(mockNsRegistry.registerNamespace("not-registered-uri
.thenReturn("ns001");
final Property p =
ResourceFactory.createProperty("not-registered-uri#", "uuid");
assertEquals("ns001:uuid", JcrRdfTools.getPropertyNameFromPredicate(
mockNode, p));
}
@Test
public void shouldMapJcrNodeNamestoRDFResources()
throws RepositoryException {
when(mockNode.getPath()).thenReturn("/abc");
assertEquals("info:fedora/abc",
JcrRdfTools.getGraphSubject(testSubjects, mockNode)
.toString());
}
@Test
public void shouldMapJcrContentNodeNamestoRDFResourcesIntheFcrNamespace()
throws RepositoryException {
when(mockNode.getPath()).thenReturn("/abc/jcr:content");
assertEquals("info:fedora/abc/fcr:content", JcrRdfTools
.getGraphSubject(testSubjects, mockNode).toString());
}
@Test
public void shouldMapRDFResourcesToJcrNodes() throws RepositoryException {
when(mockSession.nodeExists("/abc")).thenReturn(true);
when(mockSession.getNode("/abc")).thenReturn(mockNode);
assertEquals(mockNode,
JcrRdfTools.getNodeFromGraphSubject(testSubjects, mockSession,
ResourceFactory.createResource("info:fedora/abc")));
}
@Test
public void shouldMapRDFContentResourcesToJcrContentNodes()
throws RepositoryException {
when(mockSession.nodeExists("/abc/jcr:content")).thenReturn(true);
when(mockSession.getNode("/abc/jcr:content")).thenReturn(mockNode);
assertEquals(mockNode,
JcrRdfTools.getNodeFromGraphSubject(testSubjects, mockSession,
ResourceFactory.createResource("info:fedora/abc/fcr:content")));
}
@Test
public void shouldReturnNullIfItFailstoMapRDFResourcesToJcrNodes()
throws RepositoryException {
when(mockSession.nodeExists("/does-not-exist")).thenReturn(false);
assertNull("should receive null for a non-JCR resource",
JcrRdfTools.getNodeFromGraphSubject(
testSubjects, mockSession, ResourceFactory
.createResource("this-is-not-a-fedora-node/abc")));
assertNull("should receive null a JCR node that isn't found",
JcrRdfTools.getNodeFromGraphSubject(testSubjects, mockSession,
ResourceFactory
.createResource("info:fedora/does-not-exist")));
}
@Test
public void shouldDetermineIfAGraphResourceIsAJcrNode() throws RepositoryException {
GraphSubjects mockFactory = mock(GraphSubjects.class);
Resource mockSubject = mock(Resource.class);
when(mockFactory.isFedoraGraphSubject(mockSubject)).thenReturn(true);
assertTrue(JcrRdfTools.isFedoraGraphSubject(mockFactory, mockSubject));
verify(mockFactory).isFedoraGraphSubject(mockSubject);
}
@Test
public void testGetPropertiesModel() throws RepositoryException {
final Node mockParent = mock(Node.class);
when(mockParent.getPath()).thenReturn("/test");
when(mockNode.getPath()).thenReturn("/test/jcr");
when(mockNode.getParent()).thenReturn(mockParent);
final NodeType nodeType = mock(NodeType.class);
when(mockNode.getPrimaryNodeType()).thenReturn(nodeType);
when(mockNode.getPrimaryNodeType().getName()).thenReturn("");
when(mockNode.getPath()).thenReturn("/test/jcr");
final javax.jcr.NodeIterator mockNodes =
mock(javax.jcr.NodeIterator.class);
when(mockNode.getNodes()).thenReturn(mockNodes);
final PropertyIterator mockProperties =
mock(PropertyIterator.class);
when(mockNode.getProperties()).thenReturn(mockProperties);
final PropertyIterator mockParentProperties =
mock(PropertyIterator.class);
when(mockParent.getProperties()).thenReturn(mockParentProperties);
when(mockProperties.hasNext()).thenReturn(true, false);
when(mockParentProperties.hasNext()).thenReturn(true, false);
javax.jcr.Property mockProperty = mock(javax.jcr.Property.class);
when(mockProperty.isMultiple()).thenReturn(false);
when(mockProperty.getName()).thenReturn("xyz");
when(mockProperty.getType()).thenReturn(0);
final Value mockValue = mock(Value.class);
when(mockValue.getString()).thenReturn("abc");
when(mockProperty.getValue()).thenReturn(mockValue);
when(mockProperties.nextProperty()).thenReturn(mockProperty);
when(mockParentProperties.nextProperty()).thenReturn(mockProperty);
final Model actual = JcrRdfTools.getJcrPropertiesModel(testSubjects, mockNode);
assertEquals("info:fedora/fedora-system:def/internal#", actual.getNsPrefixURI("fedora-internal"));
assertTrue(actual.contains(testSubjects.getGraphSubject(mockNode), actual.getProperty("xyz"), actual.createLiteral("abc")));
}
@Test
public void testGetPropertiesModelWithContent() throws RepositoryException {
LowLevelStorageService mockLowLevelStorageService = mock(LowLevelStorageService.class);
JcrRdfTools.setLlstore(mockLowLevelStorageService);
final Node mockParent = mock(Node.class);
when(mockParent.getPath()).thenReturn("/test");
when(mockNode.getPath()).thenReturn("/test/jcr");
when(mockNode.getParent()).thenReturn(mockParent);
final NodeType nodeType = mock(NodeType.class);
when(mockNode.getPrimaryNodeType()).thenReturn(nodeType);
when(mockNode.getPrimaryNodeType().getName()).thenReturn("");
when(mockNode.getPath()).thenReturn("/test/jcr");
when(mockNode.hasNode(JcrConstants.JCR_CONTENT)).thenReturn(true);
Node mockNodeContent = mock(Node.class);
when(mockNodeContent.getPath()).thenReturn("/test/jcr/jcr:content");
javax.jcr.Property mockData = mock(javax.jcr.Property.class);
BinaryValue mockBinary = mock(BinaryValue.class);
when(mockBinary.getKey()).thenReturn(new BinaryKey("abc"));
when(mockData.getBinary()).thenReturn(mockBinary);
when(mockNodeContent.getProperty(JcrConstants.JCR_DATA)).thenReturn(mockData);
final LowLevelCacheEntry mockCacheEntry = mock(LowLevelCacheEntry.class);
when(mockCacheEntry.getExternalIdentifier()).thenReturn("xyz");
when(mockLowLevelStorageService.getLowLevelCacheEntries(mockNodeContent)).thenReturn(ImmutableSet.of(mockCacheEntry));
when(mockNode.getNode(JcrConstants.JCR_CONTENT)).thenReturn(mockNodeContent);
final javax.jcr.NodeIterator mockNodes =
mock(javax.jcr.NodeIterator.class);
when(mockNode.getNodes()).thenReturn(mockNodes);
final PropertyIterator mockProperties =
mock(PropertyIterator.class);
when(mockNode.getProperties()).thenReturn(mockProperties);
when(mockParent.getProperties()).thenReturn(mockProperties);
when(mockNodeContent.getProperties()).thenReturn(mockProperties);
when(mockProperties.hasNext()).thenReturn(false);
final Model actual = JcrRdfTools.getJcrPropertiesModel(testSubjects, mockNode);
assertEquals("info:fedora/fedora-system:def/internal#", actual.getNsPrefixURI("fedora-internal"));
assertTrue(actual.contains(testSubjects.getGraphSubject(mockNode), RdfLexicon.HAS_CONTENT, testSubjects.getGraphSubject(mockNodeContent)));
assertTrue(actual.contains(testSubjects.getGraphSubject(mockNodeContent), RdfLexicon.HAS_LOCATION, actual.createLiteral("xyz")));
}
@Test
public void testGetPropertiesModelForRootNode() throws RepositoryException {
PowerMockito.mockStatic(RegistryService.class);
MetricRegistry mockMetrics = mock(MetricRegistry.class);
Counter mockCounter = mock(Counter.class);
when(mockMetrics.getCounters()).thenReturn(ImmutableSortedMap.of(
"org.fcrepo.services.LowLevelStorageService.fixity-check-counter", mockCounter,
"org.fcrepo.services.LowLevelStorageService.fixity-error-counter", mockCounter,
"org.fcrepo.services.LowLevelStorageService.fixity-repaired-counter", mockCounter
));
when(RegistryService.getMetrics()).thenReturn(mockMetrics);
GetClusterConfiguration mockGetClusterConfiguration = mock(GetClusterConfiguration.class);
when(mockGetClusterConfiguration.apply(mockRepository)).thenReturn(ImmutableMap.of("a", "b"));
JcrRdfTools.setGetClusterConfiguration(mockGetClusterConfiguration);
when(mockNode.getPath()).thenReturn("/");
final NodeType nodeType = mock(NodeType.class);
when(mockNode.getPrimaryNodeType()).thenReturn(nodeType);
when(mockNode.getPrimaryNodeType().getName()).thenReturn(FedoraJcrTypes.ROOT);
when(mockNode.getPath()).thenReturn("/test/jcr");
final javax.jcr.NodeIterator mockNodes =
mock(javax.jcr.NodeIterator.class);
when(mockNode.getNodes()).thenReturn(mockNodes);
final PropertyIterator mockProperties =
mock(PropertyIterator.class);
when(mockNode.getProperties()).thenReturn(mockProperties);
when(mockProperties.hasNext()).thenReturn(false);
when(mockSession.getRepository()).thenReturn(mockRepository);
when(mockRepository.getDescriptorKeys()).thenReturn(new String[] { "some-descriptor-key"});
when(mockRepository.getDescriptor("some-descriptor-key")).thenReturn("some-descriptor-value");
NodeTypeManager mockNodeTypeManager = mock(NodeTypeManager.class);
NodeTypeIterator mockNodeTypeIterator = mock(NodeTypeIterator.class);
when(mockNodeTypeIterator.hasNext()).thenReturn(false);
when(mockNodeTypeManager.getAllNodeTypes()).thenReturn(mockNodeTypeIterator);
PowerMockito.mockStatic(FedoraTypesUtils.class);
when(FedoraTypesUtils.getNodeTypeManager(mockNode)).thenReturn(mockNodeTypeManager);
when(FedoraTypesUtils.getRepositoryCount(mockRepository)).thenReturn(0L);
when(FedoraTypesUtils.getRepositorySize(mockRepository)).thenReturn(0L);
final Model actual = JcrRdfTools.getJcrPropertiesModel(testSubjects, mockNode);
assertEquals("info:fedora/fedora-system:def/internal#", actual.getNsPrefixURI("fedora-internal"));
assertTrue(actual.contains(testSubjects.getGraphSubject(mockNode), actual.createProperty("info:fedora/fedora-system:def/internal#repository/some-descriptor-key"), actual.createLiteral("some-descriptor-value")));
assertTrue(actual.contains(testSubjects.getGraphSubject(mockNode), actual.createProperty("info:fedora/fedora-system:def/internal#a"), actual.createLiteral("b")));
assertTrue(actual.contains(testSubjects.getGraphSubject(mockNode), RdfLexicon.HAS_FIXITY_CHECK_COUNT));
assertTrue(actual.contains(testSubjects.getGraphSubject(mockNode), RdfLexicon.HAS_FIXITY_ERROR_COUNT));
assertTrue(actual.contains(testSubjects.getGraphSubject(mockNode), RdfLexicon.HAS_FIXITY_REPAIRED_COUNT));
}
@Test
public void shouldExcludeBinaryProperties() throws RepositoryException {
Node mockParent = mock(Node.class);
when(mockParent.getPath()).thenReturn("/test");
when(mockNode.getPath()).thenReturn("/test/jcr");
when(mockNode.getParent()).thenReturn(mockParent);
when(mockNode.getDepth()).thenReturn(2);
final NodeType nodeType = mock(NodeType.class);
when(mockNode.getPrimaryNodeType()).thenReturn(nodeType);
when(mockNode.getPrimaryNodeType().getName()).thenReturn("fedora:object");
when(mockNode.getPath()).thenReturn("/test/jcr");
PropertyIterator mockProperties = mock(PropertyIterator.class);
when(mockNode.getProperties()).thenReturn(mockProperties);
when(mockParent.getProperties()).thenReturn(mockProperties);
when(mockProperties.hasNext()).thenReturn(true, false);
javax.jcr.Property mockProperty = mock(javax.jcr.Property.class);
Value mockValue = mock(Value.class);
when(mockProperty.getValue()).thenReturn(mockValue);
when(mockValue.getType()).thenReturn(PropertyType.BINARY);
when(mockProperties.nextProperty()).thenReturn(mockProperty);
Model actual = JcrRdfTools.getJcrPropertiesModel(testSubjects, mockNode);
assertEquals(0, actual.size());
}
@Test
public void shouldIncludeParentNodeInformation() throws RepositoryException {
Node mockParent = mock(Node.class);
when(mockParent.getPath()).thenReturn("/test");
when(mockNode.getPath()).thenReturn("/test/jcr");
when(mockNode.getParent()).thenReturn(mockParent);
NodeIterator mockIterator = mock(NodeIterator.class);
when(mockIterator.hasNext()).thenReturn(false);
when(mockNode.getNodes()).thenReturn(mockIterator);
Model actual = JcrRdfTools.getJcrTreeModel(testSubjects, mockNode, 0, -1);
assertEquals(1, actual.size());
}
@Test
public void shouldIncludeChildNodeInformation() throws RepositoryException {
Node mockParent = mock(Node.class);
when(mockParent.getPath()).thenReturn("/test");
when(mockNode.getPath()).thenReturn("/test/jcr");
when(mockNode.getParent()).thenReturn(mockParent);
Node mockChildNode = mock(Node.class);
when(mockChildNode.getName()).thenReturn("some-name");
when(mockChildNode.getPath()).thenReturn("/test/jcr/1","/test/jcr/2","/test/jcr/3","/test/jcr/4","/test/jcr/5");
NodeIterator mockIterator = mock(NodeIterator.class);
when(mockIterator.hasNext()).thenReturn(true, true, true, true, true, false);
when(mockIterator.nextNode()).thenReturn(mockChildNode);
when(mockNode.getNodes()).thenReturn(mockIterator);
Model actual = JcrRdfTools.getJcrTreeModel(testSubjects, mockNode, 0, 0);
assertEquals(5*2 + 1, actual.size());
}
@Test
public void shouldIncludeFullChildNodeInformationInsideWindow() throws RepositoryException {
Node mockParent = mock(Node.class);
when(mockParent.getPath()).thenReturn("/test");
when(mockNode.getPath()).thenReturn("/test/jcr");
when(mockNode.getParent()).thenReturn(mockParent);
Node mockChildNode = mock(Node.class);
when(mockChildNode.getName()).thenReturn("some-name");
when(mockChildNode.getPath()).thenReturn("/test/jcr/1","/test/jcr/4","/test/jcr/5");
Node mockFullChildNode = mock(Node.class);
when(mockFullChildNode.getName()).thenReturn("some-other-name");
when(mockFullChildNode.getPath()).thenReturn("/test/jcr/2", "/test/jcr/3");
PropertyIterator mockProperties = mock(PropertyIterator.class);
when(mockFullChildNode.getProperties()).thenReturn(mockProperties);
when(mockProperties.hasNext()).thenReturn(false);
NodeIterator mockIterator = mock(NodeIterator.class);
when(mockIterator.hasNext()).thenReturn(true, true, true, true, true, false);
when(mockIterator.nextNode()).thenReturn(mockChildNode, mockFullChildNode, mockFullChildNode,mockChildNode, mockChildNode);
when(mockNode.getNodes()).thenReturn(mockIterator);
Model actual = JcrRdfTools.getJcrTreeModel(testSubjects, mockNode, 1, 2);
assertEquals(5*2 + 1, actual.size());
verify(mockChildNode, never()).getProperties();
}
@Test
public void shouldMapRdfValuesToJcrPropertyValues()
throws RepositoryException {
final ValueFactory mockValueFactory = mock(ValueFactory.class);
@SuppressWarnings("unchecked")
final Function<Node, ValueFactory> mockValueFactoryFunc =
mock(Function.class);
when(mockValueFactoryFunc.apply(mockNode)).thenReturn(mockValueFactory);
final Function<Node, ValueFactory> holdValueFactory =
FedoraTypesUtils.getValueFactory;
FedoraTypesUtils.getValueFactory = mockValueFactoryFunc;
try {
RDFNode n = ResourceFactory.createResource("info:fedora/abc");
// node references
when(mockSession.getNode("/abc")).thenReturn(mockNode);
JcrRdfTools.createValue(mockNode, n, PropertyType.REFERENCE);
JcrRdfTools.createValue(mockNode, n, PropertyType.WEAKREFERENCE);
verify(mockValueFactory, times(2)).createValue(mockNode);
// uris
JcrRdfTools.createValue(mockNode, n, PropertyType.UNDEFINED);
verify(mockValueFactory).createValue("info:fedora/abc",
PropertyType.URI);
// other random resources
n = ResourceFactory.createResource();
JcrRdfTools.createValue(mockNode, n, 0);
verify(mockValueFactory).createValue(n.toString(),
PropertyType.UNDEFINED);
// undeclared types, but infer them from rdf types
n = ResourceFactory.createTypedLiteral(true);
JcrRdfTools.createValue(mockNode, n, 0);
verify(mockValueFactory).createValue(true);
n = ResourceFactory.createTypedLiteral("1", XSDDatatype.XSDbyte);
JcrRdfTools.createValue(mockNode, n, 0);
verify(mockValueFactory).createValue((byte) 1);
n = ResourceFactory.createTypedLiteral((double) 2);
JcrRdfTools.createValue(mockNode, n, 0);
verify(mockValueFactory).createValue((double) 2);
n = ResourceFactory.createTypedLiteral((float) 3);
JcrRdfTools.createValue(mockNode, n, 0);
verify(mockValueFactory).createValue((float) 3);
n = ResourceFactory.createTypedLiteral(4);
JcrRdfTools.createValue(mockNode, n, 0);
verify(mockValueFactory).createValue(4);
n = ResourceFactory.createTypedLiteral("5", XSDDatatype.XSDlong);
JcrRdfTools.createValue(mockNode, n, 0);
verify(mockValueFactory).createValue(5);
n = ResourceFactory.createTypedLiteral("6", XSDDatatype.XSDshort);
JcrRdfTools.createValue(mockNode, n, 0);
verify(mockValueFactory).createValue((short) 6);
final Calendar calendar = Calendar.getInstance();
n = ResourceFactory.createTypedLiteral(calendar);
JcrRdfTools.createValue(mockNode, n, 0);
verify(mockValueFactory).createValue(any(Calendar.class));
n = ResourceFactory.createTypedLiteral("string");
JcrRdfTools.createValue(mockNode, n, 0);
verify(mockValueFactory).createValue("string", PropertyType.STRING);
n = ResourceFactory.createTypedLiteral("string");
JcrRdfTools.createValue(mockNode, n, PropertyType.NAME);
verify(mockValueFactory).createValue("string", PropertyType.NAME);
} finally {
FedoraTypesUtils.getValueFactory = holdValueFactory;
}
}
@Test
public void shouldAddPropertiesToModel() throws RepositoryException {
final javax.jcr.Property mockProperty = mock(javax.jcr.Property.class);
final Property mockPredicate = mock(Property.class);
@SuppressWarnings("unchecked")
final Function<javax.jcr.Property, com.hp.hpl.jena.rdf.model.Property> mockPredicateFactoryFunc =
mock(Function.class);
when(mockPredicateFactoryFunc.apply(mockProperty)).thenReturn(
mockPredicate);
final Function<javax.jcr.Property, com.hp.hpl.jena.rdf.model.Property> holdPredicate =
FedoraTypesUtils.getPredicateForProperty;
FedoraTypesUtils.getPredicateForProperty = mockPredicateFactoryFunc;
try {
final Resource mockSubject = mock(Resource.class);
final Model mockModel = mock(Model.class);
final Value mockValue = mock(Value.class);
when(mockValue.getString()).thenReturn("");
when(mockProperty.isMultiple()).thenReturn(false);
when(mockProperty.getValue()).thenReturn(mockValue);
JcrRdfTools
.addPropertyToModel(mockSubject, mockModel, mockProperty);
verify(mockModel).add(mockSubject, mockPredicate, "");
} finally {
FedoraTypesUtils.getPredicateForProperty = holdPredicate;
}
}
@Test
public void shouldAddMultivaluedPropertiesToModel()
throws RepositoryException {
final javax.jcr.Property mockProperty = mock(javax.jcr.Property.class);
final Property mockPredicate = mock(Property.class);
@SuppressWarnings("unchecked")
final Function<javax.jcr.Property, com.hp.hpl.jena.rdf.model.Property> mockPredicateFactoryFunc =
mock(Function.class);
when(mockPredicateFactoryFunc.apply(mockProperty)).thenReturn(
mockPredicate);
final Function<javax.jcr.Property, com.hp.hpl.jena.rdf.model.Property> holdPredicate =
FedoraTypesUtils.getPredicateForProperty;
FedoraTypesUtils.getPredicateForProperty = mockPredicateFactoryFunc;
try {
final Resource mockSubject = mock(Resource.class);
final Model mockModel = mock(Model.class);
final Value mockValue = mock(Value.class);
when(mockValue.getString()).thenReturn("1");
final Value mockValue2 = mock(Value.class);
when(mockValue2.getString()).thenReturn("2");
when(mockProperty.isMultiple()).thenReturn(true);
when(mockProperty.getValues()).thenReturn(
Arrays.asList(mockValue, mockValue2).toArray(new Value[2]));
JcrRdfTools
.addPropertyToModel(mockSubject, mockModel, mockProperty);
verify(mockModel).add(mockSubject, mockPredicate, "1");
verify(mockModel).add(mockSubject, mockPredicate, "2");
} finally {
FedoraTypesUtils.getPredicateForProperty = holdPredicate;
}
}
@Test
public void shouldMapJcrTypesToRdfDataTypes() throws RepositoryException {
final javax.jcr.Property mockProperty = mock(javax.jcr.Property.class);
final Resource mockSubject = ResourceFactory.createResource("some-resource-uri");
final Model mockModel = ModelFactory.createDefaultModel();
final Property mockPredicate = mockModel.createProperty("some-predicate-uri");
@SuppressWarnings("unchecked")
final Function<javax.jcr.Property, com.hp.hpl.jena.rdf.model.Property> mockPredicateFactoryFunc =
mock(Function.class);
when(mockPredicateFactoryFunc.apply(mockProperty)).thenReturn(
mockPredicate);
final Function<javax.jcr.Property, com.hp.hpl.jena.rdf.model.Property> holdPredicate =
FedoraTypesUtils.getPredicateForProperty;
FedoraTypesUtils.getPredicateForProperty = mockPredicateFactoryFunc;
try {
Value mockValue;
mockValue = mock(Value.class);
when(mockValue.getType()).thenReturn(PropertyType.BOOLEAN);
when(mockValue.getBoolean()).thenReturn(true);
JcrRdfTools.addPropertyToModel(mockSubject, mockModel, mockProperty, mockValue);
assertTrue(mockModel.contains(mockSubject, mockPredicate, ResourceFactory.createTypedLiteral(true)));
mockValue = mock(Value.class);
Calendar mockCalendar = Calendar.getInstance();
when(mockValue.getType()).thenReturn(PropertyType.DATE);
when(mockValue.getDate()).thenReturn(mockCalendar);
JcrRdfTools.addPropertyToModel(mockSubject, mockModel, mockProperty, mockValue);
assertTrue(mockModel.contains(mockSubject, mockPredicate, ResourceFactory.createTypedLiteral(mockCalendar)));
mockValue = mock(Value.class);
when(mockValue.getType()).thenReturn(PropertyType.DECIMAL);
when(mockValue.getDecimal()).thenReturn(BigDecimal.valueOf(0.0));
JcrRdfTools.addPropertyToModel(mockSubject, mockModel, mockProperty, mockValue);
assertTrue(mockModel.contains(mockSubject, mockPredicate, ResourceFactory.createTypedLiteral(BigDecimal.valueOf(0.0))));
mockValue = mock(Value.class);
when(mockValue.getType()).thenReturn(PropertyType.DOUBLE);
when(mockValue.getDouble()).thenReturn((double)0);
JcrRdfTools.addPropertyToModel(mockSubject, mockModel, mockProperty, mockValue);
assertTrue(mockModel.contains(mockSubject, mockPredicate, ResourceFactory.createTypedLiteral((double)0)));
mockValue = mock(Value.class);
when(mockValue.getType()).thenReturn(PropertyType.LONG);
when(mockValue.getLong()).thenReturn(0L);
JcrRdfTools.addPropertyToModel(mockSubject, mockModel, mockProperty, mockValue);
assertTrue(mockModel.contains(mockSubject, mockPredicate, ResourceFactory.createTypedLiteral(0L)));
mockValue = mock(Value.class);
when(mockValue.getType()).thenReturn(PropertyType.STRING);
when(mockValue.getString()).thenReturn("XYZ");
JcrRdfTools.addPropertyToModel(mockSubject, mockModel, mockProperty, mockValue);
assertTrue(mockModel.contains(mockSubject, mockPredicate, ResourceFactory.createTypedLiteral("XYZ")));
mockValue = mock(Value.class);
when(mockValue.getType()).thenReturn(PropertyType.URI);
when(mockValue.getString()).thenReturn("info:fedora");
JcrRdfTools.addPropertyToModel(mockSubject, mockModel,
mockProperty, mockValue);
assertTrue(mockModel.contains(mockSubject, mockPredicate, ResourceFactory.createResource("info:fedora")));
mockValue = mock(Value.class);
when(mockProperty.getSession()).thenReturn(mockSession);
when(mockSession.getNodeByIdentifier("uuid")).thenReturn(mockNode);
when(mockNode.getPath()).thenReturn("/abc");
when(mockValue.getType()).thenReturn(PropertyType.REFERENCE);
when(mockValue.getString()).thenReturn("uuid");
JcrRdfTools.addPropertyToModel(mockSubject, mockModel,
mockProperty, mockValue);
assertTrue(mockModel.contains(mockSubject, mockPredicate, ResourceFactory.createResource("info:fedora/abc")));
mockValue = mock(Value.class);
when(mockValue.getType()).thenReturn(PropertyType.WEAKREFERENCE);
when(mockValue.getString()).thenReturn("uuid");
when(mockNode.getPath()).thenReturn("/def");
JcrRdfTools.addPropertyToModel(mockSubject, mockModel,
mockProperty, mockValue);
assertTrue(mockModel.contains(mockSubject, mockPredicate, ResourceFactory.createResource("info:fedora/def")));
mockValue = mock(Value.class);
when(mockValue.getType()).thenReturn(PropertyType.PATH);
when(mockValue.getString()).thenReturn("/ghi");
JcrRdfTools.addPropertyToModel(mockSubject, mockModel,
mockProperty, mockValue);
assertTrue(mockModel.contains(mockSubject, mockPredicate, ResourceFactory.createResource("info:fedora/ghi")));
} finally {
FedoraTypesUtils.getPredicateForProperty = holdPredicate;
}
}
@Test
@Ignore
public void testJcrNodeContent() throws RepositoryException {
final NodeType nodeType = mock(NodeType.class);
when(mockNode.getPrimaryNodeType()).thenReturn(nodeType);
when(mockNode.getPrimaryNodeType().getName()).thenReturn("");
PropertyIterator mockProperties = mock(PropertyIterator.class);
when(mockProperties.hasNext()).thenReturn(false);
when(mockNode.getProperties()).thenReturn(mockProperties);
when(mockNode.getPath()).thenReturn("/path/to/node");
NodeIterator mockIterator = mock(NodeIterator.class);
when(mockIterator.hasNext()).thenReturn(false);
when(mockNode.getNodes()).thenReturn(mockIterator);
Node mockContent = mock(Node.class);
when(mockContent.getPath()).thenReturn("/path/to/node/content");
when(mockContent.getProperties()).thenReturn(mockProperties);
when(mockContent.getSession()).thenReturn(mockSession);
when(mockNode.hasNode(JcrConstants.JCR_CONTENT)).thenReturn(true);
when(mockNode.getNode(JcrConstants.JCR_CONTENT)).thenReturn(mockContent);
Model model = JcrRdfTools.getJcrPropertiesModel(testSubjects, mockNode);
assertTrue(model != null);
}
@Test
public void testJcrNodeIteratorModel() throws RepositoryException {
Resource mockResource = mock(Resource.class);
NodeIterator mockIterator = mock(NodeIterator.class);
when(mockIterator.hasNext()).thenReturn(false);
final Model model = JcrRdfTools.getJcrNodeIteratorModel(testSubjects, mockIterator, mockResource);
assertTrue(model != null);
}
@Test
public void testJcrNodeIteratorAddsPredicatesForEachNode() throws RepositoryException {
Resource mockResource = ResourceFactory.createResource("info:fedora/search/resource");
Node mockNode1 = mock(Node.class);
Node mockNode2 = mock(Node.class);
Node mockNode3 = mock(Node.class);
PropertyIterator mockProperties = mock(PropertyIterator.class);
when(mockProperties.hasNext()).thenReturn(false);
when(mockNode1.getProperties()).thenReturn(mockProperties);
when(mockNode1.getSession()).thenReturn(mockSession);
when(mockNode1.getPath()).thenReturn("/path/to/first/node");
when(mockNode2.getPath()).thenReturn("/second/path/to/node");
when(mockNode3.getPath()).thenReturn("/third/path/to/node");
when(mockNode1.getProperties()).thenReturn(mockProperties);
when(mockNode2.getProperties()).thenReturn(mockProperties);
when(mockNode3.getProperties()).thenReturn(mockProperties);
Iterator<Node> mockIterator = Arrays.asList(mockNode1, mockNode2, mockNode3).iterator();
final Model model = JcrRdfTools.getJcrNodeIteratorModel(testSubjects, mockIterator, mockResource);
assertEquals(3, model.listObjectsOfProperty(RdfLexicon.HAS_MEMBER_OF_RESULT).toSet().size());
}
@Test
public void testGetFixityResultsModel() throws RepositoryException, URISyntaxException {
LowLevelCacheEntry mockEntry = mock(LowLevelCacheEntry.class);
when(mockEntry.getExternalIdentifier()).thenReturn("xyz");
final FixityResult mockResult = new FixityResult(mockEntry, 123, new URI("abc"));
mockResult.status.add(FixityResult.FixityState.BAD_CHECKSUM);
mockResult.status.add(FixityResult.FixityState.BAD_SIZE);
final List<FixityResult> mockBlobs = Arrays.asList(mockResult);
when(mockNode.getPath()).thenReturn("/path/to/node");
PropertyIterator mockProperties = mock(PropertyIterator.class);
when(mockProperties.hasNext()).thenReturn(false);
when(mockNode.getProperties()).thenReturn(mockProperties);
final Model fixityResultsModel = JcrRdfTools.getFixityResultsModel(testSubjects, mockNode, mockBlobs);
LOGGER.info("Got graph {}", fixityResultsModel);
GraphStore gs = GraphStoreFactory.create(fixityResultsModel);
assertTrue(gs.contains(com.hp.hpl.jena.graph.Node.ANY,
com.hp.hpl.jena.graph.Node.ANY,
RdfLexicon.IS_FIXITY_RESULT_OF.asNode(),
ResourceFactory.createResource("info:fedora/path/to/node").asNode()));
assertTrue(gs.contains(com.hp.hpl.jena.graph.Node.ANY,
com.hp.hpl.jena.graph.Node.ANY,
RdfLexicon.HAS_COMPUTED_CHECKSUM.asNode(),
ResourceFactory.createResource("abc").asNode()));
assertTrue(gs.contains(com.hp.hpl.jena.graph.Node.ANY,
com.hp.hpl.jena.graph.Node.ANY,
RdfLexicon.HAS_COMPUTED_SIZE.asNode(),
ResourceFactory.createTypedLiteral(123).asNode()));
}
@Test
public void testGetJcrNamespaceModel() throws Exception {
final Model jcrNamespaceModel = JcrRdfTools.getJcrNamespaceModel(mockSession);
assertTrue(jcrNamespaceModel.contains(ResourceFactory.createResource("info:fedora/fedora-system:def/internal#"), RdfLexicon.HAS_NAMESPACE_PREFIX, "fedora-internal"));
assertTrue(jcrNamespaceModel.contains(ResourceFactory.createResource("registered-uri#"), RdfLexicon.HAS_NAMESPACE_PREFIX, "some-prefix"));
}
@Test
public void testGetJcrVersionsModel() throws Exception {
when(mockNode.getPath()).thenReturn("/test/jcr");
VersionManager mockVersionManager = mock(VersionManager.class);
VersionHistory mockVersionHistory = mock(VersionHistory.class);
when(mockVersionManager.getVersionHistory(mockNode.getPath())).thenReturn(mockVersionHistory);
VersionIterator mockVersionIterator = mock(VersionIterator.class);
when(mockVersionIterator.hasNext()).thenReturn(true, false);
Version mockVersion = mock(Version.class);
Node mockFrozenNode = mock(Node.class);
when(mockFrozenNode.getPath()).thenReturn("/jcr:system/versions/test/jcr");
when(mockVersion.getFrozenNode()).thenReturn(mockFrozenNode);
when(mockVersionIterator.nextVersion()).thenReturn(mockVersion);
when(mockVersionHistory.getAllVersions()).thenReturn(mockVersionIterator);
when(mockWorkspace.getVersionManager()).thenReturn(mockVersionManager);
when(mockVersionHistory.getVersionLabels(mockVersion)).thenReturn(new String[] { "abc" });
PropertyIterator mockProperties = mock(PropertyIterator.class);
when(mockProperties.hasNext()).thenReturn(false);
when(mockFrozenNode.getProperties()).thenReturn(mockProperties);
final Model actual = JcrRdfTools.getJcrVersionsModel(testSubjects, mockNode);
assertTrue(actual.contains(testSubjects.getGraphSubject(mockNode), RdfLexicon.HAS_VERSION, testSubjects.getGraphSubject(mockFrozenNode)));
assertTrue(actual.contains(testSubjects.getGraphSubject(mockFrozenNode), RdfLexicon.HAS_VERSION_LABEL, actual.createLiteral("abc")));
}
private void mockNamespaceRegistry() throws RepositoryException {
PowerMockito.mockStatic(NamespaceTools.class);
mockNsRegistry = mock(NamespaceRegistry.class);
when(mockNsRegistry.isRegisteredUri("registered-uri
.thenReturn(true);
when(mockNsRegistry.isRegisteredUri("not-registered-uri#")).thenReturn(
false);
when(mockNsRegistry.isRegisteredUri("http:
.thenReturn(true);
when(mockNsRegistry.getPrefix("http:
.thenReturn("jcr");
when(mockNsRegistry.getPrefix("registered-uri#")).thenReturn(
"some-prefix");
when(mockNsRegistry.getURI("jcr")).thenReturn("http:
when(mockNsRegistry.getURI("some-prefix")).thenReturn("registered-uri
when(mockNsRegistry.getPrefixes()).thenReturn(new String[] { "jcr", "some-prefix"});
when(NamespaceTools.getNamespaceRegistry(mockSession)).thenReturn(mockNsRegistry);
when(NamespaceTools.getNamespaceRegistry(mockNode)).thenReturn(
mockNsRegistry);
}
}
|
package com.datatorrent.flume.storage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.flume.Event;
import org.apache.flume.event.EventBuilder;
import com.datatorrent.api.StreamCodec;
import com.datatorrent.common.util.Slice;
/**
* <p>EventCodec class.</p>
*
* @author Chetan Narsude <chetan@datatorrent.com>
* @since 0.9.4
*/
public class EventCodec implements StreamCodec<Event>
{
private transient final Kryo kryo;
public EventCodec()
{
this.kryo = new Kryo();
this.kryo.setClassLoader(Thread.currentThread().getContextClassLoader());
}
@Override
public Object fromByteArray(Slice fragment)
{
ByteArrayInputStream is = new ByteArrayInputStream(fragment.buffer, fragment.offset, fragment.length);
Input input = new Input(is);
@SuppressWarnings("unchecked")
HashMap<String, String> headers = kryo.readObjectOrNull(input, HashMap.class);
byte[] body = kryo.readObjectOrNull(input, byte[].class);
return EventBuilder.withBody(body, headers);
}
@Override
public Slice toByteArray(Event event)
{
ByteArrayOutputStream os = new ByteArrayOutputStream();
Output output = new Output(os);
Map<String, String> headers = event.getHeaders();
if (headers != null && headers.getClass() != HashMap.class) {
HashMap<String, String> tmp = new HashMap<String, String>(headers.size());
tmp.putAll(headers);
headers = tmp;
}
kryo.writeObjectOrNull(output, headers, HashMap.class);
kryo.writeObjectOrNull(output, event.getBody(), byte[].class);
output.flush();
final byte[] bytes = os.toByteArray();
return new Slice(bytes, 0, bytes.length);
}
@Override
public int getPartition(Event o)
{
return o.hashCode();
}
private static final Logger logger = LoggerFactory.getLogger(EventCodec.class);
}
|
package fr.lip6.move.pnml2bpn;
import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.LoggerContext;
import fr.lip6.move.pnml2bpn.exceptions.PNMLImportExportException;
import fr.lip6.move.pnml2bpn.export.PNML2BPNFactory;
import fr.lip6.move.pnml2bpn.export.PNMLExporter;
/**
* Main class for command-line invocation.
*
* @author lom
*
*/
public final class MainPNML2BPN {
public static final String NL = "\n";
public static final String COLWS = ": ";
public static final String WSDASH = " -";
public static final String VERSION = "1.2.0";
private static final String BPN_EXT = ".bpn";
private static final String PNML_EXT = ".pnml";
private static final String PNML2BPN_DEBUG = "PNML2BPN_DEBUG";
private static final String CAMI_TMP_KEEP = "cami.tmp.keep";
/**
* Force BPN Generation works by default for the case where bounds checking is disabled.
*/
private static final String FORCE_BPN_GENERATION = "force.bpn.generation";
/**
* Bounds checking property.
*/
private static final String BOUNDS_CHECKING = "bounds.checking";
/**
* Remove transitions of unsafe arcs (incoming or outgoing)
*/
private static final String REMOVE_TRANS_UNSAFE_ARCS = "remove.unsafe.trans";
/**
* Force generation of unsafe nets, where it is clearly checked that
* at least one initial has more than 1 token or the inscription of an arc
* is valued to more than 1.
*/
private static final String GENERATE_UNSAFE = "generate.unsafe";
private static StringBuilder signatureMesg;
private static boolean isDebug;
private static List<String> pathDest;
private static List<String> pathSrc;
private static PNMLFilenameFilter pff;
private static DirFileFilter dff;
private static boolean isOption;
private static boolean isCamiTmpDelete;
private static boolean isForceBPNGen;
private static boolean isBoundsChecking;
private static boolean isRemoveTransUnsafeArcs;
private static boolean isGenerateUnsafe;
private MainPNML2BPN() {
super();
}
/**
* @param args
*/
public static void main(String[] args) {
long startTime = System.nanoTime();
org.slf4j.Logger myLog = LoggerFactory.getLogger(MainPNML2BPN.class
.getCanonicalName());
StringBuilder msg = new StringBuilder();
if (args.length < 1) {
myLog.error("At least the path to one PNML P/T file is expected. You may provide a file, a directory, or a mix of several of these.");
return;
}
// Debug mode?
checkDebugMode(myLog, msg);
// Keep Cami property
checkCamiKeepingMode(myLog, msg);
// Force BPN generation property
checkForceBPNGenMode(myLog, msg);
// Bounds checking property
checkBoundsCheckingMode(myLog, msg);
// Generate structural.bpn (case of forced generation in case of unsafe initial
// places or arcs
checkGenerateUnsafeMode(myLog, msg);
// Remove unsafe arcs?
checkRemoveTransUnsafeArcsMode(myLog, msg);
try {
extractSrcDestPaths(args);
} catch (IOException e1) {
myLog.error("Could not successfully extract all source files paths. See log.");
myLog.error(e1.getMessage());
if (MainPNML2BPN.isDebug) {
e1.printStackTrace();
}
}
//long startTime = System.nanoTime();
initSignatureMessage();
PNMLExporter pe = new PNML2BPNFactory().createExporter();
org.slf4j.Logger jr = LoggerFactory.getLogger(pe.getClass()
.getCanonicalName());
// TODO : optimize with threads
boolean error = false;
for (int i = 0; i < pathSrc.size(); i++) {
try {
pe.exportPNML(new File(pathSrc.get(i)),
new File(pathDest.get(i)), jr);
myLog.info(signatureMesg.toString());
signatureMesg.delete(0, signatureMesg.length());
} catch (PNMLImportExportException | InterruptedException
| IOException e) {
myLog.error(e.getMessage());
MainPNML2BPN.printStackTrace(e);
error |= true;
}
}
if (!error) {
msg.append("Finished successfully.");
myLog.info(msg.toString());
} else {
msg.append("Finished in error.");
if (!MainPNML2BPN.isDebug) {
msg.append(
" Activate debug mode to print stacktraces, like so: export ")
.append(PNML2BPN_DEBUG).append("=true");
}
myLog.error(msg.toString());
}
long endTime = System.nanoTime();
myLog.info("PNML to BPN took {} seconds.",
(endTime - startTime) / 1.0e9);
LoggerContext loggerContext = (LoggerContext) LoggerFactory
.getILoggerFactory();
loggerContext.stop();
if (error) {
System.exit(-1);
}
}
/**
* Initialises signature message.
*/
private static void initSignatureMessage() {
signatureMesg = new StringBuilder();
signatureMesg.append(COLWS).append("generated by pnml2bpn version ").append(VERSION);
if (isOption) {
signatureMesg.append(" with options ");
if (isForceBPNGen) {
signatureMesg.append(WSDASH).append(FORCE_BPN_GENERATION);
}
if (!isBoundsChecking) {
signatureMesg.append(WSDASH).append(BOUNDS_CHECKING);
}
if (isGenerateUnsafe) {
signatureMesg.append(WSDASH).append(GENERATE_UNSAFE);
}
if (isRemoveTransUnsafeArcs) {
signatureMesg.append(WSDASH).append(REMOVE_TRANS_UNSAFE_ARCS);
}
if (!isCamiTmpDelete) {
signatureMesg.append(WSDASH).append(CAMI_TMP_KEEP);
}
} else {
signatureMesg.append(" with default values for options");
}
}
private static void checkGenerateUnsafeMode(Logger myLog, StringBuilder msg) {
String genUnsafe = System.getProperty(GENERATE_UNSAFE);
if (genUnsafe != null && Boolean.valueOf(genUnsafe)) {
isGenerateUnsafe = true;
isOption = true;
myLog.warn("Generation of unsafe (structural) BPN enabled.");
} else if (genUnsafe == null) {
isGenerateUnsafe = false;
msg.append(
"Generation of unsafe BPN (structural only) not set. Default is false. If you want to "
+ "generate unsafe (structural) BPN, then invoke this program with ")
.append(GENERATE_UNSAFE)
.append(" property like so: java -D")
.append(GENERATE_UNSAFE)
.append("=true [JVM OPTIONS] -jar ...");
myLog.warn(msg.toString());
msg.delete(0, msg.length());
} else {
isGenerateUnsafe = false;
myLog.info("Generation of unsafe (structural) BPN disabled.");
}
}
private static void checkRemoveTransUnsafeArcsMode(Logger myLog,
StringBuilder msg) {
String removeua = System.getProperty(REMOVE_TRANS_UNSAFE_ARCS);
if (removeua != null && Boolean.valueOf(removeua)) {
isRemoveTransUnsafeArcs = true;
isOption = true;
myLog.warn("Removal of transitions connecte to unsafe arcs enabled.");
} else if (removeua == null) {
isRemoveTransUnsafeArcs = false;
msg.append(
"Remove transitions of unsafe arcs not set. Default is false. If you want to "
+ "remove transitions of unsafe arcs, then invoke this program with ")
.append(REMOVE_TRANS_UNSAFE_ARCS)
.append(" property like so: java -D")
.append(REMOVE_TRANS_UNSAFE_ARCS)
.append("=true [JVM OPTIONS] -jar ...");
myLog.warn(msg.toString());
msg.delete(0, msg.length());
} else {
isRemoveTransUnsafeArcs = false;
myLog.warn("Remove transitions of unsafe arcs disabled.");
}
}
private static void checkBoundsCheckingMode(org.slf4j.Logger myLog,
StringBuilder msg) {
String boundsChecking = System.getProperty(BOUNDS_CHECKING);
if (boundsChecking != null && Boolean.valueOf(boundsChecking)) {
isBoundsChecking = true;
myLog.warn("Bounds checking enabled.");
} else if (boundsChecking == null) {
isBoundsChecking = true;
msg.append(
"Bounds checking not set. Default is true. If you want to disable bounds checking, then invoke this program with ")
.append(BOUNDS_CHECKING)
.append(" property like so: java -D")
.append(BOUNDS_CHECKING)
.append("=false [JVM OPTIONS] -jar ...");
myLog.warn(msg.toString());
msg.delete(0, msg.length());
} else {
isBoundsChecking = false;
isOption = true;
myLog.warn("Bounds checking disabled.");
}
}
/**
* @param myLog
* @param msg
*/
private static void checkForceBPNGenMode(org.slf4j.Logger myLog,
StringBuilder msg) {
String forceBpnGen = System.getProperty(FORCE_BPN_GENERATION);
if (forceBpnGen != null && Boolean.valueOf(forceBpnGen)) {
isForceBPNGen = true;
isOption = true;
myLog.warn("Force BPN generation enabled.");
} else {
isForceBPNGen = false;
msg.append(
"Forcing BPN generation not set. Default is false. If you want to force BPN generation for non 1-Safe nets, then invoke this program with ")
.append(FORCE_BPN_GENERATION)
.append(" property like so: java -D")
.append(FORCE_BPN_GENERATION)
.append("=true [JVM OPTIONS] -jar ...");
myLog.warn(msg.toString());
msg.delete(0, msg.length());
}
}
/**
* @param myLog
* @param msg
*/
private static void checkCamiKeepingMode(org.slf4j.Logger myLog,
StringBuilder msg) {
String keep = System.getProperty(CAMI_TMP_KEEP);
if (keep != null && Boolean.valueOf(keep)) {
isCamiTmpDelete = false;
isOption = true;
myLog.warn("Keep temporary Cami enabled.");
} else {
isCamiTmpDelete = true;
msg.append(
"Keeping temporary Cami file property not set. If you want to keep temporary Cami file then invoke this program with ")
.append(CAMI_TMP_KEEP)
.append(" property like so: java -D")
.append(CAMI_TMP_KEEP)
.append("=true [JVM OPTIONS] -jar ...");
myLog.warn(msg.toString());
msg.delete(0, msg.length());
}
}
/**
* @param myLog
* @param msg
*/
private static void checkDebugMode(org.slf4j.Logger myLog, StringBuilder msg) {
String debug = System.getenv(PNML2BPN_DEBUG);
if ("true".equalsIgnoreCase(debug)) {
setDebug(true);
} else {
setDebug(false);
msg.append(
"Debug mode not set. If you want to activate the debug mode (print stackstaces in case of errors), then set the ")
.append(PNML2BPN_DEBUG)
.append(" environnement variable like so: export ")
.append(PNML2BPN_DEBUG).append("=true.");
myLog.warn(msg.toString());
msg.delete(0, msg.length());
}
}
/**
* Extracts PNML files (scans directories recursively) from command-line
* arguments.
*
* @param args
* @throws IOException
*/
private static void extractSrcDestPaths(String[] args) throws IOException {
pathDest = new ArrayList<String>();
pathSrc = new ArrayList<String>();
File srcf;
File[] srcFiles;
pff = new PNMLFilenameFilter();
dff = new DirFileFilter();
for (String s : args) {
srcf = new File(s);
if (srcf.isFile()) {
pathSrc.add(s);
pathDest.add(s.replaceAll(PNML_EXT, BPN_EXT));
} else if (srcf.isDirectory()) {
srcFiles = extractSrcFiles(srcf, pff, dff);
for (File f : srcFiles) {
pathSrc.add(f.getCanonicalPath());
pathDest.add(f.getCanonicalPath().replaceAll(PNML_EXT,
BPN_EXT));
}
}
}
}
private static File[] extractSrcFiles(File srcf, PNMLFilenameFilter pff,
DirFileFilter dff) {
List<File> res = new ArrayList<File>();
// filter PNML files
File[] pfiles = srcf.listFiles(pff);
res.addAll(Arrays.asList(pfiles));
// filter directories
pfiles = srcf.listFiles(dff);
for (File f : pfiles) {
res.addAll(Arrays.asList(extractSrcFiles(f, pff, dff)));
}
return res.toArray(new File[0]);
}
private static final class PNMLFilenameFilter implements FilenameFilter {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(PNML_EXT);
}
}
private static final class DirFileFilter implements FileFilter {
@Override
public boolean accept(File pathname) {
return pathname.isDirectory();
}
}
/**
* Returns true if debug mode is set.
*
* @return
*/
public static boolean isDebug() {
return isDebug;
}
/**
* Sets the debug mode according to parameter: enable (true) or disable
* (false).
*
* @param isDebug
*/
public static synchronized void setDebug(boolean isDebug) {
MainPNML2BPN.isDebug = isDebug;
}
/**
* Returns true if temporary Cami file should be deleted, false otherwise.
*
* @return
*/
public static synchronized boolean isCamiTmpDelete() {
return isCamiTmpDelete;
}
/**
* Returns true if BPN generation is forced, even if the net is not 1-safe.
*
* @return
*/
public static synchronized boolean isForceBPNGen() {
return isForceBPNGen;
}
/**
* Returns true if bounds checking is enabled (default), false otherwise.
*
* @return
*/
public static synchronized boolean isBoundsChecking() {
return isBoundsChecking;
}
/**
* Returns true if user has asked for the removal of transitions
* of unsafe arcs (incoming or outgoing).
* @return
*/
public static synchronized boolean isRemoveTransUnsafeArcs() {
return isRemoveTransUnsafeArcs;
}
/**
* Returns true if user has asked for the generation of unsafe
* BPN (structural.bpn) in the case of unsafe initial place(s) or arc(s).
* @return
*/
public static synchronized boolean isGenerateUnsafe() {
return isGenerateUnsafe;
}
public static synchronized void appendMesgLineToSignature(String msg) {
signatureMesg.append(NL).append(COLWS).append(msg);
}
/**
* Prints the stack trace of the exception passed as parameter.
*
* @param e
*/
public static synchronized void printStackTrace(Exception e) {
if (MainPNML2BPN.isDebug) {
e.printStackTrace();
}
}
}
|
package org.jfree.chart.title;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import org.jfree.chart.block.AbstractBlock;
import org.jfree.chart.block.Block;
import org.jfree.chart.block.LengthConstraintType;
import org.jfree.chart.block.RectangleConstraint;
import org.jfree.chart.util.GradientPaintTransformer;
import org.jfree.chart.util.ObjectUtilities;
import org.jfree.chart.util.PaintUtilities;
import org.jfree.chart.util.PublicCloneable;
import org.jfree.chart.util.RectangleAnchor;
import org.jfree.chart.util.SerialUtilities;
import org.jfree.chart.util.ShapeUtilities;
import org.jfree.chart.util.Size2D;
import org.jfree.chart.util.StandardGradientPaintTransformer;
/**
* The graphical item within a legend item.
*/
public class LegendGraphic extends AbstractBlock
implements Block, PublicCloneable {
/**
* A flag that controls whether or not the shape is visible - see also
* lineVisible.
*/
private boolean shapeVisible;
/**
* The shape to display. To allow for accurate positioning, the center
* of the shape should be at (0, 0).
*/
private transient Shape shape;
/**
* Defines the location within the block to which the shape will be aligned.
*/
private RectangleAnchor shapeLocation;
/**
* Defines the point on the shape's bounding rectangle that will be
* aligned to the drawing location when the shape is rendered.
*/
private RectangleAnchor shapeAnchor;
/** A flag that controls whether or not the shape is filled. */
private boolean shapeFilled;
/** The fill paint for the shape. */
private transient Paint fillPaint;
/**
* The fill paint transformer (used if the fillPaint is an instance of
* GradientPaint).
*
* @since 1.0.4
*/
private GradientPaintTransformer fillPaintTransformer;
/** A flag that controls whether or not the shape outline is visible. */
private boolean shapeOutlineVisible;
/** The outline paint for the shape. */
private transient Paint outlinePaint;
/** The outline stroke for the shape. */
private transient Stroke outlineStroke;
/**
* A flag that controls whether or not the line is visible - see also
* shapeVisible.
*/
private boolean lineVisible;
/** The line. */
private transient Shape line;
/** The line stroke. */
private transient Stroke lineStroke;
/** The line paint. */
private transient Paint linePaint;
/**
* Creates a new legend graphic.
*
* @param shape the shape (<code>null</code> not permitted).
* @param fillPaint the fill paint (<code>null</code> not permitted).
*/
public LegendGraphic(Shape shape, Paint fillPaint) {
if (shape == null) {
throw new IllegalArgumentException("Null 'shape' argument.");
}
if (fillPaint == null) {
throw new IllegalArgumentException("Null 'fillPaint' argument.");
}
this.shapeVisible = true;
this.shape = shape;
this.shapeAnchor = RectangleAnchor.CENTER;
this.shapeLocation = RectangleAnchor.CENTER;
this.shapeFilled = true;
this.fillPaint = fillPaint;
this.fillPaintTransformer = new StandardGradientPaintTransformer();
setPadding(2.0, 2.0, 2.0, 2.0);
}
/**
* Returns a flag that controls whether or not the shape
* is visible.
*
* @return A boolean.
*
* @see #setShapeVisible(boolean)
*/
public boolean isShapeVisible() {
return this.shapeVisible;
}
/**
* Sets a flag that controls whether or not the shape is
* visible.
*
* @param visible the flag.
*
* @see #isShapeVisible()
*/
public void setShapeVisible(boolean visible) {
this.shapeVisible = visible;
}
/**
* Returns the shape.
*
* @return The shape.
*
* @see #setShape(Shape)
*/
public Shape getShape() {
return this.shape;
}
/**
* Sets the shape.
*
* @param shape the shape.
*
* @see #getShape()
*/
public void setShape(Shape shape) {
this.shape = shape;
}
/**
* Returns a flag that controls whether or not the shapes
* are filled.
*
* @return A boolean.
*
* @see #setShapeFilled(boolean)
*/
public boolean isShapeFilled() {
return this.shapeFilled;
}
/**
* Sets a flag that controls whether or not the shape is
* filled.
*
* @param filled the flag.
*
* @see #isShapeFilled()
*/
public void setShapeFilled(boolean filled) {
this.shapeFilled = filled;
}
/**
* Returns the paint used to fill the shape.
*
* @return The fill paint.
*
* @see #setFillPaint(Paint)
*/
public Paint getFillPaint() {
return this.fillPaint;
}
/**
* Sets the paint used to fill the shape.
*
* @param paint the paint.
*
* @see #getFillPaint()
*/
public void setFillPaint(Paint paint) {
this.fillPaint = paint;
}
/**
* Returns the transformer used when the fill paint is an instance of
* <code>GradientPaint</code>.
*
* @return The transformer (never <code>null</code>).
*
* @since 1.0.4.
*
* @see #setFillPaintTransformer(GradientPaintTransformer)
*/
public GradientPaintTransformer getFillPaintTransformer() {
return this.fillPaintTransformer;
}
/**
* Sets the transformer used when the fill paint is an instance of
* <code>GradientPaint</code>.
*
* @param transformer the transformer (<code>null</code> not permitted).
*
* @since 1.0.4
*
* @see #getFillPaintTransformer()
*/
public void setFillPaintTransformer(GradientPaintTransformer transformer) {
if (transformer == null) {
throw new IllegalArgumentException("Null 'transformer' argument.");
}
this.fillPaintTransformer = transformer;
}
/**
* Returns a flag that controls whether the shape outline is visible.
*
* @return A boolean.
*
* @see #setShapeOutlineVisible(boolean)
*/
public boolean isShapeOutlineVisible() {
return this.shapeOutlineVisible;
}
/**
* Sets a flag that controls whether or not the shape outline
* is visible.
*
* @param visible the flag.
*
* @see #isShapeOutlineVisible()
*/
public void setShapeOutlineVisible(boolean visible) {
this.shapeOutlineVisible = visible;
}
/**
* Returns the outline paint.
*
* @return The paint.
*
* @see #setOutlinePaint(Paint)
*/
public Paint getOutlinePaint() {
return this.outlinePaint;
}
/**
* Sets the outline paint.
*
* @param paint the paint.
*
* @see #getOutlinePaint()
*/
public void setOutlinePaint(Paint paint) {
this.outlinePaint = paint;
}
/**
* Returns the outline stroke.
*
* @return The stroke.
*
* @see #setOutlineStroke(Stroke)
*/
public Stroke getOutlineStroke() {
return this.outlineStroke;
}
/**
* Sets the outline stroke.
*
* @param stroke the stroke.
*
* @see #getOutlineStroke()
*/
public void setOutlineStroke(Stroke stroke) {
this.outlineStroke = stroke;
}
/**
* Returns the shape anchor.
*
* @return The shape anchor.
*
* @see #getShapeAnchor()
*/
public RectangleAnchor getShapeAnchor() {
return this.shapeAnchor;
}
/**
* Sets the shape anchor. This defines a point on the shapes bounding
* rectangle that will be used to align the shape to a location.
*
* @param anchor the anchor (<code>null</code> not permitted).
*
* @see #setShapeAnchor(RectangleAnchor)
*/
public void setShapeAnchor(RectangleAnchor anchor) {
if (anchor == null) {
throw new IllegalArgumentException("Null 'anchor' argument.");
}
this.shapeAnchor = anchor;
}
/**
* Returns the shape location.
*
* @return The shape location.
*
* @see #setShapeLocation(RectangleAnchor)
*/
public RectangleAnchor getShapeLocation() {
return this.shapeLocation;
}
/**
* Sets the shape location. This defines a point within the drawing
* area that will be used to align the shape to.
*
* @param location the location (<code>null</code> not permitted).
*
* @see #getShapeLocation()
*/
public void setShapeLocation(RectangleAnchor location) {
if (location == null) {
throw new IllegalArgumentException("Null 'location' argument.");
}
this.shapeLocation = location;
}
/**
* Returns the flag that controls whether or not the line is visible.
*
* @return A boolean.
*
* @see #setLineVisible(boolean)
*/
public boolean isLineVisible() {
return this.lineVisible;
}
/**
* Sets the flag that controls whether or not the line is visible.
*
* @param visible the flag.
*
* @see #isLineVisible()
*/
public void setLineVisible(boolean visible) {
this.lineVisible = visible;
}
/**
* Returns the line centered about (0, 0).
*
* @return The line.
*
* @see #setLine(Shape)
*/
public Shape getLine() {
return this.line;
}
/**
* Sets the line. A Shape is used here, because then you can use Line2D,
* GeneralPath or any other Shape to represent the line.
*
* @param line the line.
*
* @see #getLine()
*/
public void setLine(Shape line) {
this.line = line;
}
/**
* Returns the line paint.
*
* @return The paint.
*
* @see #setLinePaint(Paint)
*/
public Paint getLinePaint() {
return this.linePaint;
}
/**
* Sets the line paint.
*
* @param paint the paint.
*
* @see #getLinePaint()
*/
public void setLinePaint(Paint paint) {
this.linePaint = paint;
}
/**
* Returns the line stroke.
*
* @return The stroke.
*
* @see #setLineStroke(Stroke)
*/
public Stroke getLineStroke() {
return this.lineStroke;
}
/**
* Sets the line stroke.
*
* @param stroke the stroke.
*
* @see #getLineStroke()
*/
public void setLineStroke(Stroke stroke) {
this.lineStroke = stroke;
}
/**
* Arranges the contents of the block, within the given constraints, and
* returns the block size.
*
* @param g2 the graphics device.
* @param constraint the constraint (<code>null</code> not permitted).
*
* @return The block size (in Java2D units, never <code>null</code>).
*/
public Size2D arrange(Graphics2D g2, RectangleConstraint constraint) {
RectangleConstraint contentConstraint = toContentConstraint(constraint);
LengthConstraintType w = contentConstraint.getWidthConstraintType();
LengthConstraintType h = contentConstraint.getHeightConstraintType();
Size2D contentSize = null;
if (w == LengthConstraintType.NONE) {
if (h == LengthConstraintType.NONE) {
contentSize = arrangeNN(g2);
}
else if (h == LengthConstraintType.RANGE) {
throw new RuntimeException("Not yet implemented.");
}
else if (h == LengthConstraintType.FIXED) {
throw new RuntimeException("Not yet implemented.");
}
}
else if (w == LengthConstraintType.RANGE) {
if (h == LengthConstraintType.NONE) {
throw new RuntimeException("Not yet implemented.");
}
else if (h == LengthConstraintType.RANGE) {
throw new RuntimeException("Not yet implemented.");
}
else if (h == LengthConstraintType.FIXED) {
throw new RuntimeException("Not yet implemented.");
}
}
else if (w == LengthConstraintType.FIXED) {
if (h == LengthConstraintType.NONE) {
throw new RuntimeException("Not yet implemented.");
}
else if (h == LengthConstraintType.RANGE) {
throw new RuntimeException("Not yet implemented.");
}
else if (h == LengthConstraintType.FIXED) {
contentSize = new Size2D(
contentConstraint.getWidth(),
contentConstraint.getHeight()
);
}
}
return new Size2D(
calculateTotalWidth(contentSize.getWidth()),
calculateTotalHeight(contentSize.getHeight())
);
}
/**
* Performs the layout with no constraint, so the content size is
* determined by the bounds of the shape and/or line drawn to represent
* the series.
*
* @param g2 the graphics device.
*
* @return The content size.
*/
protected Size2D arrangeNN(Graphics2D g2) {
Rectangle2D contentSize = new Rectangle2D.Double();
if (this.line != null) {
contentSize.setRect(this.line.getBounds2D());
}
if (this.shape != null) {
contentSize = contentSize.createUnion(this.shape.getBounds2D());
}
return new Size2D(contentSize.getWidth(), contentSize.getHeight());
}
/**
* Draws the graphic item within the specified area.
*
* @param g2 the graphics device.
* @param area the area.
*/
public void draw(Graphics2D g2, Rectangle2D area) {
area = trimMargin(area);
drawBorder(g2, area);
area = trimBorder(area);
area = trimPadding(area);
if (this.lineVisible) {
Point2D location = RectangleAnchor.coordinates(area,
this.shapeLocation);
Shape aLine = ShapeUtilities.createTranslatedShape(getLine(),
this.shapeAnchor, location.getX(), location.getY());
g2.setPaint(this.linePaint);
g2.setStroke(this.lineStroke);
g2.draw(aLine);
}
if (this.shapeVisible) {
Point2D location = RectangleAnchor.coordinates(area,
this.shapeLocation);
Shape s = ShapeUtilities.createTranslatedShape(this.shape,
this.shapeAnchor, location.getX(), location.getY());
if (this.shapeFilled) {
Paint p = this.fillPaint;
if (p instanceof GradientPaint) {
GradientPaint gp = (GradientPaint) this.fillPaint;
p = this.fillPaintTransformer.transform(gp, s);
}
g2.setPaint(p);
g2.fill(s);
}
if (this.shapeOutlineVisible) {
g2.setPaint(this.outlinePaint);
g2.setStroke(this.outlineStroke);
g2.draw(s);
}
}
}
/**
* Draws the block within the specified area.
*
* @param g2 the graphics device.
* @param area the area.
* @param params ignored (<code>null</code> permitted).
*
* @return Always <code>null</code>.
*/
public Object draw(Graphics2D g2, Rectangle2D area, Object params) {
draw(g2, area);
return null;
}
/**
* Tests this <code>LegendGraphic</code> instance for equality with an
* arbitrary object.
*
* @param obj the object (<code>null</code> permitted).
*
* @return A boolean.
*/
public boolean equals(Object obj) {
if (!(obj instanceof LegendGraphic)) {
return false;
}
LegendGraphic that = (LegendGraphic) obj;
if (this.shapeVisible != that.shapeVisible) {
return false;
}
if (!ShapeUtilities.equal(this.shape, that.shape)) {
return false;
}
if (this.shapeFilled != that.shapeFilled) {
return false;
}
if (!PaintUtilities.equal(this.fillPaint, that.fillPaint)) {
return false;
}
if (!ObjectUtilities.equal(this.fillPaintTransformer,
that.fillPaintTransformer)) {
return false;
}
if (this.shapeOutlineVisible != that.shapeOutlineVisible) {
return false;
}
if (!PaintUtilities.equal(this.outlinePaint, that.outlinePaint)) {
return false;
}
if (!ObjectUtilities.equal(this.outlineStroke, that.outlineStroke)) {
return false;
}
if (this.shapeAnchor != that.shapeAnchor) {
return false;
}
if (this.shapeLocation != that.shapeLocation) {
return false;
}
if (this.lineVisible != that.lineVisible) {
return false;
}
if (!ShapeUtilities.equal(this.line, that.line)) {
return false;
}
if (!PaintUtilities.equal(this.linePaint, that.linePaint)) {
return false;
}
if (!ObjectUtilities.equal(this.lineStroke, that.lineStroke)) {
return false;
}
return super.equals(obj);
}
/**
* Returns a hash code for this instance.
*
* @return A hash code.
*/
public int hashCode() {
int result = 193;
result = 37 * result + ObjectUtilities.hashCode(this.fillPaint);
// FIXME: use other fields too
return result;
}
/**
* Returns a clone of this <code>LegendGraphic</code> instance.
*
* @return A clone of this <code>LegendGraphic</code> instance.
*
* @throws CloneNotSupportedException if there is a problem cloning.
*/
public Object clone() throws CloneNotSupportedException {
LegendGraphic clone = (LegendGraphic) super.clone();
clone.shape = ShapeUtilities.clone(this.shape);
clone.line = ShapeUtilities.clone(this.line);
return clone;
}
/**
* Provides serialization support.
*
* @param stream the output stream.
*
* @throws IOException if there is an I/O error.
*/
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
SerialUtilities.writeShape(this.shape, stream);
SerialUtilities.writePaint(this.fillPaint, stream);
SerialUtilities.writePaint(this.outlinePaint, stream);
SerialUtilities.writeStroke(this.outlineStroke, stream);
SerialUtilities.writeShape(this.line, stream);
SerialUtilities.writePaint(this.linePaint, stream);
SerialUtilities.writeStroke(this.lineStroke, stream);
}
/**
* Provides serialization support.
*
* @param stream the input stream.
*
* @throws IOException if there is an I/O error.
* @throws ClassNotFoundException if there is a classpath problem.
*/
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
this.shape = SerialUtilities.readShape(stream);
this.fillPaint = SerialUtilities.readPaint(stream);
this.outlinePaint = SerialUtilities.readPaint(stream);
this.outlineStroke = SerialUtilities.readStroke(stream);
this.line = SerialUtilities.readShape(stream);
this.linePaint = SerialUtilities.readPaint(stream);
this.lineStroke = SerialUtilities.readStroke(stream);
}
}
|
package org.searchisko.ftest;
import com.jayway.restassured.http.ContentType;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.junit.InSequence;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import static com.jayway.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
/**
* Integration test for Tasks REST API {@link org.searchisko.api.rest.TaskRestService}
*
* @author Libor Krzyzanek
*/
@RunWith(Arquillian.class)
public class TaskRestServiceTest {
public static final String TASKS_REST_API = DeploymentHelpers.DEFAULT_REST_VERSION + "tasks";
@Deployment(testable = false)
public static WebArchive createDeployment() throws IOException {
return DeploymentHelpers.createDeployment();
}
@ArquillianResource
protected URL context;
@Test
@InSequence(0)
public void assertNotAuthenticated() throws MalformedURLException {
int expStatus = 401;
// GET /tasks/type
given().contentType(ContentType.JSON)
.expect().statusCode(expStatus)
.log().ifStatusCodeMatches(is(not(expStatus)))
.when().get(new URL(context, TASKS_REST_API + "/type").toExternalForm());
// GET /tasks/task
given().contentType(ContentType.JSON)
.expect().statusCode(expStatus)
.log().ifStatusCodeMatches(is(not(expStatus)))
.when().get(new URL(context, TASKS_REST_API + "/task").toExternalForm());
// GET /tasks/taskId
given().contentType(ContentType.JSON)
.expect().statusCode(expStatus)
.log().ifStatusCodeMatches(is(not(expStatus)))
.when().get(new URL(context, TASKS_REST_API + "/task/id").toExternalForm());
// POST /tasks/taskType e.g. reindex_from_persistence
given().contentType(ContentType.JSON)
.body("{\"sys_content_type\" : \"jbossorg_blog\"}")
.expect().statusCode(expStatus)
.log().ifStatusCodeMatches(is(not(expStatus)))
.when().post(new URL(context, TASKS_REST_API + "/task/reindex_from_persistence").toExternalForm());
// DELETE /tasks/task/id e.g. reindex_from_persistence
given().contentType(ContentType.JSON)
.expect().statusCode(expStatus)
.log().ifStatusCodeMatches(is(not(expStatus)))
.when().delete(new URL(context, TASKS_REST_API + "/task/id").toExternalForm());
}
@Test
@InSequence(10)
public void assertGetTasksType() throws MalformedURLException {
// GET /tasks/type
given().contentType(ContentType.JSON)
.auth().basic(DeploymentHelpers.DEFAULT_PROVIDER_NAME, DeploymentHelpers.DEFAULT_PROVIDER_PASSWORD)
.expect().statusCode(200)
.log().ifError()
.body("", containsInAnyOrder(
"reindex_from_persistence",
"renormalize_by_content_type",
"renormalize_by_project_code",
"renormalize_by_contributor_code",
"renormalize_by_contributor_lookup_id",
"renormalize_by_project_lookup_id",
"update_contributor_profile",
"reindex_contributor",
"reindex_project"
))
.when().get(new URL(context, TASKS_REST_API + "/type").toExternalForm());
}
@Test
@InSequence(11)
public void assertGetTasksTask() throws MalformedURLException {
// GET /tasks/task
given().contentType(ContentType.JSON)
.auth().basic(DeploymentHelpers.DEFAULT_PROVIDER_NAME, DeploymentHelpers.DEFAULT_PROVIDER_PASSWORD)
.expect().statusCode(200)
.log().ifError()
.body("size()", equalTo(0))
.when().get(new URL(context, TASKS_REST_API + "/task").toExternalForm());
}
static String taskID;
@Test
@InSequence(20)
public void assertReindexContributor() throws MalformedURLException {
// POST /tasks/task/reindex_contributor
taskID = given().contentType(ContentType.JSON)
.auth().basic(DeploymentHelpers.DEFAULT_PROVIDER_NAME, DeploymentHelpers.DEFAULT_PROVIDER_PASSWORD)
.body("{}")
.expect().statusCode(200)
.log().ifError()
.contentType(ContentType.JSON)
.body("id", is(not(empty())))
.when().post(new URL(context, TASKS_REST_API + "/task/reindex_contributor").toExternalForm())
.andReturn().body().jsonPath().get("id");
System.out.println("id:" + taskID);
}
@Test
@InSequence(21)
public void assertGetCreatedReindexContributorTask() throws MalformedURLException {
given().contentType(ContentType.JSON)
.pathParam("id", taskID)
.auth().basic(DeploymentHelpers.DEFAULT_PROVIDER_NAME, DeploymentHelpers.DEFAULT_PROVIDER_PASSWORD)
.expect().statusCode(200)
.log().ifError()
.body("id", is(taskID))
.body("taskType", is("reindex_contributor"))
.body("runCount", isA(Integer.class))
.body("taskStatus", notNullValue())
.body("cancelRequested", is(false))
.when().get(new URL(context, TASKS_REST_API + "/task/{id}").toExternalForm());
}
@Test
@InSequence(30)
public void assertDeleteCreatedReindexContributorTask() throws MalformedURLException {
given().contentType(ContentType.JSON)
.pathParam("id", taskID)
.auth().basic(DeploymentHelpers.DEFAULT_PROVIDER_NAME, DeploymentHelpers.DEFAULT_PROVIDER_PASSWORD)
.expect().statusCode(200)
.log().ifError()
.when().delete(new URL(context, TASKS_REST_API + "/task/{id}").toExternalForm());
}
}
|
package scal.io.liger;
import android.content.Context;
import android.content.res.AssetManager;
import android.os.Environment;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import scal.io.liger.model.Dependency;
import scal.io.liger.model.StoryPath;
import scal.io.liger.model.StoryPathLibrary;
/**
* @author Matt Bogner
* @author Josh Steiner
*/
public class JsonHelper {
private static final String TAG = "JsonHelper";
private static final String LIGER_DIR = "Liger";
private static File selectedJSONFile = null;
private static String selectedJSONPath = null;
private static ArrayList<String> jsonFileNamesList = null;
private static ArrayList<File> jsonFileList = null;
private static ArrayList<String> jsonPathList = null;
private static HashMap<String, String> jsonKeyToPath = null;
private static String sdLigerFilePath = null;
//private static String language = null; // TEMP
// TEMP - for gathering insance files to test references
public static ArrayList<String> getInstanceFiles() {
ArrayList<String> instanceList = new ArrayList<String>();
for (String s : jsonPathList) {
if (s.contains("-instance")) {
instanceList.add(s);
Log.d("FILES", "FOUND INSTANCE FILE: " + s);
}
}
return instanceList;
}
public static String loadJSONFromPath(String jsonPath, String language) {
String jsonString = "";
String sdCardState = Environment.getExternalStorageState();
String localizedFilePath = jsonPath;
// check language setting and insert country code if necessary
if (language != null) {
// just in case, check whether country code has already been inserted
if (jsonPath.lastIndexOf("-" + language + jsonPath.substring(jsonPath.lastIndexOf("."))) < 0) {
localizedFilePath = jsonPath.substring(0, jsonPath.lastIndexOf(".")) + "-" + language + jsonPath.substring(jsonPath.lastIndexOf("."));
}
Log.d("LANGUAGE", "loadJSONFromPath() - LOCALIZED PATH: " + localizedFilePath);
}
if (sdCardState.equals(Environment.MEDIA_MOUNTED)) {
try {
File jsonFile = new File(jsonPath);
InputStream jsonStream = new FileInputStream(jsonFile);
File localizedFile = new File(localizedFilePath);
// if there is a file at the localized path, use that instead
if ((localizedFile.exists()) && (!jsonPath.equals(localizedFilePath))) {
Log.d("LANGUAGE", "loadJSONFromPath() - USING LOCALIZED FILE: " + localizedFilePath);
jsonStream = new FileInputStream(localizedFile);
}
int size = jsonStream.available();
byte[] buffer = new byte[size];
jsonStream.read(buffer);
jsonStream.close();
jsonString = new String(buffer);
} catch (IOException e) {
Log.e(TAG, "READING JSON FILE FROM SD CARD FAILED: " + e.getMessage());
}
} else {
System.err.println("SD CARD NOT FOUND");
}
return jsonString;
}
public static String loadJSON(Context context, String language) {
// check for file
// paths to actual files should fully qualified
// paths within zip files should be relative
// (or at least not resolve to actual files)
File checkFile = new File(selectedJSONPath);
//if (selectedJSONFile.exists()) {
// return loadJSON(selectedJSONFile, language);
//} else {
if (checkFile.exists()) {
return loadJSON(checkFile, language);
} else {
return loadJSONFromZip(selectedJSONPath, context, language);
}
}
public static String loadJSON(File file, String language) {
if(null == file) {
return null;
}
String jsonString = "";
String sdCardState = Environment.getExternalStorageState();
String localizedFilePath = file.getPath();
// check language setting and insert country code if necessary
if (language != null) {
// just in case, check whether country code has already been inserted
if (file.getPath().lastIndexOf("-" + language + file.getPath().substring(file.getPath().lastIndexOf("."))) < 0) {
localizedFilePath = file.getPath().substring(0, file.getPath().lastIndexOf(".")) + "-" + language + file.getPath().substring(file.getPath().lastIndexOf("."));
}
Log.d("LANGUAGE", "loadJSON() - LOCALIZED PATH: " + localizedFilePath);
}
if (sdCardState.equals(Environment.MEDIA_MOUNTED)) {
try {
InputStream jsonStream = new FileInputStream(file);
File localizedFile = new File(localizedFilePath);
// if there is a file at the localized path, use that instead
if ((localizedFile.exists()) && (!file.getPath().equals(localizedFilePath))) {
Log.d("LANGUAGE", "loadJSON() - USING LOCALIZED FILE: " + localizedFilePath);
jsonStream = new FileInputStream(localizedFile);
}
int size = jsonStream.available();
byte[] buffer = new byte[size];
jsonStream.read(buffer);
jsonStream.close();
jsonString = new String(buffer);
} catch (IOException e) {
Log.e(TAG, "READING JSON FILE FRON SD CARD FAILED: " + e.getMessage());
}
} else {
Log.e(TAG, "SD CARD NOT FOUND");
}
return jsonString;
}
// NEW
// merged with regular loadJSON method
/*
public static String loadJSONFromZip(Context context, String language) {
return loadJSONFromZip(selectedJSONPath, context, language);
}
*/
public static String loadJSONFromZip(String jsonFilePath, Context context, String language) {
Log.d(" *** TESTING *** ", "NEW METHOD loadJSONFromZip CALLED FOR " + jsonFilePath);
if(null == jsonFilePath) {
return null;
}
String jsonString = "";
String localizedFilePath = jsonFilePath;
// check language setting and insert country code if necessary
if (language != null) {
// just in case, check whether country code has already been inserted
if (jsonFilePath.lastIndexOf("-" + language + jsonFilePath.substring(jsonFilePath.lastIndexOf("."))) < 0) {
localizedFilePath = jsonFilePath.substring(0, jsonFilePath.lastIndexOf(".")) + "-" + language + jsonFilePath.substring(jsonFilePath.lastIndexOf("."));
}
Log.d("LANGUAGE", "loadJSONFromZip() - LOCALIZED PATH: " + localizedFilePath);
}
// removed sd card check as expansion file should not be located on sd card
try {
InputStream jsonStream = ZipHelper.getFileInputStream(localizedFilePath, context);
// if there is no result with the localized path, retry with default path
if ((jsonStream == null) && (!jsonFilePath.equals(localizedFilePath))) {
jsonStream = ZipHelper.getFileInputStream(jsonFilePath, context);
} else {
Log.d("LANGUAGE", "loadJSONFromZip() - USING LOCALIZED FILE: " + localizedFilePath);
}
if (jsonStream == null)
return null;
int size = jsonStream.available();
byte[] buffer = new byte[size];
jsonStream.read(buffer);
jsonStream.close();
jsonString = new String(buffer);
} catch (IOException ioe) {
Log.e(TAG, "reading json file " + jsonFilePath + " from ZIP file failed: " + ioe.getMessage());
}
return jsonString;
}
public static String getSdLigerFilePath() {
return sdLigerFilePath;
}
private static void copyFilesToSdCard(Context context, String basePath) {
copyFileOrDir(context, basePath, ""); // copy all files in assets folder in my project
}
private static void copyFileOrDir(Context context, String assetFromPath, String baseToPath) {
AssetManager assetManager = context.getAssets();
String assets[] = null;
try {
Log.i("tag", "copyFileOrDir() "+assetFromPath);
assets = assetManager.list(assetFromPath);
if (assets.length == 0) {
copyFile(context, assetFromPath, baseToPath);
} else {
String fullPath = baseToPath + assetFromPath;
Log.i("tag", "path="+fullPath);
File dir = new File(fullPath);
if (!dir.exists() && !assetFromPath.startsWith("images") && !assetFromPath.startsWith("sounds") && !assetFromPath.startsWith("webkit"))
if (!dir.mkdirs())
Log.i("tag", "could not create dir "+fullPath);
for (int i = 0; i < assets.length; ++i) {
String p;
if (assetFromPath.equals(""))
p = "";
else
p = assetFromPath + "/";
if (!assetFromPath.startsWith("images") && !assetFromPath.startsWith("sounds") && !assetFromPath.startsWith("webkit"))
copyFileOrDir(context, p + assets[i], baseToPath);
}
}
} catch (IOException ex) {
Log.e("tag", "I/O Exception", ex);
}
}
private static void copyFile(Context context, String fromFilename, String baseToPath) {
AssetManager assetManager = context.getAssets();
if (fromFilename.endsWith(".obb"))
return; // let's not copy .obb files, they get copied elseware
InputStream in = null;
OutputStream out = null;
String newFileName = null;
try {
Log.i("tag", "copyFile() "+fromFilename);
in = assetManager.open(fromFilename);
if (fromFilename.endsWith(".jpg")) // extension was added to avoid compression on APK file
newFileName = baseToPath + fromFilename.substring(0, fromFilename.length()-4);
else
newFileName = baseToPath + fromFilename;
out = new FileOutputStream(newFileName);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e) {
Log.e("tag", "Exception in copyFile() of "+newFileName);
Log.e("tag", "Exception in copyFile() "+e.toString());
}
}
private static void copyObbFile(Context context, String fromFilename, String toPath) {
AssetManager assetManager = context.getAssets();
InputStream in = null;
OutputStream out = null;
try {
Log.i("tag", "copyObbFile() "+fromFilename);
in = assetManager.open(fromFilename);
out = new FileOutputStream(toPath);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e) {
Log.e("tag", "Exception in copyObbFile() of "+toPath);
Log.e("tag", "Exception in copyObbFile() "+e.toString());
}
}
public static void setupFileStructure(Context context) {
String sdCardState = Environment.getExternalStorageState();
if (sdCardState.equals(Environment.MEDIA_MOUNTED)) {
// FIXME we need to remove this, it seems like the popup stuff requires it even though we acutally read files from .obb not the Liger folder
String sdCardFolderPath = Environment.getExternalStorageDirectory().getPath();
sdLigerFilePath = sdCardFolderPath + File.separator + LIGER_DIR + File.separator;
new File(sdLigerFilePath).mkdirs();
// based on http://stackoverflow.com/questions/4447477/android-how-to-copy-files-from-assets-folder-to-sdcard/8366081#8366081
// copyFilesToSdCard(context, sdLigerFilePath); // this used to copy all assets to /sdcard/Liger
// copy the zipped assets to the right folder
String inputAssetFilename = "main.1.obb"; // FIXME we should parse this out from the assets so its always right
String zipPath = ZipHelper.getExtensionFolderPath(context);
String zipFilename = ZipHelper.getExtensionZipFilename(context, inputAssetFilename);
String zipFullpath = zipPath + zipFilename;
Log.d("JsonHelper", "copying obb file '" + inputAssetFilename + "' to '" + zipFullpath + "'");
new File(zipPath).mkdirs();
// FIXME check size & datestamp and don't copy if it exists? maybe we can check hash? key?
copyObbFile(context, inputAssetFilename, zipFullpath);
} else {
Log.e(TAG, "SD CARD NOT FOUND"); // FIXME don't bury errors in logs, we should let this crash
}
}
private static void setupJSONFileList() {
// HARD CODING LIST
if (jsonFileNamesList == null) {
jsonFileNamesList = new ArrayList<String>();
File ligerFile_1 = new File(sdLigerFilePath + "/default/default_library/default_library.json");
File ligerFile_2 = new File(sdLigerFilePath + "/default/learning_guide_TEST.json");
File ligerFile_3 = new File(sdLigerFilePath + "/default/LIB_1/LIB_1_TEST.json");
File ligerFile_4 = new File(sdLigerFilePath + "/default/LIB_2/LIB_2_TEST.json");
File ligerFile_5 = new File(sdLigerFilePath + "/default/learning_guide_library.json");
File ligerFile_6 = new File(sdLigerFilePath + "/default/learning_guide_library_SAVE.json");
jsonFileNamesList.add(ligerFile_1.getName());
jsonFileNamesList.add(ligerFile_2.getName());
jsonFileNamesList.add(ligerFile_3.getName());
jsonFileNamesList.add(ligerFile_4.getName());
jsonFileNamesList.add(ligerFile_5.getName());
jsonFileNamesList.add(ligerFile_6.getName());
jsonFileList = new ArrayList<File>();
jsonFileList.add(ligerFile_1);
jsonFileList.add(ligerFile_2);
jsonFileList.add(ligerFile_3);
jsonFileList.add(ligerFile_4);
jsonFileList.add(ligerFile_5);
jsonFileList.add(ligerFile_6);
jsonPathList = new ArrayList<String>();
jsonPathList.add("default/default_library/default_library.json");
jsonPathList.add("default/learning_guide_TEST.json");
jsonPathList.add("default/LIB_1/LIB_1_TEST.json");
jsonPathList.add("default/LIB_2/LIB_2_TEST.json");
jsonPathList.add("default/learning_guide_library.json");
jsonPathList.add("default/learning_guide_library_SAVE.json");
jsonKeyToPath = new HashMap<String, String>();
jsonKeyToPath.put("default_library", "default/default_library/default_library.json");
jsonKeyToPath.put("learning_guide_TEST", "default/learning_guide_TEST.json");
jsonKeyToPath.put("LIB_1_TEST", "default/LIB_1/LIB_1_TEST.json");
jsonKeyToPath.put("LIB_2_TEST", "default/LIB_2/LIB_2_TEST.json");
jsonKeyToPath.put("learning_guide_library", "default/learning_guide_library.json");
jsonKeyToPath.put("learning_guide_library_SAVE", "default/learning_guide_library_SAVE.json");
File jsonFolder = new File(getSdLigerFilePath());
// check for nulls (uncertain as to cause of nulls)
if ((jsonFolder != null) && (jsonFolder.listFiles() != null)) {
for (File jsonFile : jsonFolder.listFiles()) {
if (jsonFile.getName().contains("-instance") && !jsonFile.isDirectory()) {
File localFile = new File(jsonFile.getPath());
Log.d("FILES", "FOUND INSTANCE FILE: " + localFile.getName());
jsonFileNamesList.add(localFile.getName());
jsonFileList.add(localFile);
jsonPathList.add(localFile.getPath());
jsonKeyToPath.put(localFile.getName(), localFile.getPath());
}
}
} else {
Log.d("FILES", getSdLigerFilePath() + " WAS NULL OR listFiles() RETURNED NULL, CANNOT GATHER INSTANCE FILES");
}
}
}
public static String[] getJSONFileList() {
//ensure path has been set
if(null == sdLigerFilePath) {
return null;
}
setupJSONFileList();
/*
File ligerDir = new File(sdLigerFilePath);
if (ligerDir != null) {
for (File file : ligerDir.listFiles()) {
if (file.getName().endsWith(".json")) {
jsonFileNamesList.add(file.getName());
jsonFileList.add(file);
}
}
}
File defaultLigerDir = new File(sdLigerFilePath + "/default/");
if (defaultLigerDir != null) {
for (File file : defaultLigerDir.listFiles()) {
if (file.getName().endsWith(".json")) {
jsonFileNamesList.add(file.getName());
jsonFileList.add(file);
}
}
}
*/
return jsonFileNamesList.toArray(new String[jsonFileNamesList.size()]);
}
public static String getJsonPathByKey(String key) {
setupJSONFileList();
if (jsonKeyToPath.containsKey(key)) {
return jsonKeyToPath.get(key);
} else {
return null;
}
}
public static File setSelectedJSONFile(int index) {
selectedJSONFile = jsonFileList.get(index);
return selectedJSONFile;
}
public static String setSelectedJSONPath(int index) {
selectedJSONPath = jsonPathList.get(index);
return selectedJSONPath;
}
private static void addFileToSDCard(InputStream jsonInputStream, String filePath) {
OutputStream outputStream = null;
try {
// write the inputStream to a FileOutputStream
outputStream = new FileOutputStream(new File(sdLigerFilePath + filePath));
int read = 0;
byte[] bytes = new byte[1024];
while ((read = jsonInputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (jsonInputStream != null) {
try {
jsonInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static StoryPathLibrary loadStoryPathLibrary(String jsonFilePath, ArrayList<String> referencedFiles, Context context, String language) {
String storyPathLibraryJson = "";
String sdCardState = Environment.getExternalStorageState();
String localizedFilePath = jsonFilePath;
// check language setting and insert country code if necessary
if (language != null) {
// just in case, check whether country code has already been inserted
if (jsonFilePath.lastIndexOf("-" + language + jsonFilePath.substring(jsonFilePath.lastIndexOf("."))) < 0) {
localizedFilePath = jsonFilePath.substring(0, jsonFilePath.lastIndexOf(".")) + "-" + language + jsonFilePath.substring(jsonFilePath.lastIndexOf("."));
}
Log.d("LANGUAGE", "loadStoryPathLibrary() - LOCALIZED PATH: " + localizedFilePath);
}
File f = new File(localizedFilePath);
if ((!f.exists()) && (!localizedFilePath.equals(jsonFilePath))) {
f = new File(jsonFilePath);
} else {
Log.d("LANGUAGE", "loadStoryPathLibrary() - USING LOCALIZED FILE: " + localizedFilePath);
}
if (sdCardState.equals(Environment.MEDIA_MOUNTED)) {
try {
InputStream jsonStream = new FileInputStream(f);
int size = jsonStream.available();
byte[] buffer = new byte[size];
jsonStream.read(buffer);
jsonStream.close();
storyPathLibraryJson = new String(buffer);
} catch (IOException ioe) {
Log.e(TAG, "reading json file " + jsonFilePath + " from SD card failed: " + ioe.getMessage());
return null;
}
} else {
Log.e(TAG, "SD card not found");
return null;
}
return deserializeStoryPathLibrary(storyPathLibraryJson, f.getPath(), referencedFiles, context);
}
// NEW
public static StoryPathLibrary loadStoryPathLibraryFromZip(String jsonFilePath, ArrayList<String> referencedFiles, Context context, String language) {
Log.d(" *** TESTING *** ", "NEW METHOD loadStoryPathLibraryFromZip CALLED FOR " + jsonFilePath);
String storyPathLibraryJson = "";
String localizedFilePath = jsonFilePath;
// check language setting and insert country code if necessary
if (language != null) {
// just in case, check whether country code has already been inserted
if (jsonFilePath.lastIndexOf("-" + language + jsonFilePath.substring(jsonFilePath.lastIndexOf("."))) < 0) {
localizedFilePath = jsonFilePath.substring(0, jsonFilePath.lastIndexOf(".")) + "-" + language + jsonFilePath.substring(jsonFilePath.lastIndexOf("."));
}
Log.d("LANGUAGE", "loadStoryPathLibraryFromZip() - LOCALIZED PATH: " + localizedFilePath);
}
// removed sd card check as expansion file should not be located on sd card
try {
InputStream jsonStream = ZipHelper.getFileInputStream(localizedFilePath, context);
// if there is no result with the localized path, retry with default path
if ((jsonStream == null) && (!localizedFilePath.equals(jsonFilePath))) {
jsonStream = ZipHelper.getFileInputStream(jsonFilePath, context);
} else {
Log.d("LANGUAGE", "loadStoryPathLibraryFromZip() - USING LOCALIZED FILE: " + localizedFilePath);
}
int size = jsonStream.available();
byte[] buffer = new byte[size];
jsonStream.read(buffer);
jsonStream.close();
storyPathLibraryJson = new String(buffer);
} catch (IOException ioe) {
Log.e(TAG, "reading json file " + jsonFilePath + " from ZIP file failed: " + ioe.getMessage());
return null;
}
return deserializeStoryPathLibrary(storyPathLibraryJson, jsonFilePath, referencedFiles, context);
}
public static StoryPathLibrary deserializeStoryPathLibrary(String storyPathLibraryJson, String jsonFilePath, ArrayList<String> referencedFiles, Context context) {
GsonBuilder gBuild = new GsonBuilder();
gBuild.registerTypeAdapter(StoryPathLibrary.class, new StoryPathLibraryDeserializer());
Gson gson = gBuild.excludeFieldsWithoutExposeAnnotation().create();
StoryPathLibrary storyPathLibrary = gson.fromJson(storyPathLibraryJson, StoryPathLibrary.class);
// a story path library model must have a file location to manage relative paths
// if it is loaded from a saved state, the location should already be set
if ((jsonFilePath == null) || (jsonFilePath.length() == 0)) {
if ((storyPathLibrary.getFileLocation() == null) || (storyPathLibrary.getFileLocation().length() == 0)) {
Log.e(TAG, "file location for story path library " + storyPathLibrary.getId() + " could not be determined");
return null;
}
} else {
File checkFile = new File(jsonFilePath);
if (!checkFile.exists()) {
storyPathLibrary.setFileLocation(jsonFilePath); // FOR NOW, DON'T SAVE ACTIAL FILE LOCATIONS
}
}
// construct and insert dependencies
for (String referencedFile : referencedFiles) {
Dependency dependency = new Dependency();
dependency.setDependencyFile(referencedFile);
// extract id from path/file name
// assumes format <path/library id>-instance-<timestamp>.json
// assumes path/library id doesn't not contain "-"
String derivedId = referencedFile.substring(referencedFile.lastIndexOf(File.separator) + 1);
derivedId = derivedId.substring(0, derivedId.indexOf("-"));
dependency.setDependencyId(derivedId);
storyPathLibrary.addDependency(dependency);
Log.d("FILES", "DEPENDENCY: " + derivedId + " -> " + referencedFile);
}
storyPathLibrary.setCardReferences();
storyPathLibrary.initializeObservers();
storyPathLibrary.setContext(context);
return storyPathLibrary;
}
public static String getStoryPathLibrarySaveFileName(StoryPathLibrary storyPathLibrary) {
Log.d(" *** TESTING *** ", "NEW METHOD getStoryPathLibrarySaveFileName CALLED FOR " + storyPathLibrary.getId());
Date timeStamp = new Date();
//String jsonFilePath = storyPathLibrary.buildZipPath(storyPathLibrary.getId() + "_" + timeStamp.getTime() + ".json");
//TEMP
String jsonFilePath = storyPathLibrary.buildTargetPath(storyPathLibrary.getId() + "-instance-" + timeStamp.getTime() + ".json");
return jsonFilePath;
}
public static boolean saveStoryPathLibrary(StoryPathLibrary storyPathLibrary, String jsonFilePath) {
Log.d(" *** TESTING *** ", "NEW METHOD saveStoryPathLibrary CALLED FOR " + storyPathLibrary.getId() + " -> " + jsonFilePath);
String sdCardState = Environment.getExternalStorageState();
if (sdCardState.equals(Environment.MEDIA_MOUNTED)) {
try {
File storyPathLibraryFile = new File(jsonFilePath + ".swap"); // NEED TO WRITE TO SWAP AND COPY
if (storyPathLibraryFile.exists()) {
storyPathLibraryFile.delete();
}
storyPathLibraryFile.createNewFile();
FileOutputStream storyPathLibraryStream = new FileOutputStream(storyPathLibraryFile);
String storyPathLibraryJson = serializeStoryPathLibrary(storyPathLibrary);
byte storyPathLibraryData[] = storyPathLibraryJson.getBytes();
storyPathLibraryStream.write(storyPathLibraryData);
storyPathLibraryStream.flush();
storyPathLibraryStream.close();
Process p = Runtime.getRuntime().exec("mv " + jsonFilePath + ".swap " + jsonFilePath);
} catch (IOException ioe) {
Log.e(TAG, "writing json file " + jsonFilePath + " to SD card failed: " + ioe.getMessage());
return false;
}
} else {
Log.e(TAG, "SD card not found");
return false;
}
// update file location
// TEMP - this will break references to content in zip file. unsure what to do...
// storyPathLibrary.setFileLocation(jsonFilePath);
return true;
}
public static String serializeStoryPathLibrary(StoryPathLibrary storyPathLibrary) {
Log.d(" *** TESTING *** ", "NEW METHOD serializeStoryPathLibrary CALLED FOR " + storyPathLibrary.getId());
GsonBuilder gBuild = new GsonBuilder();
Gson gson = gBuild.excludeFieldsWithoutExposeAnnotation().create();
String storyPathLibraryJson = gson.toJson(storyPathLibrary);
return storyPathLibraryJson;
}
public static StoryPath loadStoryPath(String jsonFilePath, StoryPathLibrary storyPathLibrary, ArrayList<String> referencedFiles, Context context, String language) {
String storyPathJson = "";
String sdCardState = Environment.getExternalStorageState();
String localizedFilePath = jsonFilePath;
// check language setting and insert country code if necessary
if (language != null) {
// just in case, check whether country code has already been inserted
if (jsonFilePath.lastIndexOf("-" + language + jsonFilePath.substring(jsonFilePath.lastIndexOf("."))) < 0) {
localizedFilePath = jsonFilePath.substring(0, jsonFilePath.lastIndexOf(".")) + "-" + language + jsonFilePath.substring(jsonFilePath.lastIndexOf("."));
}
Log.d("LANGUAGE", "loadStoryPath() - LOCALIZED PATH: " + localizedFilePath);
}
File f = new File(localizedFilePath);
if ((!f.exists()) && (!localizedFilePath.equals(jsonFilePath))) {
f = new File(jsonFilePath);
} else {
Log.d("LANGUAGE", "loadStoryPath() - USING LOCALIZED FILE: " + localizedFilePath);
}
if (sdCardState.equals(Environment.MEDIA_MOUNTED)) {
try {
InputStream jsonStream = new FileInputStream(f);
int size = jsonStream.available();
byte[] buffer = new byte[size];
jsonStream.read(buffer);
jsonStream.close();
storyPathJson = new String(buffer);
} catch (IOException ioe) {
Log.e(TAG, "reading json file " + jsonFilePath + " from SD card failed: " + ioe.getMessage());
return null;
}
} else {
Log.e(TAG, "SD card not found");
return null;
}
return deserializeStoryPath(storyPathJson, f.getPath(), storyPathLibrary, referencedFiles, context);
}
// NEW
public static StoryPath loadStoryPathFromZip(String jsonFilePath, StoryPathLibrary storyPathLibrary, ArrayList<String> referencedFiles, Context context, String language) {
Log.d(" *** TESTING *** ", "NEW METHOD loadStoryPathFromZip CALLED FOR " + jsonFilePath);
String storyPathJson = "";
String localizedFilePath = jsonFilePath;
// check language setting and insert country code if necessary
if (language != null) {
// just in case, check whether country code has already been inserted
if (jsonFilePath.lastIndexOf("-" + language + jsonFilePath.substring(jsonFilePath.lastIndexOf("."))) < 0) {
localizedFilePath = jsonFilePath.substring(0, jsonFilePath.lastIndexOf(".")) + "-" + language + jsonFilePath.substring(jsonFilePath.lastIndexOf("."));
}
Log.d("LANGUAGE", "loadStoryPathFromZip() - LOCALIZED PATH: " + localizedFilePath);
}
// removed sd card check as expansion file should not be located on sd card
try {
InputStream jsonStream = ZipHelper.getFileInputStream(localizedFilePath, context);
// if there is no result with the localized path, retry with default path
if ((jsonStream == null) && (!localizedFilePath.equals(jsonFilePath))) {
jsonStream = ZipHelper.getFileInputStream(jsonFilePath, context);
} else {
Log.d("LANGUAGE", "loadStoryPathFromZip() - USING LOCALIZED FILE: " + localizedFilePath);
}
int size = jsonStream.available();
byte[] buffer = new byte[size];
jsonStream.read(buffer);
jsonStream.close();
storyPathJson = new String(buffer);
} catch (IOException ioe) {
Log.e(TAG, "reading json file " + jsonFilePath + " from ZIP file failed: " + ioe.getMessage());
return null;
}
return deserializeStoryPath(storyPathJson, jsonFilePath, storyPathLibrary, referencedFiles, context);
}
public static StoryPath deserializeStoryPath(String storyPathJson, String jsonFilePath, StoryPathLibrary storyPathLibrary, ArrayList<String> referencedFiles, Context context) {
GsonBuilder gBuild = new GsonBuilder();
gBuild.registerTypeAdapter(StoryPath.class, new StoryPathDeserializer());
Gson gson = gBuild.excludeFieldsWithoutExposeAnnotation().create();
StoryPath storyPath = gson.fromJson(storyPathJson, StoryPath.class);
// a story path model must have a file location to manage relative paths
// if it is loaded from a saved state, the location should already be set
if ((jsonFilePath == null) || (jsonFilePath.length() == 0)) {
if ((storyPath.getFileLocation() == null) || (storyPath.getFileLocation().length() == 0)) {
Log.e(TAG, "file location for story path " + storyPath.getId() + " could not be determined");
}
} else {
File checkFile = new File(jsonFilePath);
if (!checkFile.exists()) {
storyPath.setFileLocation(jsonFilePath); // FOR NOW, DON'T SAVE ACTIAL FILE LOCATIONS
}
}
storyPath.setCardReferences();
storyPath.initializeObservers();
storyPath.setStoryPathLibrary(storyPathLibrary);
// THIS MAY HAVE UNINTENDED CONSEQUENCES...
if (storyPath.getStoryPathLibraryFile() == null) {
storyPath.setStoryPathLibraryFile(storyPathLibrary.getFileLocation());
}
// construct and insert dependencies
for (String referencedFile : referencedFiles) {
Dependency dependency = new Dependency();
dependency.setDependencyFile(referencedFile);
// extract id from path/file name
// assumes format <path/library id>-instance-<timestamp>.json
// assumes path/library id doesn't not contain "-"
String derivedId = referencedFile.substring(referencedFile.lastIndexOf(File.separator) + 1);
derivedId = derivedId.substring(0, derivedId.indexOf("-"));
dependency.setDependencyId(derivedId);
storyPath.addDependency(dependency);
Log.d("FILES", "DEPENDENCY: " + derivedId + " -> " + referencedFile);
}
storyPath.setContext(context);
return storyPath;
}
public static String getStoryPathSaveFileName(StoryPath storyPath) {
Log.d(" *** TESTING *** ", "NEW METHOD getStoryPathSaveFileName CALLED FOR " + storyPath.getId());
Date timeStamp = new Date();
//String jsonFilePath = storyPath.buildZipPath(storyPath.getId() + "_" + timeStamp.getTime() + ".json");
//TEMP
String jsonFilePath = storyPath.buildTargetPath(storyPath.getId() + "-instance-" + timeStamp.getTime() + ".json");
return jsonFilePath;
}
public static boolean saveStoryPath(StoryPath storyPath, String jsonFilePath) {
Log.d(" *** TESTING *** ", "NEW METHOD getStoryPathSaveFileName CALLED FOR " + storyPath.getId() + " -> " + jsonFilePath);
String sdCardState = Environment.getExternalStorageState();
if (sdCardState.equals(Environment.MEDIA_MOUNTED)) {
try {
File storyPathFile = new File(jsonFilePath + ".swap"); // NEED TO WRITE TO SWAP AND COPY
if (storyPathFile.exists()) {
storyPathFile.delete();
}
storyPathFile.createNewFile();
FileOutputStream storyPathStream = new FileOutputStream(storyPathFile);
String storyPathJson = serializeStoryPath(storyPath);
byte storyPathData[] = storyPathJson.getBytes();
storyPathStream.write(storyPathData);
storyPathStream.flush();
storyPathStream.close();
Process p = Runtime.getRuntime().exec("mv " + jsonFilePath + ".swap " + jsonFilePath);
} catch (IOException ioe) {
Log.e(TAG, "writing json file " + jsonFilePath + " to SD card failed: " + ioe.getMessage());
return false;
}
} else {
Log.e(TAG, "SD card not found");
return false;
}
// update file location
// TEMP - this will break references to content in zip file. unsure what to do...
// storyPath.setFileLocation(jsonFilePath);
return true;
}
public static String serializeStoryPath(StoryPath storyPath) {
Log.d(" *** TESTING *** ", "NEW METHOD serializeStoryPath CALLED FOR " + storyPath.getId());
GsonBuilder gBuild = new GsonBuilder();
Gson gson = gBuild.excludeFieldsWithoutExposeAnnotation().create();
// set aside references to prevent circular dependencies when serializing
/*
Context tempContext = storyPath.getContext();
StoryPathLibrary tempStoryPathLibrary = storyPath.getStoryPathLibrary();
storyPath.setContext(null);
storyPath.setStoryPathLibrary(null);
storyPath.clearObservers();
storyPath.clearCardReferences();
*/
String storyPathJson = gson.toJson(storyPath);
// restore references
/*
storyPath.setCardReferences();
storyPath.initializeObservers();
storyPath.setStoryPathLibrary(tempStoryPathLibrary);
storyPath.setContext(tempContext);
*/
return storyPathJson;
}
}
|
package com.badlogic.gdx.tests.desktop;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import com.badlogic.gdx.backends.desktop.JoglApplication;
import com.badlogic.gdx.graphics.loaders.md5.MD5Loader;
import com.badlogic.gdx.graphics.loaders.md5.MD5Mesh;
import com.badlogic.gdx.graphics.loaders.md5.MD5Model;
public class MD5Test
{
public static void main( String[] argv ) throws FileNotFoundException
{
JoglApplication app = new JoglApplication( "MD5 Test", 480, 320, false );
app.getGraphics().setRenderListener( new com.badlogic.gdx.tests.MD5Test() );
}
}
|
package io.georocket;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import io.georocket.constants.AddressConstants;
import io.georocket.constants.ConfigConstants;
import io.georocket.input.FirstLevelSplitter;
import io.georocket.input.Splitter;
import io.georocket.storage.ChunkMeta;
import io.georocket.storage.Store;
import io.georocket.storage.StoreFactory;
import io.georocket.util.AsyncXMLParser;
import io.georocket.util.RxUtils;
import io.georocket.util.Window;
import io.vertx.core.Vertx;
import io.vertx.core.file.OpenOptions;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.rx.java.ObservableFuture;
import io.vertx.rx.java.RxHelper;
import io.vertx.rxjava.core.AbstractVerticle;
import io.vertx.rxjava.core.buffer.Buffer;
import io.vertx.rxjava.core.eventbus.Message;
import io.vertx.rxjava.core.file.FileSystem;
import io.vertx.rxjava.core.streams.ReadStream;
import rx.Observable;
/**
* Imports file in the background
* @author Michel Kraemer
*/
public class ImporterVerticle extends AbstractVerticle {
private static Logger log = LoggerFactory.getLogger(ImporterVerticle.class);
private static final int MAX_RETRIES = 5;
private static final int RETRY_INTERVAL = 1000;
private Store store;
private String incoming;
@Override
public void start() {
log.info("Launching importer ...");
store = StoreFactory.createStore((Vertx)vertx.getDelegate());
String storagePath = vertx.getOrCreateContext().config().getString(
ConfigConstants.STORAGE_FILE_PATH);
incoming = storagePath + "/incoming";
vertx.eventBus().consumer(AddressConstants.IMPORTER, this::onMessage);
}
/**
* Receives a message
* @param msg the message
*/
private void onMessage(Message<JsonObject> msg) {
String action = msg.body().getString("action");
switch (action) {
case "import":
onImport(msg);
break;
default:
msg.fail(400, "Invalid action: " + action);
log.error("Invalid action: " + action);
break;
}
}
/**
* Receives a name of a file to import
* @param msg the event bus message containing the filename
*/
private void onImport(Message<JsonObject> msg) {
JsonObject body = msg.body();
String filename = incoming + "/" + body.getString("filename");
String layer = body.getString("layer", "/");
// get tags
JsonArray tagsArr = body.getJsonArray("tags");
List<String> tags = tagsArr != null ? tagsArr.stream().flatMap(o -> o != null ?
Stream.of(o.toString()) : Stream.of()).collect(Collectors.toList()) : null;
log.info("Importing " + filename + " to layer " + layer);
FileSystem fs = vertx.fileSystem();
OpenOptions openOptions = new OpenOptions().setCreate(false).setWrite(false);
fs.openObservable(filename, openOptions)
.flatMap(f -> importXML(f, layer, tags).finallyDo(() -> {
// delete file from 'incoming' folder
log.info("Deleting " + filename + " from incoming folder");
f.closeObservable()
.flatMap(v -> fs.deleteObservable(filename))
.subscribe(v -> {}, err -> {
log.error("Could not delete file from 'incoming' folder", err);
});
}))
.subscribe(v -> {}, err -> {
log.error("Failed to import chunk", err);
});
}
/**
* Imports an XML file from the given input stream into the store
* @param f the XML file to read
* @param layer the layer where the file should be stored (may be null)
* @param tags the list of tags to attach to the file (may be null)
* @return an observable that will emit when the file has been imported
*/
private Observable<Void> importXML(ReadStream<Buffer> f, String layer, List<String> tags) {
AsyncXMLParser xmlParser = new AsyncXMLParser();
Window window = new Window();
Splitter splitter = new FirstLevelSplitter(window);
return f.toObservable()
.map(buf -> (io.vertx.core.buffer.Buffer)buf.getDelegate())
.doOnNext(window::append)
.flatMap(xmlParser::feed)
.flatMap(splitter::onEventObservable)
.flatMap(result -> {
// pause stream while chunk is being written
f.pause();
Observable<Void> o = addToStore(result.getChunk(),
result.getMeta(), layer, tags);
return o.doOnNext(v -> {
// go ahead
f.resume();
});
})
.last() // "wait" for last event (i.e. end of file)
.finallyDo(xmlParser::close);
}
/**
* Add a chunk to the store
* @param chunk the chunk to add
* @param meta the chunk's metadata
* @param layer the layer the chunk should be added to (may be null)
* @param tags the list of tags to attach to the chunk (may be null)
* @return an observable that will emit exactly one item when the
* operation has finished
*/
private Observable<Void> addToStoreNoRetry(String chunk, ChunkMeta meta,
String layer, List<String> tags) {
ObservableFuture<Void> o = RxHelper.observableFuture();
store.add(chunk, meta, layer, tags, o.toHandler());
return o;
}
/**
* Add a chunk to the store. Retry operation several times before failing.
* @param chunk the chunk to add
* @param meta the chunk's metadata
* @param layer the layer the chunk should be added to (may be null)
* @param tags the list of tags to attach to the chunk (may be null)
* @return an observable that will emit exactly one item when the
* operation has finished
*/
private Observable<Void> addToStore(String chunk, ChunkMeta meta,
String layer, List<String> tags) {
return Observable.<Void>create(subscriber -> {
addToStoreNoRetry(chunk, meta, layer, tags).subscribe(subscriber);
}).retryWhen(RxUtils.makeRetry(MAX_RETRIES, RETRY_INTERVAL, log));
}
}
|
package com.sinch.messagingtutorial.app;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import com.parse.ParseUser;
import com.sinch.android.rtc.ClientRegistration;
import com.sinch.android.rtc.Sinch;
import com.sinch.android.rtc.SinchClient;
import com.sinch.android.rtc.SinchClientListener;
import com.sinch.android.rtc.SinchError;
import com.sinch.android.rtc.messaging.MessageClient;
import com.sinch.android.rtc.messaging.MessageClientListener;
import com.sinch.android.rtc.messaging.WritableMessage;
public class MessageService extends Service implements SinchClientListener {
private static final String APP_KEY = "YOUR_APP_KEY";
private static final String APP_SECRET = "YOUR_APP_SECRET";
private static final String ENVIRONMENT = "sandbox.sinch.com";
private final MessageServiceInterface serviceInterface = new MessageServiceInterface();
private SinchClient sinchClient = null;
private MessageClient messageClient = null;
private String currentUserId;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
currentUserId = ParseUser.getCurrentUser().getObjectId().toString();
if (currentUserId != null && !isSinchClientStarted()) {
startSinchClient(currentUserId);
}
return super.onStartCommand(intent, flags, startId);
}
public void startSinchClient(String userName) {
sinchClient = Sinch.getSinchClientBuilder().context(this).userId(userName).applicationKey(APP_KEY)
.applicationSecret(APP_SECRET).environmentHost(ENVIRONMENT).build();
sinchClient.addSinchClientListener(this);
sinchClient.setSupportMessaging(true);
sinchClient.setSupportActiveConnectionInBackground(true);
sinchClient.checkManifest();
sinchClient.start();
}
private boolean isSinchClientStarted() {
return sinchClient != null && sinchClient.isStarted();
}
@Override
public void onClientFailed(SinchClient client, SinchError error) {
sinchClient = null;
}
@Override
public void onClientStarted(SinchClient client) {
client.startListeningOnActiveConnection();
messageClient = client.getMessageClient();
}
@Override
public void onClientStopped(SinchClient client) {
sinchClient = null;
}
public void stop() {
if (isSinchClientStarted()) {
sinchClient.stop();
sinchClient.removeSinchClientListener(this);
}
sinchClient = null;
}
@Override
public IBinder onBind(Intent intent) {
return serviceInterface;
}
@Override
public boolean onUnbind(Intent intent) {
stop();
stopSelf();
return super.onUnbind(intent);
}
@Override
public void onDestroy() {
stop();
super.onDestroy();
}
@Override
public void onLogMessage(int level, String area, String message) {
//Intentionally left blank
}
@Override
public void onRegistrationCredentialsRequired(SinchClient client, ClientRegistration clientRegistration) {
//Intentionally left blank
}
public void sendMessage(String recipientUserId, String textBody) {
if (messageClient != null) {
WritableMessage message = new WritableMessage(recipientUserId, textBody);
messageClient.send(message);
}
}
public void addMessageClientListener(MessageClientListener listener) {
if (messageClient != null) {
messageClient.addMessageClientListener(listener);
}
}
public void removeMessageClientListener(MessageClientListener listener) {
if (messageClient != null) {
messageClient.removeMessageClientListener(listener);
}
}
public class MessageServiceInterface extends Binder {
public void sendMessage(String recipientUserId, String textBody) {
MessageService.this.sendMessage(recipientUserId, textBody);
}
public void addMessageClientListener(MessageClientListener listener) {
MessageService.this.addMessageClientListener(listener);
}
public void removeMessageClientListener(MessageClientListener listener) {
MessageService.this.removeMessageClientListener(listener);
}
}
}
|
package org.bonej.wrapperPlugins;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Stream.generate;
import static org.bonej.utilities.AxisUtils.getSpatialUnit;
import static org.bonej.utilities.Streamers.spatialAxisStream;
import static org.bonej.wrapperPlugins.CommonMessages.NOT_3D_IMAGE;
import static org.bonej.wrapperPlugins.CommonMessages.NOT_BINARY;
import static org.bonej.wrapperPlugins.CommonMessages.NO_IMAGE_OPEN;
import static org.scijava.ui.DialogPrompt.MessageType.WARNING_MESSAGE;
import static org.scijava.ui.DialogPrompt.OptionType.OK_CANCEL_OPTION;
import static org.scijava.ui.DialogPrompt.Result.OK_OPTION;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.function.Function;
import java.util.stream.Stream;
import net.imagej.ImgPlus;
import net.imagej.axis.CalibratedAxis;
import net.imagej.ops.OpService;
import net.imagej.ops.special.function.BinaryFunctionOp;
import net.imagej.ops.special.function.Functions;
import net.imagej.ops.special.function.UnaryFunctionOp;
import net.imagej.table.DefaultColumn;
import net.imagej.table.Table;
import net.imagej.units.UnitService;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.type.NativeType;
import net.imglib2.type.logic.BitType;
import net.imglib2.type.numeric.RealType;
import org.bonej.ops.SolveQuadricEq;
import org.bonej.ops.ellipsoid.Ellipsoid;
import org.bonej.ops.ellipsoid.QuadricToEllipsoid;
import org.bonej.ops.mil.MILGrid;
import org.bonej.utilities.AxisUtils;
import org.bonej.utilities.ElementUtil;
import org.bonej.utilities.SharedTable;
import org.bonej.wrapperPlugins.wrapperUtils.Common;
import org.bonej.wrapperPlugins.wrapperUtils.HyperstackUtils;
import org.bonej.wrapperPlugins.wrapperUtils.HyperstackUtils.Subspace;
import org.scijava.ItemIO;
import org.scijava.ItemVisibility;
import org.scijava.app.StatusService;
import org.scijava.command.Command;
import org.scijava.command.ContextCommand;
import org.scijava.log.LogService;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
import org.scijava.ui.DialogPrompt;
import org.scijava.ui.UIService;
import org.scijava.vecmath.AxisAngle4d;
import org.scijava.vecmath.Matrix4d;
import org.scijava.vecmath.Vector3d;
import org.scijava.widget.NumberWidget;
/**
* A command that analyses the degree of anisotropy in an image.
*
* @author Richard Domander
*/
@Plugin(type = Command.class, menuPath = "Plugins>BoneJ>Anisotropy")
public class AnisotropyWrapper<T extends RealType<T> & NativeType<T>> extends
ContextCommand
{
private static BinaryFunctionOp<RandomAccessibleInterval<BitType>, AxisAngle4d, List<Vector3d>> milOp;
private static UnaryFunctionOp<Matrix4d, Ellipsoid> quadricToEllipsoidOp;
private static UnaryFunctionOp<List<Vector3d>, Matrix4d> solveQuadricOp;
private static int ROTATIONS = 1_000;
private static int DEFAULT_LINES = 50;
private static double DEFAULT_INCREMENT = 1.0;
/** Assumes that the longest radius of the ellipsoid is 1.0 */
private final Function<Ellipsoid, Double> degreeOfAnisotropy =
ellipsoid -> 1.0 - ellipsoid.getA() / ellipsoid.getC();
@SuppressWarnings("unused")
@Parameter(validater = "validateImage")
private ImgPlus<T> inputImage;
@Parameter(label = "Auto parameters", required = false, persist = false,
callback = "setAutoParam")
private boolean autoParameters = false;
@Parameter(label = "Rotations",
description = "The number of times sampling is performed from different directions",
min = "1", style = NumberWidget.SPINNER_STYLE, required = false,
callback = "setAutoParam")
private Integer rotations = ROTATIONS;
@Parameter(label = "Sampling lines",
description = "Number of sampling lines drawn. The number is squared and multiplied by three",
min = "1", style = NumberWidget.SPINNER_STYLE, required = false,
callback = "setAutoParam")
private Integer lines = DEFAULT_LINES;
@Parameter(label = "Sampling increment", min = "0.01",
description = "Distance between sampling points (in pixels)",
style = NumberWidget.SPINNER_STYLE, required = false,
callback = "setAutoParam", stepSize = "0.1")
private Double samplingIncrement = DEFAULT_INCREMENT;
@Parameter(visibility = ItemVisibility.MESSAGE)
private String instruction =
"NB parameter values can affect results significantly";
private boolean calibrationWarned;
@Parameter(label = "Print ellipsoids",
description = "Print axes of the fitted ellipsoids", required = false)
private boolean printEllipsoids;
// TODO add @Parameter to align the image to the ellipsoid
// Create a rotated view from the ImgPlus and pop that into an output
// @Parameter
// TODO add help button
@Parameter(visibility = ItemVisibility.MESSAGE)
private String divider = "- - -";
/**
* The anisotropy results in a {@link Table}.
* <p>
* Null if there are no results.
* </p>
*/
@Parameter(type = ItemIO.OUTPUT, label = "BoneJ results")
private Table<DefaultColumn<String>, String> resultsTable;
@Parameter
private LogService logService;
@Parameter
private StatusService statusService;
@Parameter
private OpService opService;
@Parameter
private UIService uiService;
@Parameter
private UnitService unitService;
@Override
public void run() {
statusService.showStatus("Anisotropy: initialising");
final ImgPlus<BitType> bitImgPlus = Common.toBitTypeImgPlus(opService,
inputImage);
final List<Subspace<BitType>> subspaces = HyperstackUtils.split3DSubspaces(
bitImgPlus).collect(toList());
matchOps(subspaces.get(0));
// TODO Does it make more sense to collect all the results we can (without
// cancelling) and then report errors at the end?
for (int i = 0; i < subspaces.size(); i++) {
final Subspace<BitType> subspace = subspaces.get(i);
statusService.showStatus("Anisotropy: sampling subspace #" + (i + 1));
final List<Vector3d> pointCloud;
try {
pointCloud = runRotationsInParallel(subspace.interval);
}
catch (ExecutionException | InterruptedException e) {
logService.trace(e.getMessage());
cancel("Parallel execution got interrupted");
return;
}
applyCalibration(pointCloud);
final Ellipsoid ellipsoid = fitEllipsoid(pointCloud);
if (ellipsoid == null) {
cancel(
"Anisotropy could not be calculated - try adding more rotations");
return;
}
statusService.showStatus("Determining anisotropy");
final double anisotropy = degreeOfAnisotropy.apply(ellipsoid);
addResults(subspace, anisotropy, ellipsoid);
}
if (SharedTable.hasData()) {
resultsTable = SharedTable.getTable();
}
}
// region -- Helper methods --
private void addResults(final Subspace<BitType> subspace,
final double anisotropy, final Ellipsoid ellipsoid)
{
final String imageName = inputImage.getName();
final String suffix = subspace.toString();
final String label = suffix.isEmpty() ? imageName : imageName + " " +
suffix;
SharedTable.add(label, "Degree of anisotropy", anisotropy);
if (printEllipsoids) {
final List<Vector3d> semiAxes = ellipsoid.getSemiAxes();
int ordinal = 1;
for (final Vector3d axis : semiAxes) {
SharedTable.add(label, "Ellipsoid axis #" + ordinal, axis.toString());
ordinal++;
}
}
}
private void applyCalibration(final List<Vector3d> pointCloud) {
final double[] scales = spatialAxisStream(inputImage).mapToDouble(
axis -> axis.averageScale(0, 1)).toArray();
final String[] units = spatialAxisStream(inputImage).map(
CalibratedAxis::unit).toArray(String[]::new);
final double yxConversion = unitService.value(1.0, units[1], units[0]);
final double zxConversion = unitService.value(1.0, units[2], units[0]);
final double xScale = scales[0];
final double yScale = scales[1] * yxConversion;
final double zScale = scales[2] * zxConversion;
pointCloud.forEach(p -> {
p.setX(p.x * xScale);
p.setY(p.y * yScale);
p.setZ(p.z * zScale);
});
}
private Ellipsoid fitEllipsoid(final List<Vector3d> pointCloud) {
if (pointCloud.size() < SolveQuadricEq.QUADRIC_TERMS) {
return null;
}
statusService.showStatus("Anisotropy: solving quadric equation");
final Matrix4d quadric = solveQuadricOp.calculate(pointCloud);
if (!QuadricToEllipsoid.isEllipsoid(quadric)) {
return null;
}
statusService.showStatus("Anisotropy: fitting ellipsoid");
return quadricToEllipsoidOp.calculate(quadric);
}
// TODO Refactor into a static utility method with unit tests
private boolean isCalibrationIsotropic() {
final Optional<String> commonUnit = getSpatialUnit(inputImage, unitService);
if (!commonUnit.isPresent()) {
return false;
}
final String unit = commonUnit.get();
return spatialAxisStream(inputImage).map(axis -> unitService.value(axis
.averageScale(0, 1), axis.unit(), unit)).distinct().count() == 1;
}
@SuppressWarnings("unchecked")
private void matchOps(final Subspace<BitType> subspace) {
milOp = (BinaryFunctionOp) Functions.binary(opService, MILGrid.class,
List.class, subspace.interval, new AxisAngle4d(), lines,
samplingIncrement, new Random());
final List<Vector3d> tmpPoints = generate(Vector3d::new).limit(
SolveQuadricEq.QUADRIC_TERMS).collect(toList());
solveQuadricOp = Functions.unary(opService, SolveQuadricEq.class,
Matrix4d.class, tmpPoints);
final Matrix4d matchingMock = new Matrix4d();
matchingMock.setIdentity();
quadricToEllipsoidOp = Functions.unary(opService, QuadricToEllipsoid.class,
Ellipsoid.class, matchingMock);
}
private List<Vector3d> runRotationsInParallel(
final RandomAccessibleInterval<BitType> interval) throws ExecutionException,
InterruptedException
{
final ExecutorService executor = Executors.newFixedThreadPool(5);
final Callable<List<Vector3d>> milTask = () -> milOp.calculate(interval);
final List<Future<List<Vector3d>>> futures = Stream.generate(() -> milTask)
.limit(rotations).map(executor::submit).collect(toList());
final List<Vector3d> pointCloud = Collections.synchronizedList(
new ArrayList<>(rotations * 3));
final int futuresSize = futures.size();
for (int j = 0; j < futuresSize; j++) {
statusService.showProgress(j, futuresSize);
final List<Vector3d> points = futures.get(j).get();
pointCloud.addAll(points);
}
executor.shutdown();
return pointCloud;
}
@SuppressWarnings("unused")
private void setAutoParam() {
if (!autoParameters) {
return;
}
rotations = ROTATIONS;
lines = DEFAULT_LINES;
samplingIncrement = DEFAULT_INCREMENT;
}
@SuppressWarnings("unused")
private void validateImage() {
if (inputImage == null) {
cancel(NO_IMAGE_OPEN);
return;
}
if (AxisUtils.countSpatialDimensions(inputImage) != 3) {
cancel(NOT_3D_IMAGE);
return;
}
if (!ElementUtil.isColorsBinary(inputImage)) {
cancel(NOT_BINARY);
return;
}
if (!isCalibrationIsotropic() && !calibrationWarned) {
final DialogPrompt.Result result = uiService.showDialog(
"The image calibration is anisotropic and may affect results. Continue anyway?",
WARNING_MESSAGE, OK_CANCEL_OPTION);
// Avoid showing warning more than once (validator gets called before and
// after dialog pops up..?)
calibrationWarned = true;
if (result != OK_OPTION) {
cancel(null);
}
}
// TODO Is the 5 slice minimum necessary?
}
// endregion
}
|
package org.bonej.wrapperPlugins;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Stream.generate;
import static org.bonej.utilities.AxisUtils.getSpatialUnit;
import static org.bonej.utilities.AxisUtils.isSpatialCalibrationsIsotropic;
import static org.bonej.utilities.Streamers.spatialAxisStream;
import static org.bonej.wrapperPlugins.CommonMessages.NOT_3D_IMAGE;
import static org.bonej.wrapperPlugins.CommonMessages.NOT_BINARY;
import static org.bonej.wrapperPlugins.CommonMessages.NO_IMAGE_OPEN;
import static org.scijava.ui.DialogPrompt.MessageType.WARNING_MESSAGE;
import static org.scijava.ui.DialogPrompt.OptionType.OK_CANCEL_OPTION;
import static org.scijava.ui.DialogPrompt.Result.OK_OPTION;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import net.imagej.ImgPlus;
import net.imagej.ops.OpService;
import net.imagej.ops.special.function.BinaryFunctionOp;
import net.imagej.ops.special.function.Functions;
import net.imagej.ops.special.function.UnaryFunctionOp;
import net.imagej.table.DefaultColumn;
import net.imagej.table.Table;
import net.imagej.units.UnitService;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.type.NativeType;
import net.imglib2.type.logic.BitType;
import net.imglib2.type.numeric.RealType;
import org.bonej.ops.RotateAboutAxis;
import org.bonej.ops.SolveQuadricEq;
import org.bonej.ops.ellipsoid.Ellipsoid;
import org.bonej.ops.ellipsoid.QuadricToEllipsoid;
import org.bonej.ops.mil.MILPlane;
import org.bonej.utilities.AxisUtils;
import org.bonej.utilities.ElementUtil;
import org.bonej.utilities.SharedTable;
import org.bonej.wrapperPlugins.wrapperUtils.Common;
import org.bonej.wrapperPlugins.wrapperUtils.HyperstackUtils;
import org.bonej.wrapperPlugins.wrapperUtils.HyperstackUtils.Subspace;
import org.scijava.ItemIO;
import org.scijava.ItemVisibility;
import org.scijava.app.StatusService;
import org.scijava.command.Command;
import org.scijava.command.ContextCommand;
import org.scijava.log.LogService;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
import org.scijava.ui.DialogPrompt.Result;
import org.scijava.ui.UIService;
import org.scijava.vecmath.AxisAngle4d;
import org.scijava.vecmath.Matrix4d;
import org.scijava.vecmath.Vector3d;
import org.scijava.widget.NumberWidget;
/**
* A command that analyses the degree of anisotropy in an image.
*
* @author Richard Domander
*/
@Plugin(type = Command.class, menuPath = "Plugins>BoneJ>Anisotropy")
public class AnisotropyWrapper<T extends RealType<T> & NativeType<T>> extends
ContextCommand
{
/**
* Default directions is 2_000 since that's roughly the number of points in
* Poisson distributed sampling that'd give points about 5 degrees apart).
*/
private static final int DEFAULT_DIRECTIONS = 2_000;
// The default number of lines was found to be sensible after experimenting
// with data at hand. Other data may need a different number.
private static final int DEFAULT_LINES = 100;
private static final double DEFAULT_INCREMENT = 1.0;
private static BinaryFunctionOp<RandomAccessibleInterval<BitType>, AxisAngle4d, Vector3d> milOp;
private static UnaryFunctionOp<Matrix4d, Optional<Ellipsoid>> quadricToEllipsoidOp;
private static UnaryFunctionOp<List<Vector3d>, Matrix4d> solveQuadricOp;
private final Function<Ellipsoid, Double> degreeOfAnisotropy =
ellipsoid -> 1.0 - ellipsoid.getA() / ellipsoid.getC();
@SuppressWarnings("unused")
@Parameter(validater = "validateImage")
private ImgPlus<T> inputImage;
@Parameter(label = "Directions",
description = "The number of times sampling is performed from different directions",
min = "9", style = NumberWidget.SPINNER_STYLE, required = false,
callback = "applyMinimum")
private Integer directions = DEFAULT_DIRECTIONS;
@Parameter(label = "Lines per dimension",
description = "How many sampling lines are projected in both 2D directions (this number squared)",
min = "1", style = NumberWidget.SPINNER_STYLE, required = false,
callback = "applyMinimum")
private Integer lines = DEFAULT_LINES;
@Parameter(label = "Sampling increment", min = "0.01",
description = "Distance between sampling points (in voxels)",
style = NumberWidget.SPINNER_STYLE, required = false, stepSize = "0.1",
callback = "applyMinimum")
private Double samplingIncrement = DEFAULT_INCREMENT;
@Parameter(label = "Recommended minimum",
description = "Apply minimum recommended values to directions, lines, and increment",
persist = false, required = false, callback = "applyMinimum")
private boolean recommendedMin;
@Parameter(visibility = ItemVisibility.MESSAGE)
private String instruction =
"NB parameter values can affect results significantly";
private boolean calibrationWarned;
@Parameter(label = "Show radii",
description = "Show the radii of the fitted ellipsoid in the results",
required = false)
private boolean printRadii;
/**
* The anisotropy results in a {@link Table}.
* <p>
* Null if there are no results.
* </p>
*/
@Parameter(type = ItemIO.OUTPUT, label = "BoneJ results")
private Table<DefaultColumn<String>, String> resultsTable;
@Parameter
private LogService logService;
@Parameter
private StatusService statusService;
@Parameter
private OpService opService;
@Parameter
private UIService uiService;
@Parameter
private UnitService unitService;
@Override
public void run() {
statusService.showStatus("Anisotropy: initialising");
final ImgPlus<BitType> bitImgPlus = Common.toBitTypeImgPlus(opService,
inputImage);
final List<Subspace<BitType>> subspaces = HyperstackUtils.split3DSubspaces(
bitImgPlus).collect(toList());
matchOps(subspaces.get(0));
final List<Ellipsoid> ellipsoids = new ArrayList<>();
for (int i = 0; i < subspaces.size(); i++) {
statusService.showStatus("Anisotropy: sampling subspace #" + (i + 1));
final Subspace<BitType> subspace = subspaces.get(i);
final Ellipsoid ellipsoid = milEllipsoid(subspace);
if (ellipsoid == null) {
return;
}
ellipsoids.add(ellipsoid);
}
addResults(subspaces, ellipsoids);
if (SharedTable.hasData()) {
resultsTable = SharedTable.getTable();
}
}
// region -- Helper methods --
private void addResult(final Subspace<BitType> subspace,
final double anisotropy, final Ellipsoid ellipsoid)
{
final String imageName = inputImage.getName();
final String suffix = subspace.toString();
final String label = suffix.isEmpty() ? imageName : imageName + " " +
suffix;
SharedTable.add(label, "Degree of anisotropy", anisotropy);
if (printRadii) {
SharedTable.add(label, "Radius a", String.format("%.2f", ellipsoid
.getA()));
SharedTable.add(label, "Radius b", String.format("%.2f", ellipsoid
.getB()));
SharedTable.add(label, "Radius c", String.format("%.2f", ellipsoid
.getC()));
}
}
private void addResults(final List<Subspace<BitType>> subspaces,
final List<Ellipsoid> ellipsoids)
{
statusService.showStatus("Anisotropy: showing results");
for (int i = 0; i < subspaces.size(); i++) {
final Subspace<BitType> subspace = subspaces.get(i);
final Ellipsoid ellipsoid = ellipsoids.get(i);
final double anisotropy = degreeOfAnisotropy.apply(ellipsoid);
addResult(subspace, anisotropy, ellipsoid);
}
}
@SuppressWarnings("unused")
private void applyMinimum() {
if (recommendedMin) {
lines = DEFAULT_LINES;
directions = DEFAULT_DIRECTIONS;
samplingIncrement = DEFAULT_INCREMENT;
}
}
private Optional<Ellipsoid> fitEllipsoid(final List<Vector3d> pointCloud) {
statusService.showStatus("Anisotropy: solving quadric equation");
final Matrix4d quadric = solveQuadricOp.calculate(pointCloud);
statusService.showStatus("Anisotropy: fitting ellipsoid");
return quadricToEllipsoidOp.calculate(quadric);
}
private Ellipsoid milEllipsoid(final Subspace<BitType> subspace) {
final List<Vector3d> pointCloud;
try {
pointCloud = runDirectionsInParallel(subspace.interval);
if (pointCloud.size() < SolveQuadricEq.QUADRIC_TERMS) {
cancel("Anisotropy could not be calculated - too few points");
return null;
}
final Optional<Ellipsoid> ellipsoid = fitEllipsoid(pointCloud);
if (!ellipsoid.isPresent()) {
cancel("Anisotropy could not be calculated - ellipsoid fitting failed");
return null;
}
return ellipsoid.get();
}
catch (final ExecutionException | InterruptedException e) {
logService.trace(e.getMessage());
cancel("The plug-in was interrupted");
}
return null;
}
// TODO Refactor into a static utility method with unit tests
private boolean isCalibrationIsotropic() {
final Optional<String> commonUnit = getSpatialUnit(inputImage, unitService);
if (!commonUnit.isPresent()) {
return false;
}
final String unit = commonUnit.get();
return spatialAxisStream(inputImage).map(axis -> unitService.value(axis
.averageScale(0, 1), axis.unit(), unit)).distinct().count() == 1;
}
@SuppressWarnings("unchecked")
private void matchOps(final Subspace<BitType> subspace) {
milOp = Functions.binary(opService, MILPlane.class, Vector3d.class,
subspace.interval, new AxisAngle4d(), lines, samplingIncrement);
final List<Vector3d> tmpPoints = generate(Vector3d::new).limit(
SolveQuadricEq.QUADRIC_TERMS).collect(toList());
solveQuadricOp = Functions.unary(opService, SolveQuadricEq.class,
Matrix4d.class, tmpPoints);
final Matrix4d matchingMock = new Matrix4d();
matchingMock.setIdentity();
quadricToEllipsoidOp = (UnaryFunctionOp) Functions.unary(opService, QuadricToEllipsoid.class,
Optional.class, matchingMock);
}
private List<Vector3d> runDirectionsInParallel(
final RandomAccessibleInterval<BitType> interval) throws ExecutionException,
InterruptedException
{
final int cores = Runtime.getRuntime().availableProcessors();
// The parallellization of the the MILPlane algorithm is a memory bound
// problem, which is why speed gains start to drop after 5 cores. With much
// larger 'nThreads' it slows down due to overhead. Of course '5' here is a
// bit of a magic number, which might not hold true for all environments,
// but we need some kind of upper bound
final int nThreads = Math.max(5, cores);
final ExecutorService executor = Executors.newFixedThreadPool(nThreads);
final Callable<Vector3d> milTask = () -> milOp.calculate(interval,
RotateAboutAxis.randomAxisAngle());
final List<Future<Vector3d>> futures = generate(() -> milTask).limit(
directions).map(executor::submit).collect(toList());
final List<Vector3d> pointCloud = Collections.synchronizedList(
new ArrayList<>(directions));
final int futuresSize = futures.size();
final AtomicInteger progress = new AtomicInteger();
for (final Future<Vector3d> future : futures) {
statusService.showProgress(progress.getAndIncrement(), futuresSize);
final Vector3d milVector = future.get();
pointCloud.add(milVector);
}
shutdownAndAwaitTermination(executor);
return pointCloud;
}
// Shuts down an ExecutorService as per recommended by Oracle
private void shutdownAndAwaitTermination(final ExecutorService executor) {
executor.shutdown(); // Disable new tasks from being submitted
try {
// Wait a while for existing tasks to terminate
if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
executor.shutdownNow(); // Cancel currently executing tasks
// Wait a while for tasks to respond to being cancelled
if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
logService.trace("Pool did not terminate");
}
}
}
catch (final InterruptedException ie) {
// (Re-)Cancel if current thread also interrupted
executor.shutdownNow();
// Preserve interrupt status
Thread.currentThread().interrupt();
}
}
@SuppressWarnings("unused")
private void validateImage() {
if (inputImage == null) {
cancel(NO_IMAGE_OPEN);
return;
}
if (AxisUtils.countSpatialDimensions(inputImage) != 3) {
cancel(NOT_3D_IMAGE);
return;
}
if (!ElementUtil.isColorsBinary(inputImage)) {
cancel(NOT_BINARY);
return;
}
if (!isSpatialCalibrationsIsotropic(inputImage, 0.01, unitService) &&
!calibrationWarned)
{
final Result result = uiService.showDialog(
"The voxels in the image are anisotropic, which may affect results. Continue anyway?",
WARNING_MESSAGE, OK_CANCEL_OPTION);
// Avoid showing warning more than once (validator gets called before and
// after dialog pops up..?)
calibrationWarned = true;
if (result != OK_OPTION) {
cancel(null);
}
}
}
// endregion
}
|
package org.epics.graphene;
import java.util.ArrayList;
import java.util.List;
import org.epics.util.array.ArrayDouble;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
/**
*
* @author carcassi
*/
public class StatisticsUtilTest {
@Test
public void statisticsOf1() {
Statistics stats = StatisticsUtil.statisticsOf(new ArrayDouble(1.0));
assertThat(stats.getAverage(), equalTo(1.0));
assertThat(stats.getStdDev(), equalTo(0.0));
assertThat(stats.getMinimum(), equalTo((Number) 1.0));
assertThat(stats.getMaximum(), equalTo((Number) 1.0));
assertThat(stats.getCount(), equalTo(1));
}
@Test
public void statisticsOf2() {
Statistics stats = StatisticsUtil.statisticsOf(new ArrayDouble(1, 3, 5, -1, 7));
assertThat(stats.getAverage(), equalTo(3.0));
assertThat(stats.getStdDev(), equalTo(2.8284271247461903));
assertThat(stats.getMinimum(), equalTo((Number) (-1.0)));
assertThat(stats.getMaximum(), equalTo((Number) 7.0));
assertThat(stats.getCount(), equalTo(5));
}
@Test
public void statisticsOf3() {
List<Statistics> list = new ArrayList<Statistics>();
for (int i = 0; i < 10; i++) {
list.add(StatisticsUtil.statisticsOf(new ArrayDouble(i)));
}
Statistics stats = StatisticsUtil.statisticsOf(list);
assertThat(stats.getAverage(), equalTo(4.5));
assertThat(stats.getStdDev(), equalTo(2.8722813232690143));
assertThat(stats.getMinimum(), equalTo((Number) 0.0));
assertThat(stats.getMaximum(), equalTo((Number) 9.0));
assertThat(stats.getCount(), equalTo(10));
}
}
|
package org.bonej.wrapperPlugins;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.bonej.utilities.Streamers.spatialAxisStream;
import static org.bonej.wrapperPlugins.CommonMessages.*;
import static org.scijava.ui.DialogPrompt.MessageType.ERROR_MESSAGE;
import static org.scijava.ui.DialogPrompt.MessageType.WARNING_MESSAGE;
import com.google.common.base.Strings;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.imagej.ImgPlus;
import net.imagej.axis.CalibratedAxis;
import net.imagej.ops.OpService;
import net.imagej.ops.Ops;
import net.imagej.ops.geom.geom3d.mesh.Facet;
import net.imagej.ops.geom.geom3d.mesh.Mesh;
import net.imagej.ops.geom.geom3d.mesh.TriangularFacet;
import net.imagej.ops.special.function.Functions;
import net.imagej.ops.special.function.UnaryFunctionOp;
import net.imagej.space.AnnotatedSpace;
import net.imagej.units.UnitService;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.type.NativeType;
import net.imglib2.type.logic.BitType;
import net.imglib2.type.numeric.RealType;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
import org.bonej.utilities.AxisUtils;
import org.bonej.utilities.ElementUtil;
import org.bonej.utilities.ResultsInserter;
import org.bonej.wrapperPlugins.wrapperUtils.Common;
import org.bonej.wrapperPlugins.wrapperUtils.ResultUtils;
import org.bonej.wrapperPlugins.wrapperUtils.ViewUtils;
import org.bonej.wrapperPlugins.wrapperUtils.ViewUtils.SpatialView;
import org.jetbrains.annotations.Nullable;
import org.scijava.command.Command;
import org.scijava.command.ContextCommand;
import org.scijava.log.LogService;
import org.scijava.platform.PlatformService;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
import org.scijava.ui.UIService;
import org.scijava.widget.Button;
import org.scijava.widget.FileWidget;
/**
* A wrapper command to calculate mesh surface area
*
* @author Richard Domander
*/
@Plugin(type = Command.class, menuPath = "Plugins>BoneJ>Isosurface", headless = true)
public class IsosurfaceWrapper<T extends RealType<T> & NativeType<T>> extends ContextCommand {
public static final String STL_WRITE_ERROR = "Failed to write the following STL files:\n\n";
public static final String STL_HEADER = Strings.padEnd("Binary STL created by BoneJ", 80, '.');
public static final String BAD_SCALING = "Cannot scale result because axis calibrations don't match";
@Parameter(validater = "validateImage")
private ImgPlus<T> inputImage;
@Parameter(label = "Export STL file(s)", description = "Create a binary STL file from the surface mesh",
required = false)
private boolean exportSTL;
@Parameter(label = "Help", description = "Open help web page", callback = "openHelpPage")
private Button helpButton;
@Parameter
private LogService logService;
@Parameter
private OpService ops;
@Parameter
private PlatformService platformService;
@Parameter
private UIService uiService;
@Parameter
private UnitService unitService;
private boolean calibrationWarned = false;
private boolean scalingWarned = false;
private UnaryFunctionOp<RandomAccessibleInterval, Mesh> marchingCubesOp;
@Override
public void run() {
final ImgPlus<BitType> bitImgPlus = Common.toBitTypeImgPlus(ops, inputImage);
final List<SpatialView<BitType>> views = ViewUtils.createSpatialViews(bitImgPlus);
matchOps(views.get(0).view);
processViews(views);
}
// -- Helper methods --
private static void writeSTLFacet(ByteBuffer buffer, TriangularFacet facet) {
writeSTLVector(buffer, facet.getNormal());
writeSTLVector(buffer, facet.getP0());
writeSTLVector(buffer, facet.getP1());
writeSTLVector(buffer, facet.getP2());
buffer.putShort((short) 0); // Attribute byte count
}
private static void writeSTLVector(ByteBuffer buffer, Vector3D v) {
buffer.putFloat((float) v.getX());
buffer.putFloat((float) v.getY());
buffer.putFloat((float) v.getZ());
}
private void matchOps(final RandomAccessibleInterval<BitType> matchingView) {
//TODO match with suitable mocked "NilTypes" (conforms == true)
marchingCubesOp = Functions.unary(ops, Ops.Geometric.MarchingCubes.class, Mesh.class, matchingView);
}
private void processViews(List<SpatialView<BitType>> views) {
final String name = inputImage.getName();
final Map<String, String> failedMeshes = new HashMap<>();
String path = "";
String extension = "";
if (exportSTL) {
path = choosePath();
if (path == null) {
return;
}
final String fileName = path.substring(path.lastIndexOf(File.separator) + 1);
final int dot = fileName.lastIndexOf(".");
if (dot >= 0) {
extension = fileName.substring(dot);
//TODO add check for bad extension when DialogPrompt YES/NO options work correctly
path = path.substring(0, path.length() - extension.length());
} else {
extension = ".stl";
}
}
for (SpatialView<?> view : views) {
final String label = name + view.hyperPosition;
final Mesh mesh = marchingCubesOp.calculate(view.view);
final double area = mesh.getSurfaceArea();
showArea(label, area);
if (exportSTL) {
try {
writeBinarySTLFile(path + view.hyperPosition + extension, mesh);
} catch (Exception e) {
failedMeshes.put(label, e.getMessage());
}
}
}
if (failedMeshes.size() > 0) {
StringBuilder msgBuilder = new StringBuilder(STL_WRITE_ERROR);
failedMeshes.forEach((k, v) -> msgBuilder.append(k).append(": ").append(v));
uiService.showDialog(msgBuilder.toString(), ERROR_MESSAGE);
}
}
@Nullable
private String choosePath() {
String initialName = stripFileExtension(inputImage.getName());
// The file dialog won't allow empty filenames, and it prompts when file already exists
File file = uiService.chooseFile(new File(initialName), FileWidget.SAVE_STYLE);
if (file == null) {
// User pressed cancel on file dialog
return null;
}
return file.getAbsolutePath();
}
//TODO make into a utility method
private static String stripFileExtension(String path) {
final int dot = path.lastIndexOf('.');
return dot == -1 ? path : path.substring(0, dot);
}
private void showArea(final String label, double area) {
final String unitHeader = ResultUtils.getUnitHeader(inputImage, unitService, '²');
if (unitHeader.isEmpty() && !calibrationWarned) {
uiService.showDialog(BAD_CALIBRATION, WARNING_MESSAGE);
calibrationWarned = true;
}
if (!isAxesMatchingSpatialCalibration(inputImage) && !scalingWarned) {
uiService.showDialog(BAD_SCALING, WARNING_MESSAGE);
scalingWarned = true;
} else {
final double scale = inputImage.axis(0).averageScale(0.0, 1.0);
final double areaCalibration = scale * scale;
area *= areaCalibration;
}
final ResultsInserter resultsInserter = ResultsInserter.getInstance();
resultsInserter.setMeasurementInFirstFreeRow(label, "Surface area " + unitHeader, area);
resultsInserter.updateResults();
}
@SuppressWarnings("unused")
private void validateImage() {
if (inputImage == null) {
cancel(NO_IMAGE_OPEN);
return;
}
if (AxisUtils.countSpatialDimensions(inputImage) != 3) {
cancel(NOT_3D_IMAGE);
}
if (!ElementUtil.isColorsBinary(inputImage)) {
cancel(NOT_BINARY);
}
}
@SuppressWarnings("unused")
private void openHelpPage() {
Help.openHelpPage("http://bonej.org/isosurface", platformService, uiService, logService);
}
// -- Utility methods --
/**
* Writes the surface mesh as a binary, little endian STL file
* <p>
* <p>
* NB: Public and static for testing purposes
* </p>
*
* @param path The absolute path to the save location of the STL file
* @param mesh A mesh consisting of triangular facets
*/
// TODO: Remove when SciJava PR goes through
public static void writeBinarySTLFile(final String path, final Mesh mesh)
throws IllegalArgumentException, IOException, NullPointerException {
checkNotNull(mesh, "Mesh cannot be null");
checkArgument(!Strings.isNullOrEmpty(path), "Filename cannot be null or empty");
final List<Facet> facets = mesh.getFacets();
final int numFacets = facets.size();
checkArgument(mesh.triangularFacets(), "Cannot write STL file: invalid surface mesh");
try (FileOutputStream writer = new FileOutputStream(path)) {
final byte[] header = STL_HEADER.getBytes();
writer.write(header);
byte[] facetBytes = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(numFacets).array();
writer.write(facetBytes);
final ByteBuffer buffer = ByteBuffer.allocate(50);
buffer.order(ByteOrder.LITTLE_ENDIAN);
for (Facet facet : facets) {
final TriangularFacet triangularFacet = (TriangularFacet) facet;
writeSTLFacet(buffer, triangularFacet);
writer.write(buffer.array());
buffer.clear();
}
}
}
/**
* Check if all the spatial axes have a matching calibration, e.g. same unit, same scaling
* <p>
* NB: Public and static for testing purposes
* </p>
*/
// TODO make into a utility method or remove if mesh area considers calibration in the future
public static <T extends AnnotatedSpace<CalibratedAxis>> boolean isAxesMatchingSpatialCalibration(T space) {
final boolean noUnits = spatialAxisStream(space).map(CalibratedAxis::unit).allMatch(Strings::isNullOrEmpty);
final boolean matchingUnit = spatialAxisStream(space).map(CalibratedAxis::unit).distinct().count() == 1;
final boolean matchingScale = spatialAxisStream(space).map(a -> a.averageScale(0, 1)).distinct().count() == 1;
return (matchingUnit || noUnits) && matchingScale;
}
}
|
package verification.platu.markovianAnalysis;
import java.util.ArrayList;
import lpn.parser.Transition;
import verification.platu.project.PrjState;
import verification.platu.stategraph.State;
public class ProbGlobalState extends PrjState {
private int color;
private double currentProb;
private double nextProb;
/**
* Index of the local state that where the most recent fired transition originates.
*/
private ArrayList<Integer> localStateIndexArray;
public ProbGlobalState(State[] other, Transition newFiredTran,
int newTranFiringCnt) {
super(other, newFiredTran, newTranFiringCnt);
localStateIndexArray = new ArrayList<Integer>();
}
public ProbGlobalState(State[] other) {
super(other);
localStateIndexArray = new ArrayList<Integer>();
}
public int getColor() {
return color;
}
public void setColor(int color) {
this.color = color;
}
public double getCurrentProb() {
return currentProb;
}
public void setCurrentProb(double currentProb) {
this.currentProb = currentProb;
}
public double getNextProb() {
return nextProb;
}
public void setNextProb(double nextProb) {
this.nextProb = nextProb;
}
public void setCurrentProbToNext() {
currentProb = nextProb;
}
public ArrayList<Integer> getLocalStateIndex() {
return localStateIndexArray;
}
// public void setLocalStateIndex(ArrayList<Integer> localStateIndex) {
// this.localStateIndexArray = localStateIndex;
public void addLocalStateIndex(int localStateIndex) {
this.localStateIndexArray.add(localStateIndex);
}
}
|
package org.bimserver.database.queries.om;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.bimserver.database.queries.om.Include.TypeDef;
import org.bimserver.emf.PackageMetaData;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EReference;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeType;
import com.fasterxml.jackson.databind.node.ObjectNode;
public class JsonQueryObjectModelConverter {
private static final Map<String, Include> CACHED_DEFINES = new HashMap<>();
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private PackageMetaData packageMetaData;
public JsonQueryObjectModelConverter(PackageMetaData packageMetaData) {
this.packageMetaData = packageMetaData;
}
public ObjectNode toJson(Query query) {
ObjectNode queryNode = OBJECT_MAPPER.createObjectNode();
Map<String, Include> defines = query.getDefines();
ObjectNode definesNode = OBJECT_MAPPER.createObjectNode();
queryNode.set("defines", definesNode);
queryNode.put("doublebuffer", query.isDoubleBuffer());
for (String key : defines.keySet()) {
Include include = defines.get(key);
definesNode.set(key, dumpInclude(include));
}
ArrayNode queryPartsNode = OBJECT_MAPPER.createArrayNode();
queryNode.set("queries", queryPartsNode);
for (QueryPart queryPart : query.getQueryParts()) {
ObjectNode queryPartNode = OBJECT_MAPPER.createObjectNode();
if (queryPart.hasTypes()) {
ArrayNode typesNode = OBJECT_MAPPER.createArrayNode();
queryPartNode.set("types", typesNode);
for (TypeDef type : queryPart.getTypes()) {
if (type.isIncludeSubTypes()) {
ObjectNode typeDefNode = OBJECT_MAPPER.createObjectNode();
typeDefNode.put("name", type.geteClass().getName());
typeDefNode.put("includeAllSubTypes", type.isIncludeSubTypes());
typesNode.add(typeDefNode);
} else {
typesNode.add(type.geteClass().getName());
}
}
}
if (queryPart.hasOids()) {
ArrayNode oidsNode = OBJECT_MAPPER.createArrayNode();
queryPartNode.set("oids", oidsNode);
for (long oid : queryPart.getOids()) {
oidsNode.add(oid);
}
}
if (queryPart.hasInBoundingBox()) {
ObjectNode inBoundingBoxNode = OBJECT_MAPPER.createObjectNode();
inBoundingBoxNode.put("x", queryPart.getInBoundingBox().getX());
inBoundingBoxNode.put("y", queryPart.getInBoundingBox().getY());
inBoundingBoxNode.put("z", queryPart.getInBoundingBox().getZ());
inBoundingBoxNode.put("width", queryPart.getInBoundingBox().getWidth());
inBoundingBoxNode.put("height", queryPart.getInBoundingBox().getHeight());
inBoundingBoxNode.put("depth", queryPart.getInBoundingBox().getDepth());
inBoundingBoxNode.put("partial", queryPart.getInBoundingBox().isPartial());
queryPartNode.set("inBoundingBox", inBoundingBoxNode);
}
if (queryPart.hasIncludes() || queryPart.hasReferences()) {
ArrayNode includesNode = OBJECT_MAPPER.createArrayNode();
queryPartNode.set("includes", includesNode);
if (queryPart.hasIncludes()) {
for (Include include : queryPart.getIncludes()) {
ObjectNode includeNode = dumpInclude(include);
includesNode.add(includeNode);
}
}
if (queryPart.hasReferences()) {
for (Reference reference : queryPart.getReferences()) {
includesNode.add(reference.getName());
}
}
}
queryPartsNode.add(queryPartNode);
}
return queryNode;
}
private ObjectNode dumpInclude(Include include) {
ObjectNode includeNode = OBJECT_MAPPER.createObjectNode();
ArrayNode typesNode = OBJECT_MAPPER.createArrayNode();
for (TypeDef type : include.getTypes()) {
typesNode.add(type.geteClass().getName());
}
includeNode.set("types", typesNode);
ArrayNode fieldsNode = OBJECT_MAPPER.createArrayNode();
for (EReference eReference : include.getFields()) {
fieldsNode.add(eReference.getName());
}
includeNode.set("fields", fieldsNode);
if (include.hasIncludes() || include.hasReferences()) {
ArrayNode includes = OBJECT_MAPPER.createArrayNode();
includeNode.set("includes", includes);
if (include.hasIncludes()) {
for (Include nextInclude : include.getIncludes()) {
includes.add(dumpInclude(nextInclude));
}
}
if (include.hasReferences()) {
for (Reference reference : include.getReferences()) {
includes.add(reference.getName());
}
}
}
if (include.hasOutputTypes()) {
throw new RuntimeException("Not implemented");
}
return includeNode;
}
public Query parseJson(String queryName, ObjectNode fullQuery) throws QueryException {
Query query = new Query(queryName, packageMetaData);
query.setDoubleBuffer(fullQuery.has("doublebuffer") ? fullQuery.get("doublebuffer").asBoolean() : false);
if (fullQuery.has("defines")) {
JsonNode defines = fullQuery.get("defines");
if (defines instanceof ObjectNode) {
parseDefines(query, (ObjectNode)fullQuery.get("defines"));
} else {
throw new QueryException("\"defines\" must be of type object");
}
}
if (fullQuery.has("queries")) {
JsonNode queriesNode = fullQuery.get("queries");
if (queriesNode instanceof ArrayNode) {
ArrayNode queries = (ArrayNode) fullQuery.get("queries");
if (queries.size() == 0) {
throw new QueryException("\"queries\" must contain at least one query");
}
for (int i=0; i<queries.size(); i++) {
parseJsonQuery(query, (ObjectNode)queries.get(i));
}
} else {
throw new QueryException("\"queries\" must be of type array");
}
} else if (fullQuery.has("query")) {
JsonNode queryNode = fullQuery.get("query");
if (queryNode instanceof ObjectNode) {
parseJsonQuery(query, (ObjectNode) fullQuery.get("query"));
} else {
throw new QueryException("\"query\" must be of type object");
}
} else if (!fullQuery.has("defines")) {
parseJsonQuery(query, fullQuery);
}
return query;
}
private void parseDefines(Query query, ObjectNode jsonNode) throws QueryException {
Iterator<String> fieldNames = jsonNode.fieldNames();
int i=0;
// First pass, get all the name and create stub includes, using two passing to allow the usage of includes defined later in the structure
while (fieldNames.hasNext()) {
String fieldName = fieldNames.next();
JsonNode defineNode = jsonNode.get(fieldName);
if (defineNode instanceof ObjectNode) {
Include include = new Include(packageMetaData);
query.addDefine(fieldName, include);
} else {
throw new QueryException("\"defines\"[" + fieldName + "] must be of type object");
}
i++;
}
// Second pass, actually construct the includes
fieldNames = jsonNode.fieldNames();
while (fieldNames.hasNext()) {
String fieldName = fieldNames.next();
JsonNode defineNode = jsonNode.get(fieldName);
ObjectNode define = (ObjectNode)defineNode;
parseInclude(query, define, query.getDefine(fieldName), null);
}
}
private Include parseInclude(Query query, ObjectNode jsonNode, Include include, CanInclude parentInclude) throws QueryException {
if (include == null) {
include = new Include(packageMetaData);
}
if (!jsonNode.has("type") && !jsonNode.has("types")) {
throw new QueryException("includes require a \"type\" or \"types\" field " + jsonNode);
}
if (jsonNode.has("type")) {
JsonNode typeNode = jsonNode.get("type");
if (typeNode.isTextual()) {
EClass eClass = packageMetaData.getEClassIncludingDependencies(typeNode.asText());
if (eClass == null) {
throw new QueryException("Cannot find type \"" + typeNode.asText() + "\"");
}
include.addType(eClass, false);
} else {
throw new QueryException("\"type\" field mst be of type string");
}
}
if (jsonNode.has("types")) {
JsonNode typesNode = jsonNode.get("types");
if (typesNode instanceof ArrayNode) {
ArrayNode types = (ArrayNode)typesNode;
if (types.size() == 0) {
throw new QueryException("\"types\" must have a least one element");
}
for (int i=0; i<types.size(); i++) {
JsonNode typeNode = types.get(i);
if (typeNode.isTextual()) {
EClass eClass = packageMetaData.getEClassIncludingDependencies(typeNode.asText());
include.addType(eClass, false);
} else {
throw new QueryException("\"types\"[" + i + "] field mst be of type string");
}
}
} else {
throw new QueryException("\"types\" must be of type array");
}
}
if (jsonNode.has("outputType")) {
JsonNode typeNode = jsonNode.get("outputType");
if (typeNode.isTextual()) {
EClass eClass = packageMetaData.getEClassIncludingDependencies(typeNode.asText());
include.addOutputType(eClass);
} else {
throw new QueryException("\"outputType\" field mst be of type string");
}
}
if (jsonNode.has("outputTypes")) {
JsonNode typesNode = jsonNode.get("outputTypes");
if (typesNode instanceof ArrayNode) {
ArrayNode types = (ArrayNode)typesNode;
if (types.size() == 0) {
throw new QueryException("\"outputTypes\" must have a least one element");
}
for (int i=0; i<types.size(); i++) {
JsonNode typeNode = types.get(i);
if (typeNode.isTextual()) {
EClass eClass = packageMetaData.getEClass(typeNode.asText());
include.addOutputType(eClass);
} else {
throw new QueryException("\"outputTypes\"[" + i + "] field mst be of type string");
}
}
} else {
throw new QueryException("\"outputTypes\" must be of type array");
}
}
if (jsonNode.has("field")) {
JsonNode fieldNode = jsonNode.get("field");
if (fieldNode.isTextual()) {
include.addField(fieldNode.asText());
} else {
throw new QueryException("\"field\" must be of type string");
}
}
if (jsonNode.has("fields")) {
JsonNode fieldsNode = jsonNode.get("fields");
if (fieldsNode instanceof ArrayNode) {
ArrayNode fields = (ArrayNode)fieldsNode;
for (int i=0; i<fields.size(); i++) {
JsonNode fieldNode = fields.get(i);
if (fieldNode.isTextual()) {
include.addField(fieldNode.asText());
} else {
throw new QueryException("\"fields\"[" + i + "] must be of type string");
}
}
} else {
throw new QueryException("\"fields\" must be of type array");
}
}
if (jsonNode.has("include")) {
JsonNode includeNode = jsonNode.get("include");
processSubInclude(query, include, includeNode);
}
if (jsonNode.has("includes")) {
JsonNode includesNode = jsonNode.get("includes");
if (includesNode instanceof ArrayNode) {
ArrayNode includes = (ArrayNode)includesNode;
for (int i=0; i<includes.size(); i++) {
processSubInclude(query, include, includes.get(i));
}
} else {
throw new QueryException("\"includes\" must be of type array");
}
}
return include;
}
// TODO thread safety and cache invalidation on file updates
public Include getDefineFromFile(String includeName) throws QueryException {
Include include = CACHED_DEFINES.get(includeName);
if (include != null) {
return include;
}
String namespaceString = includeName.substring(0, includeName.indexOf(":"));
String singleIncludeName = includeName.substring(includeName.indexOf(":") + 1);
URL resource;
try {
resource = getClass().getClassLoader().loadClass("org.bimserver.database.queries.StartFrame").getResource("json/" + namespaceString + ".json");
if (resource == null) {
throw new QueryException("Could not find '" + namespaceString + "' namespace in predefined queries");
}
} catch (ClassNotFoundException e1) {
throw new QueryException("Could not find '" + namespaceString + "' namespace in predefined queries");
}
OBJECT_MAPPER.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
try {
ObjectNode predefinedQuery = OBJECT_MAPPER.readValue(resource, ObjectNode.class);
JsonQueryObjectModelConverter converter = new JsonQueryObjectModelConverter(packageMetaData);
Query query = converter.parseJson(namespaceString, predefinedQuery);
Include define = query.getDefine(singleIncludeName);
if (define == null) {
throw new QueryException("Could not find '" + singleIncludeName + "' in defines in namespace " + query.getName());
}
CACHED_DEFINES.put(includeName, define);
return define;
} catch (JsonParseException e) {
throw new QueryException(e);
} catch (JsonMappingException e) {
throw new QueryException(e);
} catch (IOException e) {
throw new QueryException(e);
}
}
private void processSubInclude(Query query, CanInclude parentInclude, JsonNode includeNode) throws QueryException {
if (includeNode instanceof ObjectNode) {
ObjectNode innerInclude = (ObjectNode)includeNode;
parentInclude.addInclude(parseInclude(query, innerInclude, null, parentInclude));
} else if (includeNode.isTextual()) {
String includeName = includeNode.asText();
if (includeName.contains(":")) {
parentInclude.addIncludeReference(getDefineFromFile(includeName), includeName);
} else {
Include otherInclude = query.getDefine(includeName);
if (otherInclude == null) {
throw new QueryException("Cannot find define \"" + includeName + "\"");
}
parentInclude.addIncludeReference(otherInclude, includeName);
}
} else {
throw new QueryException("\"include\" must be of type object or string");
}
}
private void parseJsonQuery(Query query, ObjectNode objectNode) throws QueryException {
QueryPart queryPart = new QueryPart(packageMetaData);
if (objectNode.has("type")) {
JsonNode typeNode = objectNode.get("type");
if (typeNode.isTextual()) {
String type = typeNode.asText();
addType(objectNode, queryPart, type, false);
} else if (typeNode.isObject()) {
ObjectNode typeDef = (ObjectNode) typeNode;
if (!typeDef.has("name")) {
throw new QueryException("Missing name");
}
addType(objectNode, queryPart, typeDef.get("name").asText(), typeDef.has("includeAllSubTypes") && typeDef.get("includeAllSubTypes").asBoolean());
} else {
throw new QueryException("\"type\" must be of type string");
}
}
if (objectNode.has("types")) {
JsonNode typesNode = objectNode.get("types");
if (typesNode instanceof ArrayNode) {
ArrayNode types = (ArrayNode)typesNode;
for (int i=0; i<types.size(); i++) {
JsonNode typeNode = types.get(i);
if (typeNode.isTextual()) {
String type = typeNode.asText();
addType(objectNode, queryPart, type, false);
} else if (typeNode.isObject()) {
ObjectNode typeDef = (ObjectNode) typeNode;
addType(objectNode, queryPart, typeDef.get("name").asText(), typeDef.get("includeAllSubTypes").asBoolean());
} else {
throw new QueryException("\"types\"[" + i + "] must be of type string");
}
}
} else {
throw new QueryException("\"types\" must be of type array");
}
}
if (objectNode.has("includeAllFields") && objectNode.get("includeAllFields").asBoolean()) {
queryPart.setIncludeAllFields(true);
}
if (objectNode.has("oid")) {
JsonNode oidNode = objectNode.get("oid");
if (oidNode.isNumber()) {
queryPart.addOid(oidNode.asLong());
} else {
throw new QueryException("\"oid\" must be of type number");
}
}
if (objectNode.has("oids")) {
JsonNode oidsNode = objectNode.get("oids");
if (oidsNode instanceof ArrayNode) {
ArrayNode oids = (ArrayNode)oidsNode;
for (int i=0; i<oids.size(); i++) {
JsonNode oidNode = oids.get(i);
if (oidNode.isNumber()) {
queryPart.addOid(oidNode.asLong());
} else {
throw new QueryException("\"oids\"[" + i + "] must be of type number (" + oidNode + ")");
}
}
} else {
throw new QueryException("\"oids\" must be of type array");
}
}
if (objectNode.has("guid")) {
JsonNode guidNode = objectNode.get("guid");
if (guidNode.isTextual()) {
queryPart.addGuid(guidNode.asText());
} else {
throw new QueryException("\"guid\" must be of type string");
}
}
if (objectNode.has("name")) {
JsonNode nameNode = objectNode.get("name");
if (nameNode.isTextual()) {
queryPart.addName(nameNode.asText());
} else {
throw new QueryException("\"name\" must be of type string");
}
}
if (objectNode.has("guids")) {
JsonNode guidsNode = objectNode.get("guids");
if (guidsNode instanceof ArrayNode) {
ArrayNode guids = (ArrayNode)guidsNode;
for (int i=0; i<guids.size(); i++) {
JsonNode guidNode = guids.get(i);
if (guidNode.isTextual()) {
queryPart.addGuid(guidNode.asText());
} else {
throw new QueryException("\"guids\"[" + i + "] must be of type string");
}
}
} else {
throw new QueryException("\"guids\" must be of type array");
}
}
if (objectNode.has("names")) {
JsonNode namesNode = objectNode.get("names");
if (namesNode instanceof ArrayNode) {
ArrayNode names = (ArrayNode)namesNode;
for (int i=0; i<names.size(); i++) {
JsonNode nameNode = names.get(i);
if (nameNode.isTextual()) {
queryPart.addName(nameNode.asText());
} else {
throw new QueryException("\"names\"[" + i + "] must be of type string");
}
}
} else {
throw new QueryException("\"names\" must be of type array");
}
}
if (objectNode.has("properties")) {
JsonNode propertiesNode = objectNode.get("properties");
if (propertiesNode instanceof ObjectNode) {
ObjectNode properties = (ObjectNode) objectNode.get("properties");
Iterator<Entry<String, JsonNode>> fields = properties.fields();
while (fields.hasNext()) {
Entry<String, JsonNode> entry = fields.next();
JsonNode value = entry.getValue();
if (value.isValueNode()) {
if (value.getNodeType() == JsonNodeType.BOOLEAN) {
queryPart.addProperty(entry.getKey(), value.asBoolean());
} else if (value.getNodeType() == JsonNodeType.NUMBER) {
queryPart.addProperty(entry.getKey(), value.asDouble());
} else if (value.getNodeType() == JsonNodeType.STRING) {
queryPart.addProperty(entry.getKey(), value.asText());
} else if (value.getNodeType() == JsonNodeType.NULL) {
queryPart.addProperty(entry.getKey(), null);
}
} else {
throw new QueryException("property \"" + entry.getKey() + "\" type not supported");
}
}
} else {
throw new QueryException("\"properties\" must be of type object");
}
}
if (objectNode.has("classifications")) {
JsonNode classificationsNode = (JsonNode) objectNode.get("classifications");
if (classificationsNode instanceof ArrayNode) {
ArrayNode arrayNode = (ArrayNode)classificationsNode;
for (int i=0; i<arrayNode.size(); i++) {
JsonNode classificationNode = arrayNode.get(i);
if (classificationNode.isTextual()) {
queryPart.addClassification(classificationNode.asText());
} else {
throw new QueryException("\"classification[" + i + "]\" must be of type string");
}
}
} else {
throw new QueryException("\"classifications\" must be of type array");
}
}
if (objectNode.has("inBoundingBox")) {
JsonNode boundingBoxNode = objectNode.get("inBoundingBox");
if (boundingBoxNode instanceof ObjectNode) {
ObjectNode boundingBox = (ObjectNode) boundingBoxNode;
double x = checkFloat(boundingBox, "x");
double y = checkFloat(boundingBox, "y");
double z = checkFloat(boundingBox, "z");
double width = checkFloat(boundingBox, "width");
double height = checkFloat(boundingBox, "height");
double depth = checkFloat(boundingBox, "depth");
InBoundingBox inBoundingBox = new InBoundingBox(x, y, z, width, height, depth);
if (boundingBox.has("partial")) {
inBoundingBox.setPartial(boundingBox.get("partial").asBoolean());
}
queryPart.setInBoundingBox(inBoundingBox);
} else {
throw new QueryException("\"inBoundingBox\" should be of type object");
}
}
if (objectNode.has("include")) {
JsonNode includeNode = objectNode.get("include");
processSubInclude(query, queryPart, includeNode);
}
if (objectNode.has("includes")) {
JsonNode includesNode = objectNode.get("includes");
if (includesNode instanceof ArrayNode) {
ArrayNode includes = (ArrayNode)includesNode;
for (int i=0; i<includes.size(); i++) {
JsonNode include = includes.get(i);
processSubInclude(query, queryPart, include);
}
} else {
throw new QueryException("\"includes\" should be of type array");
}
}
if (objectNode.has("fields")) {
objectNode.get("fields"); // fields node
}
Iterator<String> fieldNames = objectNode.fieldNames();
while (fieldNames.hasNext()) {
String fieldName = fieldNames.next();
if (fieldName.equals("includeAllFields") || fieldName.equals("type") || fieldName.equals("types") || fieldName.equals("oid") || fieldName.equals("oids") || fieldName.equals("guid") || fieldName.equals("guids") || fieldName.equals("name") || fieldName.equals("names") || fieldName.equals("properties") || fieldName.equals("inBoundingBox") || fieldName.equals("include") || fieldName.equals("includes") || fieldName.equals("includeAllSubtypes") || fieldName.equals("classifications")) {
// fine
} else {
throw new QueryException("Unknown field: \"" + fieldName + "\"");
}
}
query.addQueryPart(queryPart);
}
private double checkFloat(ObjectNode node, String key) throws QueryException {
if (!node.has(key)) {
throw new QueryException("\"" + key + "\" not found on \"inBoundingBox\"");
}
JsonNode jsonNode = node.get(key);
if (jsonNode.isNumber()) {
return jsonNode.asDouble();
} else {
throw new QueryException("\"" + key + "\" should be of type number");
}
}
private void addType(ObjectNode objectNode, QueryPart queryPart, String type, boolean includeAllSubTypes) throws QueryException {
if (type.equals("Object")) {
// no type filter
return;
}
EClass eClass = packageMetaData.getEClassIncludingDependencies(type);
if (eClass == null) {
throw new QueryException("Type \"" + type + "\" not found");
}
queryPart.addType(eClass, includeAllSubTypes);
}
}
|
package verification.timed_state_exploration.zone;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Stack;
import lpn.parser.LhpnFile;
import lpn.parser.Transition;
import verification.platu.lpn.DualHashMap;
import verification.platu.lpn.VarSet;
import verification.platu.stategraph.State;
import verification.platu.stategraph.StateGraph;
/**
* Adds timing to a State.
*
* @author Andrew N. Fisher
*
*/
public class TimedState extends State{
// Abstraction Function:
// This class follows the extension pattern for extending a base class. A TimedState
// adds a Zone for keeping track of timing relations.
// A Zone for keeping track timing information.
private ZoneType _zone;
// A ZoneGraph for storing a zone.
private ZoneGraph _graph;
// Variable that determines whether zones or graph are being used.
private boolean _useGraph;
// The state that this TimingState extends.
private State _state;
@Override
public void setLpn(LhpnFile thisLpn) {
_state.setLpn(thisLpn);
}
@Override
public LhpnFile getLpn() {
return _state.getLpn();
}
@Override
public void setLabel(String lbl) {
_state.setLabel(lbl);
}
@Override
public String getLabel() {
return _state.getLabel();
}
@Override
public boolean[] getTranVector() {
return _state.getTranVector();
}
@Override
public void setIndex(int newIndex) {
_state.setIndex(newIndex);
}
@Override
public int getIndex() {
return _state.getIndex();
}
@Override
public boolean hasNonLocalEnabled() {
return _state.hasNonLocalEnabled();
}
@Override
public void hasNonLocalEnabled(boolean nonLocalEnabled) {
_state.hasNonLocalEnabled(nonLocalEnabled);
}
@Override
public boolean isFailure() {
return _state.isFailure();
}
@Override
public TimedState clone() {
// TODO: Ensure that the new TimedState contains its own copy of the zone.
if(_useGraph){
return new TimedState(_state, _zone, true);
}
else{
return new TimedState(_state, _zone, false);
}
}
@Override
public String print() {
// TODO Auto-generated method stub
return _state.print();
}
@Override
public int hashCode() {
// TODO Auto-generated method stub
return _state.hashCode();
}
@Override
public boolean equals(Object obj) {
// TODO Check for completion.
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
TimedState other = (TimedState) obj;
if(!_state.equals(other._state))
return false;
if(_useGraph){
return _graph.equals(other._graph);
}
else{
return _zone.equals(other._zone);
}
}
@Override
public void print(DualHashMap<String, Integer> VarIndexMap) {
_state.print(VarIndexMap);
}
@Override
public int[] getMarking() {
return _state.getMarking();
}
@Override
public void setMarking(int[] newMarking) {
_state.setMarking(newMarking);
}
@Override
public int[] getVector() {
return _state.getVector();
}
@Override
public HashMap<String, Integer> getOutVector(VarSet outputs,
DualHashMap<String, Integer> VarIndexMap) {
return _state.getOutVector(outputs, VarIndexMap);
}
@Override
public State getLocalState() {
return _state.getLocalState();
}
@Override
public String getEnabledSetString() {
return _state.getEnabledSetString();
}
@Override
public State update(StateGraph SG, HashMap<String, Integer> newVector,
DualHashMap<String, Integer> VarIndexMap) {
return _state.update(SG, newVector, VarIndexMap);
}
@Override
public State update(HashMap<String, Integer> newVector,
DualHashMap<String, Integer> VarIndexMap, boolean[] newTranVector) {
return _state.update(newVector, VarIndexMap, newTranVector);
}
@Override
public File serialize(String filename) throws FileNotFoundException,
IOException {
return _state.serialize(filename);
}
@Override
public boolean failure() {
return _state.failure();
}
@Override
public void setFailure() {
_state.setFailure();
}
@Override
public void print(LhpnFile lpn) {
_state.print(lpn);
}
@Override
public ArrayList<TimedState> getTimeExtension() {
//return super.getTimeExtension();
return _state.getTimeExtension();
}
@Override
public void setTimeExtension(ArrayList<TimedState> s) {
//super.setTimeExtension(s);
_state.setTimeExtension(s);
}
@Override
public void addTimeExtension(TimedState s){
//super.addTimeExtension(s);
_state.addTimeExtension(s);
}
public TimedState(LhpnFile lpn, int[] new_marking, int[] new_vector,
boolean[] new_isTranEnabled, boolean usegraph) {
super(lpn, new_marking, new_vector, new_isTranEnabled);
// TODO Find a way to remove the super call.
_state = new State(lpn, new_marking, new_vector, new_isTranEnabled);
_useGraph = usegraph;
//_zone = new Zone(new State(lpn, new_marking, new_vector, new_isTranEnabled));
Zone newZone = new Zone(new State(lpn, new_marking, new_vector, new_isTranEnabled));
if(usegraph){
_graph = ZoneGraph.extractZoneGraph(newZone);
}
else{
_zone = newZone;
}
//_state.setTimeExtension(this);
_state.addTimeExtension(this);
}
/**
* Creates a timed state by adding an initial zone.
* @param other
* The current state.
*/
public TimedState(State other, boolean usegraph) {
super(other);
// TODO Find a way to remove the super call.
_state = other;
_useGraph = usegraph;
//_zone = new Zone(other);
Zone newZone = new Zone(other);
if(usegraph){
_graph = ZoneGraph.extractZoneGraph(newZone);
}
else{
_zone = newZone;
}
//_state.setTimeExtension(this);
_state.addTimeExtension(this);
}
public TimedState(State s, ZoneType z, boolean usegraph)
{
super(s);
// TODO: Find a way to remove the super call.
_state = s;
_useGraph = usegraph;
if(usegraph && (z instanceof Zone)){
_graph = ZoneGraph.extractZoneGraph((Zone) z);
}
else{
_zone = z.clone();
}
//_state.setTimeExtension(this);
_state.addTimeExtension(this);
}
public String toString()
{
if(_useGraph){
return _state.toString() + "\n" + _graph;
}
else{
return _state.toString() + "\n" + _zone;
}
}
public List<Transition> getEnabledTransitionByZone()
{
if(_useGraph){
return _graph.extractZone().getEnabledTransitions();
}
else{
return _zone.getEnabledTransitions();
}
}
public ZoneType getZone()
{
if(_useGraph){
return _graph.extractZone();
}
else{
return _zone;
}
}
public ZoneGraph getZoneGraph(){
return _graph;
}
public State getState()
{
return _state;
}
public boolean usingGraphs(){
return _useGraph;
}
public boolean untimedStateEquals(TimedState s){
return this._state.equals(s._state);
}
public boolean untimedStateEquals(State s){
if(s instanceof TimedState){
TimedState t = (TimedState) s;
return untimedStateEquals(t);
}
return this._state.equals(s);
}
}
|
package com.ibm.bi.dml.runtime.controlprogram.parfor.opt;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.Vector;
import java.util.Map.Entry;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import au.com.bytecode.opencsv.CSVReader;
import au.com.bytecode.opencsv.CSVWriter;
import com.ibm.bi.dml.api.DMLScript;
import com.ibm.bi.dml.lops.Lops;
import com.ibm.bi.dml.parser.DMLProgram;
import com.ibm.bi.dml.parser.DMLTranslator;
import com.ibm.bi.dml.parser.DataIdentifier;
import com.ibm.bi.dml.parser.ParseException;
import com.ibm.bi.dml.parser.Expression.DataType;
import com.ibm.bi.dml.parser.Expression.ValueType;
import com.ibm.bi.dml.runtime.controlprogram.ExternalFunctionProgramBlock;
import com.ibm.bi.dml.runtime.controlprogram.ExternalFunctionProgramBlockCP;
import com.ibm.bi.dml.runtime.controlprogram.Program;
import com.ibm.bi.dml.runtime.controlprogram.ProgramBlock;
import com.ibm.bi.dml.runtime.controlprogram.parfor.stat.Timing;
import com.ibm.bi.dml.runtime.controlprogram.parfor.util.IDHandler;
import com.ibm.bi.dml.runtime.controlprogram.parfor.util.IDSequence;
import com.ibm.bi.dml.runtime.instructions.CPInstructionParser;
import com.ibm.bi.dml.runtime.instructions.Instruction;
import com.ibm.bi.dml.runtime.instructions.CPInstructions.Data;
import com.ibm.bi.dml.runtime.instructions.CPInstructions.FunctionCallCPInstruction;
import com.ibm.bi.dml.runtime.instructions.CPInstructions.MatrixObjectNew;
import com.ibm.bi.dml.runtime.instructions.CPInstructions.RandCPInstruction;
import com.ibm.bi.dml.runtime.matrix.MatrixCharacteristics;
import com.ibm.bi.dml.runtime.matrix.MatrixFormatMetaData;
import com.ibm.bi.dml.runtime.matrix.io.InputInfo;
import com.ibm.bi.dml.runtime.matrix.io.MatrixBlock;
import com.ibm.bi.dml.runtime.matrix.io.OutputInfo;
import com.ibm.bi.dml.runtime.util.MapReduceTool;
import com.ibm.bi.dml.utils.CacheException;
import com.ibm.bi.dml.utils.DMLException;
import com.ibm.bi.dml.utils.DMLRuntimeException;
import com.ibm.bi.dml.utils.DMLUnsupportedOperationException;
import com.sun.xml.internal.txw2.output.IndentingXMLStreamWriter;
/**
* DML Instructions Performance Test Tool:
*
* Creates an offline performance profile (required once per installation) of DML instructions.
* The profile is a combination of all individual statistical models trained per combination of
* instruction and test configuration. In order to train those models, we execute and measure
* real executions of DML instructions on random input data. Finally, during runtime, the profile
* is used by the costs estimator in order to create statistic estimates for cost-based optimization.
*
* TODO: complete all CP instructions
* TODO: add support for MR instructions
* TODO: add support for TestVariable.PARALLELISM
* TODO: add support for instruction-invariant cost functions
* TODO: add support for constants such as IO throughput (e.g., DFSIOTest)
* TODO: add support for known external functions and DML scripts / functions
*/
public class PerfTestTool
{
//internal parameters
public static final boolean READ_STATS_ON_STARTUP = false;
public static final int TEST_REPETITIONS = 5;
public static final int NUM_SAMPLES_PER_TEST = 11;
public static final int MODEL_MAX_ORDER = 2;
public static final boolean MODEL_INTERCEPT = true;
public static final long MIN_DATASIZE = 100;
public static final long MAX_DATASIZE = 1000000;
public static final long DEFAULT_DATASIZE = (MAX_DATASIZE-MIN_DATASIZE)/2;
public static final double MIN_DIMSIZE = 1;
public static final double MAX_DIMSIZE = 1000;
public static final double MIN_SPARSITY = 0.1;
public static final double MAX_SPARSITY = 1.0;
public static final double DEFAULT_SPARSITY = (MAX_SPARSITY-MIN_SPARSITY)/2;
public static final String PERF_TOOL_DIR = "./conf/PerfTestTool/";
public static final String PERF_RESULTS_FNAME = PERF_TOOL_DIR + "%id%.dat";
public static final String PERF_PROFILE_FNAME = PERF_TOOL_DIR + "performance_profile.xml";
public static final String DML_SCRIPT_FNAME = "./src/com/ibm/bi/dml/runtime/controlprogram/parfor/opt/PerfTestToolRegression.dml";
public static final String DML_TMP_FNAME = PERF_TOOL_DIR + "temp.dml";
//XML profile tags and attributes
public static final String XML_PROFILE = "profile";
public static final String XML_DATE = "date";
public static final String XML_INSTRUCTION = "instruction";
public static final String XML_ID = "id";
public static final String XML_NAME = "name";
public static final String XML_COSTFUNCTION = "cost_function";
public static final String XML_MEASURE = "measure";
public static final String XML_VARIABLE = "lvariable";
public static final String XML_INTERNAL_VARIABLES = "pvariables";
public static final String XML_DATAFORMAT = "dataformat";
public static final String XML_ELEMENT_DELIMITER = ",";
//ID sequences for instructions and test definitions
private static IDSequence _seqInst = null;
private static IDSequence _seqTestDef = null;
//registered instructions and test definitions
private static HashMap<Integer, PerfTestDef> _regTestDef = null;
private static HashMap<Integer, Instruction> _regInst = null;
private static HashMap<Integer, String> _regInst_IDNames = null;
private static HashMap<String, Integer> _regInst_NamesID = null;
private static HashMap<Integer, Integer[]> _regInst_IDTestDef = null;
private static HashMap<Integer, Boolean> _regInst_IDVectors = null;
private static HashMap<Integer, IOSchema> _regInst_IDIOSchema = null;
private static Integer[] _defaultConf = null;
//raw measurement data (instID, physical defID, results)
private static HashMap<Integer,HashMap<Integer,LinkedList<Double>>> _results = null;
//profile data
private static boolean _flagReadData = false;
private static HashMap<Integer,HashMap<Integer,CostFunction>> _profile = null;
public enum TestMeasure //logical test measure
{
EXEC_TIME,
MEMORY_USAGE
}
public enum TestVariable //logical test variable
{
DATA_SIZE,
SPARSITY,
PARALLELISM
}
public enum InternalTestVariable //physical test variable
{
DATA_SIZE,
DIM1_SIZE,
DIM2_SIZE,
DIM3_SIZE,
SPARSITY,
NUM_THREADS,
NUM_MAPPERS,
NUM_REDUCERS,
}
public enum IOSchema
{
NONE_NONE,
NONE_UNARY,
UNARY_NONE,
UNARY_UNARY,
BINARY_NONE,
BINARY_UNARY
}
public enum DataFormat //logical data format
{
DENSE,
SPARSE
}
public enum TestConstants //logical test constants
{
DFS_READ_THROUGHPUT,
DFS_WRITE_THROUGHPUT,
LFS_READ_THROUGHPUT,
LFS_WRITE_THROUGHPUT
}
static
{
//init repository
_seqInst = new IDSequence();
_seqTestDef = new IDSequence();
_regTestDef = new HashMap<Integer, PerfTestDef>();
_regInst = new HashMap<Integer, Instruction>();
_regInst_IDNames = new HashMap<Integer, String>();
_regInst_NamesID = new HashMap<String, Integer>();
_regInst_IDTestDef = new HashMap<Integer, Integer[]>();
_regInst_IDVectors = new HashMap<Integer, Boolean>();
_regInst_IDIOSchema = new HashMap<Integer, IOSchema>();
_results = new HashMap<Integer, HashMap<Integer,LinkedList<Double>>>();
_profile = new HashMap<Integer, HashMap<Integer,CostFunction>>();
_flagReadData = false;
//load existing profile if required
try
{
if( READ_STATS_ON_STARTUP )
{
readProfile( PERF_PROFILE_FNAME );
}
}
catch(Exception ex)
{
throw new RuntimeException(ex);
}
}
/**
*
* @throws DMLRuntimeException
*/
public static void lazyInit()
throws DMLRuntimeException
{
//read profile for first access
if( !_flagReadData )
{
try
{
//register all testdefs and instructions
registerTestConfigurations();
registerInstructions();
//read profile
readProfile( PERF_PROFILE_FNAME );
}
catch(Exception ex)
{
throw new DMLRuntimeException(ex);
}
}
if( _profile == null )
throw new DMLRuntimeException("Performance test results have not been loaded completely.");
}
/**
*
* @param opStr
* @return
* @throws DMLRuntimeException
*/
public static boolean isRegisteredInstruction(String opStr)
throws DMLRuntimeException
{
//init if required
lazyInit();
//determine if inst registered
return _regInst_NamesID.containsKey(opStr);
}
/**
*
* @param instName
* @return
* @throws DMLRuntimeException
*/
public static CostFunction getCostFunction( String instName, TestMeasure measure, TestVariable variable, DataFormat dataformat )
throws DMLRuntimeException
{
//init if required
lazyInit();
CostFunction tmp = null;
int instID = getInstructionID( instName );
if( instID != -1 ) //existing profile
{
int tdefID = getMappedTestDefID(instID, measure, variable, dataformat);
tmp = _profile.get(instID).get(tdefID);
}
return tmp;
}
/**
*
* @param measure
* @param variable
* @param dataformat
* @return
*/
public CostFunction getInvariantCostFunction( TestMeasure measure, TestVariable[] variable, DataFormat dataformat )
{
//TODO: implement for additional rewrites
throw new RuntimeException("Not implemented yet.");
}
/**
*
* @return
*/
@SuppressWarnings("all")
public static boolean runTest()
{
boolean ret = false;
try
{
Timing time = new Timing();
time.start();
//register all testdefs and instructions
registerTestConfigurations();
registerInstructions();
//execute tests for all confs and all instructions
executeTest();
//compute regression models
int rows = NUM_SAMPLES_PER_TEST;
int cols = MODEL_MAX_ORDER + (MODEL_INTERCEPT ? 1 : 0);
HashMap<Integer,Long> tmp = writeResults( PERF_TOOL_DIR );
computeRegressionModels( DML_SCRIPT_FNAME, DML_TMP_FNAME, PERF_TOOL_DIR, tmp.size(), rows, cols);
readRegressionModels( PERF_TOOL_DIR, tmp);
//execConstantRuntimeTest();
//execConstantMemoryTest();
//write final profile to XML file
writeProfile(PERF_TOOL_DIR, PERF_PROFILE_FNAME);
System.out.format("SystemML PERFORMANCE TEST TOOL: finished profiling (in %.2f min), profile written to "+PERF_PROFILE_FNAME+"%n", time.stop()/60000);
ret = true;
}
catch(Exception ex)
{
ex.printStackTrace();
}
return ret;
}
private static void registerTestConfigurations()
{
//reset ID Sequence for consistent IDs
_seqTestDef.reset();
//register default testdefs
TestMeasure[] M = new TestMeasure[]{ TestMeasure.EXEC_TIME, TestMeasure.MEMORY_USAGE };
DataFormat[] D = new DataFormat[]{DataFormat.DENSE,DataFormat.SPARSE};
Integer[] defaultConf = new Integer[M.length*D.length*2];
int i=0;
for( TestMeasure m : M ) //for all measures
for( DataFormat d : D ) //for all data formats
{
defaultConf[i++] = registerTestDef( new PerfTestDef(m, TestVariable.DATA_SIZE, d, InternalTestVariable.DATA_SIZE,
MIN_DATASIZE, MAX_DATASIZE, NUM_SAMPLES_PER_TEST ) );
defaultConf[i++] = registerTestDef( new PerfTestDef(m, TestVariable.SPARSITY, d, InternalTestVariable.SPARSITY,
MIN_SPARSITY, MAX_SPARSITY, NUM_SAMPLES_PER_TEST ) );
}
//register advanced (multi-dim) test defs
for( TestMeasure m : M ) //for all measures
for( DataFormat d : D ) //for all data formats
{
registerTestDef( new PerfTestDef( m, TestVariable.DATA_SIZE, d,
new InternalTestVariable[]{InternalTestVariable.DIM1_SIZE,InternalTestVariable.DIM2_SIZE,InternalTestVariable.DIM3_SIZE},
MIN_DIMSIZE, MAX_DIMSIZE, NUM_SAMPLES_PER_TEST ) );
}
//set default testdefs
_defaultConf = defaultConf;
}
/**
*
* @throws DMLUnsupportedOperationException
* @throws DMLRuntimeException
*/
private static void registerInstructions()
throws DMLUnsupportedOperationException, DMLRuntimeException
{
//reset ID sequences for consistent IDs
_seqInst.reset();
//matrix multiply
registerInstruction( "CP"+Lops.OPERAND_DELIMITOR+"ba+*", CPInstructionParser.parseSingleInstruction("CP"+Lops.OPERAND_DELIMITOR+"ba+*"+Lops.OPERAND_DELIMITOR+"A"+Lops.DATATYPE_PREFIX+"MATRIX"+Lops.VALUETYPE_PREFIX+"DOUBLE"+Lops.OPERAND_DELIMITOR+"B"+Lops.DATATYPE_PREFIX+"MATRIX"+Lops.VALUETYPE_PREFIX+"DOUBLE"+Lops.OPERAND_DELIMITOR+"C"+Lops.DATATYPE_PREFIX+"MATRIX"+Lops.VALUETYPE_PREFIX+"DOUBLE"),
getDefaultTestDefs(), false, IOSchema.BINARY_UNARY );
////registerInstruction( "CP"+Lops.OPERAND_DELIMITOR+"ba+*", CPInstructionParser.parseSingleInstruction("CP"+Lops.OPERAND_DELIMITOR+"ba+*"+Lops.OPERAND_DELIMITOR+"A"+Lops.DATATYPE_PREFIX+"MATRIX"+Lops.VALUETYPE_PREFIX+"DOUBLE"+Lops.OPERAND_DELIMITOR+"B"+Lops.DATATYPE_PREFIX+"MATRIX"+Lops.VALUETYPE_PREFIX+"DOUBLE"+Lops.OPERAND_DELIMITOR+"C"+Lops.DATATYPE_PREFIX+"MATRIX"+Lops.VALUETYPE_PREFIX+"DOUBLE"),
//// changeToMuliDimTestDefs(TestVariable.DATA_SIZE, getDefaultTestDefs()) );
//rand
registerInstruction( "CP"+Lops.OPERAND_DELIMITOR+"Rand", CPInstructionParser.parseSingleInstruction("CP"+Lops.OPERAND_DELIMITOR+"Rand"+Lops.OPERAND_DELIMITOR+"rows=1"+Lops.OPERAND_DELIMITOR+"cols=1"+Lops.OPERAND_DELIMITOR+"min=1.0"+Lops.OPERAND_DELIMITOR+"max=100.0"+Lops.OPERAND_DELIMITOR+"sparsity=1.0"+Lops.OPERAND_DELIMITOR+"pdf=uniform"+Lops.OPERAND_DELIMITOR+"dir=."+Lops.OPERAND_DELIMITOR+"C"+Lops.DATATYPE_PREFIX+"MATRIX"+Lops.VALUETYPE_PREFIX+"DOUBLE"),
getDefaultTestDefs(), false, IOSchema.NONE_UNARY );
//matrix transpose
registerInstruction( "CP"+Lops.OPERAND_DELIMITOR+"r'", CPInstructionParser.parseSingleInstruction("CP"+Lops.OPERAND_DELIMITOR+"r'"+Lops.OPERAND_DELIMITOR+"A"+Lops.DATATYPE_PREFIX+"MATRIX"+Lops.VALUETYPE_PREFIX+"DOUBLE"+Lops.OPERAND_DELIMITOR+"C"+Lops.DATATYPE_PREFIX+"MATRIX"+Lops.VALUETYPE_PREFIX+"DOUBLE"),
getDefaultTestDefs(), false, IOSchema.UNARY_UNARY );
//sum
registerInstruction( "CP"+Lops.OPERAND_DELIMITOR+"uak+", CPInstructionParser.parseSingleInstruction("CP"+Lops.OPERAND_DELIMITOR+"uak+"+Lops.OPERAND_DELIMITOR+"A"+Lops.DATATYPE_PREFIX+"MATRIX"+Lops.VALUETYPE_PREFIX+"DOUBLE"+Lops.OPERAND_DELIMITOR+"B"+Lops.DATATYPE_PREFIX+"MATRIX"+Lops.VALUETYPE_PREFIX+"DOUBLE"), //needs B instead of C
getDefaultTestDefs(), false, IOSchema.UNARY_UNARY );
//external function
registerInstruction( "CP"+Lops.OPERAND_DELIMITOR+"extfunct", CPInstructionParser.parseSingleInstruction("CP"+Lops.OPERAND_DELIMITOR+"extfunct"+Lops.OPERAND_DELIMITOR+DMLProgram.DEFAULT_NAMESPACE+""+Lops.OPERAND_DELIMITOR+"execPerfTestExtFunct"+Lops.OPERAND_DELIMITOR+"1"+Lops.OPERAND_DELIMITOR+"1"+Lops.OPERAND_DELIMITOR+"A"+Lops.OPERAND_DELIMITOR+"C"),
getDefaultTestDefs(), false, IOSchema.UNARY_UNARY );
//central moment
registerInstruction( "CP"+Lops.OPERAND_DELIMITOR+"cm", CPInstructionParser.parseSingleInstruction("CP"+Lops.OPERAND_DELIMITOR+"cm"+Lops.OPERAND_DELIMITOR+"A"+Lops.DATATYPE_PREFIX+"MATRIX"+Lops.VALUETYPE_PREFIX+"DOUBLE"+Lops.OPERAND_DELIMITOR+"2"+Lops.DATATYPE_PREFIX+"SCALAR"+Lops.VALUETYPE_PREFIX+"INT"+Lops.OPERAND_DELIMITOR+"c"+Lops.DATATYPE_PREFIX+"SCALAR"+Lops.VALUETYPE_PREFIX+"DOUBLE"),
getDefaultTestDefs(), true, IOSchema.UNARY_NONE );
//co-variance
registerInstruction( "CP"+Lops.OPERAND_DELIMITOR+"cov", CPInstructionParser.parseSingleInstruction("CP"+Lops.OPERAND_DELIMITOR+"cov"+Lops.OPERAND_DELIMITOR+"A"+Lops.DATATYPE_PREFIX+"MATRIX"+Lops.VALUETYPE_PREFIX+"DOUBLE"+Lops.OPERAND_DELIMITOR+"B"+Lops.DATATYPE_PREFIX+"MATRIX"+Lops.VALUETYPE_PREFIX+"DOUBLE"+Lops.OPERAND_DELIMITOR+"c"+Lops.DATATYPE_PREFIX+"SCALAR"+Lops.VALUETYPE_PREFIX+"DOUBLE"),
getDefaultTestDefs(), true, IOSchema.BINARY_NONE );
/*ADD ADDITIONAL INSTRUCTIONS HERE*/
//extend list to all (expensive) instructions; maybe also: createvar, assignvar, mvvar, rm, mv, setfilename, rmfilevar, print2
}
/**
*
* @param def
* @return
*/
private static int registerTestDef( PerfTestDef def )
{
int ID = (int)_seqTestDef.getNextID();
_regTestDef.put( ID, def );
return ID;
}
/**
*
* @param iname
* @param inst
* @param testDefIDs
* @param vectors
* @param schema
*/
private static void registerInstruction( String iname, Instruction inst, Integer[] testDefIDs, boolean vectors, IOSchema schema )
{
int ID = (int)_seqInst.getNextID();
registerInstruction(ID, iname, inst, testDefIDs, vectors, schema);
}
/**
*
* @param ID
* @param iname
* @param inst
* @param testDefIDs
* @param vector
* @param schema
*/
private static void registerInstruction( int ID, String iname, Instruction inst, Integer[] testDefIDs, boolean vector, IOSchema schema )
{
_regInst.put( ID, inst );
_regInst_IDNames.put( ID, iname );
_regInst_NamesID.put( iname, ID );
_regInst_IDTestDef.put( ID, testDefIDs );
_regInst_IDVectors.put( ID, vector );
_regInst_IDIOSchema.put( ID, schema );
}
/**
*
* @param instID
* @param measure
* @param variable
* @param dataformat
* @return
*/
private static int getMappedTestDefID( int instID, TestMeasure measure, TestVariable variable, DataFormat dataformat )
{
int ret = -1;
for( Integer defID : _regInst_IDTestDef.get(instID) )
{
PerfTestDef def = _regTestDef.get(defID);
if( def.getMeasure()==measure
&& def.getVariable()==variable
&& def.getDataformat()==dataformat )
{
ret = defID;
break;
}
}
return ret;
}
/**
*
* @param measure
* @param lvariable
* @param dataformat
* @param pvariable
* @return
*/
@SuppressWarnings("unused")
private static int getTestDefID( TestMeasure measure, TestVariable lvariable, DataFormat dataformat, InternalTestVariable pvariable )
{
return getTestDefID(measure, lvariable, dataformat, new InternalTestVariable[]{pvariable});
}
/**
*
* @param measure
* @param lvariable
* @param dataformat
* @param pvariables
* @return
*/
private static int getTestDefID( TestMeasure measure, TestVariable lvariable, DataFormat dataformat, InternalTestVariable[] pvariables )
{
int ret = -1;
for( Entry<Integer,PerfTestDef> e : _regTestDef.entrySet() )
{
PerfTestDef def = e.getValue();
TestMeasure tmp1 = def.getMeasure();
TestVariable tmp2 = def.getVariable();
DataFormat tmp3 = def.getDataformat();
InternalTestVariable[] tmp4 = def.getInternalVariables();
if( tmp1==measure && tmp2==lvariable && tmp3==dataformat )
{
boolean flag = true;
for( int i=0; i<tmp4.length; i++ )
flag &= ( tmp4[i] == pvariables[i] );
if( flag )
{
ret = e.getKey();
break;
}
}
}
return ret;
}
/**
*
* @param instName
* @return
*/
private static int getInstructionID( String instName )
{
Integer ret = _regInst_NamesID.get( instName );
return ( ret!=null )? ret : -1;
}
/**
*
* @return
*/
@SuppressWarnings("unused")
private static Integer[] getAllTestDefs()
{
return _regTestDef.keySet().toArray(new Integer[0]);
}
/**
*
* @return
*/
private static Integer[] getDefaultTestDefs()
{
return _defaultConf;
}
/**
*
* @param v
* @param IDs
* @return
*/
@SuppressWarnings("unused")
private static Integer[] changeToMuliDimTestDefs( TestVariable v, Integer[] IDs )
{
Integer[] tmp = new Integer[IDs.length];
for( int i=0; i<tmp.length; i++ )
{
PerfTestDef def = _regTestDef.get(IDs[i]);
if( def.getVariable() == v ) //filter logical variables
{
//find multidim version
InternalTestVariable[] in = null;
switch( v )
{
case DATA_SIZE:
in = new InternalTestVariable[]{InternalTestVariable.DIM1_SIZE,InternalTestVariable.DIM2_SIZE,InternalTestVariable.DIM3_SIZE};
break;
}
int newid = getTestDefID(def.getMeasure(), def.getVariable(), def.getDataformat(), in );
//exchange testdef ID
tmp[i] = newid;
}
else
{
tmp[i] = IDs[i];
}
}
return tmp;
}
/**
*
* @throws DMLRuntimeException
* @throws DMLUnsupportedOperationException
* @throws IOException
*/
private static void executeTest( )
throws DMLRuntimeException, DMLUnsupportedOperationException, IOException
{
System.out.println("SystemML PERFORMANCE TEST TOOL:");
//foreach registered instruction
for( Entry<Integer,Instruction> inst : _regInst.entrySet() )
{
int instID = inst.getKey();
System.out.println( "Running INSTRUCTION "+_regInst_IDNames.get(instID) );
Integer[] testDefIDs = _regInst_IDTestDef.get(instID);
boolean vectors = _regInst_IDVectors.get(instID);
IOSchema schema = _regInst_IDIOSchema.get(instID);
//create tmp program block and set instruction
Program prog = new Program();
ProgramBlock pb = new ProgramBlock( prog );
ArrayList<Instruction> ainst = new ArrayList<Instruction>();
ainst.add( inst.getValue() );
pb.setInstructions(ainst);
//foreach registered test configuration
for( Integer defID : testDefIDs )
{
PerfTestDef def = _regTestDef.get(defID);
TestMeasure m = def.getMeasure();
TestVariable lv = def.getVariable();
DataFormat df = def.getDataformat();
InternalTestVariable[] pv = def.getInternalVariables();
double min = def.getMin();
double max = def.getMax();
double samples = def.getNumSamples();
System.out.println( "Running TESTDEF(measure="+m+", variable="+String.valueOf(lv)+" "+pv.length+", format="+String.valueOf(df)+")" );
//vary input variable
LinkedList<Double> dmeasure = new LinkedList<Double>();
LinkedList<Double> dvariable = generateSequence(min, max, samples);
int plen = pv.length;
if( plen == 1 ) //1D function
{
for( Double var : dvariable )
{
dmeasure.add(executeTestCase1D(m, pv[0], df, var, pb, vectors, schema));
}
}
else //multi-dim function
{
//init index stack
int[] index = new int[plen];
for( int i=0; i<plen; i++ )
index[i] = 0;
//execute test
int dlen = dvariable.size();
double[] buff = new double[plen];
while( index[0]<dlen )
{
//set buffer values
for( int i=0; i<plen; i++ )
buff[i] = dvariable.get(index[i]);
//core execution
dmeasure.add(executeTestCaseMD(m, pv, df, buff, pb, schema)); //not applicable for vector flag
//increment indexes
for( int i=plen-1; i>=0; i
{
if(i==plen-1)
index[i]++;
else if( index[i+1] >= dlen )
{
index[i]++;
index[i+1]=0;
}
}
}
}
//append values to results
if( !_results.containsKey(instID) )
_results.put(instID, new HashMap<Integer, LinkedList<Double>>());
_results.get(instID).put(defID, dmeasure);
}
}
}
/**
*
* @param m
* @param v
* @param df
* @param varValue
* @param pb
* @param vectors
* @param schema
* @return
* @throws DMLRuntimeException
* @throws DMLUnsupportedOperationException
* @throws IOException
*/
private static double executeTestCase1D( TestMeasure m, InternalTestVariable v, DataFormat df, double varValue, ProgramBlock pb, boolean vectors, IOSchema schema )
throws DMLRuntimeException, DMLUnsupportedOperationException, IOException
{
double datasize = -1;
double dim1 = -1, dim2 = -1;
double sparsity = -1;
System.out.println( "VAR VALUE "+varValue );
//set test variables
switch ( v )
{
case DATA_SIZE:
datasize = varValue;
sparsity = DEFAULT_SPARSITY;
break;
case SPARSITY:
datasize = DEFAULT_DATASIZE;
sparsity = varValue;
break;
}
//set specific dimensions
if( vectors )
{
dim1 = datasize;
dim2 = 1;
}
else
{
dim1 = Math.sqrt( datasize );
dim2 = dim1;
}
//instruction-specific configurations
Instruction inst = pb.getInstruction(0); //always exactly one instruction
if( inst instanceof RandCPInstruction )
{
RandCPInstruction rand = (RandCPInstruction) inst;
rand.rows = (long)dim1;
rand.cols = (long)dim2;
rand.sparsity = sparsity;
}
else if ( inst instanceof FunctionCallCPInstruction ) //ExternalFunctionInvocationInstruction
{
Program prog = pb.getProgram();
Vector<DataIdentifier> in = new Vector<DataIdentifier>();
DataIdentifier dat1 = new DataIdentifier("A");
dat1.setDataType(DataType.MATRIX);
dat1.setValueType(ValueType.DOUBLE);
in.add(dat1);
Vector<DataIdentifier> out = new Vector<DataIdentifier>();
DataIdentifier dat2 = new DataIdentifier("C");
dat2.setDataType(DataType.MATRIX);
dat2.setValueType(ValueType.DOUBLE);
out.add(dat2);
HashMap<String, String> params = new HashMap<String, String>();
params.put(ExternalFunctionProgramBlock.CLASSNAME, PerfTestExtFunctCP.class.getName());
ExternalFunctionProgramBlockCP fpb = new ExternalFunctionProgramBlockCP(prog, in, out, params, PERF_TOOL_DIR);
prog.addFunctionProgramBlock(DMLProgram.DEFAULT_NAMESPACE, "execPerfTestExtFunct", fpb);
}
//generate input and output matrices
pb.getVariables().removeAll();
double mem1 = PerfTestMemoryObserver.getUsedMemory();
if( schema!=IOSchema.NONE_NONE && schema!=IOSchema.NONE_UNARY )
pb.getVariables().put("A", generateInputDataset(PERF_TOOL_DIR+"/A", dim1, dim2, sparsity, df));
if( schema==IOSchema.BINARY_NONE || schema==IOSchema.BINARY_UNARY || schema==IOSchema.UNARY_UNARY )
pb.getVariables().put("B", generateInputDataset(PERF_TOOL_DIR+"/B", dim1, dim2, sparsity, df));
if( schema==IOSchema.NONE_UNARY || schema==IOSchema.UNARY_UNARY || schema==IOSchema.BINARY_UNARY)
pb.getVariables().put("C", generateEmptyResult(PERF_TOOL_DIR+"/C", dim1, dim2, df));
double mem2 = PerfTestMemoryObserver.getUsedMemory();
//foreach repetition
double value = 0;
for( int i=0; i<TEST_REPETITIONS; i++ )
{
System.out.println("run "+i);
value += executeGenericProgramBlock( m, pb );
}
value/=TEST_REPETITIONS;
//result correction and print result
switch( m )
{
case EXEC_TIME: System.out.println("--- RESULT: "+value+" ms"); break;
case MEMORY_USAGE:
if( (mem2-mem1) > 0 )
value = value + mem2-mem1; //correction: input sizes added
System.out.println("--- RESULT: "+value+" byte"); break;
default: System.out.println("--- RESULT: "+value); break;
}
return value;
}
/**
*
* @param m
* @param v
* @param df
* @param varValue
* @param pb
* @param schema
* @return
* @throws DMLRuntimeException
* @throws DMLUnsupportedOperationException
* @throws IOException
*/
private static double executeTestCaseMD( TestMeasure m, InternalTestVariable[] v, DataFormat df, double[] varValue, ProgramBlock pb, IOSchema schema )
throws DMLRuntimeException, DMLUnsupportedOperationException, IOException
{
//double datasize = DEFAULT_DATASIZE;
double sparsity = DEFAULT_SPARSITY;
double dim1 = -1;
double dim2 = -1;
double dim3 = -1;
for( int i=0; i<v.length; i++ )
{
System.out.println( "VAR VALUE "+varValue[i] );
switch( v[i] )
{
case DIM1_SIZE: dim1=varValue[i]; break;
case DIM2_SIZE: dim2=varValue[i]; break;
case DIM3_SIZE: dim3=varValue[i]; break;
}
}
//generate input and output matrices
pb.getVariables().removeAll();
double mem1 = PerfTestMemoryObserver.getUsedMemory();
if( schema!=IOSchema.NONE_NONE && schema!=IOSchema.NONE_UNARY )
pb.getVariables().put("A", generateInputDataset(PERF_TOOL_DIR+"/A", dim1, dim2, sparsity, df));
if( schema==IOSchema.BINARY_NONE || schema==IOSchema.BINARY_UNARY || schema==IOSchema.UNARY_UNARY )
pb.getVariables().put("B", generateInputDataset(PERF_TOOL_DIR+"/B", dim2, dim3, sparsity, df));
if( schema==IOSchema.NONE_UNARY || schema==IOSchema.UNARY_UNARY || schema==IOSchema.BINARY_UNARY)
pb.getVariables().put("C", generateEmptyResult(PERF_TOOL_DIR+"/C", dim1, dim3, df));
double mem2 = PerfTestMemoryObserver.getUsedMemory();
//foreach repetition
double value = 0;
for( int i=0; i<TEST_REPETITIONS; i++ )
{
System.out.println("run "+i);
value += executeGenericProgramBlock( m, pb );
}
value/=TEST_REPETITIONS;
//result correction and print result
switch( m )
{
case EXEC_TIME: System.out.println("--- RESULT: "+value+" ms"); break;
case MEMORY_USAGE:
if( (mem2-mem1) > 0 )
value = value + mem2-mem1; //correction: input sizes added
System.out.println("--- RESULT: "+value+" byte"); break;
default: System.out.println("--- RESULT: "+value); break;
}
return value;
}
/**
*
* @param measure
* @param pb
* @return
* @throws DMLRuntimeException
* @throws DMLUnsupportedOperationException
*/
public static double executeGenericProgramBlock( TestMeasure measure, ProgramBlock pb )
throws DMLRuntimeException, DMLUnsupportedOperationException
{
double value = 0;
try
{
switch( measure )
{
case EXEC_TIME:
Timing time = new Timing();
time.start();
pb.execute( null );
value = time.stop();
break;
case MEMORY_USAGE:
PerfTestMemoryObserver mo = new PerfTestMemoryObserver();
mo.measureStartMem();
Thread t = new Thread(mo);
t.start();
pb.execute( null );
mo.setStopped();
value = mo.getMaxMemConsumption();
t.join();
break;
}
}
catch(Exception ex)
{
throw new DMLRuntimeException(ex);
}
//clear matrixes from cache
for( String str : pb.getVariables().keySet() )
{
Data dat = pb.getVariable(str);
if( dat.getDataType() == DataType.MATRIX )
((MatrixObjectNew)dat).clearData();
}
return value;
}
/**
*
* @param min
* @param max
* @param num
* @return
*/
public static LinkedList<Double> generateSequence( double min, double max, double num )
{
LinkedList<Double> data = new LinkedList<Double>();
double increment = (max-min)/(num-1);
for( int i=0; i<num; i++ )
data.add( new Double(min+i*increment) );
return data;
}
/**
*
* @param fname
* @param datasize
* @param sparsity
* @param df
* @return
* @throws IOException
* @throws CacheException
*/
public static MatrixObjectNew generateInputDataset(String fname, double datasize, double sparsity, DataFormat df)
throws IOException, CacheException
{
int dim = (int)Math.sqrt( datasize );
//create random test data
double[][] d = generateTestMatrix(dim, dim, 1, 100, sparsity, 7);
//create matrix block
MatrixBlock mb = null;
switch( df )
{
case DENSE:
mb = new MatrixBlock(dim,dim,false);
break;
case SPARSE:
mb = new MatrixBlock(dim,dim,true);
break;
}
//insert data
for(int i=0; i < dim; i++)
for(int j=0; j < dim; j++)
if( d[i][j]!=0 )
mb.setValue(i, j, d[i][j]);
MapReduceTool.deleteFileIfExistOnHDFS(fname);
MatrixCharacteristics mc = new MatrixCharacteristics(dim, dim, DMLTranslator.DMLBlockSize, DMLTranslator.DMLBlockSize);
MatrixFormatMetaData md = new MatrixFormatMetaData(mc, OutputInfo.BinaryBlockOutputInfo, InputInfo.BinaryBlockInputInfo);
MatrixObjectNew mo = new MatrixObjectNew(ValueType.DOUBLE,fname,md);
mo.acquireModify(mb);
mo.release();
mo.exportData(); //write to HDFS
return mo;
}
/**
*
* @param fname
* @param dim1
* @param dim2
* @param sparsity
* @param df
* @return
* @throws IOException
* @throws CacheException
*/
public static MatrixObjectNew generateInputDataset(String fname, double dim1, double dim2, double sparsity, DataFormat df)
throws IOException, CacheException
{
int d1 = (int) dim1;
int d2 = (int) dim2;
System.out.println(d1+" "+d2);
//create random test data
double[][] d = generateTestMatrix(d1, d2, 1, 100, sparsity, 7);
//create matrix block
MatrixBlock mb = null;
switch( df )
{
case DENSE:
mb = new MatrixBlock(d1,d2,false);
break;
case SPARSE:
mb = new MatrixBlock(d1,d2,true);
break;
}
//insert data
for(int i=0; i < d1; i++)
for(int j=0; j < d2; j++)
if( d[i][j]!=0 )
mb.setValue(i, j, d[i][j]);
MapReduceTool.deleteFileIfExistOnHDFS(fname);
MatrixCharacteristics mc = new MatrixCharacteristics(d1, d2, DMLTranslator.DMLBlockSize, DMLTranslator.DMLBlockSize);
MatrixFormatMetaData md = new MatrixFormatMetaData(mc, OutputInfo.BinaryBlockOutputInfo, InputInfo.BinaryBlockInputInfo);
MatrixObjectNew mo = new MatrixObjectNew(ValueType.DOUBLE,fname,md);
mo.acquireModify(mb);
mo.release();
mo.exportData(); //write to HDFS
return mo;
}
/**
*
* @param fname
* @param datasize
* @param df
* @return
* @throws IOException
* @throws CacheException
*/
public static MatrixObjectNew generateEmptyResult(String fname, double datasize, DataFormat df )
throws IOException, CacheException
{
int dim = (int)Math.sqrt( datasize );
/*
MatrixBlock mb = null;
switch( df )
{
case DENSE:
mb = new MatrixBlock(dim,dim,false);
break;
case SPARSE:
mb = new MatrixBlock(dim,dim,true);
break;
}*/
MatrixCharacteristics mc = new MatrixCharacteristics(dim, dim, DMLTranslator.DMLBlockSize, DMLTranslator.DMLBlockSize);
MatrixFormatMetaData md = new MatrixFormatMetaData(mc, OutputInfo.BinaryBlockOutputInfo, InputInfo.BinaryBlockInputInfo);
MatrixObjectNew mo = new MatrixObjectNew(ValueType.DOUBLE,fname,md);
return mo;
}
/**
*
* @param fname
* @param dim1
* @param dim2
* @param df
* @return
* @throws IOException
* @throws CacheException
*/
public static MatrixObjectNew generateEmptyResult(String fname, double dim1, double dim2, DataFormat df )
throws IOException, CacheException
{
int d1 = (int)dim1;
int d2 = (int)dim2;
/*
MatrixBlock mb = null;
switch( df )
{
case DENSE:
mb = new MatrixBlock(dim,dim,false);
break;
case SPARSE:
mb = new MatrixBlock(dim,dim,true);
break;
}*/
MatrixCharacteristics mc = new MatrixCharacteristics(d1, d2, DMLTranslator.DMLBlockSize, DMLTranslator.DMLBlockSize);
MatrixFormatMetaData md = new MatrixFormatMetaData(mc, OutputInfo.BinaryBlockOutputInfo, InputInfo.BinaryBlockInputInfo);
MatrixObjectNew mo = new MatrixObjectNew(ValueType.DOUBLE,fname,md);
return mo;
}
/**
* NOTE: This is a copy of TestUtils.generateTestMatrix, it was replicated in order to prevent
* dependency of SystemML.jar to our test package.
*/
public static double[][] generateTestMatrix(int rows, int cols, double min, double max, double sparsity, long seed) {
double[][] matrix = new double[rows][cols];
Random random;
if (seed == -1)
random = new Random(System.nanoTime());
else
random = new Random(seed);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (random.nextDouble() > sparsity)
continue;
matrix[i][j] = (random.nextDouble() * (max - min) + min);
}
}
return matrix;
}
/**
*
* @param fname
* @throws DMLUnsupportedOperationException
* @throws DMLRuntimeException
* @throws XMLStreamException
* @throws IOException
*/
public static void externalReadProfile( String fname )
throws DMLUnsupportedOperationException, DMLRuntimeException, XMLStreamException, IOException
{
registerTestConfigurations();
registerInstructions();
readProfile( fname );
}
/**
*
* @param dirname
* @return
* @throws IOException
* @throws DMLUnsupportedOperationException
*/
@SuppressWarnings("all")
private static HashMap<Integer,Long> writeResults( String dirname )
throws IOException, DMLUnsupportedOperationException
{
HashMap<Integer,Long> map = new HashMap<Integer, Long>();
int count = 1;
int offset = (MODEL_INTERCEPT ? 1 : 0);
int cols = MODEL_MAX_ORDER + offset;
for( Entry<Integer,HashMap<Integer,LinkedList<Double>>> inst : _results.entrySet() )
{
int instID = inst.getKey();
HashMap<Integer,LinkedList<Double>> instCF = inst.getValue();
for( Entry<Integer,LinkedList<Double>> cfun : instCF.entrySet() )
{
int tDefID = cfun.getKey();
long ID = IDHandler.concatIntIDsToLong(instID, tDefID);
LinkedList<Double> dmeasure = cfun.getValue();
PerfTestDef def = _regTestDef.get(tDefID);
LinkedList<Double> dvariable = generateSequence(def.getMin(), def.getMax(), NUM_SAMPLES_PER_TEST);
int dlen = dvariable.size();
int plen = def.getInternalVariables().length;
//write variable data set
CSVWriter writer1 = new CSVWriter( new FileWriter( dirname+count+"_in1.csv" ),',', CSVWriter.NO_QUOTE_CHARACTER);
if( plen == 1 ) //one dimensional function
{
//write 1, x, x^2, x^3, ...
String[] sbuff = new String[cols];
for( Double val : dvariable )
{
for( int j=0; j<cols; j++ )
sbuff[j] = String.valueOf( Math.pow(val, j+1-offset) );
writer1.writeNext(sbuff);
}
}
else // multi-dimensional function
{
//write 1, x,y,z,x^2,y^2,z^2, xy, xz, yz, xyz
String[] sbuff = new String[(int)Math.pow(2,plen)-1+plen+offset-1];
//String[] sbuff = new String[plen+offset];
if(offset==1)
sbuff[0]="1";
//init index stack
int[] index = new int[plen];
for( int i=0; i<plen; i++ )
index[i] = 0;
//execute test
double[] buff = new double[plen];
while( index[0]<dlen )
{
//set buffer values
for( int i=0; i<plen; i++ )
buff[i] = dvariable.get(index[i]);
//core writing
for( int i=1; i<=plen; i++ )
{
if( i==1 )
{
for( int j=0; j<plen; j++ )
sbuff[offset+j] = String.valueOf( buff[j] );
for( int j=0; j<plen; j++ )
sbuff[offset+plen+j] = String.valueOf( Math.pow(buff[j],2) );
}
else if( i==2 )
{
int ix=0;
for( int j=0; j<plen-1; j++ )
for( int k=j+1; k<plen; k++, ix++ )
sbuff[offset+2*plen+ix] = String.valueOf( buff[j]*buff[k] );
}
else if( i==plen )
{
//double tmp=1;
//for( int j=0; j<plen; j++ )
// tmp *= buff[j];
//sbuff[offset+2*plen+plen*(plen-1)/2] = String.valueOf(tmp);
}
else
throw new DMLUnsupportedOperationException("More than 3 dims currently not supported.");
}
//for( int i=0; i<plen; i++ )
// sbuff[offset+i] = String.valueOf( buff[i] );
writer1.writeNext(sbuff);
//increment indexes
for( int i=plen-1; i>=0; i
{
if(i==plen-1)
index[i]++;
else if( index[i+1] >= dlen )
{
index[i]++;
index[i+1]=0;
}
}
}
}
writer1.close();
//write measure data set
CSVWriter writer2 = new CSVWriter( new FileWriter( dirname+count+"_in2.csv" ),',', CSVWriter.NO_QUOTE_CHARACTER);
String[] buff2 = new String[1];
for( Double val : dmeasure )
{
buff2[0] = String.valueOf( val );
writer2.writeNext(buff2);
}
writer2.close();
map.put(count, ID);
count++;
}
}
return map;
}
/**
*
* @param dmlname
* @param dmltmpname
* @param dir
* @param models
* @param rows
* @param cols
* @throws IOException
* @throws ParseException
* @throws DMLException
*/
private static void computeRegressionModels( String dmlname, String dmltmpname, String dir, int models, int rows, int cols )
throws IOException, ParseException, DMLException
{
//clean scratch space
//AutomatedTestBase.cleanupScratchSpace();
//read DML template
StringBuffer buffer = new StringBuffer();
BufferedReader br = new BufferedReader( new FileReader(new File( dmlname )) );
String line = "";
while( (line=br.readLine()) != null )
{
buffer.append(line);
buffer.append("\n");
}
br.close();
String template = buffer.toString();
//replace parameters
template = template.replaceAll("%numModels%", String.valueOf(models));
template = template.replaceAll("%numRows%", String.valueOf(rows));
template = template.replaceAll("%numCols%", String.valueOf(cols));
template = template.replaceAll("%indir%", String.valueOf(dir));
// write temp DML file
File fout = new File(dmltmpname);
FileOutputStream fos = new FileOutputStream(fout);
fos.write(template.getBytes());
fos.close();
// execute DML script
DMLScript.main(new String[] { "-f", dmltmpname });
}
/**
*
* @param dname
* @param IDMapping
* @throws IOException
*/
private static void readRegressionModels( String dname, HashMap<Integer,Long> IDMapping )
throws IOException
{
for( Integer count : IDMapping.keySet() )
{
long ID = IDMapping.get(count);
int instID = IDHandler.extractIntIDFromLong(ID, 1);
int tDefID = IDHandler.extractIntIDFromLong(ID, 2);
//read file and parse
LinkedList<Double> params = new LinkedList<Double>();
CSVReader reader1 = new CSVReader( new FileReader(dname+count+"_out.csv"), ',' );
String[] nextline = null;
while( (nextline = reader1.readNext()) != null )
{
params.add(Double.parseDouble(nextline[0]));
}
reader1.close();
double[] dparams = new double[params.size()];
int i=0;
for( Double d : params )
{
dparams[i] = d;
i++;
}
//create new cost function
boolean multidim = _regTestDef.get(tDefID).getInternalVariables().length > 1;
CostFunction cf = new CostFunction(dparams, multidim);
//append to profile
if( !_profile.containsKey(instID) )
_profile.put(instID, new HashMap<Integer, CostFunction>());
_profile.get(instID).put(tDefID, cf);
}
}
/**
*
* @param vars
* @return
*/
private static String serializeTestVariables( InternalTestVariable[] vars )
{
StringBuffer sb = new StringBuffer();
for( int i=0; i<vars.length; i++ )
{
if( i>0 )
sb.append( XML_ELEMENT_DELIMITER );
sb.append( String.valueOf(vars[i]) );
}
return sb.toString();
}
/**
*
* @param vars
* @return
*/
private static InternalTestVariable[] parseTestVariables(String vars)
{
StringTokenizer st = new StringTokenizer(vars, XML_ELEMENT_DELIMITER);
InternalTestVariable[] v = new InternalTestVariable[st.countTokens()];
for( int i=0; i<v.length; i++ )
v[i] = InternalTestVariable.valueOf(st.nextToken());
return v;
}
/**
*
* @param vals
* @return
*/
private static String serializeParams( double[] vals )
{
StringBuffer sb = new StringBuffer();
for( int i=0; i<vals.length; i++ )
{
if( i>0 )
sb.append( XML_ELEMENT_DELIMITER );
sb.append( String.valueOf(vals[i]) );
}
return sb.toString();
}
/**
*
* @param valStr
* @return
*/
private static double[] parseParams( String valStr )
{
StringTokenizer st = new StringTokenizer(valStr, XML_ELEMENT_DELIMITER);
double[] params = new double[st.countTokens()];
for( int i=0; i<params.length; i++ )
params[i] = Double.parseDouble(st.nextToken());
return params;
}
/**
*
* @param fname
* @throws XMLStreamException
* @throws IOException
*/
private static void readProfile( String fname )
throws XMLStreamException, IOException
{
//init profile map
_profile = new HashMap<Integer, HashMap<Integer,CostFunction>>();
//check file for existence
File f = new File( fname );
if( !f.exists() )
System.out.println("ParFOR PerfTestTool: Warning cannot read profile file "+fname);
FileInputStream fis = new FileInputStream( f );
//xml parsing
XMLInputFactory xif = XMLInputFactory.newInstance();
XMLStreamReader xsr = xif.createXMLStreamReader( fis );
int e = xsr.nextTag(); // profile start
while( true ) //read all instructions
{
e = xsr.nextTag(); // instruction start
if( e == XMLStreamConstants.END_ELEMENT )
break; //reached profile end tag
//parse instruction
int ID = Integer.parseInt( xsr.getAttributeValue(null, XML_ID) );
//String name = xsr.getAttributeValue(null, XML_NAME).trim().replaceAll(" ", Lops.OPERAND_DELIMITOR);
HashMap<Integer, CostFunction> tmp = new HashMap<Integer, CostFunction>();
_profile.put( ID, tmp );
while( true )
{
e = xsr.nextTag(); // cost function start
if( e == XMLStreamConstants.END_ELEMENT )
break; //reached instruction end tag
//parse cost function
TestMeasure m = TestMeasure.valueOf( xsr.getAttributeValue(null, XML_MEASURE) );
TestVariable lv = TestVariable.valueOf( xsr.getAttributeValue(null, XML_VARIABLE) );
InternalTestVariable[] pv = parseTestVariables( xsr.getAttributeValue(null, XML_INTERNAL_VARIABLES) );
DataFormat df = DataFormat.valueOf( xsr.getAttributeValue(null, XML_DATAFORMAT) );
int tDefID = getTestDefID(m, lv, df, pv);
xsr.next(); //read characters
double[] params = parseParams(xsr.getText());
boolean multidim = _regTestDef.get(tDefID).getInternalVariables().length > 1;
CostFunction cf = new CostFunction( params, multidim );
tmp.put(tDefID, cf);
xsr.nextTag(); // cost function end
//System.out.println("added cost function");
}
}
xsr.close();
fis.close();
//mark profile as successfully read
_flagReadData = true;
}
/**
* StAX for efficient streaming XML writing.
*
* @throws IOException
* @throws XMLStreamException
*/
private static void writeProfile( String dname, String fname )
throws IOException, XMLStreamException
{
//create initial directory and file
File dir = new File( dname );
if( !dir.exists() )
dir.mkdir();
File f = new File( fname );
f.createNewFile();
FileOutputStream fos = new FileOutputStream( f );
//create document
XMLOutputFactory xof = XMLOutputFactory.newInstance();
XMLStreamWriter xsw = xof.createXMLStreamWriter( fos );
xsw = new IndentingXMLStreamWriter( xsw ); //remove this line if no indenting required
//write document content
xsw.writeStartDocument();
xsw.writeStartElement( XML_PROFILE );
xsw.writeAttribute(XML_DATE, String.valueOf(new Date()) );
//foreach instruction (boundle of cost functions)
for( Entry<Integer,HashMap<Integer,CostFunction>> inst : _profile.entrySet() )
{
int instID = inst.getKey();
String instName = _regInst_IDNames.get( instID );
xsw.writeStartElement( XML_INSTRUCTION );
xsw.writeAttribute(XML_ID, String.valueOf( instID ));
xsw.writeAttribute(XML_NAME, instName.replaceAll(Lops.OPERAND_DELIMITOR, " "));
//foreach testdef cost function
for( Entry<Integer,CostFunction> cfun : inst.getValue().entrySet() )
{
int tdefID = cfun.getKey();
PerfTestDef def = _regTestDef.get(tdefID);
CostFunction cf = cfun.getValue();
xsw.writeStartElement( XML_COSTFUNCTION );
xsw.writeAttribute( XML_ID, String.valueOf( tdefID ));
xsw.writeAttribute( XML_MEASURE, def.getMeasure().toString() );
xsw.writeAttribute( XML_VARIABLE, def.getVariable().toString() );
xsw.writeAttribute( XML_INTERNAL_VARIABLES, serializeTestVariables(def.getInternalVariables()) );
xsw.writeAttribute( XML_DATAFORMAT, def.getDataformat().toString() );
xsw.writeCharacters(serializeParams( cf.getParams() ));
xsw.writeEndElement();// XML_COSTFUNCTION
}
xsw.writeEndElement(); //XML_INSTRUCTION
}
xsw.writeEndElement();//XML_PROFILE
xsw.writeEndDocument();
xsw.close();
fos.close();
}
/**
* Main for invoking the actual performance test in order to produce profile.xml
*
* @param args
*/
public static void main(String[] args)
{
//execute the local / remote performance test
try
{
PerfTestTool.runTest();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
|
package com.example.michael.ui.activities;
import android.app.FragmentManager;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.location.Location;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.michael.ui.R;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.parse.FunctionCallback;
import com.parse.ParseCloud;
import com.parse.ParseException;
import com.parse.ParseGeoPoint;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseRelation;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import butterknife.ButterKnife;
import butterknife.InjectView;
public class GameMapActivity extends FragmentActivity implements Button.OnTouchListener, MediaPlayer.OnCompletionListener, EndGameDialog.Communicator, LocationProvider.LocationCallback {
@InjectView(R.id.distanceView)
TextView distanceView;
@InjectView(R.id.catchButton)
Button catchBtn;
@InjectView(R.id.talkButton)
Button talkBtn;
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private Handler updateHandler;
private Location preyLoc;
private String playerObjID;
private Location loc;
private boolean update;
private boolean isPrey;
private MediaRecorder mRecorder;
private MediaPlayer mPlayer;
private String mFileName;
private String gameID;
private int markerRadius;
private List<byte[]> playedAudioFiles;
private Map<String, MarkerOptions> markers;
private Runnable updateLocation;
private Runnable retrieveAudio;
private Thread locationThread;
private Thread audioThread;
private long updateLocationInterval;
private int distanceToPrey;
private CountDownTimer gameDurationCDT;
private CountDownTimer catchBtnBlockCDT;
private final long startTime = 5000;
private final long interval = 1000;
private String nickName;
private FragmentManager fragmentManager;
private EndGameDialog dialog;
private boolean isLobbyLeader;
private ProgressBar pb;
private LocationProvider locationProvider;
public static final String TAG = GameMapActivity.class.getSimpleName();
private int gameDuration;
private int catchRadius;
private int gameDurationProgressValue;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_map);
ButterKnife.inject(this);
setUpMapIfNeeded();
locationProvider = new LocationProvider(this, this);
locationProvider.connect();
gameID = getIntent().getStringExtra("gameID");
nickName = getIntent().getStringExtra("nickName");
isLobbyLeader = getIntent().getBooleanExtra("isLobbyLeader", false);
catchRadius = getIntent().getIntExtra("catchRadius", 0);
playerObjID = getIntent().getStringExtra("playerObjID");
isPrey = getIntent().getBooleanExtra("isPrey", false);
gameDuration = 10;//In seconds
gameDurationProgressValue = gameDuration * 10;
pb = (ProgressBar) findViewById(R.id.timerProgress);
talkBtn.setOnTouchListener(this);
mPlayer = new MediaPlayer();
mPlayer.setOnCompletionListener(this);
preyLoc = new Location("");
preyLoc.setLatitude(0);
preyLoc.setLongitude(0);
loc = new Location("");
loc.setLatitude(0);
loc.setLongitude(0);
fragmentManager = getFragmentManager();
dialog = new EndGameDialog();
mFileName = getFilesDir().getAbsolutePath();
mFileName += "/AudioRecord_ThePursuit.3gp";
update = true; //Make it true elsewhere...
markerRadius = 25;
markers = new HashMap<>();
playedAudioFiles = new ArrayList<>();
updateLocationInterval = 1000;
if (isPrey) {
catchBtn.setVisibility(View.GONE);
talkBtn.setVisibility(View.GONE);
}
talkBtn.setVisibility(View.GONE);
pb.setMax(gameDurationProgressValue);
pb.setProgress(gameDurationProgressValue);
gameDurationCDT = new CountDownTimer(gameDuration * 1000, 100) {
@Override
public void onTick(long millisUntilFinished) {
pb.setProgress((gameDurationProgressValue) - ((int) millisUntilFinished/100));
}
@Override
public void onFinish() {
pb.setProgress(gameDurationProgressValue);
HashMap<String, Object> endGameInfo = new HashMap<>();
endGameInfo.put("gameID", gameID);
ParseCloud.callFunctionInBackground("endGame", endGameInfo, new FunctionCallback<ParseObject>() {
@Override
public void done(ParseObject game, ParseException e) {
if (e == null) {
} else {
//TODO: Error msg...
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
};
catchBtnBlockCDT = new CountDownTimer(startTime, interval) {
@Override
public void onTick(long millisUntilFinished) {
catchBtn.setText(String.valueOf(millisUntilFinished / 1000));
}
@Override
public void onFinish() {
catchBtn.setText("Catch");
catchBtn.setEnabled(true);
}
};
updateHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
mMap.clear();
for (MarkerOptions mo : markers.values()) {
mMap.addMarker(mo);
}
if (isPrey) {
distanceView.setText("You're the Prey, Hide!");//Create separate methods to call when you're prey and so on...
} else {
distanceToPrey = Math.round(loc.distanceTo(preyLoc));
if (distanceToPrey < 10) {
distanceView.setText("You're very close!");
} else {
distanceView.setText("Prey: " + distanceToPrey + "m");
}
/*
//Change update frequency
if (distanceToPrey > 100) {
updateLocationInterval = 2000;
} else if (distanceToPrey > 20) {
updateLocationInterval = 1000;
} else {
updateLocationInterval = 500;
}
*/
}
}
};
updateLocation = new Runnable() {
@Override
public void run() {
while (update) {
HashMap<String, Object> updateInfo = new HashMap<>();
//Get my location method
updateInfo.put("gameID", gameID);
updateInfo.put("playerObjID", getIntent().getStringExtra("playerObjID"));
updateInfo.put("latitude", loc.getLatitude());
updateInfo.put("longitude", loc.getLongitude());
ParseCloud.callFunctionInBackground("updateGame", updateInfo, new FunctionCallback<ParseObject>() {
@Override
public void done(ParseObject game, ParseException e) {
if (e == null) {
try {
if (game.getRelation("state").getQuery().getFirst().getBoolean("preyCaught")) {
update = false;
if (isPrey) {
dialog.setStatusText("You LOST! :<");
} else {
dialog.setStatusText("Someone has caught the prey, your team WON! :) ");
}
dialog.show(fragmentManager, "Game has finished!");
} else {
for (ParseObject player : game.getRelation("players").getQuery().find()) {
ParseGeoPoint geo = (ParseGeoPoint) player.get("location");
if (player.getBoolean("isPrey")) {
preyLoc.setLatitude(geo.getLatitude());
preyLoc.setLongitude(geo.getLongitude());
} else if (!player.getObjectId().equals(getIntent().getStringExtra("playerObjID"))) {
String playerName = player.get("name").toString();
LatLng latLng = new LatLng(geo.getLatitude(), geo.getLongitude());
MarkerOptions markerOptions = new MarkerOptions().position(latLng).title(playerName).icon(BitmapDescriptorFactory.fromBitmap(makeMarkerIcon(player.get("playerColor").toString())));
markers.put(playerName, markerOptions);
}
}
updateHandler.sendEmptyMessage(0);
}
} catch (ParseException e1) {
e1.printStackTrace();
//TODO: Print query error
}
} else {
//TODO: Error msg...
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
});
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
retrieveAudio = new Runnable() {
@Override
public void run() {
while (update) {
try {
ParseObject game = ParseQuery.getQuery("Game").whereEqualTo("gameID", gameID).getFirst();
List<ParseObject> audioFiles = game.getRelation("audioFiles").getQuery().find();
if (audioFiles != null) {
for (ParseObject audioFile : audioFiles) {
byte[] serverSoundData = audioFile.getBytes("sound");
if (!byteListContains(playedAudioFiles, serverSoundData)) {
playSoundData(serverSoundData);
playedAudioFiles.add(serverSoundData);
break;
}
}
}
} catch (ParseException e) {
e.printStackTrace();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
locationThread = new Thread(updateLocation);
audioThread = new Thread(retrieveAudio);
//locationThread.start();
audioThread.start();
gameDurationCDT.start();
}
@Override
public void onResume() {
super.onResume();
setUpMapIfNeeded();
locationProvider.connect();
}
@Override
protected void onPause() {
super.onPause();
//locationProvider.disconnect();
}
/**
* Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
* installed) and the map has not already been instantiated.. This will ensure that we only ever
* call {@link #setUpMap()} once when {@link #mMap} is not null.
* <p/>
* If it isn't installed {@link SupportMapFragment} (and
* {@link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
* install/update the Google Play services APK on their device.
* <p/>
* A user can return to this FragmentActivity after following the prompt and correctly
* installing/updating/enabling the Google Play services. Since the FragmentActivity may not
* have been completely destroyed during this process (it is likely that it would only be
* stopped or paused), {@link #onCreate(Bundle)} may not be called again so we should call this
* method in {@link #onResume()} to guarantee that it will be called.
*/
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
/**
* This is where we can add markers or lines, add listeners or move the camera. In this case, we
* just add a marker near Africa.
* This should only be called once and when we are sure that mMap is not null.
*/
private void setUpMap() {
// Set map type
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//mMap.setMyLocationEnabled(true);
//Disable scrolling
mMap.getUiSettings().setRotateGesturesEnabled(false);
mMap.getUiSettings().setScrollGesturesEnabled(false);
mMap.animateCamera(CameraUpdateFactory.zoomTo(18));
}
public boolean byteListContains(List<byte[]> byteArrayList, byte[] byteArray) {
for (byte[] bae : byteArrayList) {
if (Arrays.equals(bae, byteArray)) {
return true;
}
}
return false;
}
public void playSoundData(byte[] soundData) {
try {
File tempFile = File.createTempFile("TempRetrievedAudio", "3gp");
FileOutputStream fos = new FileOutputStream(tempFile);
fos.write(soundData);
fos.close();
FileInputStream storedFIS = new FileInputStream(tempFile);
//Play sound
mPlayer.setDataSource(storedFIS.getFD());
mPlayer.prepare();
mPlayer.start();
} catch (IOException e) {
Log.e("MediaPlayer", "prepare() failed");
}
while (mPlayer.isPlaying()) {
//wait for it to finnish
}
}
@Override
public void onBackPressed() {
update = false;
gameDurationCDT.cancel();
locationProvider.disconnect();
mPlayer.stop();
mPlayer.release();
super.onBackPressed();
finish();
}
/*
* String of hexColor format can be either #RRGGBB (normal rgb) or #AARRGGBB (with transparent alpha value)
*/
public Bitmap makeMarkerIcon(String hexColor) {
Bitmap bmp = Bitmap.createBitmap(markerRadius, markerRadius + 25, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bmp);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(Color.parseColor(hexColor));
paint.setStyle(Paint.Style.FILL);
/*
// the triangle laid under the circle
int pointedness = 20;
Path path = new Path();
path.setFillType(Path.FillType.EVEN_ODD);
path.moveTo(markerRadius / 2, markerRadius + 15);
path.lineTo(markerRadius / 2 + pointedness, markerRadius - 10);
path.lineTo(markerRadius / 2 - pointedness, markerRadius - 10);
canvas.drawPath(path, paint);
*/
// circle background
RectF rect = new RectF(0, 0, markerRadius, markerRadius);
canvas.drawRoundRect(rect, markerRadius / 2, markerRadius / 2, paint);
return bmp;
}
public void catchButton(View view) {
HashMap<String, Object> tryCatchInfo = new HashMap<>();
tryCatchInfo.put("gameID", gameID);
tryCatchInfo.put("playerObjID", playerObjID);
ParseCloud.callFunctionInBackground("tryCatch", tryCatchInfo, new FunctionCallback<ParseObject>() {
@Override
public void done(ParseObject game, ParseException e) {
if (e == null) {
update = false;
locationProvider.disconnect();
//dialog.setStatusText("Congratulations, you caught the prey! :D");
//dialog.show(fragmentManager, "Game has finished!");
//Toast.makeText(getApplicationContext(), "CAUGHT!", Toast.LENGTH_LONG).show();
gameDurationCDT.cancel();
} else {
Toast.makeText(getApplicationContext(), "You're not close enough!", Toast.LENGTH_LONG).show();
catchBtn.setEnabled(false);
catchBtnBlockCDT.start();
}
}
});
}
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
talkBtn.setPressed(true);
talkBtn.setText("Recording...");
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mRecorder.setOutputFile(mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e("MediaRecorder", "prepare() failed");
}
mRecorder.start();
return true;
} else if (event.getAction() == MotionEvent.ACTION_UP) {
//Add timer for talk button here...
talkBtn.setPressed(false);
talkBtn.setText("Talk");
//Stop recording
mRecorder.stop();
mRecorder.release();
mRecorder = null;
//Convert
FileInputStream fis;
File fileObj = new File(mFileName);
byte[] data = new byte[(int) fileObj.length()];
try {
fis = new FileInputStream(fileObj);
fis.read(data);
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
playedAudioFiles.add(data);
//Upload audio file to server
try {
ParseObject game = ParseQuery.getQuery("Game").whereEqualTo("gameID", gameID).getFirst();
ParseRelation gameAudioRelation = game.getRelation("audioFiles");
ParseObject audio = new ParseObject("Audio");
audio.put("sound", data);
audio.put("timesListened", 1);
audio.save();
gameAudioRelation.add(audio);
game.saveInBackground();
} catch (ParseException e) {
e.printStackTrace();
}
return true;
}
return false;
}
@Override
public void onCompletion(MediaPlayer mp) {
mp.stop();
mp.reset();
talkBtn.setEnabled(true);
}
@Override
public void onDialogMessage() {
mPlayer.stop();
mPlayer.release();
ArrayList<String> players = new ArrayList<>();
try {
for (ParseObject player : ParseQuery.getQuery("Game").whereEqualTo("gameID", gameID).getFirst().getRelation("players").getQuery().find()) {
players.add(player.get("name").toString());
}
Intent intent = new Intent(GameMapActivity.this, LobbyActivity.class);
intent.putStringArrayListExtra("players", players);
intent.putExtra("gameID", gameID);
intent.putExtra("nickName", nickName); // May be redundant. Check for other intents.
intent.putExtra("playerObjID", playerObjID);
intent.putExtra("isLobbyLeader", isLobbyLeader);
intent.putExtra("gameDuration", gameDuration);
intent.putExtra("catchRadius", catchRadius);
startActivity(intent);
finish();
} catch (ParseException e1) {
e1.printStackTrace();
super.onBackPressed();
finish();
//TODO: No internet connection or game leader left which causes game object to destroy?
}
}
public void drawMarkers() {
mMap.clear();
LatLng latLng = new LatLng(loc.getLatitude(), loc.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
for (MarkerOptions mo : markers.values()) {
mMap.addMarker(mo);
}
if (isPrey) {
distanceView.setText("You're the Prey, Hide!");//Create separate methods to call when you're prey and so on...
} else {
distanceToPrey = Math.round(loc.distanceTo(preyLoc));
if (distanceToPrey < 20) {
distanceView.setText("You're very close!");
} else {
distanceView.setText("Prey: " + distanceToPrey + "m");
}
/*
//Change update frequency
if (distanceToPrey > 100) {
updateLocationInterval = 2000;
} else if (distanceToPrey > 20) {
updateLocationInterval = 1000;
} else {
updateLocationInterval = 500;
}
*/
}
}
@Override
public void handleNewLocation(final Location location) {
Log.d(TAG, "Date: " + new Date().toString());
loc = location;
HashMap<String, Object> updateInfo = new HashMap<>();
updateInfo.put("gameID", gameID);
updateInfo.put("playerObjID", playerObjID);
updateInfo.put("latitude", loc.getLatitude());
updateInfo.put("longitude", loc.getLongitude());
ParseCloud.callFunctionInBackground("updateGame", updateInfo, new FunctionCallback<ParseObject>() {
@Override
public void done(ParseObject game, ParseException e) {
if (e == null) {
try {
if (!game.getRelation("state").getQuery().getFirst().getBoolean("isPlaying")) {
update = false;
locationProvider.disconnect();
if (game.getRelation("state").getQuery().getFirst().getBoolean("preyCaught")) {
if (isPrey) {
dialog.setStatusText("You LOSE! You won't survive a zombie apocalypse :<");
} else {
dialog.setStatusText("Someone has caught the prey, you WIN! :)");
}
} else {
if (isPrey) {
dialog.setStatusText("TIME OUT!" + "\n" + "They couldn't find you." + "\n" + "You WIN! :)");
} else {
dialog.setStatusText("TIME OUT!" + "\n" + "You guys suck at hunting." + "\n" + "You LOSE! >:(");
}
}
dialog.show(fragmentManager, "Game has finished!");
} else {
for (ParseObject player : game.getRelation("players").getQuery().find()) {
ParseGeoPoint geo = (ParseGeoPoint) player.get("location");
if (player.getBoolean("isPrey")) {
preyLoc.setLatitude(geo.getLatitude());
preyLoc.setLongitude(geo.getLongitude());
} else {
String playerName = player.get("name").toString();
LatLng latLng = new LatLng(geo.getLatitude(), geo.getLongitude());
MarkerOptions markerOptions = new MarkerOptions().position(latLng).title(playerName).icon(BitmapDescriptorFactory.fromBitmap(makeMarkerIcon(player.get("playerColor").toString())));
markers.put(playerName, markerOptions);
}
}
drawMarkers();
}
} catch (ParseException e1) {
e1.printStackTrace();
//TODO: Print query error
}
} else {
//TODO: Error msg...
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
}
|
package ucar.nc2.iosp;
import org.junit.*;
import org.junit.experimental.categories.Category;
import ucar.ma2.Array;
import ucar.ma2.DataType;
import ucar.ma2.InvalidRangeException;
import ucar.nc2.Attribute;
import ucar.nc2.NetcdfFile;
import ucar.nc2.Variable;
import ucar.nc2.constants.CDM;
import ucar.nc2.util.Misc;
import ucar.nc2.util.cache.FileCache;
import ucar.unidata.io.RandomAccessFile;
import ucar.unidata.test.util.NeedsCdmUnitTest;
import ucar.unidata.test.util.TestDir;
import java.io.IOException;
import java.util.Arrays;
/**
* Misc tests on iosp, mostly just sanity (opens ok)
*
* @author caron
* @since 7/29/2014
*/
@Category(NeedsCdmUnitTest.class)
public class TestMiscIosp {
private static int leaks;
@BeforeClass
static public void startup() {
RandomAccessFile.setDebugLeaks(true);
RandomAccessFile.enableDefaultGlobalFileCache();
leaks = RandomAccessFile.getOpenFiles().size();
}
@AfterClass
static public void checkLeaks() {
FileCache.shutdown();
RandomAccessFile.setGlobalFileCache(null);
assert leaks == TestDir.checkLeaks();
RandomAccessFile.setDebugLeaks(false);
}
@Test
public void testFyiosp() throws IOException {
String fileIn = TestDir.cdmUnitTestDir + "formats/fysat/SATE_L3_F2C_VISSR_MWB_SNO_CNB-DAY-2008010115.AWX";
try (ucar.nc2.NetcdfFile ncf = ucar.nc2.NetcdfFile.open(fileIn)) {
System.out.printf("open %s %n", ncf.getLocation());
String val = ncf.findAttValueIgnoreCase(null, "version", null);
assert val != null;
assert val.equals("SAT2004");
Variable v = ncf.findVariable("snow");
assert v != null;
assert v.getDataType() == DataType.SHORT;
Array data = v.read();
assert Arrays.equals(data.getShape(), new int[]{1, 91, 181});
}
}
@Test
public void testUamiv() throws IOException {
try (NetcdfFile ncfile = NetcdfFile.open(TestDir.cdmUnitTestDir + "formats/uamiv/uamiv.grid", null)) {
System.out.printf("open %s %n", ncfile.getLocation());
ucar.nc2.Variable v = ncfile.findVariable("UP");
assert v != null;
assert v.getDataType() == DataType.FLOAT;
Array data = v.read();
assert Arrays.equals(data.getShape(), new int[]{12, 5, 7, 6});
}
}
@Test
public void testGini() throws IOException, InvalidRangeException {
String fileIn = TestDir.cdmUnitTestDir + "formats/gini/n0r_20041013_1852-compress";
try (ucar.nc2.NetcdfFile ncf = ucar.nc2.NetcdfFile.open(fileIn)) {
System.out.printf("open %s %n", ncf.getLocation());
ucar.nc2.Variable v = ncf.findVariable("Reflectivity");
assert v != null;
assert v.getDataType() == DataType.FLOAT;
Array data = v.read();
assert Arrays.equals(data.getShape(), new int[]{1, 3000, 4736});
}
}
@Test
public void testGrads() throws IOException, InvalidRangeException {
String fileIn = TestDir.cdmUnitTestDir + "formats/grads/mask.ctl";
try (ucar.nc2.NetcdfFile ncf = ucar.nc2.NetcdfFile.open(fileIn)) {
System.out.printf("open %s %n", ncf.getLocation());
ucar.nc2.Variable v = ncf.findVariable("mask");
assert v != null;
assert v.getDataType() == DataType.FLOAT;
Attribute att = v.findAttribute(CDM.MISSING_VALUE);
assert att != null;
assert att.getDataType() == DataType.FLOAT;
assert Misc.closeEnough(att.getNumericValue().floatValue(), -9999.0f);
Array data = v.read();
assert Arrays.equals(data.getShape(), new int[]{1, 1, 180, 360});
}
}
@Test
public void testGradsWithRAFCache() throws IOException, InvalidRangeException {
String fileIn = TestDir.cdmUnitTestDir + "formats/grads/mask.ctl";
try (ucar.nc2.NetcdfFile ncf = ucar.nc2.NetcdfFile.open(fileIn)) {
System.out.printf("open %s %n", ncf.getLocation());
ucar.nc2.Variable v = ncf.findVariable("mask");
assert v != null;
assert v.getDataType() == DataType.FLOAT;
Attribute att = v.findAttribute(CDM.MISSING_VALUE);
assert att != null;
assert att.getDataType() == DataType.FLOAT;
assert Misc.closeEnough(att.getNumericValue().floatValue(), -9999.0f);
Array data = v.read();
assert Arrays.equals(data.getShape(), new int[]{1, 1, 180, 360});
}
}
// @Test
// dunno what kind of grads file this is.
public void testGrads2() throws IOException, InvalidRangeException {
String fileIn = TestDir.cdmUnitTestDir + "formats/grads/pdef.ctl";
try (ucar.nc2.NetcdfFile ncf = ucar.nc2.NetcdfFile.open(fileIn)) {
System.out.printf("open %s %n", ncf.getLocation());
ucar.nc2.Variable v = ncf.findVariable("pdef");
assert v != null;
assert v.getDataType() == DataType.FLOAT;
Attribute att = v.findAttribute(CDM.MISSING_VALUE);
assert att != null;
assert att.getDataType() == DataType.FLOAT;
assert Misc.closeEnough(att.getNumericValue().floatValue(), -9999.0f);
Array data = v.read();
assert Arrays.equals(data.getShape(), new int[]{1, 1, 180, 360});
}
}
}
|
package com.servlet;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import de.unibonn.iai.eis.linda.example.SPARQLExample;
/**
* Root resource (exposed at "myresource" path)
*/
@Path("/example/{type}/")
public class MyResource {
/**
* Method handling HTTP GET requests. The returned object will be sent
* to the client as "text/plain" media type.
*
* @return String that will be returned as a text/plain response.
*/
@GET
@Produces(MediaType.TEXT_PLAIN)
public String getExample(@PathParam("type") String type) {
return SPARQLExample.exampleResultSet(type);
}
}
|
package edu.wustl.catissuecore.action;
import javax.servlet.http.HttpServletRequest;
import edu.wustl.catissuecore.util.global.Constants;
/**
* @author mandar_deshmukh
*
* This class initializes the fields in the CheckInCheckOutEventParameters Add/Edit webpage.
*/
public class CheckInCheckOutEventParametersAction extends SpecimenEventParametersAction
{
protected void setRequestParameters(HttpServletRequest request)
{
super.setRequestParameters(request);
// set array of CheckInCheckOutEventParameters
request.setAttribute(Constants.STORAGESTATUSLIST, Constants.STORAGESTATUSARRAY);
// List embeddingMediumList = CDEManager.getCDEManager().getList(Constants.CDE_NAME_EMBEDDING_MEDIUM);
// request.setAttribute(Constants.EMBEDDINGMEDIUMLIST, embeddingMediumList);
}
}
|
package ucar.unidata.util;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* Holds state for constructing time based queries.
*/
public class DateSelection {
/*
The time modes determine how we define the start and end time.
*/
/** The mode for when we have an absolute time as a range bounds */
public static final int TIMEMODE_FIXED = 0;
/** The mode for when we use the current time */
public static final int TIMEMODE_CURRENT = 1;
/** When one of the ranges is relative to another */
public static final int TIMEMODE_RELATIVE = 2;
/** Mode for using the first or last time in the data set. Not sure if this will be useful here */
public static final int TIMEMODE_DATA = 3;
/** Mode for constructing set */
public static int[] TIMEMODES = { TIMEMODE_FIXED, TIMEMODE_CURRENT,
TIMEMODE_RELATIVE, TIMEMODE_DATA };
/** Mode for constructing set */
public static String[] STARTMODELABELS = { "Fixed", "Current Time (Now)",
"Relative to End Time", "From Data" };
/** Mode for constructing set */
public static String[] ENDMODELABELS = { "Fixed", "Current Time (Now)",
"Relative to Start Time",
"From Data" };
/** Start mode */
private int startMode = TIMEMODE_FIXED;
/** End mode */
private int endMode = TIMEMODE_FIXED;
/** The start fixed time in milliseconds */
private long startFixedTime = Long.MAX_VALUE;
/** The end fixed time in milliseconds */
private long endFixedTime = Long.MAX_VALUE;
/** Start offset */
private double startOffset = 0;
/** End offset */
private double endOffset = 0;
/** The range before before the interval mark */
private double preRange = Double.NaN;
/** The range after the interval mark */
private double postRange = Double.NaN;
/** Interval time */
private double interval = Double.NaN;
/** milliseconds to round to */
private double roundTo = 0;
/** The total count of times we want */
private int count = Integer.MAX_VALUE;
/** How many times do we choose within a given interval range */
private int numTimesInRange = 1;
/** This can hold a set of absolute times. If non-null then these times override any of the query information */
private List times;
/**
* ctor
*/
public DateSelection() {}
/**
* ctor
*
* @param startTime start time
* @param endTime end time
*/
public DateSelection(Date startTime, Date endTime) {
this.startFixedTime = startTime.getTime();
this.endFixedTime = endTime.getTime();
startMode = TIMEMODE_FIXED;
endMode = TIMEMODE_FIXED;
interval = 0;
}
/**
* copy ctor
*
* @param that object to copy from
*/
public DateSelection(DateSelection that) {
this.startMode = that.startMode;
this.endMode = that.endMode;
this.startFixedTime = that.startFixedTime;
this.endFixedTime = that.endFixedTime;
this.startOffset = that.startOffset;
this.endOffset = that.endOffset;
this.postRange = that.postRange;
this.preRange = that.preRange;
this.interval = that.interval;
this.roundTo = that.roundTo;
this.count = that.count;
}
/**
* Apply this date selection query to the list of DatedThing-s
*
* @param datedThings input list of DatedThing-s
*
* @return The filtered list
*/
public List apply(List datedThings) {
datedThings = DatedObject.sort(datedThings, false);
List result = new ArrayList();
Date[] range = getRange();
long startTime = range[0].getTime();
long endTime = range[1].getTime();
boolean hasInterval = hasInterval();
//Get the interval ranges to use
double beforeRange = getPreRangeToUse();
double afterRange = getPostRangeToUse();
System.err.println("range:" + range[0] + " -- " + range[1]);
double[] ticks = null;
if (hasInterval) {
//Pad the times with the interval so we handle the edge cases
double tickStartTime = startTime-interval;
double tickEndTime = endTime+interval;
double base = round(tickEndTime);
System.err.println("base:" + new Date((long) base));
ticks = computeTicks(tickEndTime, tickStartTime, base, interval);
if (ticks == null) {
return result;
}
for (int i = 0; i < ticks.length; i++) {
System.err.println("Interval " + i + ": "
+ new Date((long) (ticks[i]
- beforeRange)) + "
+ new Date((long) (ticks[i]))
+ "
+ new Date((long) (ticks[i]
+ afterRange)));
}
}
int totalThings = 0;
// List[] intervalList = new List[ticks.length];
DatedThing[] closest = null;
double[] minDistance = null;
int currentInterval = 0;
if (ticks != null) {
closest = new DatedThing[ticks.length];
minDistance = new double[ticks.length];
currentInterval = ticks.length - 1;
}
//Remember, we're going backwards in time
for (int i = 0; i < datedThings.size(); i++) {
//Have we maxed out?
if (totalThings >= count) {
break;
}
DatedThing datedThing = (DatedThing) datedThings.get(i);
long time = datedThing.getDate().getTime();
//Check the time range bounds
if (time > endTime) {
System.err.println("after range:" + datedThing);
continue;
}
//We're done
if (time < startTime) {
System.err.println("before range:" + datedThing);
break;
}
//If no interval then just add it
if ( !hasInterval) {
result.add(datedThing);
totalThings++;
continue;
}
while ((currentInterval >= 0)
&& (ticks[currentInterval] - beforeRange > time)) {
currentInterval
}
//Done
if (currentInterval < 0) {
break;
}
boolean thingInInterval = ((time
>= (ticks[currentInterval]
- beforeRange)) && (time
<= (ticks[currentInterval]
+ afterRange)));
if ( !thingInInterval) {
System.err.println("Not in interval:" + datedThing);
continue;
}
double distance = Math.abs(time - ticks[currentInterval]);
if ((closest[currentInterval] == null)
|| (distance < minDistance[currentInterval])) {
if (closest[currentInterval] == null) {
totalThings++;
}
closest[currentInterval] = datedThing;
minDistance[currentInterval] = distance;
}
// if(intervalList[currentInterval]==null) {
// intervalList[currentInterval] = new ArrayList();
//intervalList[currentInterval].add(datedThing);
}
//If we had intervals then add them in
if (closest != null) {
for (int i = 0; i < closest.length - 1; i++) {
if (closest[i] != null) {
result.add(closest[i]);
}
}
}
return result;
}
/**
* Compute the tick mark values based on the input. Cut-and-pasted from Misc
*
* @param high highest value of range
* @param low low value of range
* @param base base value for centering ticks
* @param interval interval between ticks
*
* @return array of computed tick values
*/
private static double[] computeTicks(double high, double low,
double base, double interval) {
double[] vals = null;
// System.err.println ("ticks:" + high + " " + low +" " + base + " " + interval);
// compute nlo and nhi, for low and high contour values in the box
long nlo = Math.round((Math.ceil((low - base) / Math.abs(interval))));
long nhi = Math.round((Math.floor((high - base)
/ Math.abs(interval))));
// how many contour lines are needed.
int numc = (int) (nhi - nlo) + 1;
if (numc < 1) {
return vals;
}
vals = new double[numc];
for (int i = 0; i < numc; i++) {
vals[i] = base + (nlo + i) * interval;
}
return vals;
}
/**
* Construct and return the start and end time range
*
* @return time range
*/
public Date[] getRange() {
double now = (double) (System.currentTimeMillis());
double start = 0;
double end = 0;
if (startMode == TIMEMODE_CURRENT) {
start = now;
} else if (startMode == TIMEMODE_FIXED) {
start = startFixedTime;
}
if (endMode == TIMEMODE_CURRENT) {
end = now;
} else if (endMode == TIMEMODE_FIXED) {
end = endFixedTime;
}
if (startMode != TIMEMODE_RELATIVE) {
start += startOffset;
}
if (endMode != TIMEMODE_RELATIVE) {
end += endOffset;
}
if (startMode == TIMEMODE_RELATIVE) {
start = end + startOffset;
}
if (endMode == TIMEMODE_RELATIVE) {
end = start + endOffset;
}
Date startDate = new Date((long) start);
Date endDate = new Date((long) end);
return new Date[] { startDate, endDate };
}
/**
* Utility to round the given seconds
*
* @param milliSeconds time to round
*
* @return Rounded value
*/
private double round(double milliSeconds) {
return roundTo(roundTo, milliSeconds);
}
/**
* Utility to round the given seconds
*
*
* @param roundTo round to
* @param milliSeconds time to round
*
* @return Rounded value
*/
public static double roundTo(double roundTo, double milliSeconds) {
if(roundTo == 0) return milliSeconds;
double seconds = milliSeconds / 1000;
double rtSeconds = roundTo / 1000;
return 1000 * (seconds - ((int) seconds) % rtSeconds);
}
/**
* Create the time set
*
* @return The time set
*
*/
protected Object makeTimeSet() {
return null;
}
/**
* Set the StartMode property.
*
* @param value The new value for StartMode
*/
public void setStartMode(int value) {
startMode = value;
}
/**
* Get the StartMode property.
*
* @return The StartMode
*/
public int getStartMode() {
return startMode;
}
/**
* Set the EndMode property.
*
* @param value The new value for EndMode
*/
public void setEndMode(int value) {
endMode = value;
}
/**
* Get the EndMode property.
*
* @return The EndMode
*/
public int getEndMode() {
return endMode;
}
/**
* Do we have an interval defined
*
* @return Have interval defined
*/
public boolean hasInterval() {
return interval > 0;
}
/**
* Do we have a pre range defined
*
* @return Is pre-range defined
*/
public boolean hasPreRange() {
return preRange == preRange;
}
/**
* Do we have a post range defined
*
* @return Is post-range defined
*/
public boolean hasPostRange() {
return postRange == postRange;
}
/**
* Set the Interval property.
*
* @param value The new value for Interval
*/
public void setInterval(double value) {
interval = value;
}
/**
* Get the Interval property.
*
* @return The Interval
*/
public double getInterval() {
return interval;
}
/**
* Set the StartOffset property.
*
* @param value The new value for StartOffset
*/
public void setStartOffset(double value) {
startOffset = value;
}
/**
* Get the StartOffset property.
*
* @return The StartOffset
*/
public double getStartOffset() {
return startOffset;
}
/**
* Set the EndOffset property.
*
* @param value The new value for EndOffset
*/
public void setEndOffset(double value) {
endOffset = value;
}
/**
* Get the EndOffset property.
*
* @return The EndOffset
*/
public double getEndOffset() {
return endOffset;
}
/**
* Set the RoundTo property.
*
* @param value The new value for RoundTo
*/
public void setRoundTo(double value) {
roundTo = value;
}
/**
* Get the RoundTo property.
*
* @return The RoundTo
*/
public double getRoundTo() {
return roundTo;
}
/**
* Set the StartFixedTime property.
*
* @param value The new value for StartFixedTime
*/
public void setStartFixedTime(long value) {
startFixedTime = value;
}
/**
* set property
*
* @param d property
*/
public void setStartFixedTime(Date d) {
startFixedTime = d.getTime();
startMode = TIMEMODE_FIXED;
}
/**
* set property
*
* @param d property
*/
public void setEndFixedTime(Date d) {
endFixedTime = d.getTime();
endMode = TIMEMODE_FIXED;
}
/**
* get the property
*
* @return property
*/
public Date getStartFixedDate() {
return new Date(getStartFixedTime());
}
/**
* get the property
*
* @return property
*/
public Date getEndFixedDate() {
return new Date(getEndFixedTime());
}
/**
* Get the StartFixedTime property.
*
* @return The StartFixedTime
*/
public long getStartFixedTime() {
return startFixedTime;
}
/**
* Set the EndFixedTime property.
*
* @param value The new value for EndFixedTime
*/
public void setEndFixedTime(long value) {
endFixedTime = value;
}
/**
* Get the EndFixedTime property.
*
* @return The EndFixedTime
*/
public long getEndFixedTime() {
return endFixedTime;
}
/**
* A utility method to set the pre and post range symmetrically.
* Each are set with half of the given value
*
* @param value interval range
*/
public void setIntervalRange(double value) {
setPreRange(value / 2);
setPostRange(value / 2);
}
/**
* Set the PreRange property.
*
* @param value The new value for PreRange
*/
public void setPreRange(double value) {
preRange = value;
}
/**
* Get the pre interval range to use. If we have a preRange then return that, else,
* return half of the interval.
*
* @return The pre range to use
*/
public double getPreRangeToUse() {
return (hasPreRange()
? preRange
: interval / 2);
}
/**
* Get the post interval range to use. If we have a postRange then return that, else,
* return half of the interval.
*
* @return The post range to use
*/
public double getPostRangeToUse() {
return (hasPostRange()
? postRange
: interval / 2);
}
/**
* Get the PreRange property.
*
* @return The PreRange
*/
public double getPreRange() {
return preRange;
}
/**
* Set the PostRange property.
*
* @param value The new value for PostRange
*/
public void setPostRange(double value) {
postRange = value;
}
/**
* Get the PostRange property.
*
* @return The PostRange
*/
public double getPostRange() {
return postRange;
}
/**
* Set the Count property.
*
* @param value The new value for Count
*/
public void setCount(int value) {
count = value;
}
/**
* Get the Count property.
*
* @return The Count
*/
public int getCount() {
return count;
}
/**
* Set the NumTimesInRange property.
*
* @param value The new value for NumTimesInRange
*/
public void setNumTimesInRange(int value) {
numTimesInRange = value;
}
/**
* Get the NumTimesInRange property.
*
* @return The NumTimesInRange
*/
public int getNumTimesInRange() {
return numTimesInRange;
}
/**
* Set the Times property.
*
* @param value The new value for Times
*/
public void setTimes(List value) {
times = value;
}
/**
* Get the Times property.
*
* @return The Times
*/
public List getTimes() {
return times;
}
/**
* Get the hashcode for this object
*
* @return the hashcode
*/
public int hashCode() {
int hashCode = 0;
if (times != null) {
hashCode ^= times.hashCode();
}
return hashCode ^ new Double(this.startMode).hashCode()
^ new Double(this.endMode).hashCode()
^ new Double(this.startFixedTime).hashCode()
^ new Double(this.endFixedTime).hashCode()
^ new Double(this.startOffset).hashCode()
^ new Double(this.endOffset).hashCode()
^ new Double(this.postRange).hashCode()
^ new Double(this.preRange).hashCode()
^ new Double(this.interval).hashCode()
^ new Double(this.roundTo).hashCode() ^ this.numTimesInRange
^ this.count;
}
/**
* equals method
*
* @param o object to check
*
* @return equals
*/
public boolean equals(Object o) {
if ( !(o instanceof DateSelection)) {
return false;
}
DateSelection that = (DateSelection) o;
if (this.times != that.times) {
return false;
}
if ((this.times != null) && !this.times.equals(that.times)) {
return false;
}
return (this.startMode == that.startMode)
&& (this.endMode == that.endMode)
&& (this.startFixedTime == that.startFixedTime)
&& (this.endFixedTime == that.endFixedTime)
&& (this.startOffset == that.startOffset)
&& (this.endOffset == that.endOffset)
&& (this.postRange == that.postRange)
&& (this.preRange == that.preRange)
&& (this.interval == that.interval)
&& (this.roundTo == that.roundTo)
&& (this.numTimesInRange == that.numTimesInRange)
&& (this.count == that.count);
}
/**
* utility to convert a given number of hours to milliseconds
*
* @param hour hours
*
* @return milliseconds
*/
public static long hourToMillis(long hour) {
return minuteToMillis(hour*60);
}
/**
* utility to convert a given number of minutes to milliseconds
*
* @param minute minutes
*
* @return milliseconds
*/
public static long minuteToMillis(long minute) {
return minute * 60 * 1000;
}
/**
* test
*
* @param msg msg to print out
*/
private void testRange(String msg) {
Date[] range = getRange();
if (msg != null) {
System.err.println(msg);
}
System.err.println(range[0] + " -- " + range[1]);
}
/**
* test main
*
* @param args cmd line args
*/
public static void main(String[] args) {
DateSelection dateSelection = new DateSelection();
List dates = new ArrayList();
long now = System.currentTimeMillis();
for (int i = 0; i < 20; i++) {
dates.add(new DatedObject(new Date(now + minuteToMillis(20)
- i * 10 * 60 * 1000)));
}
dateSelection.setEndMode(TIMEMODE_FIXED);
dateSelection.setEndFixedTime(now);
//Go 2 hours before start
dateSelection.setStartMode(TIMEMODE_RELATIVE);
dateSelection.setStartOffset(hourToMillis(-2));
//15 minute interval
dateSelection.setRoundTo(hourToMillis(12));
dateSelection.setInterval(minuteToMillis(15));
dateSelection.setIntervalRange(minuteToMillis(6));
dates = dateSelection.apply(dates);
System.err.println("result:" + dates);
}
}
|
package cgeo.geocaching.network;
import cgeo.geocaching.CgeoApplication;
import cgeo.geocaching.R;
import cgeo.geocaching.compatibility.Compatibility;
import cgeo.geocaching.connector.ConnectorFactory;
import cgeo.geocaching.files.LocalStorage;
import cgeo.geocaching.list.StoredList;
import cgeo.geocaching.utils.CancellableHandler;
import cgeo.geocaching.utils.FileUtils;
import cgeo.geocaching.utils.ImageUtils;
import cgeo.geocaching.utils.ImageUtils.ContainerDrawable;
import cgeo.geocaching.utils.Log;
import cgeo.geocaching.utils.RxUtils;
import cgeo.geocaching.utils.RxUtils.ObservableCache;
import ch.boye.httpclientandroidlib.HttpResponse;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;
import rx.Observable;
import rx.Observable.OnSubscribe;
import rx.Subscriber;
import rx.functions.Action0;
import rx.functions.Func0;
import rx.functions.Func1;
import rx.subjects.PublishSubject;
import rx.subscriptions.CompositeSubscription;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.text.Html;
import android.widget.TextView;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
/**
* All-purpose image getter that can also be used as a ImageGetter interface when displaying caches.
*/
public class HtmlImage implements Html.ImageGetter {
private static final String[] BLOCKED = new String[] {
"gccounter.de",
"gccounter.com",
"cachercounter/?",
"gccounter/imgcount.php",
"flagcounter.com",
"compteur-blog.net",
"counter.digits.com",
"andyhoppe",
"besucherzaehler-homepage.de",
"hitwebcounter.com",
"kostenloser-counter.eu",
"trendcounter.com",
"hit-counter-download.com",
"gcwetterau.de/counter"
};
public static final String SHARED = "shared";
@NonNull final private String geocode;
/**
* on error: return large error image, if {@code true}, otherwise empty 1x1 image
*/
final private boolean returnErrorImage;
final private int listId;
final private boolean onlySave;
final private int maxWidth;
final private int maxHeight;
final private Resources resources;
protected final TextView view;
final private Map<String, BitmapDrawable> cache = new HashMap<>();
final private ObservableCache<String, BitmapDrawable> observableCache = new ObservableCache<>(new Func1<String, Observable<BitmapDrawable>>() {
@Override
public Observable<BitmapDrawable> call(final String url) {
return fetchDrawableUncached(url);
}
});
// Background loading
final private PublishSubject<Observable<String>> loading = PublishSubject.create();
final private Observable<String> waitForEnd = Observable.merge(loading).cache();
final private CompositeSubscription subscription = new CompositeSubscription(waitForEnd.subscribe());
/**
* Create a new HtmlImage object with different behaviors depending on <tt>onlySave</tt> and <tt>view</tt> values.
* There are the three possible use cases:
* <ul>
* <li>If onlySave is true, {@link #getDrawable(String)} will return <tt>null</tt> immediately and will queue the
* image retrieval and saving in the loading subject. Downloads will start in parallel when the blocking
* {@link #waitForEndObservable(cgeo.geocaching.utils.CancellableHandler)} method is called, and they can be
* cancelled through the given handler.</li>
* <li>If <tt>onlySave</tt> is <tt>false</tt> and the instance is called through {@link #fetchDrawable(String)},
* then an observable for the given URL will be returned. This observable will emit the local copy of the image if
* it is present regardless of its freshness, then if needed an updated fresher copy after retrieving it from the
* network.</li>
* <li>If <tt>onlySave</tt> is <tt>false</tt> and the instance is used as an {@link android.text.Html.ImageGetter},
* only the final version of the image will be returned, unless a view has been provided. If it has, then a dummy
* drawable is returned and is updated when the image is available, possibly several times if we had a stale copy of
* the image and then got a new one from the network.</li>
* </ul>
*
* @param geocode
* the geocode of the item for which we are requesting the image, or {@link #SHARED} to use the shared
* cache directory
* @param returnErrorImage
* set to <tt>true</tt> if an error image should be returned in case of a problem, <tt>false</tt> to get
* a transparent 1x1 image instead
* @param listId
* the list this cache belongs to, used to determine if an older image for the offline case can be used
* or not
* @param onlySave
* if set to <tt>true</tt>, {@link #getDrawable(String)} will only fetch and store the image, not return
* it
* @param view
* if non-null, {@link #getDrawable(String)} will return an initially empty drawable which will be
* redrawn when
* the image is ready through an invalidation of the given view
*/
public HtmlImage(@NonNull final String geocode, final boolean returnErrorImage, final int listId, final boolean onlySave, final TextView view) {
this.geocode = geocode;
this.returnErrorImage = returnErrorImage;
this.listId = listId;
this.onlySave = onlySave;
this.view = view;
final Point displaySize = Compatibility.getDisplaySize();
this.maxWidth = displaySize.x - 25;
this.maxHeight = displaySize.y - 25;
this.resources = CgeoApplication.getInstance().getResources();
}
/**
* Create a new HtmlImage object with different behaviors depending on <tt>onlySave</tt> value. No view object
* will be tied to this HtmlImage.
*
* For documentation, see {@link #HtmlImage(String, boolean, int, boolean, TextView)}.
*/
public HtmlImage(@NonNull final String geocode, final boolean returnErrorImage, final int listId, final boolean onlySave) {
this(geocode, returnErrorImage, listId, onlySave, null);
}
/**
* Retrieve and optionally display an image.
* See {@link #HtmlImage(String, boolean, int, boolean, TextView)} for the various behaviours.
*
* @param url
* the URL to fetch from cache or network
* @return a drawable containing the image, or <tt>null</tt> if <tt>onlySave</tt> is <tt>true</tt>
*/
@Nullable
@Override
public BitmapDrawable getDrawable(final String url) {
if (cache.containsKey(url)) {
return cache.get(url);
}
final Observable<BitmapDrawable> drawable = fetchDrawable(url);
if (onlySave) {
loading.onNext(drawable.map(new Func1<BitmapDrawable, String>() {
@Override
public String call(final BitmapDrawable bitmapDrawable) {
return url;
}
}));
cache.put(url, null);
return null;
}
final BitmapDrawable result = view == null ? drawable.toBlocking().lastOrDefault(null) : getContainerDrawable(drawable);
cache.put(url, result);
return result;
}
protected BitmapDrawable getContainerDrawable(final Observable<BitmapDrawable> drawable) {
return new ContainerDrawable(view, drawable);
}
public Observable<BitmapDrawable> fetchDrawable(final String url) {
return observableCache.get(url);
}
// Caches are loaded from disk on a computation scheduler to avoid using more threads than cores while decoding
// the image. Downloads happen on downloadScheduler, in parallel with image decoding.
private Observable<BitmapDrawable> fetchDrawableUncached(final String url) {
if (StringUtils.isBlank(url) || ImageUtils.containsPattern(url, BLOCKED)) {
return Observable.just(ImageUtils.getTransparent1x1Drawable(resources));
}
// Explicit local file URLs are loaded from the filesystem regardless of their age. The IO part is short
// enough to make the whole operation on the computation scheduler.
if (FileUtils.isFileUrl(url)) {
return Observable.defer(new Func0<Observable<BitmapDrawable>>() {
@Override
public Observable<BitmapDrawable> call() {
final Bitmap bitmap = loadCachedImage(FileUtils.urlToFile(url), true).left;
return bitmap != null ? Observable.just(ImageUtils.scaleBitmapToFitDisplay(bitmap)) : Observable.<BitmapDrawable>empty();
}
}).subscribeOn(RxUtils.computationScheduler);
}
final boolean shared = url.contains("/images/icons/icon_");
final String pseudoGeocode = shared ? SHARED : geocode;
return Observable.create(new OnSubscribe<BitmapDrawable>() {
@Override
public void call(final Subscriber<? super BitmapDrawable> subscriber) {
subscription.add(subscriber);
subscriber.add(RxUtils.computationScheduler.createWorker().schedule(new Action0() {
@Override
public void call() {
final ImmutablePair<BitmapDrawable, Boolean> loaded = loadFromDisk();
final BitmapDrawable bitmap = loaded.left;
if (loaded.right) {
subscriber.onNext(bitmap);
subscriber.onCompleted();
return;
}
if (bitmap != null && !onlySave) {
subscriber.onNext(bitmap);
}
RxUtils.networkScheduler.createWorker().schedule(new Action0() {
@Override public void call() {
downloadAndSave(subscriber);
}
});
}
}));
}
private ImmutablePair<BitmapDrawable, Boolean> loadFromDisk() {
final ImmutablePair<Bitmap, Boolean> loadResult = loadImageFromStorage(url, pseudoGeocode, shared);
return scaleImage(loadResult);
}
private void downloadAndSave(final Subscriber<? super BitmapDrawable> subscriber) {
final File file = LocalStorage.getStorageFile(pseudoGeocode, url, true, true);
if (url.startsWith("data:image/")) {
if (url.contains(";base64,")) {
ImageUtils.decodeBase64ToFile(StringUtils.substringAfter(url, ";base64,"), file);
} else {
Log.e("HtmlImage.getDrawable: unable to decode non-base64 inline image");
subscriber.onCompleted();
return;
}
} else if (subscriber.isUnsubscribed() || downloadOrRefreshCopy(url, file)) {
// The existing copy was fresh enough or we were unsubscribed earlier.
subscriber.onCompleted();
return;
}
if (onlySave) {
subscriber.onCompleted();
return;
}
RxUtils.computationScheduler.createWorker().schedule(new Action0() {
@Override
public void call() {
final ImmutablePair<BitmapDrawable, Boolean> loaded = loadFromDisk();
final BitmapDrawable image = loaded.left;
if (image != null) {
subscriber.onNext(image);
} else {
subscriber.onNext(returnErrorImage ?
new BitmapDrawable(resources, BitmapFactory.decodeResource(resources, R.drawable.image_not_loaded)) :
ImageUtils.getTransparent1x1Drawable(resources));
}
subscriber.onCompleted();
}
});
}
});
}
@SuppressWarnings("static-method")
protected ImmutablePair<BitmapDrawable, Boolean> scaleImage(final ImmutablePair<Bitmap, Boolean> loadResult) {
final Bitmap bitmap = loadResult.left;
return ImmutablePair.of(bitmap != null ? ImageUtils.scaleBitmapToFitDisplay(bitmap) : null, loadResult.right);
}
public Observable<String> waitForEndObservable(@Nullable final CancellableHandler handler) {
if (handler != null) {
handler.unsubscribeIfCancelled(subscription);
}
loading.onCompleted();
return waitForEnd;
}
/**
* Download or refresh the copy of <code>url</code> in <code>file</code>.
*
* @param url the url of the document
* @param file the file to save the document in
* @return <code>true</code> if the existing file was up-to-date, <code>false</code> otherwise
*/
private boolean downloadOrRefreshCopy(final String url, final File file) {
final String absoluteURL = makeAbsoluteURL(url);
if (absoluteURL != null) {
try {
final HttpResponse httpResponse = Network.getRequest(absoluteURL, null, file);
if (httpResponse != null) {
final int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode == 200) {
LocalStorage.saveEntityToFile(httpResponse, file);
} else if (statusCode == 304) {
if (!file.setLastModified(System.currentTimeMillis())) {
makeFreshCopy(file);
}
return true;
}
}
} catch (final Exception e) {
Log.e("HtmlImage.downloadOrRefreshCopy", e);
}
}
return false;
}
/**
* Make a fresh copy of the file to reset its timestamp. On some storage, it is impossible
* to modify the modified time after the fact, in which case a brand new file must be
* created if we want to be able to use the time as validity hint.
*
* See Android issue 1699.
*
* @param file the file to refresh
*/
private static void makeFreshCopy(final File file) {
final File tempFile = new File(file.getParentFile(), file.getName() + "-temp");
if (file.renameTo(tempFile)) {
LocalStorage.copy(tempFile, file);
FileUtils.deleteIgnoringFailure(tempFile);
}
else {
Log.e("Could not reset timestamp of file " + file.getAbsolutePath());
}
}
/**
* Load an image from primary or secondary storage.
*
* @param url the image URL
* @param pseudoGeocode the geocode or the shared name
* @param forceKeep keep the image if it is there, without checking its freshness
* @return A pair whose first element is the bitmap if available, and the second one is <code>true</code> if the image is present and fresh enough.
*/
@NonNull
private ImmutablePair<Bitmap, Boolean> loadImageFromStorage(final String url, @NonNull final String pseudoGeocode, final boolean forceKeep) {
try {
final File file = LocalStorage.getStorageFile(pseudoGeocode, url, true, false);
final ImmutablePair<Bitmap, Boolean> image = loadCachedImage(file, forceKeep);
if (image.right || image.left != null) {
return image;
}
final File fileSec = LocalStorage.getStorageSecFile(pseudoGeocode, url, true);
return loadCachedImage(fileSec, forceKeep);
} catch (final Exception e) {
Log.w("HtmlImage.loadImageFromStorage", e);
}
return ImmutablePair.of((Bitmap) null, false);
}
@Nullable
private String makeAbsoluteURL(final String url) {
// Check if uri is absolute or not, if not attach the connector hostname
// FIXME: that should also include the scheme
if (Uri.parse(url).isAbsolute()) {
return url;
}
final String host = ConnectorFactory.getConnector(geocode).getHost();
if (StringUtils.isNotEmpty(host)) {
final StringBuilder builder = new StringBuilder("http:
builder.append(host);
if (!StringUtils.startsWith(url, "/")) {
// FIXME: explain why the result URL would be valid if the path does not start with
// a '/', or signal an error.
builder.append('/');
}
builder.append(url);
return builder.toString();
}
return null;
}
/**
* Load a previously saved image.
*
* @param file the file on disk
* @param forceKeep keep the image if it is there, without checking its freshness
* @return a pair with <code>true</code> in the second component if the image was there and is fresh enough or <code>false</code> otherwise,
* and the image (possibly <code>null</code> if the second component is <code>false</code> and the image
* could not be loaded, or if the second component is <code>true</code> and <code>onlySave</code> is also
* <code>true</code>)
*/
@NonNull
private ImmutablePair<Bitmap, Boolean> loadCachedImage(final File file, final boolean forceKeep) {
if (file.exists()) {
final boolean freshEnough = listId >= StoredList.STANDARD_LIST_ID || file.lastModified() > (System.currentTimeMillis() - (24 * 60 * 60 * 1000)) || forceKeep;
if (freshEnough && onlySave) {
return ImmutablePair.of((Bitmap) null, true);
}
final BitmapFactory.Options bfOptions = new BitmapFactory.Options();
bfOptions.inTempStorage = new byte[16 * 1024];
bfOptions.inPreferredConfig = Bitmap.Config.RGB_565;
setSampleSize(file, bfOptions);
final Bitmap image = BitmapFactory.decodeFile(file.getPath(), bfOptions);
if (image == null) {
Log.e("Cannot decode bitmap from " + file.getPath());
return ImmutablePair.of((Bitmap) null, false);
}
return ImmutablePair.of(image, freshEnough);
}
return ImmutablePair.of((Bitmap) null, false);
}
private void setSampleSize(final File file, final BitmapFactory.Options bfOptions) {
//Decode image size only
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BufferedInputStream stream = null;
try {
stream = new BufferedInputStream(new FileInputStream(file));
BitmapFactory.decodeStream(stream, null, options);
} catch (final FileNotFoundException e) {
Log.e("HtmlImage.setSampleSize", e);
} finally {
IOUtils.closeQuietly(stream);
}
int scale = 1;
if (options.outHeight > maxHeight || options.outWidth > maxWidth) {
scale = Math.max(options.outHeight / maxHeight, options.outWidth / maxWidth);
}
bfOptions.inSampleSize = scale;
}
}
|
package cgeo.geocaching.settings;
import cgeo.geocaching.CgeoApplication;
import cgeo.geocaching.R;
import cgeo.geocaching.apps.cache.navi.NavigationAppFactory.NavigationAppsEnum;
import cgeo.geocaching.connector.gc.GCConstants;
import cgeo.geocaching.connector.gc.Login;
import cgeo.geocaching.enumerations.CacheType;
import cgeo.geocaching.enumerations.LiveMapStrategy.Strategy;
import cgeo.geocaching.enumerations.LogType;
import cgeo.geocaching.geopoint.Geopoint;
import cgeo.geocaching.list.StoredList;
import cgeo.geocaching.maps.MapProviderFactory;
import cgeo.geocaching.maps.google.GoogleMapProvider;
import cgeo.geocaching.maps.interfaces.GeoPointImpl;
import cgeo.geocaching.maps.interfaces.MapProvider;
import cgeo.geocaching.maps.interfaces.MapSource;
import cgeo.geocaching.maps.mapsforge.MapsforgeMapProvider;
import cgeo.geocaching.maps.mapsforge.MapsforgeMapProvider.OfflineMapSource;
import cgeo.geocaching.utils.CryptUtils;
import cgeo.geocaching.utils.FileUtils;
import cgeo.geocaching.utils.FileUtils.FileSelector;
import cgeo.geocaching.utils.Log;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.eclipse.jdt.annotation.Nullable;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Environment;
import android.preference.PreferenceManager;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
* General c:geo preferences/settings set by the user
*/
public final class Settings {
public static final int SHOW_WP_THRESHOLD_DEFAULT = 10;
public static final int SHOW_WP_THRESHOLD_MAX = 50;
private static final int MAP_SOURCE_DEFAULT = GoogleMapProvider.GOOGLE_MAP_ID.hashCode();
private final static int unitsMetric = 1;
// twitter api keys
private final static String keyConsumerPublic = CryptUtils.rot13("ESnsCvAv3kEupF1GCR3jGj");
private final static String keyConsumerSecret = CryptUtils.rot13("7vQWceACV9umEjJucmlpFe9FCMZSeqIqfkQ2BnhV9x");
public enum CoordInputFormatEnum {
Plain,
Deg,
Min,
Sec;
public static CoordInputFormatEnum fromInt(int id) {
final CoordInputFormatEnum[] values = CoordInputFormatEnum.values();
if (id < 0 || id >= values.length) {
return Min;
}
return values[id];
}
}
private static final SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(CgeoApplication.getInstance().getBaseContext());
static {
migrateSettings();
Log.setDebug(sharedPrefs.getBoolean(getKey(R.string.pref_debug), false));
}
/**
* Cache the mapsource locally. If that is an offline map source, each request would potentially access the
* underlying map file, leading to delays.
*/
private static MapSource mapSource;
private Settings() {
// this class is not to be instantiated;
}
private static void migrateSettings() {
// migrate from non standard file location and integer based boolean types
int oldVersion = getInt(R.string.pref_settingsversion, 0);
if (oldVersion < 1) {
final String oldPreferencesName = "cgeo.pref";
final SharedPreferences old = CgeoApplication.getInstance().getSharedPreferences(oldPreferencesName, Context.MODE_PRIVATE);
final Editor e = sharedPrefs.edit();
e.putString(getKey(R.string.pref_temp_twitter_token_secret), old.getString(getKey(R.string.pref_temp_twitter_token_secret), null));
e.putString(getKey(R.string.pref_temp_twitter_token_public), old.getString(getKey(R.string.pref_temp_twitter_token_public), null));
e.putBoolean(getKey(R.string.pref_help_shown), old.getInt(getKey(R.string.pref_help_shown), 0) != 0);
e.putFloat(getKey(R.string.pref_anylongitude), old.getFloat(getKey(R.string.pref_anylongitude), 0));
e.putFloat(getKey(R.string.pref_anylatitude), old.getFloat(getKey(R.string.pref_anylatitude), 0));
e.putBoolean(getKey(R.string.pref_offlinemaps), 0 != old.getInt(getKey(R.string.pref_offlinemaps), 1));
e.putBoolean(getKey(R.string.pref_offlinewpmaps), 0 != old.getInt(getKey(R.string.pref_offlinewpmaps), 0));
e.putString(getKey(R.string.pref_webDeviceCode), old.getString(getKey(R.string.pref_webDeviceCode), null));
e.putString(getKey(R.string.pref_webDeviceName), old.getString(getKey(R.string.pref_webDeviceName), null));
e.putBoolean(getKey(R.string.pref_maplive), old.getInt(getKey(R.string.pref_maplive), 1) != 0);
e.putInt(getKey(R.string.pref_mapsource), old.getInt(getKey(R.string.pref_mapsource), MAP_SOURCE_DEFAULT));
e.putBoolean(getKey(R.string.pref_twitter), 0 != old.getInt(getKey(R.string.pref_twitter), 0));
e.putBoolean(getKey(R.string.pref_showaddress), 0 != old.getInt(getKey(R.string.pref_showaddress), 1));
e.putBoolean(getKey(R.string.pref_showcaptcha), old.getBoolean(getKey(R.string.pref_showcaptcha), false));
e.putBoolean(getKey(R.string.pref_maptrail), old.getInt(getKey(R.string.pref_maptrail), 1) != 0);
e.putInt(getKey(R.string.pref_lastmapzoom), old.getInt(getKey(R.string.pref_lastmapzoom), 14));
e.putBoolean(getKey(R.string.pref_livelist), 0 != old.getInt(getKey(R.string.pref_livelist), 1));
e.putBoolean(getKey(R.string.pref_units), old.getInt(getKey(R.string.pref_units), unitsMetric) == unitsMetric);
e.putBoolean(getKey(R.string.pref_skin), old.getInt(getKey(R.string.pref_skin), 0) != 0);
e.putInt(getKey(R.string.pref_lastusedlist), old.getInt(getKey(R.string.pref_lastusedlist), StoredList.STANDARD_LIST_ID));
e.putString(getKey(R.string.pref_cachetype), old.getString(getKey(R.string.pref_cachetype), CacheType.ALL.id));
e.putString(getKey(R.string.pref_twitter_token_secret), old.getString(getKey(R.string.pref_twitter_token_secret), null));
e.putString(getKey(R.string.pref_twitter_token_public), old.getString(getKey(R.string.pref_twitter_token_public), null));
e.putInt(getKey(R.string.pref_version), old.getInt(getKey(R.string.pref_version), 0));
e.putBoolean(getKey(R.string.pref_autoloaddesc), 0 != old.getInt(getKey(R.string.pref_autoloaddesc), 1));
e.putBoolean(getKey(R.string.pref_ratingwanted), old.getBoolean(getKey(R.string.pref_ratingwanted), true));
e.putBoolean(getKey(R.string.pref_friendlogswanted), old.getBoolean(getKey(R.string.pref_friendlogswanted), true));
e.putBoolean(getKey(R.string.pref_useenglish), old.getBoolean(getKey(R.string.pref_useenglish), false));
e.putBoolean(getKey(R.string.pref_usecompass), 0 != old.getInt(getKey(R.string.pref_usecompass), 1));
e.putBoolean(getKey(R.string.pref_trackautovisit), old.getBoolean(getKey(R.string.pref_trackautovisit), false));
e.putBoolean(getKey(R.string.pref_sigautoinsert), old.getBoolean(getKey(R.string.pref_sigautoinsert), false));
e.putBoolean(getKey(R.string.pref_logimages), old.getBoolean(getKey(R.string.pref_logimages), false));
e.putBoolean(getKey(R.string.pref_excludedisabled), 0 != old.getInt(getKey(R.string.pref_excludedisabled), 0));
e.putBoolean(getKey(R.string.pref_excludemine), 0 != old.getInt(getKey(R.string.pref_excludemine), 0));
e.putString(getKey(R.string.pref_mapfile), old.getString(getKey(R.string.pref_mapfile), null));
e.putString(getKey(R.string.pref_signature), old.getString(getKey(R.string.pref_signature), null));
e.putString(getKey(R.string.pref_pass_vote), old.getString(getKey(R.string.pref_pass_vote), null));
e.putString(getKey(R.string.pref_password), old.getString(getKey(R.string.pref_password), null));
e.putString(getKey(R.string.pref_username), old.getString(getKey(R.string.pref_username), null));
e.putString(getKey(R.string.pref_memberstatus), old.getString(getKey(R.string.pref_memberstatus), ""));
e.putInt(getKey(R.string.pref_coordinputformat), old.getInt(getKey(R.string.pref_coordinputformat), 0));
e.putBoolean(getKey(R.string.pref_log_offline), old.getBoolean(getKey(R.string.pref_log_offline), false));
e.putBoolean(getKey(R.string.pref_choose_list), old.getBoolean(getKey(R.string.pref_choose_list), true));
e.putBoolean(getKey(R.string.pref_loaddirectionimg), old.getBoolean(getKey(R.string.pref_loaddirectionimg), true));
e.putString(getKey(R.string.pref_gccustomdate), old.getString(getKey(R.string.pref_gccustomdate), null));
e.putInt(getKey(R.string.pref_showwaypointsthreshold), old.getInt(getKey(R.string.pref_showwaypointsthreshold), SHOW_WP_THRESHOLD_DEFAULT));
e.putString(getKey(R.string.pref_cookiestore), old.getString(getKey(R.string.pref_cookiestore), null));
e.putBoolean(getKey(R.string.pref_opendetailslastpage), old.getBoolean(getKey(R.string.pref_opendetailslastpage), false));
e.putInt(getKey(R.string.pref_lastdetailspage), old.getInt(getKey(R.string.pref_lastdetailspage), 1));
e.putInt(getKey(R.string.pref_defaultNavigationTool), old.getInt(getKey(R.string.pref_defaultNavigationTool), NavigationAppsEnum.COMPASS.id));
e.putInt(getKey(R.string.pref_defaultNavigationTool2), old.getInt(getKey(R.string.pref_defaultNavigationTool2), NavigationAppsEnum.INTERNAL_MAP.id));
e.putInt(getKey(R.string.pref_livemapstrategy), old.getInt(getKey(R.string.pref_livemapstrategy), Strategy.AUTO.id));
e.putBoolean(getKey(R.string.pref_debug), old.getBoolean(getKey(R.string.pref_debug), false));
e.putBoolean(getKey(R.string.pref_hidelivemaphint), old.getInt(getKey(R.string.pref_hidelivemaphint), 0) != 0);
e.putInt(getKey(R.string.pref_livemaphintshowcount), old.getInt(getKey(R.string.pref_livemaphintshowcount), 0));
e.putInt(getKey(R.string.pref_settingsversion), 1); // mark migrated
e.commit();
}
// changes for new settings dialog
if (oldVersion < 2) {
final Editor e = sharedPrefs.edit();
e.putBoolean(getKey(R.string.pref_units), !isUseImperialUnits());
// show waypoints threshold now as a slider
int wpThreshold = getWayPointsThreshold();
if (wpThreshold < 0) {
wpThreshold = 0;
} else if (wpThreshold > SHOW_WP_THRESHOLD_MAX) {
wpThreshold = SHOW_WP_THRESHOLD_MAX;
}
e.putInt(getKey(R.string.pref_showwaypointsthreshold), wpThreshold);
// KEY_MAP_SOURCE must be string, because it is the key for a ListPreference now
int ms = sharedPrefs.getInt(getKey(R.string.pref_mapsource), MAP_SOURCE_DEFAULT);
e.remove(getKey(R.string.pref_mapsource));
e.putString(getKey(R.string.pref_mapsource), String.valueOf(ms));
// navigation tool ids must be string, because ListPreference uses strings as keys
int dnt1 = sharedPrefs.getInt(getKey(R.string.pref_defaultNavigationTool), NavigationAppsEnum.COMPASS.id);
int dnt2 = sharedPrefs.getInt(getKey(R.string.pref_defaultNavigationTool2), NavigationAppsEnum.INTERNAL_MAP.id);
e.remove(getKey(R.string.pref_defaultNavigationTool));
e.remove(getKey(R.string.pref_defaultNavigationTool2));
e.putString(getKey(R.string.pref_defaultNavigationTool), String.valueOf(dnt1));
e.putString(getKey(R.string.pref_defaultNavigationTool2), String.valueOf(dnt2));
// defaults for gpx directories
e.putString(getKey(R.string.pref_gpxImportDir), getGpxImportDir());
e.putString(getKey(R.string.pref_gpxExportDir), getGpxExportDir());
e.putInt(getKey(R.string.pref_settingsversion), 2); // mark migrated
e.commit();
}
}
private static String getKey(final int prefKeyId) {
return CgeoApplication.getInstance().getString(prefKeyId);
}
static String getString(final int prefKeyId, final String defaultValue) {
return sharedPrefs.getString(getKey(prefKeyId), defaultValue);
}
private static int getInt(final int prefKeyId, final int defaultValue) {
return sharedPrefs.getInt(getKey(prefKeyId), defaultValue);
}
private static long getLong(final int prefKeyId, final long defaultValue) {
return sharedPrefs.getLong(getKey(prefKeyId), defaultValue);
}
private static boolean getBoolean(final int prefKeyId, final boolean defaultValue) {
return sharedPrefs.getBoolean(getKey(prefKeyId), defaultValue);
}
private static float getFloat(final int prefKeyId, final float defaultValue) {
return sharedPrefs.getFloat(getKey(prefKeyId), defaultValue);
}
static boolean putString(final int prefKeyId, final String value) {
final SharedPreferences.Editor edit = sharedPrefs.edit();
edit.putString(getKey(prefKeyId), value);
return edit.commit();
}
private static boolean putBoolean(final int prefKeyId, final boolean value) {
final SharedPreferences.Editor edit = sharedPrefs.edit();
edit.putBoolean(getKey(prefKeyId), value);
return edit.commit();
}
private static boolean putInt(final int prefKeyId, final int value) {
final SharedPreferences.Editor edit = sharedPrefs.edit();
edit.putInt(getKey(prefKeyId), value);
return edit.commit();
}
private static boolean putLong(final int prefKeyId, final long value) {
final SharedPreferences.Editor edit = sharedPrefs.edit();
edit.putLong(getKey(prefKeyId), value);
return edit.commit();
}
private static boolean putFloat(final int prefKeyId, final float value) {
final SharedPreferences.Editor edit = sharedPrefs.edit();
edit.putFloat(getKey(prefKeyId), value);
return edit.commit();
}
private static boolean remove(final int prefKeyId) {
final SharedPreferences.Editor edit = sharedPrefs.edit();
edit.remove(getKey(prefKeyId));
return edit.commit();
}
private static boolean contains(final int prefKeyId) {
return sharedPrefs.contains(getKey(prefKeyId));
}
public static void setLanguage(boolean useEnglish) {
final Configuration config = new Configuration();
config.locale = useEnglish ? Locale.ENGLISH : Locale.getDefault();
final Resources resources = CgeoApplication.getInstance().getResources();
resources.updateConfiguration(config, resources.getDisplayMetrics());
}
public static boolean isLogin() {
final String preUsername = getString(R.string.pref_username, null);
final String prePassword = getString(R.string.pref_password, null);
return !StringUtils.isBlank(preUsername) && !StringUtils.isBlank(prePassword);
}
/**
* Get login and password information.
*
* @return a pair either with (login, password) or (empty, empty) if no valid information is stored
*/
public static ImmutablePair<String, String> getGcLogin() {
final String username = getString(R.string.pref_username, null);
final String password = getString(R.string.pref_password, null);
if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
return new ImmutablePair<String, String>(StringUtils.EMPTY, StringUtils.EMPTY);
}
return new ImmutablePair<String, String>(username, password);
}
public static String getUsername() {
return getString(R.string.pref_username, null);
}
public static boolean isGCConnectorActive() {
return getBoolean(R.string.pref_connectorGCActive, true);
}
public static boolean isPremiumMember() {
// Basic Member, Premium Member, ???
return GCConstants.MEMBER_STATUS_PM.equalsIgnoreCase(Settings.getMemberStatus());
}
public static String getMemberStatus() {
return getString(R.string.pref_memberstatus, "");
}
public static boolean setMemberStatus(final String memberStatus) {
if (StringUtils.isBlank(memberStatus)) {
return remove(R.string.pref_memberstatus);
}
return putString(R.string.pref_memberstatus, memberStatus);
}
public static ImmutablePair<String, String> getTokenPair(final int tokenPublicPrefKey, final int tokenSecretPrefKey) {
return new ImmutablePair<String, String>(getString(tokenPublicPrefKey, null), getString(tokenSecretPrefKey, null));
}
public static void setTokens(final int tokenPublicPrefKey, @Nullable final String tokenPublic, final int tokenSecretPrefKey, @Nullable final String tokenSecret) {
if (tokenPublic == null) {
remove(tokenPublicPrefKey);
} else {
putString(tokenPublicPrefKey, tokenPublic);
}
if (tokenSecret == null) {
remove(tokenSecretPrefKey);
} else {
putString(tokenSecretPrefKey, tokenSecret);
}
}
public static boolean isOCConnectorActive(int isActivePrefKeyId) {
return getBoolean(isActivePrefKeyId, false);
}
public static boolean hasOCAuthorization(int tokenPublicPrefKeyId, int tokenSecretPrefKeyId) {
return StringUtils.isNotBlank(getString(tokenPublicPrefKeyId, ""))
&& StringUtils.isNotBlank(getString(tokenSecretPrefKeyId, ""));
}
public static boolean isGCvoteLogin() {
final String preUsername = getString(R.string.pref_username, null);
final String prePassword = getString(R.string.pref_pass_vote, null);
return !StringUtils.isBlank(preUsername) && !StringUtils.isBlank(prePassword);
}
public static ImmutablePair<String, String> getGCvoteLogin() {
final String username = getString(R.string.pref_username, null);
final String password = getString(R.string.pref_pass_vote, null);
if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
return null;
}
return new ImmutablePair<String, String>(username, password);
}
public static String getSignature() {
return getString(R.string.pref_signature, null);
}
public static boolean setCookieStore(final String cookies) {
if (StringUtils.isBlank(cookies)) {
// erase cookies
return remove(R.string.pref_cookiestore);
}
// save cookies
return putString(R.string.pref_cookiestore, cookies);
}
public static String getCookieStore() {
return getString(R.string.pref_cookiestore, null);
}
/**
* @param cacheType
* The cache type used for future filtering
*/
public static void setCacheType(final CacheType cacheType) {
if (cacheType == null) {
remove(R.string.pref_cachetype);
} else {
putString(R.string.pref_cachetype, cacheType.id);
}
}
public static int getLastList() {
return getInt(R.string.pref_lastusedlist, StoredList.STANDARD_LIST_ID);
}
public static void saveLastList(final int listId) {
putInt(R.string.pref_lastusedlist, listId);
}
public static void setWebNameCode(final String name, final String code) {
putString(R.string.pref_webDeviceName, name);
putString(R.string.pref_webDeviceCode, code);
}
public static MapProvider getMapProvider() {
return getMapSource().getMapProvider();
}
public static String getMapFile() {
return getString(R.string.pref_mapfile, null);
}
public static boolean setMapFile(final String mapFile) {
boolean result = putString(R.string.pref_mapfile, mapFile);
if (mapFile != null) {
setMapFileDirectory(new File(mapFile).getParent());
}
return result;
}
public static String getMapFileDirectory() {
final String mapDir = getString(R.string.pref_mapDirectory, null);
if (mapDir != null) {
return mapDir;
}
final String mapFile = getMapFile();
if (mapFile != null) {
return new File(mapFile).getParent();
}
return null;
}
public static boolean setMapFileDirectory(final String mapFileDirectory) {
boolean result = putString(R.string.pref_mapDirectory, mapFileDirectory);
MapsforgeMapProvider.getInstance().updateOfflineMaps();
return result;
}
public static boolean isValidMapFile() {
return isValidMapFile(getMapFile());
}
public static boolean isValidMapFile(final String mapFileIn) {
return MapsforgeMapProvider.isValidMapFile(mapFileIn);
}
public static boolean isScaleMapsforgeText() {
return getBoolean(R.string.pref_mapsforge_scale_text, true);
}
public static CoordInputFormatEnum getCoordInputFormat() {
return CoordInputFormatEnum.fromInt(getInt(R.string.pref_coordinputformat, 0));
}
public static void setCoordInputFormat(final CoordInputFormatEnum format) {
putInt(R.string.pref_coordinputformat, format.ordinal());
}
static void setLogOffline(final boolean offline) {
putBoolean(R.string.pref_log_offline, offline);
}
public static boolean getLogOffline() {
return getBoolean(R.string.pref_log_offline, false);
}
public static boolean getChooseList() {
return getBoolean(R.string.pref_choose_list, false);
}
public static boolean getLoadDirImg() {
return !isPremiumMember() && getBoolean(R.string.pref_loaddirectionimg, true);
}
public static void setGcCustomDate(final String format) {
putString(R.string.pref_gccustomdate, format);
}
/**
* @return User selected date format on GC.com
* @see Login#GC_CUSTOM_DATE_FORMATS
*/
public static String getGcCustomDate() {
return getString(R.string.pref_gccustomdate, null);
}
public static boolean isExcludeMyCaches() {
return getBoolean(R.string.pref_excludemine, false);
}
public static void setUseEnglish(final boolean english) {
putBoolean(R.string.pref_useenglish, english);
setLanguage(english);
}
public static boolean isUseEnglish() {
return getBoolean(R.string.pref_useenglish, false);
}
public static boolean isShowAddress() {
return getBoolean(R.string.pref_showaddress, true);
}
public static boolean isShowCaptcha() {
return !isPremiumMember() && getBoolean(R.string.pref_showcaptcha, false);
}
public static boolean isExcludeDisabledCaches() {
return getBoolean(R.string.pref_excludedisabled, false);
}
public static boolean isStoreOfflineMaps() {
return getBoolean(R.string.pref_offlinemaps, true);
}
public static boolean isStoreOfflineWpMaps() {
return getBoolean(R.string.pref_offlinewpmaps, false);
}
public static boolean isStoreLogImages() {
return getBoolean(R.string.pref_logimages, false);
}
public static boolean isAutoLoadDescription() {
return getBoolean(R.string.pref_autoloaddesc, true);
}
public static boolean isRatingWanted() {
return getBoolean(R.string.pref_ratingwanted, true);
}
public static boolean isFriendLogsWanted() {
if (!isLogin()) {
// don't show a friends log if the user is anonymous
return false;
}
return getBoolean(R.string.pref_friendlogswanted, true);
}
public static boolean isLiveList() {
return getBoolean(R.string.pref_livelist, true);
}
public static boolean isTrackableAutoVisit() {
return getBoolean(R.string.pref_trackautovisit, false);
}
public static boolean isAutoInsertSignature() {
return getBoolean(R.string.pref_sigautoinsert, false);
}
public static boolean isUseImperialUnits() {
return getBoolean(R.string.pref_units, getImperialUnitsDefault());
}
static boolean getImperialUnitsDefault() {
final String countryCode = Locale.getDefault().getCountry();
return "US".equals(countryCode) // USA
|| "LR".equals(countryCode) // Liberia
|| "MM".equals(countryCode); // Burma
}
public static boolean isLiveMap() {
return getBoolean(R.string.pref_maplive, true);
}
public static void setLiveMap(final boolean live) {
putBoolean(R.string.pref_maplive, live);
}
public static boolean isMapTrail() {
return getBoolean(R.string.pref_maptrail, true);
}
public static void setMapTrail(final boolean showTrail) {
putBoolean(R.string.pref_maptrail, showTrail);
}
public static int getMapZoom() {
return getInt(R.string.pref_lastmapzoom, 14);
}
public static void setMapZoom(final int mapZoomLevel) {
putInt(R.string.pref_lastmapzoom, mapZoomLevel);
}
public static GeoPointImpl getMapCenter() {
return getMapProvider().getMapItemFactory()
.getGeoPointBase(new Geopoint(getInt(R.string.pref_lastmaplat, 0) / 1e6,
getInt(R.string.pref_lastmaplon, 0) / 1e6));
}
public static void setMapCenter(final GeoPointImpl mapViewCenter) {
putInt(R.string.pref_lastmaplat, mapViewCenter.getLatitudeE6());
putInt(R.string.pref_lastmaplon, mapViewCenter.getLongitudeE6());
}
public static MapSource getMapSource() {
if (mapSource != null) {
return mapSource;
}
final int id = getConvertedMapId();
mapSource = MapProviderFactory.getMapSource(id);
if (mapSource != null) {
// don't use offline maps if the map file is not valid
if ((!(mapSource instanceof OfflineMapSource)) || (isValidMapFile())) {
return mapSource;
}
}
// fallback to first available map
return MapProviderFactory.getDefaultSource();
}
private final static int GOOGLEMAP_BASEID = 30;
private final static int MAP = 1;
private final static int SATELLITE = 2;
private final static int MFMAP_BASEID = 40;
private final static int MAPNIK = 1;
private final static int CYCLEMAP = 3;
private final static int OFFLINE = 4;
/**
* convert old preference ids for maps (based on constant values) into new hash based ids
*
* @return
*/
private static int getConvertedMapId() {
// what the heck is happening here?? hashCodes of Strings?
// why not strings?
final int id = Integer.parseInt(getString(R.string.pref_mapsource,
String.valueOf(MAP_SOURCE_DEFAULT)));
switch (id) {
case GOOGLEMAP_BASEID + MAP:
return GoogleMapProvider.GOOGLE_MAP_ID.hashCode();
case GOOGLEMAP_BASEID + SATELLITE:
return GoogleMapProvider.GOOGLE_SATELLITE_ID.hashCode();
case MFMAP_BASEID + MAPNIK:
return MapsforgeMapProvider.MAPSFORGE_MAPNIK_ID.hashCode();
case MFMAP_BASEID + CYCLEMAP:
return MapsforgeMapProvider.MAPSFORGE_CYCLEMAP_ID.hashCode();
case MFMAP_BASEID + OFFLINE: {
final String mapFile = Settings.getMapFile();
if (StringUtils.isNotEmpty(mapFile)) {
return mapFile.hashCode();
}
break;
}
default:
break;
}
return id;
}
public static void setMapSource(final MapSource newMapSource) {
putString(R.string.pref_mapsource, String.valueOf(newMapSource.getNumericalId()));
if (newMapSource instanceof OfflineMapSource) {
setMapFile(((OfflineMapSource) newMapSource).getFileName());
}
// cache the value
mapSource = newMapSource;
}
public static void setAnyCoordinates(final Geopoint coords) {
if (null != coords) {
putFloat(R.string.pref_anylatitude, (float) coords.getLatitude());
putFloat(R.string.pref_anylongitude, (float) coords.getLongitude());
} else {
remove(R.string.pref_anylatitude);
remove(R.string.pref_anylongitude);
}
}
public static Geopoint getAnyCoordinates() {
if (contains(R.string.pref_anylatitude) && contains(R.string.pref_anylongitude)) {
float lat = getFloat(R.string.pref_anylatitude, 0);
float lon = getFloat(R.string.pref_anylongitude, 0);
return new Geopoint(lat, lon);
}
return null;
}
public static boolean isUseCompass() {
return getBoolean(R.string.pref_usecompass, true);
}
public static void setUseCompass(final boolean useCompass) {
putBoolean(R.string.pref_usecompass, useCompass);
}
public static boolean isLightSkin() {
return getBoolean(R.string.pref_skin, false);
}
public static String getKeyConsumerPublic() {
return keyConsumerPublic;
}
public static String getKeyConsumerSecret() {
return keyConsumerSecret;
}
public static String getWebDeviceCode() {
return getString(R.string.pref_webDeviceCode, null);
}
public static String getWebDeviceName() {
return getString(R.string.pref_webDeviceName, android.os.Build.MODEL);
}
/**
* @return The cache type used for filtering or ALL if no filter is active.
* Returns never null
*/
public static CacheType getCacheType() {
return CacheType.getById(getString(R.string.pref_cachetype, CacheType.ALL.id));
}
/**
* The Threshold for the showing of child waypoints
*/
public static int getWayPointsThreshold() {
return getInt(R.string.pref_showwaypointsthreshold, SHOW_WP_THRESHOLD_DEFAULT);
}
public static void setShowWaypointsThreshold(final int threshold) {
putInt(R.string.pref_showwaypointsthreshold, threshold);
}
public static boolean isUseTwitter() {
return getBoolean(R.string.pref_twitter, false);
}
public static void setUseTwitter(final boolean useTwitter) {
putBoolean(R.string.pref_twitter, useTwitter);
}
public static boolean isTwitterLoginValid() {
return !StringUtils.isBlank(getTokenPublic())
&& !StringUtils.isBlank(getTokenSecret());
}
public static String getTokenPublic() {
return getString(R.string.pref_twitter_token_public, null);
}
public static String getTokenSecret() {
return getString(R.string.pref_twitter_token_secret, null);
}
public static boolean hasTwitterAuthorization() {
return StringUtils.isNotBlank(getTokenPublic())
&& StringUtils.isNotBlank(getTokenSecret());
}
public static void setTwitterTokens(@Nullable final String tokenPublic,
@Nullable final String tokenSecret, boolean enableTwitter) {
putString(R.string.pref_twitter_token_public, tokenPublic);
putString(R.string.pref_twitter_token_secret, tokenSecret);
if (tokenPublic != null) {
remove(R.string.pref_temp_twitter_token_public);
remove(R.string.pref_temp_twitter_token_secret);
}
setUseTwitter(enableTwitter);
}
public static void setTwitterTempTokens(@Nullable final String tokenPublic,
@Nullable final String tokenSecret) {
putString(R.string.pref_temp_twitter_token_public, tokenPublic);
putString(R.string.pref_temp_twitter_token_secret, tokenSecret);
}
public static ImmutablePair<String, String> getTempToken() {
String tokenPublic = getString(R.string.pref_temp_twitter_token_public, null);
String tokenSecret = getString(R.string.pref_temp_twitter_token_secret, null);
return new ImmutablePair<String, String>(tokenPublic, tokenSecret);
}
public static int getVersion() {
return getInt(R.string.pref_version, 0);
}
public static void setVersion(final int version) {
putInt(R.string.pref_version, version);
}
public static boolean isOpenLastDetailsPage() {
return getBoolean(R.string.pref_opendetailslastpage, false);
}
public static int getLastDetailsPage() {
return getInt(R.string.pref_lastdetailspage, 1);
}
public static void setLastDetailsPage(final int index) {
putInt(R.string.pref_lastdetailspage, index);
}
public static int getDefaultNavigationTool() {
return Integer.parseInt(getString(
R.string.pref_defaultNavigationTool,
String.valueOf(NavigationAppsEnum.COMPASS.id)));
}
public static void setDefaultNavigationTool(final int defaultNavigationTool) {
putString(R.string.pref_defaultNavigationTool,
String.valueOf(defaultNavigationTool));
}
public static int getDefaultNavigationTool2() {
return Integer.parseInt(getString(
R.string.pref_defaultNavigationTool2,
String.valueOf(NavigationAppsEnum.INTERNAL_MAP.id)));
}
public static void setDefaultNavigationTool2(final int defaultNavigationTool) {
putString(R.string.pref_defaultNavigationTool2,
String.valueOf(defaultNavigationTool));
}
public static Strategy getLiveMapStrategy() {
return Strategy.getById(getInt(R.string.pref_livemapstrategy, Strategy.AUTO.id));
}
public static void setLiveMapStrategy(final Strategy strategy) {
putInt(R.string.pref_livemapstrategy, strategy.id);
}
public static boolean isDebug() {
return Log.isDebug();
}
public static boolean getHideLiveMapHint() {
return getBoolean(R.string.pref_hidelivemaphint, false);
}
public static void setHideLiveHint(final boolean hide) {
putBoolean(R.string.pref_hidelivemaphint, hide);
}
public static int getLiveMapHintShowCount() {
return getInt(R.string.pref_livemaphintshowcount, 0);
}
public static void setLiveMapHintShowCount(final int showCount) {
putInt(R.string.pref_livemaphintshowcount, showCount);
}
public static boolean isDbOnSDCard() {
return getBoolean(R.string.pref_dbonsdcard, false);
}
public static void setDbOnSDCard(final boolean dbOnSDCard) {
putBoolean(R.string.pref_dbonsdcard, dbOnSDCard);
}
public static String getGpxExportDir() {
return getString(R.string.pref_gpxExportDir,
Environment.getExternalStorageDirectory().getPath() + "/gpx");
}
public static String getGpxImportDir() {
return getString(R.string.pref_gpxImportDir,
Environment.getExternalStorageDirectory().getPath() + "/gpx");
}
public static boolean getShareAfterExport() {
return getBoolean(R.string.pref_shareafterexport, true);
}
public static void setShareAfterExport(final boolean shareAfterExport) {
putBoolean(R.string.pref_shareafterexport, shareAfterExport);
}
public static int getTrackableAction() {
return getInt(R.string.pref_trackableaction, LogType.RETRIEVED_IT.id);
}
public static void setTrackableAction(final int trackableAction) {
putInt(R.string.pref_trackableaction, trackableAction);
}
public static String getCustomRenderThemeBaseFolder() {
return getString(R.string.pref_renderthemepath, "");
}
public static String getCustomRenderThemeFilePath() {
return getString(R.string.pref_renderthemefile, "");
}
public static void setCustomRenderThemeFile(final String customRenderThemeFile) {
putString(R.string.pref_renderthemefile, customRenderThemeFile);
}
public static File[] getMapThemeFiles() {
File directory = new File(Settings.getCustomRenderThemeBaseFolder());
List<File> result = new ArrayList<File>();
FileUtils.listDir(result, directory, new ExtensionsBasedFileSelector(new String[] { "xml" }), null);
return result.toArray(new File[result.size()]);
}
private static class ExtensionsBasedFileSelector extends FileSelector {
private final String[] extensions;
public ExtensionsBasedFileSelector(String[] extensions) {
this.extensions = extensions;
}
@Override
public boolean isSelected(File file) {
String filename = file.getName();
for (String ext : extensions) {
if (StringUtils.endsWithIgnoreCase(filename, ext)) {
return true;
}
}
return false;
}
@Override
public boolean shouldEnd() {
return false;
}
}
public static boolean getPlainLogs() {
return getBoolean(R.string.pref_plainLogs, false);
}
public static boolean getUseNativeUa() {
return getBoolean(R.string.pref_nativeUa, false);
}
public static String getCacheTwitterMessage() {
// TODO make customizable from UI
return "I found [NAME] ([URL])";
}
public static String getTrackableTwitterMessage() {
// TODO make customizable from UI
return "I touched [NAME] ([URL])!";
}
public static int getLogImageScale() {
return getInt(R.string.pref_logImageScale, -1);
}
public static void setLogImageScale(final int scale) {
putInt(R.string.pref_logImageScale, scale);
}
// Only for tests!
static void setExcludeDisabledCaches(final boolean exclude) {
putBoolean(R.string.pref_excludedisabled, exclude);
}
public static void setExcludeMine(final boolean exclude) {
putBoolean(R.string.pref_excludemine, exclude);
}
static boolean setLogin(final String username, final String password) {
if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
// erase username and password
boolean a = remove(R.string.pref_username);
boolean b = remove(R.string.pref_password);
return a && b;
}
// save username and password
boolean a = putString(R.string.pref_username, username);
boolean b = putString(R.string.pref_password, password);
return a && b;
}
static void setStoreOfflineMaps(final boolean offlineMaps) {
putBoolean(R.string.pref_offlinemaps, offlineMaps);
}
static void setStoreOfflineWpMaps(final boolean offlineWpMaps) {
putBoolean(R.string.pref_offlinewpmaps, offlineWpMaps);
}
static void setUseImperialUnits(final boolean imperial) {
putBoolean(R.string.pref_units, imperial);
}
public static long getFieldnoteExportDate() {
return getLong(R.string.pref_fieldnoteExportDate, 0);
}
public static void setFieldnoteExportDate(final long date) {
putLong(R.string.pref_fieldnoteExportDate, date);
}
public static boolean isUseNavigationApp(NavigationAppsEnum navApp) {
return getBoolean(navApp.preferenceKey, true);
}
}
|
package cgeo.geocaching.storage;
import cgeo.geocaching.CgeoApplication;
import cgeo.geocaching.Intents;
import cgeo.geocaching.R;
import cgeo.geocaching.SearchResult;
import cgeo.geocaching.connector.IConnector;
import cgeo.geocaching.connector.gc.Tile;
import cgeo.geocaching.enumerations.CacheSize;
import cgeo.geocaching.enumerations.CacheType;
import cgeo.geocaching.enumerations.LoadFlags;
import cgeo.geocaching.enumerations.LoadFlags.LoadFlag;
import cgeo.geocaching.enumerations.LoadFlags.RemoveFlag;
import cgeo.geocaching.enumerations.LoadFlags.SaveFlag;
import cgeo.geocaching.enumerations.WaypointType;
import cgeo.geocaching.list.AbstractList;
import cgeo.geocaching.list.PseudoList;
import cgeo.geocaching.list.StoredList;
import cgeo.geocaching.location.Geopoint;
import cgeo.geocaching.location.Viewport;
import cgeo.geocaching.log.LogEntry;
import cgeo.geocaching.log.LogType;
import cgeo.geocaching.models.Destination;
import cgeo.geocaching.models.Geocache;
import cgeo.geocaching.models.Image;
import cgeo.geocaching.models.Trackable;
import cgeo.geocaching.models.Waypoint;
import cgeo.geocaching.search.SearchSuggestionCursor;
import cgeo.geocaching.settings.Settings;
import cgeo.geocaching.ui.dialog.Dialogs;
import cgeo.geocaching.utils.AndroidRxUtils;
import cgeo.geocaching.utils.FileUtils;
import cgeo.geocaching.utils.Log;
import cgeo.geocaching.utils.Version;
import cgeo.geocaching.utils.functions.Func1;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.MatrixCursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteDoneException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import io.reactivex.Observable;
import io.reactivex.Single;
import io.reactivex.SingleEmitter;
import io.reactivex.SingleOnSubscribe;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
public class DataStore {
private DataStore() {
// utility class
}
public enum StorageLocation {
HEAP,
CACHE,
DATABASE,
}
private static final Func1<Cursor, String> GET_STRING_0 = new Func1<Cursor, String>() {
@Override
public String call(final Cursor cursor) {
return cursor.getString(0);
}
};
private static final Func1<Cursor, Integer> GET_INTEGER_0 = new Func1<Cursor, Integer>() {
@Override
public Integer call(final Cursor cursor) {
return cursor.getInt(0);
}
};
// Columns and indices for the cache data
private static final String QUERY_CACHE_DATA =
"SELECT " +
"cg_caches.updated," +
"cg_caches.reason," +
"cg_caches.detailed," +
"cg_caches.detailedupdate," +
"cg_caches.visiteddate," +
"cg_caches.geocode," +
"cg_caches.cacheid," +
"cg_caches.guid," +
"cg_caches.type," +
"cg_caches.name," +
"cg_caches.owner," +
"cg_caches.owner_real," +
"cg_caches.hidden," +
"cg_caches.hint," +
"cg_caches.size," +
"cg_caches.difficulty," +
"cg_caches.direction," +
"cg_caches.distance," +
"cg_caches.terrain," +
"cg_caches.location," +
"cg_caches.personal_note," +
"cg_caches.shortdesc," +
"cg_caches.favourite_cnt," +
"cg_caches.rating," +
"cg_caches.votes," +
"cg_caches.myvote," +
"cg_caches.disabled," +
"cg_caches.archived," +
"cg_caches.members," +
"cg_caches.found," +
"cg_caches.favourite," +
"cg_caches.inventoryunknown," +
"cg_caches.onWatchlist," +
"cg_caches.reliable_latlon," +
"cg_caches.coordsChanged," +
"cg_caches.latitude," +
"cg_caches.longitude," +
"cg_caches.finalDefined," +
"cg_caches._id," +
"cg_caches.inventorycoins," +
"cg_caches.inventorytags," +
"cg_caches.logPasswordRequired," +
"cg_caches.watchlistCount";
/** The list of fields needed for mapping. */
private static final String[] WAYPOINT_COLUMNS = { "_id", "geocode", "updated", "type", "prefix", "lookup", "name", "latitude", "longitude", "note", "own", "visited" };
/** Number of days (as ms) after temporarily saved caches are deleted */
private static final long DAYS_AFTER_CACHE_IS_DELETED = 3 * 24 * 60 * 60 * 1000;
/**
* holds the column indexes of the cache table to avoid lookups
*/
private static final CacheCache cacheCache = new CacheCache();
private static volatile SQLiteDatabase database = null;
private static final int dbVersion = 71;
public static final int customListIdOffset = 10;
@NonNull private static final String dbName = "data";
@NonNull private static final String dbTableCaches = "cg_caches";
@NonNull private static final String dbTableLists = "cg_lists";
@NonNull private static final String dbTableCachesLists = "cg_caches_lists";
@NonNull private static final String dbTableAttributes = "cg_attributes";
@NonNull private static final String dbTableWaypoints = "cg_waypoints";
@NonNull private static final String dbTableSpoilers = "cg_spoilers";
@NonNull private static final String dbTableLogs = "cg_logs";
@NonNull private static final String dbTableLogCount = "cg_logCount";
@NonNull private static final String dbTableLogImages = "cg_logImages";
@NonNull private static final String dbTableLogsOffline = "cg_logs_offline";
@NonNull private static final String dbTableTrackables = "cg_trackables";
@NonNull private static final String dbTableSearchDestinationHistory = "cg_search_destination_history";
@NonNull private static final String dbCreateCaches = ""
+ "CREATE TABLE " + dbTableCaches + " ("
+ "_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "updated LONG NOT NULL, "
+ "detailed INTEGER NOT NULL DEFAULT 0, "
+ "detailedupdate LONG, "
+ "visiteddate LONG, "
+ "geocode TEXT UNIQUE NOT NULL, "
+ "reason INTEGER NOT NULL DEFAULT 0, " // cached, favorite...
+ "cacheid TEXT, "
+ "guid TEXT, "
+ "type TEXT, "
+ "name TEXT, "
+ "owner TEXT, "
+ "owner_real TEXT, "
+ "hidden LONG, "
+ "hint TEXT, "
+ "size TEXT, "
+ "difficulty FLOAT, "
+ "terrain FLOAT, "
+ "location TEXT, "
+ "direction DOUBLE, "
+ "distance DOUBLE, "
+ "latitude DOUBLE, "
+ "longitude DOUBLE, "
+ "reliable_latlon INTEGER, "
+ "personal_note TEXT, "
+ "shortdesc TEXT, "
+ "description TEXT, "
+ "favourite_cnt INTEGER, "
+ "rating FLOAT, "
+ "votes INTEGER, "
+ "myvote FLOAT, "
+ "disabled INTEGER NOT NULL DEFAULT 0, "
+ "archived INTEGER NOT NULL DEFAULT 0, "
+ "members INTEGER NOT NULL DEFAULT 0, "
+ "found INTEGER NOT NULL DEFAULT 0, "
+ "favourite INTEGER NOT NULL DEFAULT 0, "
+ "inventorycoins INTEGER DEFAULT 0, "
+ "inventorytags INTEGER DEFAULT 0, "
+ "inventoryunknown INTEGER DEFAULT 0, "
+ "onWatchlist INTEGER DEFAULT 0, "
+ "coordsChanged INTEGER DEFAULT 0, "
+ "finalDefined INTEGER DEFAULT 0, "
+ "logPasswordRequired INTEGER DEFAULT 0,"
+ "watchlistCount INTEGER DEFAULT -1"
+ "); ";
private static final String dbCreateLists = ""
+ "CREATE TABLE " + dbTableLists + " ("
+ "_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "title TEXT NOT NULL, "
+ "updated LONG NOT NULL"
+ "); ";
private static final String dbCreateCachesLists = ""
+ "CREATE TABLE " + dbTableCachesLists + " ("
+ "list_id INTEGER NOT NULL, "
+ "geocode TEXT NOT NULL, "
+ "PRIMARY KEY (list_id, geocode)"
+ "); ";
private static final String dbCreateAttributes = ""
+ "CREATE TABLE " + dbTableAttributes + " ("
+ "_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "geocode TEXT NOT NULL, "
+ "updated LONG NOT NULL, " // date of save
+ "attribute TEXT "
+ "); ";
private static final String dbCreateWaypoints = ""
+ "CREATE TABLE " + dbTableWaypoints + " ("
+ "_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "geocode TEXT NOT NULL, "
+ "updated LONG NOT NULL, " // date of save
+ "type TEXT NOT NULL DEFAULT 'waypoint', "
+ "prefix TEXT, "
+ "lookup TEXT, "
+ "name TEXT, "
+ "latitude DOUBLE, "
+ "longitude DOUBLE, "
+ "note TEXT, "
+ "own INTEGER DEFAULT 0, "
+ "visited INTEGER DEFAULT 0"
+ "); ";
private static final String dbCreateSpoilers = ""
+ "CREATE TABLE " + dbTableSpoilers + " ("
+ "_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "geocode TEXT NOT NULL, "
+ "updated LONG NOT NULL, " // date of save
+ "url TEXT, "
+ "title TEXT, "
+ "description TEXT "
+ "); ";
private static final String dbCreateLogs = ""
+ "CREATE TABLE " + dbTableLogs + " ("
+ "_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "geocode TEXT NOT NULL, "
+ "updated LONG NOT NULL, " // date of save
+ "type INTEGER NOT NULL DEFAULT 4, "
+ "author TEXT, "
+ "log TEXT, "
+ "date LONG, "
+ "found INTEGER NOT NULL DEFAULT 0, "
+ "friend INTEGER "
+ "); ";
private static final String dbCreateLogCount = ""
+ "CREATE TABLE " + dbTableLogCount + " ("
+ "_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "geocode TEXT NOT NULL, "
+ "updated LONG NOT NULL, " // date of save
+ "type INTEGER NOT NULL DEFAULT 4, "
+ "count INTEGER NOT NULL DEFAULT 0 "
+ "); ";
private static final String dbCreateLogImages = ""
+ "CREATE TABLE " + dbTableLogImages + " ("
+ "_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "log_id INTEGER NOT NULL, "
+ "title TEXT NOT NULL, "
+ "url TEXT NOT NULL, "
+ "description TEXT "
+ "); ";
private static final String dbCreateLogsOffline = ""
+ "CREATE TABLE " + dbTableLogsOffline + " ("
+ "_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "geocode TEXT NOT NULL, "
+ "updated LONG NOT NULL, " // date of save
+ "type INTEGER NOT NULL DEFAULT 4, "
+ "log TEXT, "
+ "date LONG "
+ "); ";
private static final String dbCreateTrackables = ""
+ "CREATE TABLE " + dbTableTrackables + " ("
+ "_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "updated LONG NOT NULL, " // date of save
+ "tbcode TEXT NOT NULL, "
+ "guid TEXT, "
+ "title TEXT, "
+ "owner TEXT, "
+ "released LONG, "
+ "goal TEXT, "
+ "description TEXT, "
+ "geocode TEXT "
+ "); ";
private static final String dbCreateSearchDestinationHistory = ""
+ "CREATE TABLE " + dbTableSearchDestinationHistory + " ("
+ "_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "date LONG NOT NULL, "
+ "latitude DOUBLE, "
+ "longitude DOUBLE "
+ "); ";
private static final Single<Integer> allCachesCountObservable = Single.create(new SingleOnSubscribe<Integer>() {
@Override
public void subscribe(final SingleEmitter<Integer> emitter) throws Exception {
if (isInitialized()) {
emitter.onSuccess(getAllCachesCount());
}
}
}).timeout(500, TimeUnit.MILLISECONDS).retry(10).subscribeOn(Schedulers.io());
private static boolean newlyCreatedDatabase = false;
private static boolean databaseCleaned = false;
public static void init() {
if (database != null) {
return;
}
synchronized (DataStore.class) {
if (database != null) {
return;
}
final DbHelper dbHelper = new DbHelper(new DBContext(CgeoApplication.getInstance()));
try {
database = dbHelper.getWritableDatabase();
} catch (final Exception e) {
Log.e("DataStore.init: unable to open database for R/W", e);
recreateDatabase(dbHelper);
}
}
}
/**
* Attempt to recreate the database if opening has failed
*
* @param dbHelper dbHelper to use to reopen the database
*/
private static void recreateDatabase(final DbHelper dbHelper) {
final File dbPath = databasePath();
final File corruptedPath = new File(LocalStorage.getStorage(), dbPath.getName() + ".corrupted");
if (LocalStorage.copy(dbPath, corruptedPath)) {
Log.i("DataStore.init: renamed " + dbPath + " into " + corruptedPath);
} else {
Log.e("DataStore.init: unable to rename corrupted database");
}
try {
database = dbHelper.getWritableDatabase();
} catch (final Exception f) {
Log.e("DataStore.init: unable to recreate database and open it for R/W", f);
}
}
public static synchronized void closeDb() {
if (database == null) {
return;
}
cacheCache.removeAllFromCache();
PreparedStatement.clearPreparedStatements();
database.close();
database = null;
}
@NonNull
public static File getBackupFileInternal() {
return new File(LocalStorage.getStorage(), "cgeo.sqlite");
}
public static String backupDatabaseInternal() {
if (!LocalStorage.isExternalStorageAvailable()) {
Log.w("Database wasn't backed up: no external memory");
return null;
}
final File target = getBackupFileInternal();
closeDb();
final boolean backupDone = LocalStorage.copy(databasePath(), target);
init();
if (!backupDone) {
Log.e("Database could not be copied to " + target);
return null;
}
Log.i("Database was copied to " + target);
return target.getPath();
}
/**
* Move the database to/from external cgdata in a new thread,
* showing a progress window
*
*/
public static void moveDatabase(final Activity fromActivity) {
final ProgressDialog dialog = ProgressDialog.show(fromActivity, fromActivity.getString(R.string.init_dbmove_dbmove), fromActivity.getString(R.string.init_dbmove_running), true, false);
AndroidRxUtils.bindActivity(fromActivity, Observable.defer(new Callable<Observable<Boolean>>() {
@Override
public Observable<Boolean> call() {
if (!LocalStorage.isExternalStorageAvailable()) {
Log.w("Database was not moved: external memory not available");
return Observable.just(false);
}
closeDb();
final File source = databasePath();
final File target = databaseAlternatePath();
if (!LocalStorage.copy(source, target)) {
Log.e("Database could not be moved to " + target);
init();
return Observable.just(false);
}
if (!FileUtils.delete(source)) {
Log.e("Original database could not be deleted during move");
}
Settings.setDbOnSDCard(!Settings.isDbOnSDCard());
Log.i("Database was moved to " + target);
init();
return Observable.just(true);
}
}).subscribeOn(Schedulers.io())).subscribe(new Consumer<Boolean>() {
@Override
public void accept(final Boolean success) {
dialog.dismiss();
final String message = success ? fromActivity.getString(R.string.init_dbmove_success) : fromActivity.getString(R.string.init_dbmove_failed);
Dialogs.message(fromActivity, R.string.init_dbmove_dbmove, message);
}
});
}
@NonNull
private static File databasePath(final boolean internal) {
return new File(internal ? LocalStorage.getInternalDbDirectory() : LocalStorage.getExternalDbDirectory(), dbName);
}
@NonNull
private static File databasePath() {
return databasePath(!Settings.isDbOnSDCard());
}
@NonNull
private static File databaseAlternatePath() {
return databasePath(Settings.isDbOnSDCard());
}
public static boolean restoreDatabaseInternal() {
if (!LocalStorage.isExternalStorageAvailable()) {
Log.w("Database wasn't restored: no external memory");
return false;
}
final File sourceFile = getBackupFileInternal();
closeDb();
final boolean restoreDone = LocalStorage.copy(sourceFile, databasePath());
init();
if (restoreDone) {
Log.i("Database successfully restored from " + sourceFile.getPath());
} else {
Log.e("Could not restore database from " + sourceFile.getPath());
}
return restoreDone;
}
private static class DBContext extends ContextWrapper {
DBContext(final Context base) {
super(base);
}
/**
* We override the default open/create as it doesn't work on OS 1.6 and
* causes issues on other devices too.
*/
@Override
public SQLiteDatabase openOrCreateDatabase(final String name, final int mode,
final CursorFactory factory) {
final File file = new File(name);
FileUtils.mkdirs(file.getParentFile());
return SQLiteDatabase.openOrCreateDatabase(file, factory);
}
}
private static class DbHelper extends SQLiteOpenHelper {
private static boolean firstRun = true;
DbHelper(final Context context) {
super(context, databasePath().getPath(), null, dbVersion);
}
@Override
public void onCreate(final SQLiteDatabase db) {
newlyCreatedDatabase = true;
db.execSQL(dbCreateCaches);
db.execSQL(dbCreateLists);
db.execSQL(dbCreateCachesLists);
db.execSQL(dbCreateAttributes);
db.execSQL(dbCreateWaypoints);
db.execSQL(dbCreateSpoilers);
db.execSQL(dbCreateLogs);
db.execSQL(dbCreateLogCount);
db.execSQL(dbCreateLogImages);
db.execSQL(dbCreateLogsOffline);
db.execSQL(dbCreateTrackables);
db.execSQL(dbCreateSearchDestinationHistory);
createIndices(db);
}
private static void createIndices(final SQLiteDatabase db) {
db.execSQL("CREATE INDEX IF NOT EXISTS in_caches_geo ON " + dbTableCaches + " (geocode)");
db.execSQL("CREATE INDEX IF NOT EXISTS in_caches_guid ON " + dbTableCaches + " (guid)");
db.execSQL("CREATE INDEX IF NOT EXISTS in_caches_lat ON " + dbTableCaches + " (latitude)");
db.execSQL("CREATE INDEX IF NOT EXISTS in_caches_lon ON " + dbTableCaches + " (longitude)");
db.execSQL("CREATE INDEX IF NOT EXISTS in_caches_reason ON " + dbTableCaches + " (reason)");
db.execSQL("CREATE INDEX IF NOT EXISTS in_caches_detailed ON " + dbTableCaches + " (detailed)");
db.execSQL("CREATE INDEX IF NOT EXISTS in_caches_type ON " + dbTableCaches + " (type)");
db.execSQL("CREATE INDEX IF NOT EXISTS in_caches_visit_detail ON " + dbTableCaches + " (visiteddate, detailedupdate)");
db.execSQL("CREATE INDEX IF NOT EXISTS in_attr_geo ON " + dbTableAttributes + " (geocode)");
db.execSQL("CREATE INDEX IF NOT EXISTS in_wpts_geo ON " + dbTableWaypoints + " (geocode)");
db.execSQL("CREATE INDEX IF NOT EXISTS in_wpts_geo_type ON " + dbTableWaypoints + " (geocode, type)");
db.execSQL("CREATE INDEX IF NOT EXISTS in_spoil_geo ON " + dbTableSpoilers + " (geocode)");
db.execSQL("CREATE INDEX IF NOT EXISTS in_logs_geo ON " + dbTableLogs + " (geocode)");
db.execSQL("CREATE INDEX IF NOT EXISTS in_logcount_geo ON " + dbTableLogCount + " (geocode)");
db.execSQL("CREATE INDEX IF NOT EXISTS in_logsoff_geo ON " + dbTableLogsOffline + " (geocode)");
db.execSQL("CREATE INDEX IF NOT EXISTS in_trck_geo ON " + dbTableTrackables + " (geocode)");
db.execSQL("CREATE INDEX IF NOT EXISTS in_lists_geo ON " + dbTableCachesLists + " (geocode)");
}
@Override
public void onUpgrade(final SQLiteDatabase db, final int oldVersion, final int newVersion) {
Log.i("Upgrade database from ver. " + oldVersion + " to ver. " + newVersion + ": start");
try {
if (db.isReadOnly()) {
return;
}
db.beginTransaction();
if (oldVersion <= 0) { // new table
dropDatabase(db);
onCreate(db);
Log.i("Database structure created.");
}
if (oldVersion > 0) {
db.execSQL("DELETE FROM " + dbTableCaches + " WHERE reason = 0");
if (oldVersion < 52) { // upgrade to 52
try {
db.execSQL(dbCreateSearchDestinationHistory);
Log.i("Added table " + dbTableSearchDestinationHistory + ".");
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 52", e);
}
}
if (oldVersion < 53) { // upgrade to 53
try {
db.execSQL("ALTER TABLE " + dbTableCaches + " ADD COLUMN onWatchlist INTEGER");
Log.i("Column onWatchlist added to " + dbTableCaches + ".");
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 53", e);
}
}
if (oldVersion < 54) { // update to 54
try {
db.execSQL(dbCreateLogImages);
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 54", e);
}
}
if (oldVersion < 55) { // update to 55
try {
db.execSQL("ALTER TABLE " + dbTableCaches + " ADD COLUMN personal_note TEXT");
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 55", e);
}
}
// make all internal attribute names lowercase
// @see issue #299
if (oldVersion < 56) { // update to 56
try {
db.execSQL("UPDATE " + dbTableAttributes + " SET attribute = " +
"LOWER(attribute) WHERE attribute LIKE \"%_yes\" " +
"OR attribute LIKE \"%_no\"");
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 56", e);
}
}
// Create missing indices. See issue #435
if (oldVersion < 57) { // update to 57
try {
db.execSQL("DROP INDEX in_a");
db.execSQL("DROP INDEX in_b");
db.execSQL("DROP INDEX in_c");
db.execSQL("DROP INDEX in_d");
db.execSQL("DROP INDEX in_e");
db.execSQL("DROP INDEX in_f");
createIndices(db);
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 57", e);
}
}
if (oldVersion < 58) { // upgrade to 58
try {
db.beginTransaction();
final String dbTableCachesTemp = dbTableCaches + "_temp";
final String dbCreateCachesTemp = ""
+ "CREATE TABLE " + dbTableCachesTemp + " ("
+ "_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "updated LONG NOT NULL, "
+ "detailed INTEGER NOT NULL DEFAULT 0, "
+ "detailedupdate LONG, "
+ "visiteddate LONG, "
+ "geocode TEXT UNIQUE NOT NULL, "
+ "reason INTEGER NOT NULL DEFAULT 0, "
+ "cacheid TEXT, "
+ "guid TEXT, "
+ "type TEXT, "
+ "name TEXT, "
+ "own INTEGER NOT NULL DEFAULT 0, "
+ "owner TEXT, "
+ "owner_real TEXT, "
+ "hidden LONG, "
+ "hint TEXT, "
+ "size TEXT, "
+ "difficulty FLOAT, "
+ "terrain FLOAT, "
+ "location TEXT, "
+ "direction DOUBLE, "
+ "distance DOUBLE, "
+ "latitude DOUBLE, "
+ "longitude DOUBLE, "
+ "reliable_latlon INTEGER, "
+ "personal_note TEXT, "
+ "shortdesc TEXT, "
+ "description TEXT, "
+ "favourite_cnt INTEGER, "
+ "rating FLOAT, "
+ "votes INTEGER, "
+ "myvote FLOAT, "
+ "disabled INTEGER NOT NULL DEFAULT 0, "
+ "archived INTEGER NOT NULL DEFAULT 0, "
+ "members INTEGER NOT NULL DEFAULT 0, "
+ "found INTEGER NOT NULL DEFAULT 0, "
+ "favourite INTEGER NOT NULL DEFAULT 0, "
+ "inventorycoins INTEGER DEFAULT 0, "
+ "inventorytags INTEGER DEFAULT 0, "
+ "inventoryunknown INTEGER DEFAULT 0, "
+ "onWatchlist INTEGER DEFAULT 0 "
+ "); ";
db.execSQL(dbCreateCachesTemp);
db.execSQL("INSERT INTO " + dbTableCachesTemp + " SELECT _id,updated,detailed,detailedupdate,visiteddate,geocode,reason,cacheid,guid,type,name,own,owner,owner_real," +
"hidden,hint,size,difficulty,terrain,location,direction,distance,latitude,longitude, 0," +
"personal_note,shortdesc,description,favourite_cnt,rating,votes,myvote,disabled,archived,members,found,favourite,inventorycoins," +
"inventorytags,inventoryunknown,onWatchlist FROM " + dbTableCaches);
db.execSQL("DROP TABLE " + dbTableCaches);
db.execSQL("ALTER TABLE " + dbTableCachesTemp + " RENAME TO " + dbTableCaches);
final String dbTableWaypointsTemp = dbTableWaypoints + "_temp";
final String dbCreateWaypointsTemp = ""
+ "CREATE TABLE " + dbTableWaypointsTemp + " ("
+ "_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "geocode TEXT NOT NULL, "
+ "updated LONG NOT NULL, " // date of save
+ "type TEXT NOT NULL DEFAULT 'waypoint', "
+ "prefix TEXT, "
+ "lookup TEXT, "
+ "name TEXT, "
+ "latitude DOUBLE, "
+ "longitude DOUBLE, "
+ "note TEXT "
+ "); ";
db.execSQL(dbCreateWaypointsTemp);
db.execSQL("INSERT INTO " + dbTableWaypointsTemp + " SELECT _id, geocode, updated, type, prefix, lookup, name, latitude, longitude, note FROM " + dbTableWaypoints);
db.execSQL("DROP TABLE " + dbTableWaypoints);
db.execSQL("ALTER TABLE " + dbTableWaypointsTemp + " RENAME TO " + dbTableWaypoints);
createIndices(db);
db.setTransactionSuccessful();
Log.i("Removed latitude_string and longitude_string columns");
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 58", e);
} finally {
db.endTransaction();
}
}
if (oldVersion < 59) {
try {
// Add new indices and remove obsolete cache files
createIndices(db);
removeObsoleteCacheDirectories();
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 59", e);
}
}
if (oldVersion < 60) {
try {
removeSecEmptyDirs();
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 60", e);
}
}
if (oldVersion < 61) {
try {
db.execSQL("ALTER TABLE " + dbTableLogs + " ADD COLUMN friend INTEGER");
db.execSQL("ALTER TABLE " + dbTableCaches + " ADD COLUMN coordsChanged INTEGER DEFAULT 0");
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 61", e);
}
}
// Introduces finalDefined on caches and own on waypoints
if (oldVersion < 62) {
try {
db.execSQL("ALTER TABLE " + dbTableCaches + " ADD COLUMN finalDefined INTEGER DEFAULT 0");
db.execSQL("ALTER TABLE " + dbTableWaypoints + " ADD COLUMN own INTEGER DEFAULT 0");
db.execSQL("UPDATE " + dbTableWaypoints + " SET own = 1 WHERE type = 'own'");
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 62", e);
}
}
if (oldVersion < 63) {
try {
removeDoubleUnderscoreMapFiles();
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 63", e);
}
}
if (oldVersion < 64) {
try {
// No cache should ever be stored into the ALL_CACHES list. Here we use hardcoded list ids
// rather than symbolic ones because the fix must be applied with the values at the time
// of the problem. The problem was introduced in release 2012.06.01.
db.execSQL("UPDATE " + dbTableCaches + " SET reason=1 WHERE reason=2");
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 64", e);
}
}
if (oldVersion < 65) {
try {
// Set all waypoints where name is Original coordinates to type ORIGINAL
db.execSQL("UPDATE " + dbTableWaypoints + " SET type='original', own=0 WHERE name='Original Coordinates'");
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 65:", e);
}
}
// Introduces visited feature on waypoints
if (oldVersion < 66) {
try {
db.execSQL("ALTER TABLE " + dbTableWaypoints + " ADD COLUMN visited INTEGER DEFAULT 0");
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 66", e);
}
}
// issue2662 OC: Leichtes Klettern / Easy climbing
if (oldVersion < 67) {
try {
db.execSQL("UPDATE " + dbTableAttributes + " SET attribute = 'easy_climbing_yes' WHERE geocode LIKE 'OC%' AND attribute = 'climbing_yes'");
db.execSQL("UPDATE " + dbTableAttributes + " SET attribute = 'easy_climbing_no' WHERE geocode LIKE 'OC%' AND attribute = 'climbing_no'");
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 67", e);
}
}
// Introduces logPasswordRequired on caches
if (oldVersion < 68) {
try {
db.execSQL("ALTER TABLE " + dbTableCaches + " ADD COLUMN logPasswordRequired INTEGER DEFAULT 0");
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 68", e);
}
}
// description for log Images
if (oldVersion < 69) {
try {
db.execSQL("ALTER TABLE " + dbTableLogImages + " ADD COLUMN description TEXT");
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 69", e);
}
}
// Introduces watchListCount
if (oldVersion < 70) {
try {
db.execSQL("ALTER TABLE " + dbTableCaches + " ADD COLUMN watchlistCount INTEGER DEFAULT -1");
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 70", e);
}
}
// Introduces cachesLists
if (oldVersion < 71) {
try {
db.execSQL(dbCreateCachesLists);
createIndices(db);
db.execSQL("INSERT INTO " + dbTableCachesLists + " SELECT reason, geocode FROM " + dbTableCaches);
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 71", e);
}
}
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
Log.i("Upgrade database from ver. " + oldVersion + " to ver. " + newVersion + ": completed");
}
@Override
public void onOpen(final SQLiteDatabase db) {
if (firstRun) {
sanityChecks(db);
firstRun = false;
}
}
/**
* Execute sanity checks that should be performed once per application after the database has been
* opened.
*
* @param db the database to perform sanity checks against
*/
private static void sanityChecks(final SQLiteDatabase db) {
// Check that the history of searches is well formed as some dates seem to be missing according
// to NPE traces.
final int staleHistorySearches = db.delete(dbTableSearchDestinationHistory, "date IS NULL", null);
if (staleHistorySearches > 0) {
Log.w(String.format(Locale.getDefault(), "DataStore.dbHelper.onOpen: removed %d bad search history entries", staleHistorySearches));
}
}
/**
* Method to remove static map files with double underscore due to issue#1670
* introduced with release on 2012-05-24.
*/
private static void removeDoubleUnderscoreMapFiles() {
final File[] geocodeDirs = LocalStorage.getStorage().listFiles();
if (ArrayUtils.isNotEmpty(geocodeDirs)) {
final FilenameFilter filter = new FilenameFilter() {
@Override
public boolean accept(final File dir, final String filename) {
return filename.startsWith("map_") && filename.contains("__");
}
};
for (final File dir : geocodeDirs) {
final File[] wrongFiles = dir.listFiles(filter);
if (wrongFiles != null) {
for (final File wrongFile : wrongFiles) {
FileUtils.deleteIgnoringFailure(wrongFile);
}
}
}
}
}
/*
* Remove empty directories created in the secondary storage area.
*/
private static void removeSecEmptyDirs() {
final File[] files = LocalStorage.getStorageSec().listFiles();
if (ArrayUtils.isNotEmpty(files)) {
for (final File file : files) {
if (file.isDirectory()) {
// This will silently fail if the directory is not empty.
FileUtils.deleteIgnoringFailure(file);
}
}
}
}
private static void dropDatabase(final SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS " + dbTableCachesLists);
db.execSQL("DROP TABLE IF EXISTS " + dbTableCaches);
db.execSQL("DROP TABLE IF EXISTS " + dbTableAttributes);
db.execSQL("DROP TABLE IF EXISTS " + dbTableWaypoints);
db.execSQL("DROP TABLE IF EXISTS " + dbTableSpoilers);
db.execSQL("DROP TABLE IF EXISTS " + dbTableLogs);
db.execSQL("DROP TABLE IF EXISTS " + dbTableLogCount);
db.execSQL("DROP TABLE IF EXISTS " + dbTableLogsOffline);
db.execSQL("DROP TABLE IF EXISTS " + dbTableTrackables);
}
}
/**
* Remove obsolete cache directories in c:geo private storage.
*/
public static void removeObsoleteCacheDirectories() {
final File[] files = LocalStorage.getStorage().listFiles();
if (ArrayUtils.isNotEmpty(files)) {
final Pattern oldFilePattern = Pattern.compile("^[GC|TB|EC|GK|O][A-Z0-9]{4,7}$");
final SQLiteStatement select = PreparedStatement.CHECK_IF_PRESENT.getStatement();
final List<File> toRemove = new ArrayList<>(files.length);
for (final File file : files) {
if (file.isDirectory()) {
final String geocode = file.getName();
if (oldFilePattern.matcher(geocode).find()) {
synchronized (select) {
select.bindString(1, geocode);
if (select.simpleQueryForLong() == 0) {
toRemove.add(file);
}
}
}
}
}
// Use a background thread for the real removal to avoid keeping the database locked
// if we are called from within a transaction.
Schedulers.io().scheduleDirect(new Runnable() {
@Override
public void run() {
for (final File dir : toRemove) {
Log.i("Removing obsolete cache directory for " + dir.getName());
FileUtils.deleteDirectory(dir);
}
}
});
}
}
public static boolean isThere(final String geocode, final String guid, final boolean checkTime) {
init();
long dataDetailedUpdate = 0;
int dataDetailed = 0;
try {
final Cursor cursor;
if (StringUtils.isNotBlank(geocode)) {
cursor = database.query(
dbTableCaches,
new String[]{"detailed", "detailedupdate", "updated"},
"geocode = ?",
new String[]{geocode},
null,
null,
null,
"1");
} else if (StringUtils.isNotBlank(guid)) {
cursor = database.query(
dbTableCaches,
new String[]{"detailed", "detailedupdate", "updated"},
"guid = ?",
new String[]{guid},
null,
null,
null,
"1");
} else {
return false;
}
if (cursor.moveToFirst()) {
dataDetailed = cursor.getInt(0);
dataDetailedUpdate = cursor.getLong(1);
}
cursor.close();
} catch (final Exception e) {
Log.e("DataStore.isThere", e);
}
if (dataDetailed == 0) {
// we want details, but these are not stored
return false;
}
if (checkTime && dataDetailedUpdate < (System.currentTimeMillis() - DAYS_AFTER_CACHE_IS_DELETED)) {
// we want to check time for detailed cache, but data are older than 3 days
return false;
}
// we have some cache
return true;
}
/** is cache stored in one of the lists (not only temporary) */
public static boolean isOffline(final String geocode, final String guid) {
if (StringUtils.isBlank(geocode) && StringUtils.isBlank(guid)) {
return false;
}
init();
try {
final SQLiteStatement offlineListCount;
final String value;
if (StringUtils.isNotBlank(geocode)) {
offlineListCount = PreparedStatement.GEOCODE_OFFLINE.getStatement();
value = geocode;
} else {
offlineListCount = PreparedStatement.GUID_OFFLINE.getStatement();
value = guid;
}
synchronized (offlineListCount) {
offlineListCount.bindString(1, value);
return offlineListCount.simpleQueryForLong() > 0;
}
} catch (final SQLiteDoneException ignored) {
// Do nothing, it only means we have no information on the cache
} catch (final Exception e) {
Log.e("DataStore.isOffline", e);
}
return false;
}
@Nullable
public static String getGeocodeForGuid(final String guid) {
if (StringUtils.isBlank(guid)) {
return null;
}
init();
try {
final SQLiteStatement description = PreparedStatement.GEOCODE_OF_GUID.getStatement();
synchronized (description) {
description.bindString(1, guid);
return description.simpleQueryForString();
}
} catch (final SQLiteDoneException ignored) {
// Do nothing, it only means we have no information on the cache
} catch (final Exception e) {
Log.e("DataStore.getGeocodeForGuid", e);
}
return null;
}
@Nullable
public static String getGeocodeForTitle(@NonNull final String title) {
if (StringUtils.isBlank(title)) {
return null;
}
init();
try {
final SQLiteStatement sqlStatement = PreparedStatement.GEOCODE_FROM_TITLE.getStatement();
synchronized (sqlStatement) {
sqlStatement.bindString(1, title);
return sqlStatement.simpleQueryForString();
}
} catch (final SQLiteDoneException ignored) {
// Do nothing, it only means we have no information on the cache
} catch (final Exception e) {
Log.e("DataStore.getGeocodeForGuid", e);
}
return null;
}
/**
* Save/store a cache to the CacheCache
*
* @param cache
* the Cache to save in the CacheCache/DB
*
*/
public static void saveCache(final Geocache cache, final Set<LoadFlags.SaveFlag> saveFlags) {
saveCaches(Collections.singletonList(cache), saveFlags);
}
/**
* Save/store a cache to the CacheCache
*
* @param caches
* the caches to save in the CacheCache/DB
*
*/
public static void saveCaches(final Collection<Geocache> caches, final Set<LoadFlags.SaveFlag> saveFlags) {
if (CollectionUtils.isEmpty(caches)) {
return;
}
final List<String> cachesFromDatabase = new ArrayList<>();
final Map<String, Geocache> existingCaches = new HashMap<>();
// first check which caches are in the memory cache
for (final Geocache cache : caches) {
final String geocode = cache.getGeocode();
final Geocache cacheFromCache = cacheCache.getCacheFromCache(geocode);
if (cacheFromCache == null) {
cachesFromDatabase.add(geocode);
} else {
existingCaches.put(geocode, cacheFromCache);
}
}
// then load all remaining caches from the database in one step
for (final Geocache cacheFromDatabase : loadCaches(cachesFromDatabase, LoadFlags.LOAD_ALL_DB_ONLY)) {
existingCaches.put(cacheFromDatabase.getGeocode(), cacheFromDatabase);
}
final List<Geocache> toBeStored = new ArrayList<>();
// Merge with the data already stored in the CacheCache or in the database if
// the cache had not been loaded before, and update the CacheCache.
// Also, a DB update is required if the merge data comes from the CacheCache
// (as it may be more recent than the version in the database), or if the
// version coming from the database is different than the version we are entering
// into the cache (that includes absence from the database).
for (final Geocache cache : caches) {
final String geocode = cache.getGeocode();
final Geocache existingCache = existingCaches.get(geocode);
boolean dbUpdateRequired = !cache.gatherMissingFrom(existingCache) || cacheCache.getCacheFromCache(geocode) != null;
// parse the note AFTER merging the local information in
dbUpdateRequired |= cache.parseWaypointsFromNote();
cache.addStorageLocation(StorageLocation.CACHE);
cacheCache.putCacheInCache(cache);
// Only save the cache in the database if it is requested by the caller and
// the cache contains detailed information.
if (saveFlags.contains(SaveFlag.DB) && dbUpdateRequired) {
toBeStored.add(cache);
}
}
for (final Geocache geocache : toBeStored) {
storeIntoDatabase(geocache);
}
}
private static boolean storeIntoDatabase(final Geocache cache) {
cache.addStorageLocation(StorageLocation.DATABASE);
cacheCache.putCacheInCache(cache);
Log.d("Saving " + cache.toString() + " (" + cache.getLists() + ") to DB");
final ContentValues values = new ContentValues();
if (cache.getUpdated() == 0) {
values.put("updated", System.currentTimeMillis());
} else {
values.put("updated", cache.getUpdated());
}
values.put("reason", StoredList.STANDARD_LIST_ID);
values.put("detailed", cache.isDetailed() ? 1 : 0);
values.put("detailedupdate", cache.getDetailedUpdate());
values.put("visiteddate", cache.getVisitedDate());
values.put("geocode", cache.getGeocode());
values.put("cacheid", cache.getCacheId());
values.put("guid", cache.getGuid());
values.put("type", cache.getType().id);
values.put("name", cache.getName());
values.put("owner", cache.getOwnerDisplayName());
values.put("owner_real", cache.getOwnerUserId());
final Date hiddenDate = cache.getHiddenDate();
if (hiddenDate == null) {
values.put("hidden", 0);
} else {
values.put("hidden", hiddenDate.getTime());
}
values.put("hint", cache.getHint());
values.put("size", cache.getSize().id);
values.put("difficulty", cache.getDifficulty());
values.put("terrain", cache.getTerrain());
values.put("location", cache.getLocation());
values.put("distance", cache.getDistance());
values.put("direction", cache.getDirection());
putCoords(values, cache.getCoords());
values.put("reliable_latlon", cache.isReliableLatLon() ? 1 : 0);
values.put("shortdesc", cache.getShortDescription());
values.put("personal_note", cache.getPersonalNote());
values.put("description", cache.getDescription());
values.put("favourite_cnt", cache.getFavoritePoints());
values.put("rating", cache.getRating());
values.put("votes", cache.getVotes());
values.put("myvote", cache.getMyVote());
values.put("disabled", cache.isDisabled() ? 1 : 0);
values.put("archived", cache.isArchived() ? 1 : 0);
values.put("members", cache.isPremiumMembersOnly() ? 1 : 0);
values.put("found", cache.isFound() ? 1 : 0);
values.put("favourite", cache.isFavorite() ? 1 : 0);
values.put("inventoryunknown", cache.getInventoryItems());
values.put("onWatchlist", cache.isOnWatchlist() ? 1 : 0);
values.put("coordsChanged", cache.hasUserModifiedCoords() ? 1 : 0);
values.put("finalDefined", cache.hasFinalDefined() ? 1 : 0);
values.put("logPasswordRequired", cache.isLogPasswordRequired() ? 1 : 0);
values.put("watchlistCount", cache.getWatchlistCount());
init();
// try to update record else insert fresh..
database.beginTransaction();
try {
saveAttributesWithoutTransaction(cache);
saveWaypointsWithoutTransaction(cache);
saveSpoilersWithoutTransaction(cache);
saveLogCountsWithoutTransaction(cache);
saveInventoryWithoutTransaction(cache.getGeocode(), cache.getInventory());
saveListsWithoutTransaction(cache);
final int rows = database.update(dbTableCaches, values, "geocode = ?", new String[] { cache.getGeocode() });
if (rows == 0) {
// cache is not in the DB, insert it
/* long id = */
database.insert(dbTableCaches, null, values);
}
database.setTransactionSuccessful();
return true;
} catch (final Exception e) {
Log.e("SaveCache", e);
} finally {
database.endTransaction();
}
return false;
}
private static void saveAttributesWithoutTransaction(final Geocache cache) {
final String geocode = cache.getGeocode();
// The attributes must be fetched first because lazy loading may load
// a null set otherwise.
final List<String> attributes = cache.getAttributes();
database.delete(dbTableAttributes, "geocode = ?", new String[]{geocode});
if (attributes.isEmpty()) {
return;
}
final SQLiteStatement statement = PreparedStatement.INSERT_ATTRIBUTE.getStatement();
final long timestamp = System.currentTimeMillis();
for (final String attribute : attributes) {
statement.bindString(1, geocode);
statement.bindLong(2, timestamp);
statement.bindString(3, attribute);
statement.executeInsert();
}
}
private static void saveListsWithoutTransaction(final Geocache cache) {
final String geocode = cache.getGeocode();
// The lists must be fetched first because lazy loading may load
// a null set otherwise.
final Set<Integer> lists = cache.getLists();
if (lists.isEmpty()) {
return;
}
final SQLiteStatement statement = PreparedStatement.ADD_TO_LIST.getStatement();
for (final Integer listId : lists) {
statement.bindLong(1, listId);
statement.bindString(2, geocode);
statement.executeInsert();
}
}
/**
* Persists the given {@code destination} into the database.
*
* @param destination
* a destination to save
*/
public static void saveSearchedDestination(final Destination destination) {
init();
database.beginTransaction();
try {
final SQLiteStatement insertDestination = PreparedStatement.INSERT_SEARCH_DESTINATION.getStatement();
insertDestination.bindLong(1, destination.getDate());
final Geopoint coords = destination.getCoords();
insertDestination.bindDouble(2, coords.getLatitude());
insertDestination.bindDouble(3, coords.getLongitude());
insertDestination.executeInsert();
database.setTransactionSuccessful();
} catch (final Exception e) {
Log.e("Updating searchedDestinations db failed", e);
} finally {
database.endTransaction();
}
}
public static boolean saveWaypoints(final Geocache cache) {
init();
database.beginTransaction();
try {
saveWaypointsWithoutTransaction(cache);
database.setTransactionSuccessful();
return true;
} catch (final Exception e) {
Log.e("saveWaypoints", e);
} finally {
database.endTransaction();
}
return false;
}
private static void saveWaypointsWithoutTransaction(final Geocache cache) {
final String geocode = cache.getGeocode();
final List<Waypoint> waypoints = cache.getWaypoints();
if (CollectionUtils.isNotEmpty(waypoints)) {
final List<String> currentWaypointIds = new ArrayList<>();
final ContentValues values = new ContentValues();
final long timeStamp = System.currentTimeMillis();
for (final Waypoint oneWaypoint : waypoints) {
values.clear();
values.put("geocode", geocode);
values.put("updated", timeStamp);
values.put("type", oneWaypoint.getWaypointType() != null ? oneWaypoint.getWaypointType().id : null);
values.put("prefix", oneWaypoint.getPrefix());
values.put("lookup", oneWaypoint.getLookup());
values.put("name", oneWaypoint.getName());
putCoords(values, oneWaypoint.getCoords());
values.put("note", oneWaypoint.getNote());
values.put("own", oneWaypoint.isUserDefined() ? 1 : 0);
values.put("visited", oneWaypoint.isVisited() ? 1 : 0);
if (oneWaypoint.getId() < 0) {
final long rowId = database.insert(dbTableWaypoints, null, values);
oneWaypoint.setId((int) rowId);
} else {
database.update(dbTableWaypoints, values, "_id = ?", new String[] { Integer.toString(oneWaypoint.getId(), 10) });
}
currentWaypointIds.add(Integer.toString(oneWaypoint.getId()));
}
removeOutdatedWaypointsOfCache(cache, currentWaypointIds);
}
}
/**
* remove all waypoints of the given cache, where the id is not in the given list
*
* @param remainingWaypointIds
* ids of waypoints which shall not be deleted
*/
private static void removeOutdatedWaypointsOfCache(@NonNull final Geocache cache, @NonNull final Collection<String> remainingWaypointIds) {
final String idList = StringUtils.join(remainingWaypointIds, ',');
database.delete(dbTableWaypoints, "geocode = ? AND _id NOT IN (" + idList + ")", new String[]{cache.getGeocode()});
}
/**
* Save coordinates into a ContentValues
*
* @param values
* a ContentValues to save coordinates in
* @param coords
* coordinates to save, or null to save empty coordinates
*/
private static void putCoords(final ContentValues values, final Geopoint coords) {
values.put("latitude", coords == null ? null : coords.getLatitude());
values.put("longitude", coords == null ? null : coords.getLongitude());
}
/**
* Retrieve coordinates from a Cursor
*
* @param cursor
* a Cursor representing a row in the database
* @param indexLat
* index of the latitude column
* @param indexLon
* index of the longitude column
* @return the coordinates, or null if latitude or longitude is null or the coordinates are invalid
*/
@Nullable
private static Geopoint getCoords(final Cursor cursor, final int indexLat, final int indexLon) {
if (cursor.isNull(indexLat) || cursor.isNull(indexLon)) {
return null;
}
return new Geopoint(cursor.getDouble(indexLat), cursor.getDouble(indexLon));
}
private static boolean saveWaypointInternal(final int id, final String geocode, final Waypoint waypoint) {
if ((StringUtils.isBlank(geocode) && id <= 0) || waypoint == null) {
return false;
}
init();
database.beginTransaction();
boolean ok = false;
try {
final ContentValues values = new ContentValues();
values.put("geocode", geocode);
values.put("updated", System.currentTimeMillis());
values.put("type", waypoint.getWaypointType() != null ? waypoint.getWaypointType().id : null);
values.put("prefix", waypoint.getPrefix());
values.put("lookup", waypoint.getLookup());
values.put("name", waypoint.getName());
putCoords(values, waypoint.getCoords());
values.put("note", waypoint.getNote());
values.put("own", waypoint.isUserDefined() ? 1 : 0);
values.put("visited", waypoint.isVisited() ? 1 : 0);
if (id <= 0) {
final long rowId = database.insert(dbTableWaypoints, null, values);
waypoint.setId((int) rowId);
ok = true;
} else {
final int rows = database.update(dbTableWaypoints, values, "_id = " + id, null);
ok = rows > 0;
}
database.setTransactionSuccessful();
} finally {
database.endTransaction();
}
return ok;
}
public static boolean deleteWaypoint(final int id) {
if (id == 0) {
return false;
}
init();
return database.delete(dbTableWaypoints, "_id = " + id, null) > 0;
}
private static void saveSpoilersWithoutTransaction(final Geocache cache) {
if (cache.hasSpoilersSet()) {
final String geocode = cache.getGeocode();
final SQLiteStatement remove = PreparedStatement.REMOVE_SPOILERS.getStatement();
remove.bindString(1, cache.getGeocode());
remove.execute();
final SQLiteStatement insertSpoiler = PreparedStatement.INSERT_SPOILER.getStatement();
final long timestamp = System.currentTimeMillis();
for (final Image spoiler : cache.getSpoilers()) {
insertSpoiler.bindString(1, geocode);
insertSpoiler.bindLong(2, timestamp);
insertSpoiler.bindString(3, spoiler.getUrl());
insertSpoiler.bindString(4, StringUtils.defaultIfBlank(spoiler.title, ""));
final String description = spoiler.getDescription();
if (StringUtils.isNotBlank(description)) {
insertSpoiler.bindString(5, description);
} else {
insertSpoiler.bindNull(5);
}
insertSpoiler.executeInsert();
}
}
}
public static void saveLogs(final String geocode, final Iterable<LogEntry> logs) {
database.beginTransaction();
try {
saveLogsWithoutTransaction(geocode, logs);
database.setTransactionSuccessful();
} finally {
database.endTransaction();
}
}
private static void saveLogsWithoutTransaction(final String geocode, final Iterable<LogEntry> logs) {
if (!logs.iterator().hasNext()) {
return;
}
// TODO delete logimages referring these logs
database.delete(dbTableLogs, "geocode = ?", new String[]{geocode});
final SQLiteStatement insertLog = PreparedStatement.INSERT_LOG.getStatement();
final long timestamp = System.currentTimeMillis();
for (final LogEntry log : logs) {
insertLog.bindString(1, geocode);
insertLog.bindLong(2, timestamp);
insertLog.bindLong(3, log.getType().id);
insertLog.bindString(4, log.author);
insertLog.bindString(5, log.log);
insertLog.bindLong(6, log.date);
insertLog.bindLong(7, log.found);
insertLog.bindLong(8, log.friend ? 1 : 0);
final long logId = insertLog.executeInsert();
if (log.hasLogImages()) {
final SQLiteStatement insertImage = PreparedStatement.INSERT_LOG_IMAGE.getStatement();
for (final Image img : log.getLogImages()) {
insertImage.bindLong(1, logId);
insertImage.bindString(2, StringUtils.defaultIfBlank(img.title, ""));
insertImage.bindString(3, img.getUrl());
insertImage.bindString(4, StringUtils.defaultIfBlank(img.getDescription(), ""));
insertImage.executeInsert();
}
}
}
}
private static void saveLogCountsWithoutTransaction(final Geocache cache) {
final String geocode = cache.getGeocode();
database.delete(dbTableLogCount, "geocode = ?", new String[]{geocode});
final Map<LogType, Integer> logCounts = cache.getLogCounts();
if (MapUtils.isNotEmpty(logCounts)) {
final Set<Entry<LogType, Integer>> logCountsItems = logCounts.entrySet();
final SQLiteStatement insertLogCounts = PreparedStatement.INSERT_LOG_COUNTS.getStatement();
final long timestamp = System.currentTimeMillis();
for (final Entry<LogType, Integer> pair : logCountsItems) {
insertLogCounts.bindString(1, geocode);
insertLogCounts.bindLong(2, timestamp);
insertLogCounts.bindLong(3, pair.getKey().id);
insertLogCounts.bindLong(4, pair.getValue());
insertLogCounts.executeInsert();
}
}
}
public static void saveTrackable(final Trackable trackable) {
init();
database.beginTransaction();
try {
saveInventoryWithoutTransaction(null, Collections.singletonList(trackable));
database.setTransactionSuccessful();
} finally {
database.endTransaction();
}
}
private static void saveInventoryWithoutTransaction(final String geocode, final List<Trackable> trackables) {
if (geocode != null) {
database.delete(dbTableTrackables, "geocode = ?", new String[]{geocode});
}
if (CollectionUtils.isNotEmpty(trackables)) {
final ContentValues values = new ContentValues();
final long timeStamp = System.currentTimeMillis();
for (final Trackable trackable : trackables) {
final String tbCode = trackable.getGeocode();
if (StringUtils.isNotBlank(tbCode)) {
database.delete(dbTableTrackables, "tbcode = ?", new String[] { tbCode });
}
values.clear();
if (geocode != null) {
values.put("geocode", geocode);
}
values.put("updated", timeStamp);
values.put("tbcode", tbCode);
values.put("guid", trackable.getGuid());
values.put("title", trackable.getName());
values.put("owner", trackable.getOwner());
final Date releasedDate = trackable.getReleased();
if (releasedDate != null) {
values.put("released", releasedDate.getTime());
} else {
values.put("released", 0L);
}
values.put("goal", trackable.getGoal());
values.put("description", trackable.getDetails());
database.insert(dbTableTrackables, null, values);
saveLogsWithoutTransaction(tbCode, trackable.getLogs());
}
}
}
@Nullable
public static Viewport getBounds(final Set<String> geocodes) {
if (CollectionUtils.isEmpty(geocodes)) {
return null;
}
final Set<Geocache> caches = loadCaches(geocodes, LoadFlags.LOAD_CACHE_OR_DB);
return Viewport.containing(caches);
}
/**
* Load a single Cache.
*
* @param geocode
* The Geocode GCXXXX
* @return the loaded cache (if found). Can be null
*/
@Nullable
public static Geocache loadCache(final String geocode, final EnumSet<LoadFlag> loadFlags) {
if (StringUtils.isBlank(geocode)) {
throw new IllegalArgumentException("geocode must not be empty");
}
final Set<Geocache> caches = loadCaches(Collections.singleton(geocode), loadFlags);
return caches.isEmpty() ? null : caches.iterator().next();
}
/**
* Load caches.
*
* @return Set of loaded caches. Never null.
*/
@NonNull
public static Set<Geocache> loadCaches(final Collection<String> geocodes, final EnumSet<LoadFlag> loadFlags) {
if (CollectionUtils.isEmpty(geocodes)) {
return new HashSet<>();
}
final Set<Geocache> result = new HashSet<>(geocodes.size());
final Set<String> remaining = new HashSet<>(geocodes);
if (loadFlags.contains(LoadFlag.CACHE_BEFORE)) {
for (final String geocode : geocodes) {
final Geocache cache = cacheCache.getCacheFromCache(geocode);
if (cache != null) {
result.add(cache);
remaining.remove(cache.getGeocode());
}
}
}
if (loadFlags.contains(LoadFlag.DB_MINIMAL) ||
loadFlags.contains(LoadFlag.ATTRIBUTES) ||
loadFlags.contains(LoadFlag.WAYPOINTS) ||
loadFlags.contains(LoadFlag.SPOILERS) ||
loadFlags.contains(LoadFlag.LOGS) ||
loadFlags.contains(LoadFlag.INVENTORY) ||
loadFlags.contains(LoadFlag.OFFLINE_LOG)) {
final Set<Geocache> cachesFromDB = loadCachesFromGeocodes(remaining, loadFlags);
result.addAll(cachesFromDB);
for (final Geocache cache : cachesFromDB) {
remaining.remove(cache.getGeocode());
}
}
if (loadFlags.contains(LoadFlag.CACHE_AFTER)) {
for (final String geocode : new HashSet<>(remaining)) {
final Geocache cache = cacheCache.getCacheFromCache(geocode);
if (cache != null) {
result.add(cache);
remaining.remove(cache.getGeocode());
}
}
}
if (CollectionUtils.isNotEmpty(remaining)) {
Log.d("DataStore.loadCaches(" + remaining.toString() + ") returned no results");
}
return result;
}
/**
* Load caches.
*
* @return Set of loaded caches. Never null.
*/
@NonNull
private static Set<Geocache> loadCachesFromGeocodes(final Set<String> geocodes, final EnumSet<LoadFlag> loadFlags) {
if (CollectionUtils.isEmpty(geocodes)) {
return Collections.emptySet();
}
// do not log the entire collection of geo codes to the debug log. This can be more than 100 KB of text for large lists!
init();
final StringBuilder query = new StringBuilder(QUERY_CACHE_DATA);
if (loadFlags.contains(LoadFlag.OFFLINE_LOG)) {
query.append(',').append(dbTableLogsOffline).append(".log");
}
query.append(" FROM ").append(dbTableCaches);
if (loadFlags.contains(LoadFlag.OFFLINE_LOG)) {
query.append(" LEFT OUTER JOIN ").append(dbTableLogsOffline).append(" ON ( ").append(dbTableCaches).append(".geocode == ").append(dbTableLogsOffline).append(".geocode) ");
}
query.append(" WHERE ").append(dbTableCaches).append('.');
query.append(whereGeocodeIn(geocodes));
final Cursor cursor = database.rawQuery(query.toString(), null);
try {
final Set<Geocache> caches = new HashSet<>();
int logIndex = -1;
while (cursor.moveToNext()) {
final Geocache cache = createCacheFromDatabaseContent(cursor);
if (loadFlags.contains(LoadFlag.ATTRIBUTES)) {
cache.setAttributes(loadAttributes(cache.getGeocode()));
}
if (loadFlags.contains(LoadFlag.WAYPOINTS)) {
final List<Waypoint> waypoints = loadWaypoints(cache.getGeocode());
if (CollectionUtils.isNotEmpty(waypoints)) {
cache.setWaypoints(waypoints, false);
}
}
if (loadFlags.contains(LoadFlag.SPOILERS)) {
final List<Image> spoilers = loadSpoilers(cache.getGeocode());
cache.setSpoilers(spoilers);
}
if (loadFlags.contains(LoadFlag.LOGS)) {
final Map<LogType, Integer> logCounts = loadLogCounts(cache.getGeocode());
if (MapUtils.isNotEmpty(logCounts)) {
cache.getLogCounts().clear();
cache.getLogCounts().putAll(logCounts);
}
}
if (loadFlags.contains(LoadFlag.INVENTORY)) {
final List<Trackable> inventory = loadInventory(cache.getGeocode());
if (CollectionUtils.isNotEmpty(inventory)) {
cache.setInventory(inventory);
}
}
if (loadFlags.contains(LoadFlag.OFFLINE_LOG)) {
if (logIndex < 0) {
logIndex = cursor.getColumnIndex("log");
}
cache.setLogOffline(!cursor.isNull(logIndex));
}
cache.addStorageLocation(StorageLocation.DATABASE);
cacheCache.putCacheInCache(cache);
caches.add(cache);
}
final Map<String, Set<Integer>> cacheLists = loadLists(geocodes);
for (final Geocache geocache : caches) {
final Set<Integer> listIds = cacheLists.get(geocache.getGeocode());
if (listIds != null) {
geocache.setLists(listIds);
}
}
return caches;
} finally {
cursor.close();
}
}
/**
* Builds a where for a viewport with the size enhanced by 50%.
*
*/
@NonNull
private static StringBuilder buildCoordinateWhere(final String dbTable, final Viewport viewport) {
return viewport.resize(1.5).sqlWhere(dbTable);
}
/**
* creates a Cache from the cursor. Doesn't next.
*
* @return Cache from DB
*/
@NonNull
private static Geocache createCacheFromDatabaseContent(final Cursor cursor) {
final Geocache cache = new Geocache();
cache.setUpdated(cursor.getLong(0));
cache.setDetailed(cursor.getInt(2) == 1);
cache.setDetailedUpdate(cursor.getLong(3));
cache.setVisitedDate(cursor.getLong(4));
cache.setGeocode(cursor.getString(5));
cache.setCacheId(cursor.getString(6));
cache.setGuid(cursor.getString(7));
cache.setType(CacheType.getById(cursor.getString(8)));
cache.setName(cursor.getString(9));
cache.setOwnerDisplayName(cursor.getString(10));
cache.setOwnerUserId(cursor.getString(11));
final long dateValue = cursor.getLong(12);
if (dateValue != 0) {
cache.setHidden(new Date(dateValue));
}
// do not set cache.hint
cache.setSize(CacheSize.getById(cursor.getString(14)));
cache.setDifficulty(cursor.getFloat(15));
final int directionIndex = 16;
if (cursor.isNull(directionIndex)) {
cache.setDirection(null);
} else {
cache.setDirection(cursor.getFloat(directionIndex));
}
final int distanceIndex = 17;
if (cursor.isNull(distanceIndex)) {
cache.setDistance(null);
} else {
cache.setDistance(cursor.getFloat(distanceIndex));
}
cache.setTerrain(cursor.getFloat(18));
// do not set cache.location
cache.setPersonalNote(cursor.getString(20));
// do not set cache.shortdesc
// do not set cache.description
cache.setFavoritePoints(cursor.getInt(22));
cache.setRating(cursor.getFloat(23));
cache.setVotes(cursor.getInt(24));
cache.setMyVote(cursor.getFloat(25));
cache.setDisabled(cursor.getInt(26) == 1);
cache.setArchived(cursor.getInt(27) == 1);
cache.setPremiumMembersOnly(cursor.getInt(28) == 1);
cache.setFound(cursor.getInt(29) == 1);
cache.setFavorite(cursor.getInt(30) == 1);
cache.setInventoryItems(cursor.getInt(31));
cache.setOnWatchlist(cursor.getInt(32) == 1);
cache.setReliableLatLon(cursor.getInt(33) > 0);
cache.setUserModifiedCoords(cursor.getInt(34) > 0);
cache.setCoords(getCoords(cursor, 35, 36));
cache.setFinalDefined(cursor.getInt(37) > 0);
cache.setLogPasswordRequired(cursor.getInt(41) > 0);
cache.setWatchlistCount(cursor.getInt(42));
Log.d("Loading " + cache.toString() + " from DB");
return cache;
}
@Nullable
public static List<String> loadAttributes(final String geocode) {
if (StringUtils.isBlank(geocode)) {
return null;
}
return queryToColl(dbTableAttributes,
new String[]{"attribute"},
"geocode = ?",
new String[]{geocode},
null,
"100",
new LinkedList<String>(),
GET_STRING_0);
}
@Nullable
public static Set<Integer> loadLists(final String geocode) {
if (StringUtils.isBlank(geocode)) {
return null;
}
return queryToColl(dbTableCachesLists,
new String[]{"list_id"},
"geocode = ?",
new String[]{geocode},
null,
"100",
new HashSet<Integer>(),
GET_INTEGER_0);
}
@NonNull
public static Map<String, Set<Integer>> loadLists(final Collection<String> geocodes) {
final Map<String, Set<Integer>> cacheLists = new HashMap<>();
final StringBuilder query = new StringBuilder("SELECT list_id, geocode FROM ");
query.append(dbTableCachesLists);
query.append(" WHERE ");
query.append(whereGeocodeIn(geocodes));
final Cursor cursor = database.rawQuery(query.toString(), null);
try {
while (cursor.moveToNext()) {
final Integer listId = cursor.getInt(0);
final String geocode = cursor.getString(1);
Set<Integer> listIds = cacheLists.get(geocode);
if (listIds != null) {
listIds.add(listId);
} else {
listIds = new HashSet<>();
listIds.add(listId);
cacheLists.put(geocode, listIds);
}
}
} finally {
cursor.close();
}
return cacheLists;
}
@Nullable
public static Waypoint loadWaypoint(final int id) {
if (id == 0) {
return null;
}
init();
final Cursor cursor = database.query(
dbTableWaypoints,
WAYPOINT_COLUMNS,
"_id = ?",
new String[]{Integer.toString(id)},
null,
null,
null,
"1");
Log.d("DataStore.loadWaypoint(" + id + ")");
final Waypoint waypoint = cursor.moveToFirst() ? createWaypointFromDatabaseContent(cursor) : null;
cursor.close();
return waypoint;
}
@Nullable
public static List<Waypoint> loadWaypoints(final String geocode) {
if (StringUtils.isBlank(geocode)) {
return null;
}
return queryToColl(dbTableWaypoints,
WAYPOINT_COLUMNS,
"geocode = ?",
new String[]{geocode},
"_id",
null,
new LinkedList<Waypoint>(),
new Func1<Cursor, Waypoint>() {
@Override
public Waypoint call(final Cursor cursor) {
return createWaypointFromDatabaseContent(cursor);
}
});
}
@NonNull
private static Waypoint createWaypointFromDatabaseContent(final Cursor cursor) {
final String name = cursor.getString(cursor.getColumnIndex("name"));
final WaypointType type = WaypointType.findById(cursor.getString(cursor.getColumnIndex("type")));
final boolean own = cursor.getInt(cursor.getColumnIndex("own")) != 0;
final Waypoint waypoint = new Waypoint(name, type, own);
waypoint.setVisited(cursor.getInt(cursor.getColumnIndex("visited")) != 0);
waypoint.setId(cursor.getInt(cursor.getColumnIndex("_id")));
waypoint.setGeocode(cursor.getString(cursor.getColumnIndex("geocode")));
waypoint.setPrefix(cursor.getString(cursor.getColumnIndex("prefix")));
waypoint.setLookup(cursor.getString(cursor.getColumnIndex("lookup")));
waypoint.setCoords(getCoords(cursor, cursor.getColumnIndex("latitude"), cursor.getColumnIndex("longitude")));
waypoint.setNote(cursor.getString(cursor.getColumnIndex("note")));
return waypoint;
}
@Nullable
private static List<Image> loadSpoilers(final String geocode) {
if (StringUtils.isBlank(geocode)) {
return null;
}
return queryToColl(dbTableSpoilers,
new String[]{"url", "title", "description"},
"geocode = ?",
new String[]{geocode},
null,
"100",
new LinkedList<Image>(),
new Func1<Cursor, Image>() {
@Override
public Image call(final Cursor cursor) {
return new Image.Builder()
.setUrl(cursor.getString(0))
.setTitle(cursor.getString(1))
.setDescription(cursor.getString(2))
.build();
}
});
}
/**
* Loads the history of previously entered destinations from
* the database. If no destinations exist, an {@link Collections#emptyList()} will be returned.
*
* @return A list of previously entered destinations or an empty list.
*/
@NonNull
public static List<Destination> loadHistoryOfSearchedLocations() {
return queryToColl(dbTableSearchDestinationHistory,
new String[]{"_id", "date", "latitude", "longitude"},
"latitude IS NOT NULL AND longitude IS NOT NULL",
null,
"date DESC",
"100",
new LinkedList<Destination>(),
new Func1<Cursor, Destination>() {
@Override
public Destination call(final Cursor cursor) {
return new Destination(cursor.getLong(0), cursor.getLong(1), getCoords(cursor, 2, 3));
}
});
}
public static boolean clearSearchedDestinations() {
init();
database.beginTransaction();
try {
database.delete(dbTableSearchDestinationHistory, null, null);
database.setTransactionSuccessful();
return true;
} catch (final Exception e) {
Log.e("Unable to clear searched destinations", e);
} finally {
database.endTransaction();
}
return false;
}
/**
* @return an immutable, non null list of logs
*/
@NonNull
public static List<LogEntry> loadLogs(final String geocode) {
final List<LogEntry> logs = new ArrayList<>();
if (StringUtils.isBlank(geocode)) {
return logs;
}
init();
final Cursor cursor = database.rawQuery(
// 0 1 2 3 4 5 6 7 8 9 10 11
"SELECT cg_logs._id AS cg_logs_id, type, author, log, date, found, friend, " + dbTableLogImages + "._id as cg_logImages_id, log_id, title, url, description"
+ " FROM " + dbTableLogs + " LEFT OUTER JOIN " + dbTableLogImages
+ " ON ( cg_logs._id = log_id ) WHERE geocode = ? ORDER BY date DESC, cg_logs._id ASC", new String[]{geocode});
LogEntry.Builder log = null;
while (cursor.moveToNext() && logs.size() < 100) {
if (log == null || log.getId() != cursor.getInt(0)) {
// Start of a new log entry group (we may have several entries if the log has several images).
if (log != null) {
logs.add(log.build());
}
log = new LogEntry.Builder()
.setAuthor(cursor.getString(2))
.setDate(cursor.getLong(4))
.setLogType(LogType.getById(cursor.getInt(1)))
.setLog(cursor.getString(3))
.setId(cursor.getInt(0))
.setFound(cursor.getInt(5))
.setFriend(cursor.getInt(6) == 1);
if (!cursor.isNull(7)) {
log.addLogImage(new Image.Builder().setUrl(cursor.getString(10)).setTitle(cursor.getString(9)).setDescription(cursor.getString(11)).build());
}
} else {
// We cannot get several lines for the same log entry if it does not contain an image.
log.addLogImage(new Image.Builder().setUrl(cursor.getString(10)).setTitle(cursor.getString(9)).setDescription(cursor.getString(11)).build());
}
}
if (log != null) {
logs.add(log.build());
}
cursor.close();
return Collections.unmodifiableList(logs);
}
@Nullable
public static Map<LogType, Integer> loadLogCounts(final String geocode) {
if (StringUtils.isBlank(geocode)) {
return null;
}
init();
final Map<LogType, Integer> logCounts = new EnumMap<>(LogType.class);
final Cursor cursor = database.query(
dbTableLogCount,
new String[]{"type", "count"},
"geocode = ?",
new String[]{geocode},
null,
null,
null,
"100");
while (cursor.moveToNext()) {
logCounts.put(LogType.getById(cursor.getInt(0)), cursor.getInt(1));
}
cursor.close();
return logCounts;
}
@Nullable
private static List<Trackable> loadInventory(final String geocode) {
if (StringUtils.isBlank(geocode)) {
return null;
}
init();
final List<Trackable> trackables = new ArrayList<>();
final Cursor cursor = database.query(
dbTableTrackables,
new String[]{"_id", "updated", "tbcode", "guid", "title", "owner", "released", "goal", "description"},
"geocode = ?",
new String[]{geocode},
null,
null,
"title COLLATE NOCASE ASC",
"100");
while (cursor.moveToNext()) {
trackables.add(createTrackableFromDatabaseContent(cursor));
}
cursor.close();
return trackables;
}
@Nullable
public static Trackable loadTrackable(final String geocode) {
if (StringUtils.isBlank(geocode)) {
return null;
}
init();
final Cursor cursor = database.query(
dbTableTrackables,
new String[]{"updated", "tbcode", "guid", "title", "owner", "released", "goal", "description"},
"tbcode = ?",
new String[]{geocode},
null,
null,
null,
"1");
final Trackable trackable = cursor.moveToFirst() ? createTrackableFromDatabaseContent(cursor) : null;
cursor.close();
return trackable;
}
@NonNull
private static Trackable createTrackableFromDatabaseContent(final Cursor cursor) {
final Trackable trackable = new Trackable();
trackable.setGeocode(cursor.getString(cursor.getColumnIndex("tbcode")));
trackable.setGuid(cursor.getString(cursor.getColumnIndex("guid")));
trackable.setName(cursor.getString(cursor.getColumnIndex("title")));
trackable.setOwner(cursor.getString(cursor.getColumnIndex("owner")));
final String released = cursor.getString(cursor.getColumnIndex("released"));
if (released != null) {
try {
final long releaseMilliSeconds = Long.parseLong(released);
trackable.setReleased(new Date(releaseMilliSeconds));
} catch (final NumberFormatException e) {
Log.e("createTrackableFromDatabaseContent", e);
}
}
trackable.setGoal(cursor.getString(cursor.getColumnIndex("goal")));
trackable.setDetails(cursor.getString(cursor.getColumnIndex("description")));
trackable.setLogs(loadLogs(trackable.getGeocode()));
return trackable;
}
/**
* Number of caches stored for a given type and/or list
*
*/
public static int getAllStoredCachesCount(final CacheType cacheType, final int list) {
if (cacheType == null) {
throw new IllegalArgumentException("cacheType must not be null");
}
if (list <= 0) {
throw new IllegalArgumentException("list must be > 0");
}
init();
try {
final SQLiteStatement compiledStmnt;
synchronized (PreparedStatement.COUNT_TYPE_LIST) {
// All the statements here are used only once and are protected through the current synchronized block
if (list == PseudoList.ALL_LIST.id) {
if (cacheType == CacheType.ALL) {
compiledStmnt = PreparedStatement.COUNT_ALL_TYPES_ALL_LIST.getStatement();
} else {
compiledStmnt = PreparedStatement.COUNT_TYPE_ALL_LIST.getStatement();
compiledStmnt.bindString(1, cacheType.id);
}
} else if (cacheType == CacheType.ALL) {
compiledStmnt = PreparedStatement.COUNT_ALL_TYPES_LIST.getStatement();
compiledStmnt.bindLong(1, list);
} else {
compiledStmnt = PreparedStatement.COUNT_TYPE_LIST.getStatement();
compiledStmnt.bindString(1, cacheType.id);
compiledStmnt.bindLong(1, list);
}
return (int) compiledStmnt.simpleQueryForLong();
}
} catch (final Exception e) {
Log.e("DataStore.loadAllStoredCachesCount", e);
}
return 0;
}
public static int getAllHistoryCachesCount() {
init();
try {
return (int) PreparedStatement.HISTORY_COUNT.simpleQueryForLong();
} catch (final Exception e) {
Log.e("DataStore.getAllHistoricCachesCount", e);
}
return 0;
}
@NonNull
private static<T, U extends Collection<? super T>> U queryToColl(@NonNull final String table,
final String[] columns,
final String selection,
final String[] selectionArgs,
final String orderBy,
final String limit,
final U result,
final Func1<? super Cursor, ? extends T> func) {
init();
final Cursor cursor = database.query(table, columns, selection, selectionArgs, null, null, orderBy, limit);
return cursorToColl(cursor, result, func);
}
private static <T, U extends Collection<? super T>> U cursorToColl(final Cursor cursor, final U result, final Func1<? super Cursor, ? extends T> func) {
try {
while (cursor.moveToNext()) {
result.add(func.call(cursor));
}
return result;
} finally {
cursor.close();
}
}
/**
* Return a batch of stored geocodes.
*
* @param coords
* the current coordinates to sort by distance, or null to sort by geocode
* @return a non-null set of geocodes
*/
@NonNull
private static Set<String> loadBatchOfStoredGeocodes(final Geopoint coords, final CacheType cacheType, final int listId) {
if (cacheType == null) {
throw new IllegalArgumentException("cacheType must not be null");
}
final StringBuilder selection = new StringBuilder();
String[] selectionArgs = null;
if (cacheType != CacheType.ALL) {
selection.append(" type = ? AND");
selectionArgs = new String[] { String.valueOf(cacheType.id) };
}
selection.append(" geocode IN (SELECT geocode FROM ");
selection.append(dbTableCachesLists);
selection.append(" WHERE list_id ");
selection.append(listId != PseudoList.ALL_LIST.id ? "=" + Math.max(listId, 1) : ">= " + StoredList.STANDARD_LIST_ID);
selection.append(')');
try {
if (coords != null) {
return queryToColl(dbTableCaches,
new String[]{"geocode", "(ABS(latitude-" + String.format((Locale) null, "%.6f", coords.getLatitude()) +
") + ABS(longitude-" + String.format((Locale) null, "%.6f", coords.getLongitude()) + ")) AS dif"},
selection.toString(),
selectionArgs,
"dif",
null,
new HashSet<String>(),
GET_STRING_0);
}
return queryToColl(dbTableCaches,
new String[] { "geocode" },
selection.toString(),
selectionArgs,
"geocode",
null,
new HashSet<String>(),
GET_STRING_0);
} catch (final Exception e) {
Log.e("DataStore.loadBatchOfStoredGeocodes", e);
return Collections.emptySet();
}
}
@NonNull
private static Set<String> loadBatchOfHistoricGeocodes(final CacheType cacheType) {
final StringBuilder selection = new StringBuilder();
String[] selectionArgs = null;
if (cacheType != CacheType.ALL) {
selection.append(" type = ? AND ");
selectionArgs = new String[] { String.valueOf(cacheType.id) };
}
selection.append(" ( visiteddate > 0 OR geocode IN (SELECT geocode FROM " + dbTableLogsOffline + ") )");
try {
final Cursor cursor = database.rawQuery("SELECT geocode FROM " + dbTableCaches + " WHERE " + selection, selectionArgs);
return cursorToColl(cursor, new HashSet<String>(), GET_STRING_0);
} catch (final Exception e) {
Log.e("DataStore.loadBatchOfHistoricGeocodes", e);
}
return Collections.emptySet();
}
/** Retrieve all stored caches from DB */
@NonNull
public static SearchResult loadCachedInViewport(final Viewport viewport, final CacheType cacheType) {
return loadInViewport(false, viewport, cacheType);
}
/** Retrieve stored caches from DB with listId >= 1 */
@NonNull
public static SearchResult loadStoredInViewport(final Viewport viewport, final CacheType cacheType) {
return loadInViewport(true, viewport, cacheType);
}
/**
* Loads the geocodes of caches in a viewport from CacheCache and/or Database
*
* @param stored {@code true} to query caches stored in the database, {@code false} to also use the CacheCache
* @param viewport the viewport defining the area to scan
* @param cacheType the cache type
* @return the matching caches
*/
@NonNull
private static SearchResult loadInViewport(final boolean stored, final Viewport viewport, final CacheType cacheType) {
final Set<String> geocodes = new HashSet<>();
// if not stored only, get codes from CacheCache as well
if (!stored) {
geocodes.addAll(cacheCache.getInViewport(viewport, cacheType));
}
// viewport limitation
final StringBuilder selection = buildCoordinateWhere(dbTableCaches, viewport);
// cacheType limitation
String[] selectionArgs = null;
if (cacheType != CacheType.ALL) {
selection.append(" AND type = ?");
selectionArgs = new String[] { String.valueOf(cacheType.id) };
}
// offline caches only
if (stored) {
selection.append(" AND geocode IN (SELECT geocode FROM " + dbTableCachesLists + " WHERE list_id >= " + StoredList.STANDARD_LIST_ID + ")");
}
try {
return new SearchResult(queryToColl(dbTableCaches,
new String[]{"geocode"},
selection.toString(),
selectionArgs,
null,
"500",
geocodes,
GET_STRING_0));
} catch (final Exception e) {
Log.e("DataStore.loadInViewport", e);
}
return new SearchResult();
}
/**
* Remove caches which are not on any list in the background. Once it has been executed once it will not do anything.
* This must be called from the UI thread to ensure synchronization of an internal variable.
*/
public static void cleanIfNeeded(final Context context) {
if (databaseCleaned) {
return;
}
databaseCleaned = true;
Schedulers.io().scheduleDirect(new Runnable() {
@Override
public void run() {
Log.d("Database clean: started");
try {
final int version = Version.getVersionCode(context);
final Set<String> geocodes = new HashSet<>();
if (version != Settings.getVersion()) {
queryToColl(dbTableCaches,
new String[]{"geocode"},
"geocode NOT IN (SELECT DISTINCT (geocode) FROM " + dbTableCachesLists + ")",
null,
null,
null,
geocodes,
GET_STRING_0);
} else {
final long timestamp = System.currentTimeMillis() - DAYS_AFTER_CACHE_IS_DELETED;
final String timestampString = Long.toString(timestamp);
queryToColl(dbTableCaches,
new String[]{"geocode"},
"detailed < ? AND detailedupdate < ? AND visiteddate < ? AND geocode NOT IN (SELECT DISTINCT (geocode) FROM " + dbTableCachesLists + ")",
new String[]{timestampString, timestampString, timestampString},
null,
null,
geocodes,
GET_STRING_0);
}
final Set<String> withoutOfflineLogs = exceptCachesWithOfflineLog(geocodes);
Log.d("Database clean: removing " + withoutOfflineLogs.size() + " geocaches");
removeCaches(withoutOfflineLogs, LoadFlags.REMOVE_ALL);
// remove non-existing caches from lists
Log.d("Database clean: removing non-existing caches from lists");
database.delete(dbTableCachesLists, "geocode NOT IN (SELECT geocode FROM " + dbTableCaches + ")", null);
// Remove the obsolete "_others" directory where the user avatar used to be stored.
FileUtils.deleteDirectory(LocalStorage.getStorageDir("_others"));
if (version > -1) {
Settings.setVersion(version);
}
} catch (final Exception e) {
Log.w("DataStore.clean", e);
}
Log.d("Database clean: finished");
}
});
}
/**
* remove all geocodes from the given list of geocodes where an offline log exists
*
*/
@NonNull
private static Set<String> exceptCachesWithOfflineLog(@NonNull final Set<String> geocodes) {
if (geocodes.isEmpty()) {
return geocodes;
}
final List<String> geocodesWithOfflineLog = queryToColl(dbTableLogsOffline,
new String[] { "geocode" },
null,
null,
null,
null,
new LinkedList<String>(),
GET_STRING_0);
geocodes.removeAll(geocodesWithOfflineLog);
return geocodes;
}
public static void removeAllFromCache() {
// clean up CacheCache
cacheCache.removeAllFromCache();
}
public static void removeCache(final String geocode, final EnumSet<LoadFlags.RemoveFlag> removeFlags) {
removeCaches(Collections.singleton(geocode), removeFlags);
}
/**
* Drop caches from the tables they are stored into, as well as the cache files
*
* @param geocodes
* list of geocodes to drop from cache
*/
public static void removeCaches(final Set<String> geocodes, final EnumSet<LoadFlags.RemoveFlag> removeFlags) {
if (CollectionUtils.isEmpty(geocodes)) {
return;
}
init();
if (removeFlags.contains(RemoveFlag.CACHE)) {
for (final String geocode : geocodes) {
cacheCache.removeCacheFromCache(geocode);
}
}
if (removeFlags.contains(RemoveFlag.DB)) {
// Drop caches from the database
final ArrayList<String> quotedGeocodes = new ArrayList<>(geocodes.size());
for (final String geocode : geocodes) {
quotedGeocodes.add(DatabaseUtils.sqlEscapeString(geocode));
}
final String geocodeList = StringUtils.join(quotedGeocodes.toArray(), ',');
final String baseWhereClause = "geocode IN (" + geocodeList + ")";
database.beginTransaction();
try {
database.delete(dbTableCaches, baseWhereClause, null);
database.delete(dbTableAttributes, baseWhereClause, null);
database.delete(dbTableSpoilers, baseWhereClause, null);
database.delete(dbTableLogImages, "log_id IN (SELECT _id FROM " + dbTableLogs + " WHERE " + baseWhereClause + ")", null);
database.delete(dbTableLogs, baseWhereClause, null);
database.delete(dbTableLogCount, baseWhereClause, null);
database.delete(dbTableLogsOffline, baseWhereClause, null);
String wayPointClause = baseWhereClause;
if (!removeFlags.contains(RemoveFlag.OWN_WAYPOINTS_ONLY_FOR_TESTING)) {
wayPointClause += " AND type <> 'own'";
}
database.delete(dbTableWaypoints, wayPointClause, null);
database.delete(dbTableTrackables, baseWhereClause, null);
database.setTransactionSuccessful();
} finally {
database.endTransaction();
}
// Delete cache directories
for (final String geocode : geocodes) {
FileUtils.deleteDirectory(LocalStorage.getStorageDir(geocode));
}
}
}
public static boolean saveLogOffline(final String geocode, final Date date, final LogType type, final String log) {
if (StringUtils.isBlank(geocode)) {
Log.e("DataStore.saveLogOffline: cannot log a blank geocode");
return false;
}
if (type == LogType.UNKNOWN && StringUtils.isBlank(log)) {
Log.e("DataStore.saveLogOffline: cannot log an unknown log type and no message");
return false;
}
init();
final ContentValues values = new ContentValues();
values.put("geocode", geocode);
values.put("updated", System.currentTimeMillis());
values.put("type", type.id);
values.put("log", log);
values.put("date", date.getTime());
if (hasLogOffline(geocode)) {
final int rows = database.update(dbTableLogsOffline, values, "geocode = ?", new String[] { geocode });
return rows > 0;
}
final long id = database.insert(dbTableLogsOffline, null, values);
return id != -1;
}
@Nullable
public static LogEntry loadLogOffline(final String geocode) {
if (StringUtils.isBlank(geocode)) {
return null;
}
init();
final Cursor cursor = database.query(
dbTableLogsOffline,
new String[]{"_id", "type", "log", "date"},
"geocode = ?",
new String[]{geocode},
null,
null,
"_id DESC",
"1");
LogEntry log = null;
if (cursor.moveToFirst()) {
log = new LogEntry.Builder()
.setDate(cursor.getLong(3))
.setLogType(LogType.getById(cursor.getInt(1)))
.setLog(cursor.getString(2))
.setId(cursor.getInt(0))
.build();
}
cursor.close();
return log;
}
public static void clearLogOffline(final String geocode) {
if (StringUtils.isBlank(geocode)) {
return;
}
init();
final String[] geocodeWhereArgs = {geocode};
database.delete(dbTableLogsOffline, "geocode = ?", geocodeWhereArgs);
}
public static void clearLogsOffline(final Collection<Geocache> caches) {
if (CollectionUtils.isEmpty(caches)) {
return;
}
init();
for (final Geocache cache : caches) {
cache.setLogOffline(false);
}
final String geocodes = whereGeocodeIn(Geocache.getGeocodes(caches)).toString();
database.execSQL(String.format("DELETE FROM %s WHERE %s", dbTableLogsOffline, geocodes));
}
public static boolean hasLogOffline(final String geocode) {
if (StringUtils.isBlank(geocode)) {
return false;
}
init();
try {
final SQLiteStatement logCount = PreparedStatement.LOG_COUNT_OF_GEOCODE.getStatement();
synchronized (logCount) {
logCount.bindString(1, geocode);
return logCount.simpleQueryForLong() > 0;
}
} catch (final Exception e) {
Log.e("DataStore.hasLogOffline", e);
}
return false;
}
private static void setVisitDate(final Collection<String> geocodes, final long visitedDate) {
if (geocodes.isEmpty()) {
return;
}
init();
database.beginTransaction();
try {
final SQLiteStatement setVisit = PreparedStatement.UPDATE_VISIT_DATE.getStatement();
for (final String geocode : geocodes) {
setVisit.bindLong(1, visitedDate);
setVisit.bindString(2, geocode);
setVisit.execute();
}
database.setTransactionSuccessful();
} finally {
database.endTransaction();
}
}
@NonNull
public static List<StoredList> getLists() {
init();
final Resources res = CgeoApplication.getInstance().getResources();
final List<StoredList> lists = new ArrayList<>();
lists.add(new StoredList(StoredList.STANDARD_LIST_ID, res.getString(R.string.list_inbox), (int) PreparedStatement.COUNT_CACHES_ON_STANDARD_LIST.simpleQueryForLong()));
try {
final String query = "SELECT l._id AS _id, l.title AS title, COUNT(c.geocode) AS count" +
" FROM " + dbTableLists + " l LEFT OUTER JOIN " + dbTableCachesLists + " c" +
" ON l._id + " + customListIdOffset + " = c.list_id" +
" GROUP BY l._id" +
" ORDER BY l.title COLLATE NOCASE ASC";
lists.addAll(getListsFromCursor(database.rawQuery(query, null)));
} catch (final Exception e) {
Log.e("DataStore.readLists", e);
}
return lists;
}
@NonNull
private static List<StoredList> getListsFromCursor(final Cursor cursor) {
final int indexId = cursor.getColumnIndex("_id");
final int indexTitle = cursor.getColumnIndex("title");
final int indexCount = cursor.getColumnIndex("count");
return cursorToColl(cursor, new ArrayList<StoredList>(), new Func1<Cursor, StoredList>() {
@Override
public StoredList call(final Cursor cursor) {
final int count = indexCount != -1 ? cursor.getInt(indexCount) : 0;
return new StoredList(cursor.getInt(indexId) + customListIdOffset, cursor.getString(indexTitle), count);
}
});
}
@NonNull
public static StoredList getList(final int id) {
init();
if (id >= customListIdOffset) {
final Cursor cursor = database.query(
dbTableLists,
new String[]{"_id", "title"},
"_id = ? ",
new String[] { String.valueOf(id - customListIdOffset) },
null,
null,
null);
final List<StoredList> lists = getListsFromCursor(cursor);
if (!lists.isEmpty()) {
return lists.get(0);
}
}
final Resources res = CgeoApplication.getInstance().getResources();
if (id == PseudoList.ALL_LIST.id) {
return new StoredList(PseudoList.ALL_LIST.id, res.getString(R.string.list_all_lists), getAllCachesCount());
}
// fall back to standard list in case of invalid list id
return new StoredList(StoredList.STANDARD_LIST_ID, res.getString(R.string.list_inbox), (int) PreparedStatement.COUNT_CACHES_ON_STANDARD_LIST.simpleQueryForLong());
}
public static int getAllCachesCount() {
return (int) PreparedStatement.COUNT_ALL_CACHES.simpleQueryForLong();
}
/**
* Count all caches in the background.
*
* @return a single containing a unique element if the caches could be counted, or an error otherwise
*/
public static Single<Integer> getAllCachesCountObservable() {
return allCachesCountObservable;
}
/**
* Create a new list
*
* @param name
* Name
* @return new listId
*/
public static int createList(final String name) {
int id = -1;
if (StringUtils.isBlank(name)) {
return id;
}
init();
database.beginTransaction();
try {
final ContentValues values = new ContentValues();
values.put("title", name);
values.put("updated", System.currentTimeMillis());
id = (int) database.insert(dbTableLists, null, values);
database.setTransactionSuccessful();
} finally {
database.endTransaction();
}
return id >= 0 ? id + customListIdOffset : -1;
}
/**
* @param listId
* List to change
* @param name
* New name of list
* @return Number of lists changed
*/
public static int renameList(final int listId, final String name) {
if (StringUtils.isBlank(name) || listId == StoredList.STANDARD_LIST_ID) {
return 0;
}
init();
database.beginTransaction();
int count = 0;
try {
final ContentValues values = new ContentValues();
values.put("title", name);
values.put("updated", System.currentTimeMillis());
count = database.update(dbTableLists, values, "_id = " + (listId - customListIdOffset), null);
database.setTransactionSuccessful();
} finally {
database.endTransaction();
}
return count;
}
/**
* Remove a list. Caches in the list are moved to the standard list.
*
* @return true if the list got deleted, false else
*/
public static boolean removeList(final int listId) {
if (listId < customListIdOffset) {
return false;
}
init();
database.beginTransaction();
boolean status = false;
try {
final int cnt = database.delete(dbTableLists, "_id = " + (listId - customListIdOffset), null);
if (cnt > 0) {
// move caches from deleted list to standard list
final SQLiteStatement moveToStandard = PreparedStatement.MOVE_TO_STANDARD_LIST.getStatement();
moveToStandard.bindLong(1, listId);
moveToStandard.execute();
final SQLiteStatement removeAllFromList = PreparedStatement.REMOVE_ALL_FROM_LIST.getStatement();
removeAllFromList.bindLong(1, listId);
removeAllFromList.execute();
status = true;
}
database.setTransactionSuccessful();
} finally {
database.endTransaction();
}
return status;
}
public static void moveToList(final Collection<Geocache> caches, final int oldListId, final int newListId) {
if (caches.isEmpty()) {
return;
}
final AbstractList list = AbstractList.getListById(newListId);
if (list == null) {
return;
}
if (!list.isConcrete()) {
return;
}
init();
final SQLiteStatement remove = PreparedStatement.REMOVE_FROM_LIST.getStatement();
final SQLiteStatement add = PreparedStatement.ADD_TO_LIST.getStatement();
database.beginTransaction();
try {
for (final Geocache cache : caches) {
remove.bindLong(1, oldListId);
remove.bindString(2, cache.getGeocode());
remove.execute();
add.bindLong(1, newListId);
add.bindString(2, cache.getGeocode());
add.execute();
cache.getLists().remove(oldListId);
cache.getLists().add(newListId);
}
database.setTransactionSuccessful();
} finally {
database.endTransaction();
}
}
public static void removeFromList(final Collection<Geocache> caches, final int oldListId) {
init();
final SQLiteStatement remove = PreparedStatement.REMOVE_FROM_LIST.getStatement();
database.beginTransaction();
try {
for (final Geocache cache : caches) {
remove.bindLong(1, oldListId);
remove.bindString(2, cache.getGeocode());
remove.execute();
cache.getLists().remove(oldListId);
}
database.setTransactionSuccessful();
} finally {
database.endTransaction();
}
}
public static void addToList(final Collection<Geocache> caches, final int listId) {
if (caches.isEmpty()) {
return;
}
final AbstractList list = AbstractList.getListById(listId);
if (list == null) {
return;
}
if (!list.isConcrete()) {
return;
}
init();
final SQLiteStatement add = PreparedStatement.ADD_TO_LIST.getStatement();
database.beginTransaction();
try {
for (final Geocache cache : caches) {
add.bindLong(1, listId);
add.bindString(2, cache.getGeocode());
add.execute();
cache.getLists().add(listId);
}
database.setTransactionSuccessful();
} finally {
database.endTransaction();
}
}
public static void saveLists(final Collection<Geocache> caches, final Set<Integer> listIds) {
if (caches.isEmpty()) {
return;
}
init();
final SQLiteStatement add = PreparedStatement.ADD_TO_LIST.getStatement();
final SQLiteStatement remove = PreparedStatement.REMOVE_FROM_ALL_LISTS.getStatement();
database.beginTransaction();
try {
for (final Geocache cache : caches) {
remove.bindString(1, cache.getGeocode());
remove.execute();
cache.getLists().clear();
for (final Integer listId : listIds) {
final AbstractList list = AbstractList.getListById(listId);
if (list == null) {
return;
}
if (!list.isConcrete()) {
return;
}
add.bindLong(1, listId);
add.bindString(2, cache.getGeocode());
add.execute();
cache.getLists().add(listId);
}
}
database.setTransactionSuccessful();
} finally {
database.endTransaction();
}
}
public static void addToLists(final Collection<Geocache> caches, final Map<String, Set<Integer>> cachesLists) {
if (caches.isEmpty() || cachesLists.isEmpty()) {
return;
}
init();
final SQLiteStatement add = PreparedStatement.ADD_TO_LIST.getStatement();
database.beginTransaction();
try {
for (final Geocache cache : caches) {
final Set<Integer> lists = cachesLists.get(cache.getGeocode());
if (lists.isEmpty()) {
continue;
}
for (final Integer listId : lists) {
add.bindLong(1, listId);
add.bindString(2, cache.getGeocode());
add.execute();
}
}
database.setTransactionSuccessful();
} finally {
database.endTransaction();
}
}
public static boolean isInitialized() {
return database != null;
}
public static boolean removeSearchedDestination(final Destination destination) {
if (destination == null) {
return false;
}
init();
database.beginTransaction();
try {
database.delete(dbTableSearchDestinationHistory, "_id = " + destination.getId(), null);
database.setTransactionSuccessful();
return true;
} catch (final Exception e) {
Log.e("Unable to remove searched destination", e);
} finally {
database.endTransaction();
}
return false;
}
/**
* Load the lazily initialized fields of a cache and return them as partial cache (all other fields unset).
*
*/
@NonNull
public static Geocache loadCacheTexts(final String geocode) {
final Geocache partial = new Geocache();
// in case of database issues, we still need to return a result to avoid endless loops
partial.setDescription(StringUtils.EMPTY);
partial.setShortDescription(StringUtils.EMPTY);
partial.setHint(StringUtils.EMPTY);
partial.setLocation(StringUtils.EMPTY);
init();
try {
final Cursor cursor = database.query(
dbTableCaches,
new String[] { "description", "shortdesc", "hint", "location" },
"geocode = ?",
new String[] { geocode },
null,
null,
null,
"1");
if (cursor.moveToFirst()) {
partial.setDescription(StringUtils.defaultString(cursor.getString(0)));
partial.setShortDescription(StringUtils.defaultString(cursor.getString(1)));
partial.setHint(StringUtils.defaultString(cursor.getString(2)));
partial.setLocation(StringUtils.defaultString(cursor.getString(3)));
}
cursor.close();
} catch (final SQLiteDoneException ignored) {
// Do nothing, it only means we have no information on the cache
} catch (final Exception e) {
Log.e("DataStore.getCacheDescription", e);
}
return partial;
}
/**
* checks if this is a newly created database
*/
public static boolean isNewlyCreatedDatebase() {
return newlyCreatedDatabase;
}
/**
* resets flag for newly created database to avoid asking the user multiple times
*/
public static void resetNewlyCreatedDatabase() {
newlyCreatedDatabase = false;
}
/**
* Creates the WHERE clause for matching multiple geocodes. This automatically converts all given codes to
* UPPERCASE.
*/
@NonNull
private static StringBuilder whereGeocodeIn(final Collection<String> geocodes) {
final StringBuilder whereExpr = new StringBuilder("geocode IN (");
final Iterator<String> iterator = geocodes.iterator();
while (true) {
DatabaseUtils.appendEscapedSQLString(whereExpr, StringUtils.upperCase(iterator.next()));
if (!iterator.hasNext()) {
break;
}
whereExpr.append(',');
}
return whereExpr.append(')');
}
/**
* Loads all Waypoints in the coordinate rectangle.
*
*/
@NonNull
public static Set<Waypoint> loadWaypoints(final Viewport viewport, final boolean excludeMine, final boolean excludeDisabled, final CacheType type) {
final StringBuilder where = buildCoordinateWhere(dbTableWaypoints, viewport);
if (excludeMine) {
where.append(" AND ").append(dbTableCaches).append(".found == 0");
}
if (excludeDisabled) {
where.append(" AND ").append(dbTableCaches).append(".disabled == 0");
where.append(" AND ").append(dbTableCaches).append(".archived == 0");
}
if (type != CacheType.ALL) {
where.append(" AND ").append(dbTableCaches).append(".type == '").append(type.id).append('\'');
}
final StringBuilder query = new StringBuilder("SELECT ");
for (int i = 0; i < WAYPOINT_COLUMNS.length; i++) {
query.append(i > 0 ? ", " : "").append(dbTableWaypoints).append('.').append(WAYPOINT_COLUMNS[i]).append(' ');
}
query.append(" FROM ").append(dbTableWaypoints).append(", ").append(dbTableCaches).append(" WHERE ").append(dbTableWaypoints)
.append(".geocode == ").append(dbTableCaches).append(".geocode AND ").append(where)
.append(" LIMIT " + (Settings.SHOW_WP_THRESHOLD_MAX * 2)); // Hardcoded limit to avoid memory overflow
return cursorToColl(database.rawQuery(query.toString(), null), new HashSet<Waypoint>(), new Func1<Cursor, Waypoint>() {
@Override
public Waypoint call(final Cursor cursor) {
return createWaypointFromDatabaseContent(cursor);
}
});
}
public static void saveChangedCache(final Geocache cache) {
saveCache(cache, cache.inDatabase() ? LoadFlags.SAVE_ALL : EnumSet.of(SaveFlag.CACHE));
}
private enum PreparedStatement {
HISTORY_COUNT("SELECT COUNT(*) FROM " + dbTableCaches + " WHERE visiteddate > 0 OR geocode IN (SELECT geocode FROM " + dbTableLogsOffline + ")"),
MOVE_TO_STANDARD_LIST("UPDATE " + dbTableCachesLists + " SET list_id = " + StoredList.STANDARD_LIST_ID + " WHERE list_id = ? AND geocode NOT IN (SELECT DISTINCT (geocode) FROM " + dbTableCachesLists + " WHERE list_id = " + StoredList.STANDARD_LIST_ID + ")"),
REMOVE_FROM_LIST("DELETE FROM " + dbTableCachesLists + " WHERE list_id = ? AND geocode = ?"),
REMOVE_FROM_ALL_LISTS("DELETE FROM " + dbTableCachesLists + " WHERE geocode = ?"),
REMOVE_ALL_FROM_LIST("DELETE FROM " + dbTableCachesLists + " WHERE list_id = ?"),
UPDATE_VISIT_DATE("UPDATE " + dbTableCaches + " SET visiteddate = ? WHERE geocode = ?"),
INSERT_LOG_IMAGE("INSERT INTO " + dbTableLogImages + " (log_id, title, url, description) VALUES (?, ?, ?, ?)"),
INSERT_LOG_COUNTS("INSERT INTO " + dbTableLogCount + " (geocode, updated, type, count) VALUES (?, ?, ?, ?)"),
INSERT_SPOILER("INSERT INTO " + dbTableSpoilers + " (geocode, updated, url, title, description) VALUES (?, ?, ?, ?, ?)"),
REMOVE_SPOILERS("DELETE FROM " + dbTableSpoilers + " WHERE geocode = ?"),
LOG_COUNT_OF_GEOCODE("SELECT COUNT(_id) FROM " + dbTableLogsOffline + " WHERE geocode = ?"),
COUNT_CACHES_ON_STANDARD_LIST("SELECT COUNT(geocode) FROM " + dbTableCachesLists + " WHERE list_id = " + StoredList.STANDARD_LIST_ID),
COUNT_ALL_CACHES("SELECT COUNT(DISTINCT(geocode)) FROM " + dbTableCachesLists + " WHERE list_id >= " + StoredList.STANDARD_LIST_ID),
INSERT_LOG("INSERT INTO " + dbTableLogs + " (geocode, updated, type, author, log, date, found, friend) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"),
INSERT_ATTRIBUTE("INSERT INTO " + dbTableAttributes + " (geocode, updated, attribute) VALUES (?, ?, ?)"),
ADD_TO_LIST("INSERT OR REPLACE INTO " + dbTableCachesLists + " (list_id, geocode) VALUES (?, ?)"),
GEOCODE_OFFLINE("SELECT COUNT(list_id) FROM " + dbTableCachesLists + " WHERE geocode = ? AND list_id != " + StoredList.TEMPORARY_LIST.id),
GUID_OFFLINE("SELECT COUNT(list_id) FROM " + dbTableCachesLists + " WHERE geocode = (SELECT geocode FROM " + dbTableCaches + " WHERE guid = ?) AND list_id != " + StoredList.TEMPORARY_LIST.id),
GEOCODE_OF_GUID("SELECT geocode FROM " + dbTableCaches + " WHERE guid = ?"),
GEOCODE_FROM_TITLE("SELECT geocode FROM " + dbTableCaches + " WHERE name = ?"),
INSERT_SEARCH_DESTINATION("INSERT INTO " + dbTableSearchDestinationHistory + " (date, latitude, longitude) VALUES (?, ?, ?)"),
COUNT_TYPE_ALL_LIST("SELECT COUNT(c._id) FROM " + dbTableCaches + " c, " + dbTableCachesLists + " l WHERE c.type = ? AND c.geocode = l.geocode AND l.list_id > 0"), // See use of COUNT_TYPE_LIST for synchronization
COUNT_ALL_TYPES_ALL_LIST("SELECT COUNT(c._id) FROM " + dbTableCaches + " c, " + dbTableCachesLists + " l WHERE c.geocode = l.geocode AND l.list_id > 0"), // See use of COUNT_TYPE_LIST for synchronization
COUNT_TYPE_LIST("SELECT COUNT(c._id) FROM " + dbTableCaches + " c, " + dbTableCachesLists + " l WHERE c.type = ? AND c.geocode = l.geocode AND l.list_id = ?"),
COUNT_ALL_TYPES_LIST("SELECT COUNT(c._id) FROM " + dbTableCaches + " c, " + dbTableCachesLists + " l WHERE c.geocode = l.geocode AND l.list_id = ?"), // See use of COUNT_TYPE_LIST for synchronization
CHECK_IF_PRESENT("SELECT COUNT(*) FROM " + dbTableCaches + " WHERE geocode = ?");
private static final List<PreparedStatement> statements = new ArrayList<>();
@Nullable
private volatile SQLiteStatement statement = null; // initialized lazily
final String query;
PreparedStatement(final String query) {
this.query = query;
}
public long simpleQueryForLong() {
return getStatement().simpleQueryForLong();
}
private SQLiteStatement getStatement() {
if (statement == null) {
synchronized (statements) {
if (statement == null) {
init();
statement = database.compileStatement(query);
statements.add(this);
}
}
}
return statement;
}
private static void clearPreparedStatements() {
for (final PreparedStatement preparedStatement : statements) {
final SQLiteStatement statement = preparedStatement.statement;
if (statement != null) {
statement.close();
preparedStatement.statement = null;
}
}
statements.clear();
}
}
public static void saveVisitDate(final String geocode, final long visitedDate) {
setVisitDate(Collections.singletonList(geocode), visitedDate);
}
public static Map<String, Set<Integer>> markDropped(final Collection<Geocache> caches) {
final SQLiteStatement remove = PreparedStatement.REMOVE_FROM_ALL_LISTS.getStatement();
final Map<String, Set<Integer>> oldLists = new HashMap<>();
database.beginTransaction();
try {
final Set<String> geocodes = new HashSet<>(caches.size());
for (final Geocache cache : caches) {
oldLists.put(cache.getGeocode(), loadLists(cache.getGeocode()));
remove.bindString(1, cache.getGeocode());
remove.execute();
geocodes.add(cache.getGeocode());
cache.getLists().clear();
}
clearVisitDate(geocodes);
clearLogsOffline(caches);
database.setTransactionSuccessful();
} finally {
database.endTransaction();
}
return oldLists;
}
@Nullable
public static Viewport getBounds(final String geocode) {
if (geocode == null) {
return null;
}
return getBounds(Collections.singleton(geocode));
}
public static void clearVisitDate(final Collection<String> selected) {
setVisitDate(selected, 0);
}
@NonNull
public static SearchResult getBatchOfStoredCaches(final Geopoint coords, final CacheType cacheType, final int listId) {
final Set<String> geocodes = loadBatchOfStoredGeocodes(coords, cacheType, listId);
return new SearchResult(geocodes, getAllStoredCachesCount(cacheType, listId));
}
@NonNull
public static SearchResult getHistoryOfCaches(final CacheType cacheType) {
final Set<String> geocodes = loadBatchOfHistoricGeocodes(cacheType);
return new SearchResult(geocodes, getAllHistoryCachesCount());
}
public static boolean saveWaypoint(final int id, final String geocode, final Waypoint waypoint) {
if (saveWaypointInternal(id, geocode, waypoint)) {
removeCache(geocode, EnumSet.of(RemoveFlag.CACHE));
return true;
}
return false;
}
@NonNull
public static Set<String> getCachedMissingFromSearch(final SearchResult searchResult, final Set<Tile> tiles, final IConnector connector, final int maxZoom) {
// get cached CacheListActivity
final Set<String> cachedGeocodes = new HashSet<>();
for (final Tile tile : tiles) {
cachedGeocodes.addAll(cacheCache.getInViewport(tile.getViewport(), CacheType.ALL));
}
// remove found in search result
cachedGeocodes.removeAll(searchResult.getGeocodes());
// check remaining against viewports
final Set<String> missingFromSearch = new HashSet<>();
for (final String geocode : cachedGeocodes) {
if (connector.canHandle(geocode)) {
final Geocache geocache = cacheCache.getCacheFromCache(geocode);
// TODO: parallel searches seem to have the potential to make some caches be expunged from the CacheCache (see issue #3716).
if (geocache != null && geocache.getCoordZoomLevel() <= maxZoom) {
for (final Tile tile : tiles) {
if (tile.containsPoint(geocache)) {
missingFromSearch.add(geocode);
break;
}
}
}
}
}
return missingFromSearch;
}
@Nullable
public static Cursor findSuggestions(final String searchTerm) {
// require 3 characters, otherwise there are to many results
if (StringUtils.length(searchTerm) < 3) {
return null;
}
init();
final SearchSuggestionCursor resultCursor = new SearchSuggestionCursor();
try {
final String selectionArg = getSuggestionArgument(searchTerm);
findCaches(resultCursor, selectionArg);
findTrackables(resultCursor, selectionArg);
} catch (final Exception e) {
Log.e("DataStore.loadBatchOfStoredGeocodes", e);
}
return resultCursor;
}
private static void findCaches(final SearchSuggestionCursor resultCursor, final String selectionArg) {
final Cursor cursor = database.query(
dbTableCaches,
new String[] { "geocode", "name", "type" },
"geocode IS NOT NULL AND geocode != '' AND (geocode LIKE ? OR name LIKE ? OR owner LIKE ?)",
new String[] { selectionArg, selectionArg, selectionArg },
null,
null,
"name");
while (cursor.moveToNext()) {
final String geocode = cursor.getString(0);
final String cacheName = cursor.getString(1);
final String type = cursor.getString(2);
resultCursor.addCache(geocode, cacheName, type);
}
cursor.close();
}
@NonNull
private static String getSuggestionArgument(final String input) {
return "%" + StringUtils.trim(input) + "%";
}
private static void findTrackables(final MatrixCursor resultCursor, final String selectionArg) {
final Cursor cursor = database.query(
dbTableTrackables,
new String[] { "tbcode", "title" },
"tbcode IS NOT NULL AND tbcode != '' AND (tbcode LIKE ? OR title LIKE ?)",
new String[] { selectionArg, selectionArg },
null,
null,
"title");
while (cursor.moveToNext()) {
final String tbcode = cursor.getString(0);
resultCursor.addRow(new String[] {
String.valueOf(resultCursor.getCount()),
cursor.getString(1),
tbcode,
Intents.ACTION_TRACKABLE,
tbcode,
String.valueOf(R.drawable.trackable_all)
});
}
cursor.close();
}
@NonNull
public static String[] getSuggestions(final String table, final String column, final String input) {
try {
final Cursor cursor = database.rawQuery("SELECT DISTINCT " + column
+ " FROM " + table
+ " WHERE " + column + " LIKE ?"
+ " ORDER BY " + column + " COLLATE NOCASE ASC;", new String[] { getSuggestionArgument(input) });
return cursorToColl(cursor, new LinkedList<String>(), GET_STRING_0).toArray(new String[cursor.getCount()]);
} catch (final RuntimeException e) {
Log.e("cannot get suggestions from " + table + "->" + column + " for input '" + input + "'", e);
return ArrayUtils.EMPTY_STRING_ARRAY;
}
}
@NonNull
public static String[] getSuggestionsOwnerName(final String input) {
return getSuggestions(dbTableCaches, "owner_real", input);
}
@NonNull
public static String[] getSuggestionsTrackableCode(final String input) {
return getSuggestions(dbTableTrackables, "tbcode", input);
}
@NonNull
public static String[] getSuggestionsFinderName(final String input) {
return getSuggestions(dbTableLogs, "author", input);
}
@NonNull
public static String[] getSuggestionsGeocode(final String input) {
return getSuggestions(dbTableCaches, "geocode", input);
}
@NonNull
public static String[] getSuggestionsKeyword(final String input) {
return getSuggestions(dbTableCaches, "name", input);
}
/**
*
* @return list of last caches opened in the details view, ordered by most recent first
*/
@NonNull
public static List<Geocache> getLastOpenedCaches() {
final List<String> geocodes = Settings.getLastOpenedCaches();
final Set<Geocache> cachesSet = loadCaches(geocodes, LoadFlags.LOAD_CACHE_OR_DB);
// order result set by time again
final List<Geocache> caches = new ArrayList<>(cachesSet);
Collections.sort(caches, new Comparator<Geocache>() {
@Override
public int compare(final Geocache lhs, final Geocache rhs) {
final int lhsIndex = geocodes.indexOf(lhs.getGeocode());
final int rhsIndex = geocodes.indexOf(rhs.getGeocode());
return lhsIndex < rhsIndex ? -1 : (lhsIndex == rhsIndex ? 0 : 1);
}
});
return caches;
}
}
|
package uk.ac.ox.oucs.vle;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.util.ResourceLoader;
public class CourseSignupServiceImpl implements CourseSignupService {
private final static Log log = LogFactory.getLog(CourseSignupServiceImpl.class);
private final static ResourceLoader rb = new ResourceLoader("messages");
private CourseDAO dao;
private SakaiProxy proxy;
private Date now;
public void setDao(CourseDAO dao) {
this.dao = dao;
}
public void setProxy(SakaiProxy proxy) {
this.proxy = proxy;
}
public void approve(String signupId) {
CourseSignupDAO signupDao = dao.findSignupById(signupId);
if (signupDao == null) {
throw new NotFoundException(signupId);
}
CourseGroupDAO groupDao = signupDao.getGroup();
String currentUserId = proxy.getCurrentUser().getId();
boolean canApprove = false;
if (currentUserId.equals(signupDao.getSupervisorId())) {
canApprove = true;
} else {
canApprove = isAdministrator(groupDao, currentUserId, canApprove);
}
if (!canApprove) {
throw new PermissionDeniedException(currentUserId);
}
signupDao.setStatus(Status.APPROVED);
dao.save(signupDao);
proxy.logEvent(groupDao.getId(), EVENT_SIGNUP);
String url = proxy.getMyUrl();
sendSignupEmail(signupDao.getUserId(), signupDao, "approved.student.subject","approved.student.body", new Object[]{url});
}
public void accept(String signupId) {
CourseSignupDAO signupDao = dao.findSignupById(signupId);
if (signupDao == null) {
throw new NotFoundException(signupId);
}
String currentUserId = proxy.getCurrentUser().getId();
boolean canAccept = false;
// If is course admin on one of the components.
canAccept = isAdministrator(signupDao.getGroup(), currentUserId, canAccept);
if (!canAccept) {
throw new PermissionDeniedException(currentUserId);
}
if (!Status.PENDING.equals(signupDao.getStatus())) {
throw new IllegalStateException("You can only accept signups that are pending.");
}
for (CourseComponentDAO componentDao : signupDao.getComponents()) {
componentDao.setTaken(componentDao.getTaken()+1);
dao.save(componentDao);
}
signupDao.setStatus(Status.ACCEPTED);
dao.save(signupDao);
proxy.logEvent(signupDao.getGroup().getId(), EVENT_ACCEPT);
String supervisorId = signupDao.getSupervisorId();
String url = proxy.getConfirmUrl(signupId);
if (supervisorId != null) {
sendSignupEmail(supervisorId, signupDao, "approval.supervisor.subject", "approval.supervisor.body", new Object[]{url});
}
}
public String findSupervisor(String search) {
// TODO Auto-generated method stub
return null;
}
public List<CourseGroup> getAdministering() {
String userId = proxy.getCurrentUser().getId();
List <CourseGroupDAO> groupDaos = dao.findAdminCourseGroups(userId);
List<CourseGroup> groups = new ArrayList<CourseGroup>(groupDaos.size());
for(CourseGroupDAO groupDao : groupDaos) {
groups.add(new CourseGroupImpl(groupDao, this));
}
return groups;
}
public List<CourseSignup> getApprovals() {
String currentUser = proxy.getCurrentUser().getId();
List <CourseSignupDAO> signupDaos = dao.findSignupPending(currentUser);
List<CourseSignup> signups = new ArrayList<CourseSignup>(signupDaos.size());
for(CourseSignupDAO signupDao : signupDaos) {
signups.add(new CourseSignupImpl(signupDao, this));
}
return signups;
}
public List<CourseSignup> getMySignups(Set<Status> statuses) {
String userId = proxy.getCurrentUser().getId();
if (log.isDebugEnabled()) {
log.debug("Loading all signups for : "+ userId+ " of status "+ statuses);
}
List<CourseSignup> signups = new ArrayList<CourseSignup>();
for (CourseSignupDAO signupDao: dao.findSignupForUser(userId, (statuses==null)?Collections.EMPTY_SET:statuses)) {
signups.add(new CourseSignupImpl(signupDao, this));
}
return signups;
}
public CourseGroup getCourseGroup(String courseId, Range range) {
if (range == null) {
range = Range.UPCOMING;
}
CourseGroupDAO courseGroupDao = dao.findCourseGroupById(courseId, range, getNow());
CourseGroup courseGroup = null;
if (courseGroupDao != null) {
courseGroup = new CourseGroupImpl(courseGroupDao, this);
}
return courseGroup;
}
public List<CourseSignup> getCourseSignups(String courseId) {
// Find all the components and then find all the signups.
String userId = proxy.getCurrentUser().getId();
CourseGroupDAO groupDao = dao.findCourseGroupById(courseId);
if (groupDao == null) {
return null;
}
if(!isAdministrator(groupDao, userId, false)) {
throw new PermissionDeniedException(userId);
}
List<CourseSignupDAO> signupDaos = dao.findSignupByCourse(userId, courseId);
List<CourseSignup> signups = new ArrayList<CourseSignup>(signupDaos.size());
for(CourseSignupDAO signupDao: signupDaos) {
signups.add(new CourseSignupImpl(signupDao, this));
}
return signups;
}
public List<CourseSignup> getComponentSignups(String componentId) {
CourseComponentDAO componentDao = dao.findCourseComponent(componentId);
if (componentDao == null) {
throw new NotFoundException(componentId);
}
String currentUserId = proxy.getCurrentUser().getId();
if (!isAdministrator(componentDao, currentUserId, false)) {
throw new PermissionDeniedException(currentUserId);
}
List<CourseSignupDAO> signupDaos = dao.findSignupByComponent(componentId);
List<CourseSignup> signups = new ArrayList<CourseSignup>(signupDaos.size());
for(CourseSignupDAO signupDao : signupDaos) {
signups.add(new CourseSignupImpl(signupDao, this));
}
return signups;
}
private boolean isAdministrator(CourseGroupDAO groupGroup, String currentUserId, boolean defaultValue) {
boolean isAdmin = defaultValue;
if(groupGroup.getAdministrator().equals(currentUserId)) {
isAdmin = true;
}
return isAdmin;
}
private boolean isAdministrator(CourseComponentDAO componentDao,
String userId, boolean defaultValue) {
for (CourseGroupDAO groupDao: componentDao.getGroups()) {
if (groupDao.getAdministrator().equals(userId)) {
return true;
}
}
return false;
}
public void reject(String signupId) {
String currentUserId = proxy.getCurrentUser().getId();
CourseSignupDAO signupDao = dao.findSignupById(signupId);
if (signupDao == null) {
throw new NotFoundException(signupId);
}
if (Status.PENDING.equals(signupDao.getStatus())) { // Rejected by administrator.
if (isAdministrator(signupDao.getGroup(), currentUserId, false)) {
signupDao.setStatus(Status.REJECTED);
dao.save(signupDao);
proxy.logEvent(signupDao.getGroup().getId(), EVENT_REJECT);
sendSignupEmail(signupDao.getUserId(), signupDao, "reject-admin.student.subject", "reject-admin.student.body", new Object[] {proxy.getCurrentUser().getName(), proxy.getMyUrl()});
} else {
throw new PermissionDeniedException(currentUserId);
}
} else if (Status.ACCEPTED.equals(signupDao.getStatus())) {// Rejected by lecturer.
if (isAdministrator(signupDao.getGroup(), currentUserId, currentUserId.equals(signupDao.getSupervisorId()))) {
signupDao.setStatus(Status.REJECTED);
dao.save(signupDao);
for (CourseComponentDAO componentDao: signupDao.getComponents()) {
componentDao.setTaken(componentDao.getTaken()-1);
dao.save(componentDao);
}
proxy.logEvent(signupDao.getGroup().getId(), EVENT_REJECT);
sendSignupEmail(signupDao.getUserId(), signupDao, "reject-supervisor.student.subject", "reject-supervisor.student.body", new Object[] {proxy.getCurrentUser().getName(), proxy.getMyUrl()});
} else {
throw new PermissionDeniedException(currentUserId);
}
} else {
throw new IllegalStateException("You can only reject signups that are PENDING or ACCEPTED");
}
}
public void setSignupStatus(String signupId, Status newStatus) {
CourseSignupDAO signupDao = dao.findSignupById(signupId);
if (signupDao == null) {
throw new NotFoundException(signupId);
}
String currentUserId = proxy.getCurrentUser().getId();
if (isAdministrator(signupDao.getGroup(), currentUserId, false)) {
Status currentStatus = signupDao.getStatus();
if (!currentStatus.equals(newStatus)) { // Check it actually needs changing.
signupDao.setStatus(newStatus);
dao.save(signupDao);
int spaceAdjustment = (-currentStatus.getSpacesTaken()) + newStatus.getSpacesTaken();
if (spaceAdjustment != 0) {
for(CourseComponentDAO component: signupDao.getComponents()) {
component.setTaken(component.getTaken()+spaceAdjustment);
dao.save(component);
}
}
}
} else {
throw new PermissionDeniedException(currentUserId);
}
}
public void signup(String userId, String courseId, Set<String> componentIds) {
CourseGroupDAO groupDao = dao.findCourseGroupById(courseId);
if (groupDao == null) {
throw new NotFoundException(courseId);
}
// Need to find all the components.
if (componentIds == null) {
throw new IllegalArgumentException("You must specify some components to signup to.");
}
Set<CourseComponentDAO> componentDaos = new HashSet<CourseComponentDAO>(componentIds.size());
for(String componentId: componentIds) {
CourseComponentDAO componentDao = dao.findCourseComponent(componentId);
if (componentDao != null) {
componentDaos.add(componentDao);
if (!componentDao.getGroups().contains(groupDao)) { // Check that the component is actually part of the set.
throw new IllegalArgumentException("The component: "+ componentId+ " is not part of the course: "+ courseId);
}
} else {
throw new NotFoundException(componentId);
}
}
String currentUserId = proxy.getCurrentUser().getId();
if (!isAdministrator(groupDao, currentUserId, false)) {
throw new PermissionDeniedException(currentUserId);
}
CourseSignupDAO signupDao = dao.newSignup(userId, null);
signupDao.setCreated(getNow());
signupDao.setGroup(groupDao);
signupDao.setStatus(Status.ACCEPTED);
dao.save(signupDao);
for (CourseComponentDAO componentDao: componentDaos) {
List<CourseSignupDAO> signupsToRemove = new ArrayList<CourseSignupDAO>();
for(CourseSignupDAO componentSignupDao: componentDao.getSignups()) {
if (componentSignupDao.getUserId().equals(userId)) {
signupsToRemove.add(componentSignupDao);
}
}
Set <CourseSignupDAO> signupDaos = componentDao.getSignups();
for (CourseSignupDAO removeSignup: signupsToRemove) {
// If they had already been accepted then decrement the taken count.
if (removeSignup.getStatus().equals(Status.APPROVED) || removeSignup.getStatus().equals(Status.ACCEPTED)) {
for (CourseComponentDAO signupComponentDao : removeSignup.getComponents()) {
signupComponentDao.setTaken(signupComponentDao.getTaken()-1);
dao.save(signupComponentDao);
}
}
signupDaos.remove(removeSignup);
dao.remove(removeSignup);
}
componentDao.getSignups().add(signupDao);
componentDao.setTaken(componentDao.getTaken()+1);
dao.save(componentDao);
}
proxy.logEvent(signupDao.getGroup().getId(), EVENT_ACCEPT);
}
public void signup(String courseId, Set<String> componentIds, String supervisorEmail,
String message){
CourseGroupDAO groupDao = dao.findCourseGroupById(courseId);
if (groupDao == null) {
throw new NotFoundException(courseId);
}
// Need to find all the components.
Set<CourseComponentDAO> componentDaos = new HashSet<CourseComponentDAO>(componentIds.size());
for(String componentId: componentIds) {
CourseComponentDAO componentDao = dao.findCourseComponent(componentId);
if (componentDao != null) {
componentDaos.add(componentDao);
if (!componentDao.getGroups().contains(groupDao)) { // Check that the component is actually part of the set.
throw new IllegalArgumentException("The component: "+ componentId+ " is not part of the course: "+ courseId);
}
} else {
throw new NotFoundException(componentId);
}
}
// Check they are valid as a choice (in signup period (student), not for same component in same term)
Date now = getNow();
String userId = proxy.getCurrentUser().getId();
List<CourseSignupDAO> existingSignups = new ArrayList<CourseSignupDAO>();
for(CourseComponentDAO componentDao: componentDaos) {
if(componentDao.getOpens().after(now) || componentDao.getCloses().before(now)) {
throw new IllegalStateException("Component isn't currently open: "+ componentDao.getId());
}
if ( (componentDao.getSize()-componentDao.getTaken()) < 1) {
throw new IllegalStateException("No places left on: "+ componentDao.getId());
}
for (CourseSignupDAO signupDao: componentDao.getSignups()) {
// Look for exisiting signups for these components
if ( userId.equals(signupDao.getUserId())) {
existingSignups.add(signupDao);
if(!signupDao.getStatus().equals(Status.WITHDRAWN)) {
throw new IllegalStateException("User "+ userId+ " already has a place on component: "+ componentDao.getId());
}
}
}
}
// Remove all traces of the existing signup.
for (CourseSignupDAO existingSignup :existingSignups) {
for (CourseComponentDAO componentDao: existingSignup.getComponents()) {
componentDao.getSignups().remove(existingSignup);
dao.save(componentDao);
}
dao.remove(existingSignup);
}
// Set the supervisor
UserProxy supervisor = proxy.findUserByEmail(supervisorEmail);
if (supervisor == null) {
throw new IllegalArgumentException("Can't find a supervisor with email: "+ supervisorEmail);
}
// Create the signup.
String supervisorId = supervisor.getId();
CourseSignupDAO signupDao = dao.newSignup(userId, supervisorId);
signupDao.setCreated(getNow());
signupDao.setGroup(groupDao);
signupDao.setStatus(Status.PENDING);
signupDao.getProperties().put("message", message);
String signupId = dao.save(signupDao);
// We're going to decrement the places on acceptance.
for (CourseComponentDAO componentDao: componentDaos) {
//componentDao.getSignups().add(signupDao); // Link to the signup
//componentDao.setTaken(componentDao.getTaken()+1); // Increment places taken
componentDao.getSignups().add(signupDao);
signupDao.getComponents().add(componentDao); // So when sending out email we know the components.
dao.save(componentDao);
}
proxy.logEvent(groupDao.getId(), EVENT_SIGNUP);
String adminId = groupDao.getAdministrator();
String url = proxy.getConfirmUrl(signupId);
if (adminId != null) {
sendSignupEmail(adminId, signupDao, "signup.admin.subject", "signup.admin.body", new Object[]{url});
} else {
log.warn("Failed to send email as no administrator set for: "+ groupDao.getId());
}
}
/**
* Generic method for sending out a signup email.
* @param userId The ID of the user who the message should be sent to.
* @param signupDao The signup the message is about.
* @param subjectKey The resource bundle key for the subject
* @param bodyKey The resource bundle key for the body.
* @param additionalBodyData Additional objects used to format the email body. Typically used for the confirm URL.
*/
public void sendSignupEmail(String userId, CourseSignupDAO signupDao, String subjectKey, String bodyKey, Object[] additionalBodyData) {
UserProxy user = proxy.findUserById(userId);
if (user == null) {
log.warn("Failed to find user for sending email: "+ userId);
return;
}
String to = user.getEmail();
String subject = MessageFormat.format(rb.getString(subjectKey), new Object[]{proxy.getCurrentUser().getName(), signupDao.getGroup().getTitle()});
String componentDetails = formatSignup(signupDao);
Object[] baseBodyData = new Object[] {
proxy.getCurrentUser().getName(),
componentDetails,
signupDao.getGroup().getTitle()
};
Object[] bodyData = baseBodyData;
if (additionalBodyData != null) {
bodyData = new Object[bodyData.length + additionalBodyData.length];
System.arraycopy(baseBodyData, 0, bodyData, 0, baseBodyData.length);
System.arraycopy(additionalBodyData, 0, bodyData, baseBodyData.length, additionalBodyData.length);
}
String body = MessageFormat.format(rb.getString(bodyKey), bodyData);
proxy.sendEmail(to, subject, body);
}
// Computer-Aided Formal Verification (Computing Laboratory)
// - Lectures: 16 lectures for 16 sessions starts in Michaelmas 2010 with Daniel Kroening
/**
* This formats the details of a signup into plain text.
*
* @param signupDao
* @return
*/
public String formatSignup(CourseSignupDAO signupDao) {
CourseSignup signup = new CourseSignupImpl(signupDao, this); // wrap is up to make it easier to handle.
StringBuilder output = new StringBuilder(); // TODO Maybe should use resource bundle.
output.append(signup.getGroup().getTitle());
output.append(" (");
output.append(signup.getGroup().getDepartment());
output.append(" )\n");
for(CourseComponent component: signup.getComponents()) {
output.append(" - ");
output.append(component.getTitle());
output.append(": ");
output.append(component.getSlot());
output.append(" for ");
output.append(component.getSessions());
output.append(" starts in ");
output.append(component.getWhen());
Person presenter = component.getPresenter();
if(presenter != null) {
output.append(" with ");
output.append(presenter.getName());
}
output.append("\n");
}
return output.toString();
}
public void withdraw(String signupId) {
CourseSignupDAO signupDao = dao.findSignupById(signupId);
if (signupDao == null) {
throw new NotFoundException(signupId);
}
if (!Status.PENDING.equals(signupDao.getStatus())) {
throw new IllegalStateException("Can only withdraw from pending signups: "+ signupId);
}
signupDao.setStatus(Status.WITHDRAWN);
dao.save(signupDao);
proxy.logEvent(signupDao.getGroup().getId(), EVENT_WITHDRAW);
}
public CourseGroup getAvailableCourseGroup(String courseId) {
// TODO Auto-generated method stub
return null;
}
public List<CourseGroup> getCourseGroups(String deptId, Range range) {
List<CourseGroupDAO> cgDaos = dao.findCourseGroupByDept(deptId, range, getNow());
List<CourseGroup> cgs = new ArrayList<CourseGroup>(cgDaos.size());
for (CourseGroupDAO cgDao: cgDaos) {
cgs.add(new CourseGroupImpl(cgDao, this));
}
return cgs;
}
public Date getNow() {
return (now==null)?new Date():now;
}
public void setNow(Date now) {
this.now = now;
}
/**
* Loads details about a user.
* @return
*/
UserProxy loadUser(String id) {
return proxy.findUserById(id);
}
public List<CourseGroup> search(String search) {
String words[] = search.split(" ");
List<CourseGroupDAO> groupDaos = dao.findCourseGroupByWords(words, Range.UPCOMING, getNow());
List<CourseGroup> groups = new ArrayList<CourseGroup>(groupDaos.size());
for(CourseGroupDAO groupDao: groupDaos) {
groups.add(new CourseGroupImpl(groupDao, this));
}
return groups;
}
public CourseSignup getCourseSignup(String signupId) {
CourseSignupDAO signupDao = dao.findSignupById(signupId);
if (signupDao == null) {
return null;
}
String currentUserId = proxy.getCurrentUser().getId();
if (
currentUserId.equals(signupDao.getUserId()) ||
currentUserId.equals(signupDao.getSupervisorId()) ||
isAdministrator(signupDao.getGroup(), currentUserId, false)
) {
return new CourseSignupImpl(signupDao, this);
} else {
throw new PermissionDeniedException(currentUserId);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.