answer
stringlengths 17
10.2M
|
|---|
package org.apache.lucene.store;
import java.io.IOException;
import java.io.File;
import java.util.Vector;
import java.util.Hashtable;
import java.util.Enumeration;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.InputStream;
import org.apache.lucene.store.OutputStream;
/**
* A memory-resident {@link Directory} implementation.
*
* @version $Id$
*/
public final class RAMDirectory extends Directory {
Hashtable files = new Hashtable();
/** Constructs an empty {@link Directory}. */
public RAMDirectory() {
}
/**
* Creates a new <code>RAMDirectory</code> instance from a different
* <code>Directory</code> implementation. This can be used to load
* a disk-based index into memory.
* <P>
* This should be used only with indices that can fit into memory.
*
* @param dir a <code>Directory</code> value
* @exception IOException if an error occurs
*/
public RAMDirectory(Directory dir) throws IOException {
final String[] ar = dir.list();
for (int i = 0; i < ar.length; i++) {
// make place on ram disk
OutputStream os = createFile(ar[i]);
// read current file
InputStream is = dir.openFile(ar[i]);
// and copy to ram disk
int len = (int) is.length();
byte[] buf = new byte[len];
is.readBytes(buf, 0, len);
os.writeBytes(buf, len);
// graceful cleanup
is.close();
os.close();
}
}
/**
* Creates a new <code>RAMDirectory</code> instance from the {@link FSDirectory}.
*
* @param dir a <code>File</code> specifying the index directory
*/
public RAMDirectory(File dir) throws IOException {
this(FSDirectory.getDirectory(dir, false));
}
/**
* Creates a new <code>RAMDirectory</code> instance from the {@link FSDirectory}.
*
* @param dir a <code>String</code> specifying the full index directory path
*/
public RAMDirectory(String dir) throws IOException {
this(FSDirectory.getDirectory(dir, false));
}
/** Returns an array of strings, one for each file in the directory. */
public final String[] list() {
String[] result = new String[files.size()];
int i = 0;
Enumeration names = files.keys();
while (names.hasMoreElements())
result[i++] = (String)names.nextElement();
return result;
}
/** Returns true iff the named file exists in this directory. */
public final boolean fileExists(String name) {
RAMFile file = (RAMFile)files.get(name);
return file != null;
}
/** Returns the time the named file was last modified. */
public final long fileModified(String name) throws IOException {
RAMFile file = (RAMFile)files.get(name);
return file.lastModified;
}
/** Set the modified time of an existing file to now. */
public void touchFile(String name) throws IOException {
final boolean MONITOR = false;
int count = 0;
RAMFile file = (RAMFile)files.get(name);
long ts2, ts1 = System.currentTimeMillis();
do {
try {
Thread.sleep(0, 1);
} catch (InterruptedException e) {}
ts2 = System.currentTimeMillis();
if (MONITOR) count ++;
} while(ts1 == ts2);
file.lastModified = ts2;
if (MONITOR)
System.out.println("SLEEP COUNT: " + count);
}
/** Returns the length in bytes of a file in the directory. */
public final long fileLength(String name) {
RAMFile file = (RAMFile)files.get(name);
return file.length;
}
/** Removes an existing file in the directory. */
public final void deleteFile(String name) {
files.remove(name);
}
/** Removes an existing file in the directory. */
public final void renameFile(String from, String to) {
RAMFile file = (RAMFile)files.get(from);
files.remove(from);
files.put(to, file);
}
/** Creates a new, empty file in the directory with the given name.
Returns a stream writing this file. */
public final OutputStream createFile(String name) {
RAMFile file = new RAMFile();
files.put(name, file);
return new RAMOutputStream(file);
}
/** Returns a stream reading an existing file. */
public final InputStream openFile(String name) {
RAMFile file = (RAMFile)files.get(name);
return new RAMInputStream(file);
}
/** Construct a {@link Lock}.
* @param name the name of the lock file
*/
public final Lock makeLock(final String name) {
return new Lock() {
public boolean obtain() throws IOException {
synchronized (files) {
if (!fileExists(name)) {
createFile(name).close();
return true;
}
return false;
}
}
public void release() {
deleteFile(name);
}
public boolean isLocked() {
return fileExists(name);
}
};
}
/** Closes the store to future operations. */
public final void close() {
}
}
final class RAMInputStream extends InputStream implements Cloneable {
RAMFile file;
int pointer = 0;
public RAMInputStream(RAMFile f) {
file = f;
length = file.length;
}
/** InputStream methods */
public final void readInternal(byte[] dest, int destOffset, int len) {
int remainder = len;
int start = pointer;
while (remainder != 0) {
int bufferNumber = start/InputStream.BUFFER_SIZE;
int bufferOffset = start%InputStream.BUFFER_SIZE;
int bytesInBuffer = InputStream.BUFFER_SIZE - bufferOffset;
int bytesToCopy = bytesInBuffer >= remainder ? remainder : bytesInBuffer;
byte[] buffer = (byte[])file.buffers.elementAt(bufferNumber);
System.arraycopy(buffer, bufferOffset, dest, destOffset, bytesToCopy);
destOffset += bytesToCopy;
start += bytesToCopy;
remainder -= bytesToCopy;
}
pointer += len;
}
public final void close() {
}
/** Random-access methods */
public final void seekInternal(long pos) {
pointer = (int)pos;
}
}
final class RAMOutputStream extends OutputStream {
RAMFile file;
int pointer = 0;
public RAMOutputStream(RAMFile f) {
file = f;
}
/** output methods: */
public final void flushBuffer(byte[] src, int len) {
int bufferNumber = pointer/OutputStream.BUFFER_SIZE;
int bufferOffset = pointer%OutputStream.BUFFER_SIZE;
int bytesInBuffer = OutputStream.BUFFER_SIZE - bufferOffset;
int bytesToCopy = bytesInBuffer >= len ? len : bytesInBuffer;
if (bufferNumber == file.buffers.size())
file.buffers.addElement(new byte[OutputStream.BUFFER_SIZE]);
byte[] buffer = (byte[])file.buffers.elementAt(bufferNumber);
System.arraycopy(src, 0, buffer, bufferOffset, bytesToCopy);
if (bytesToCopy < len) { // not all in one buffer
int srcOffset = bytesToCopy;
bytesToCopy = len - bytesToCopy; // remaining bytes
bufferNumber++;
if (bufferNumber == file.buffers.size())
file.buffers.addElement(new byte[OutputStream.BUFFER_SIZE]);
buffer = (byte[])file.buffers.elementAt(bufferNumber);
System.arraycopy(src, srcOffset, buffer, 0, bytesToCopy);
}
pointer += len;
if (pointer > file.length)
file.length = pointer;
file.lastModified = System.currentTimeMillis();
}
public final void close() throws IOException {
super.close();
}
/** Random-access methods */
public final void seek(long pos) throws IOException {
super.seek(pos);
pointer = (int)pos;
}
public final long length() throws IOException {
return file.length;
}
}
final class RAMFile {
Vector buffers = new Vector();
long length;
long lastModified = System.currentTimeMillis();
}
|
package org.jboss.pnc.mavenrepositorymanager;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
import org.commonjava.aprox.boot.BootStatus;
import org.commonjava.aprox.model.core.Group;
import org.commonjava.aprox.model.core.StoreKey;
import org.commonjava.aprox.test.fixture.core.CoreServerFixture;
import org.jboss.pnc.common.Configuration;
import org.jboss.pnc.common.json.ModuleConfigJson;
import org.jboss.pnc.common.json.moduleconfig.MavenRepoDriverModuleConfig;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.TemporaryFolder;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.util.List;
import java.util.Properties;
public class AbstractRepositoryManagerDriverTest {
protected static final String CONFIG_SYSPROP = "pnc-config-file";
@Rule
public TemporaryFolder temp = new TemporaryFolder();
protected RepositoryManagerDriver driver;
protected CoreServerFixture fixture;
protected String url;
private String oldIni;
@Before
public void setup() throws Exception {
fixture = new CoreServerFixture(temp);
Properties sysprops = System.getProperties();
oldIni = sysprops.getProperty(CONFIG_SYSPROP);
url = fixture.getUrl();
File configFile = temp.newFile("pnc-config.json");
ModuleConfigJson moduleConfigJson = new ModuleConfigJson("pnc-config");
MavenRepoDriverModuleConfig mavenRepoDriverModuleConfig = new MavenRepoDriverModuleConfig(fixture.getUrl());
moduleConfigJson.addConfig(mavenRepoDriverModuleConfig);
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(configFile, moduleConfigJson);
sysprops.setProperty(CONFIG_SYSPROP, configFile.getAbsolutePath());
System.setProperties(sysprops);
fixture.start();
if (!fixture.isStarted()) {
final BootStatus status = fixture.getBootStatus();
throw new IllegalStateException("server fixture failed to boot.", status.getError());
}
Properties props = new Properties();
props.setProperty("base.url", url);
System.out.println("Using base URL: " + url);
Configuration<MavenRepoDriverModuleConfig> config = new Configuration<MavenRepoDriverModuleConfig>();
driver = new RepositoryManagerDriver(config);
}
@After
public void teardown() throws Exception {
Properties sysprops = System.getProperties();
if (oldIni == null) {
sysprops.remove(CONFIG_SYSPROP);
} else {
sysprops.setProperty(CONFIG_SYSPROP, oldIni);
}
System.setProperties(sysprops);
if (fixture != null) {
fixture.stop();
}
}
protected void assertGroupConstituents(Group buildGroup, StoreKey... constituents) {
List<StoreKey> groupConstituents = buildGroup.getConstituents();
for (int i = 0; i < constituents.length; i++) {
assertThat("Group constituency too small to contain all the expected members.", groupConstituents.size() > i,
equalTo(true));
StoreKey expected = constituents[i];
StoreKey actual = groupConstituents.get(i);
assertThat(actual, equalTo(expected));
}
}
}
|
package org.apache.velocity.util;
import java.io.*;
import java.net.MalformedURLException;
import java.util.Hashtable;
import java.util.StringTokenizer;
import java.util.Vector;
/**
* This class provides some methods for dynamically
* invoking methods in objects, and some string
* manipulation methods used by torque. The string
* methods will soon be moved into the turbine
* string utilities class.
*
* @author <a href="mailto:jvanzyl@periapt.com">Jason van Zyl</a>
* @version $Id: StringUtils.java,v 1.5 2000/12/17 21:53:42 jon Exp $
*/
public class StringUtils
{
/**
* Create a string array from a string separated by delim
*
* @param line the line to split
* @param delim the delimter to split by
* @return a string array of the split fields
*/
public static String [] split(String line, String delim)
{
Vector v = new Vector();
StringTokenizer t = new StringTokenizer(line, delim);
while (t.hasMoreTokens())
v.addElement(t.nextToken());
String [] s = new String[v.size()];
for (int i = 0; i < v.size(); i++)
s[i] = (String) v.elementAt(i);
return s;
}
/**
* This was borrowed form xml-fop. Convert a file
* name into a string that represents a well-formed
* URL.
*
* d:\path\to\logfile
* file://d:/path/to/logfile
*
* NOTE: this is a total hack-a-roo! This should
* be dealt with in the org.apache.log package. Client
* packages should not have to mess around making
* properly formed URLs when log files are almost
* always going to be specified with file paths!
*/
public static String fileToURL(String filename)
throws MalformedURLException
{
File file = new File(filename);
String path = file.getAbsolutePath();
String fSep = System.getProperty("file.separator");
if (fSep != null && fSep.length() == 1)
path = "file://" + path.replace(fSep.charAt(0), '/');
return path;
}
public static StringBuffer stringSubstitution(String argStr,
Hashtable vars)
{
StringBuffer argBuf = new StringBuffer();
for (int cIdx = 0 ; cIdx < argStr.length();)
{
char ch = argStr.charAt(cIdx);
switch (ch)
{
case '$':
StringBuffer nameBuf = new StringBuffer();
for (++cIdx ; cIdx < argStr.length(); ++cIdx)
{
ch = argStr.charAt(cIdx);
if (ch == '_' || Character.isLetterOrDigit(ch))
nameBuf.append(ch);
else
break;
}
if (nameBuf.length() > 0)
{
String value =
(String) vars.get(nameBuf.toString());
if (value != null)
{
argBuf.append(value);
}
}
break;
default:
argBuf.append(ch);
++cIdx;
break;
}
}
return argBuf;
}
public static String fileContentsToString(String file)
{
String contents = "";
File f = new File(file);
if (f.exists())
{
try
{
FileReader fr = new FileReader(f);
char[] template = new char[(int) f.length()];
fr.read(template, 0, (int) f.length());
contents = new String(template);
}
catch (Exception e)
{
System.out.println(e);
e.printStackTrace();
}
}
return contents;
}
/**
* Remove/collapse multiple newline characters.
*/
public static String collapseNewlines(String argStr)
{
char last = argStr.charAt(0);
StringBuffer argBuf = new StringBuffer();
for (int cIdx = 0 ; cIdx < argStr.length(); cIdx++)
{
char ch = argStr.charAt(cIdx);
if (ch != '\n' || last != '\n')
{
argBuf.append(ch);
last = ch;
}
}
return argBuf.toString();
}
/**
* Remove/collapse multiple spaces.
*/
public static String collapseSpaces(String argStr)
{
char last = argStr.charAt(0);
StringBuffer argBuf = new StringBuffer();
for (int cIdx = 0 ; cIdx < argStr.length(); cIdx++)
{
char ch = argStr.charAt(cIdx);
if (ch != ' ' || last != ' ')
{
argBuf.append(ch);
last = ch;
}
}
return argBuf.toString();
}
/**
* Chop i characters off the end of a string.
*
* @param string String to chop
* @param i Number of characters to chop
*/
public static String chop(String string, int i)
{
return(string.substring(0, string.length() - i));
}
/**
* Replaces all instances of oldString with newString in line.
* Taken from the Jive forum package.
*/
public static final String replace(String line, String oldString,
String newString)
{
int i = 0;
if ((i = line.indexOf(oldString, i)) >= 0)
{
char [] line2 = line.toCharArray();
char [] newString2 = newString.toCharArray();
int oLength = oldString.length();
StringBuffer buf = new StringBuffer(line2.length);
buf.append(line2, 0, i).append(newString2);
i += oLength;
int j = i;
while ((i = line.indexOf(oldString, i)) > 0)
{
buf.append(line2, j, i - j).append(newString2);
i += oLength;
j = i;
}
buf.append(line2, j, line2.length - j);
return buf.toString();
}
return line;
}
/**
* Returns the output of printStackTrace as a String.
*
* @param e A Throwable.
* @return A String.
*/
public static final String stackTrace(Throwable e)
{
String foo = null;
try
{
// And show the Error Screen.
ByteArrayOutputStream ostr = new ByteArrayOutputStream();
e.printStackTrace( new PrintWriter(ostr,true) );
foo = ostr.toString();
}
catch (Exception f)
{
// Do nothing.
}
return foo;
}
/**
* Return a context-relative path, beginning with a "/", that represents
* the canonical version of the specified path after ".." and "." elements
* are resolved out. If the specified path attempts to go outside the
* boundaries of the current context (i.e. too many ".." path elements
* are present), return <code>null</code> instead.
*
* @param path Path to be normalized
*/
public static final String normalizePath(String path)
{
// Normalize the slashes and add leading slash if necessary
String normalized = path;
if (normalized.indexOf('\\') >= 0)
{
normalized = normalized.replace('\\', '/');
}
if (!normalized.startsWith("/"))
{
normalized = "/" + normalized;
}
// Resolve occurrences of "//" in the normalized path
while (true)
{
int index = normalized.indexOf("
if (index < 0)
break;
normalized = normalized.substring(0, index) +
normalized.substring(index + 1);
}
// Resolve occurrences of "%20" in the normalized path
while (true)
{
int index = normalized.indexOf("%20");
if (index < 0)
break;
normalized = normalized.substring(0, index) + " " +
normalized.substring(index + 3);
}
// Resolve occurrences of "/./" in the normalized path
while (true)
{
int index = normalized.indexOf("/./");
if (index < 0)
break;
normalized = normalized.substring(0, index) +
normalized.substring(index + 2);
}
// Resolve occurrences of "/../" in the normalized path
while (true)
{
int index = normalized.indexOf("/../");
if (index < 0)
break;
if (index == 0)
return (null); // Trying to go outside our context
int index2 = normalized.lastIndexOf('/', index - 1);
normalized = normalized.substring(0, index2) +
normalized.substring(index + 3);
}
// Return the normalized path that we have completed
return (normalized);
}
}
|
package org.jivesoftware.wildfire;
import org.dom4j.Document;
import org.dom4j.io.SAXReader;
import org.jivesoftware.database.DbConnectionManager;
import org.jivesoftware.util.*;
import org.jivesoftware.wildfire.audit.AuditManager;
import org.jivesoftware.wildfire.audit.spi.AuditManagerImpl;
import org.jivesoftware.wildfire.commands.AdHocCommandHandler;
import org.jivesoftware.wildfire.component.InternalComponentManager;
import org.jivesoftware.wildfire.container.Module;
import org.jivesoftware.wildfire.container.Plugin;
import org.jivesoftware.wildfire.container.PluginListener;
import org.jivesoftware.wildfire.container.PluginManager;
import org.jivesoftware.wildfire.disco.IQDiscoInfoHandler;
import org.jivesoftware.wildfire.disco.IQDiscoItemsHandler;
import org.jivesoftware.wildfire.disco.ServerFeaturesProvider;
import org.jivesoftware.wildfire.disco.ServerItemsProvider;
import org.jivesoftware.wildfire.filetransfer.DefaultFileTransferManager;
import org.jivesoftware.wildfire.filetransfer.FileTransferManager;
import org.jivesoftware.wildfire.filetransfer.proxy.FileTransferProxy;
import org.jivesoftware.wildfire.handler.*;
import org.jivesoftware.wildfire.muc.MultiUserChatServer;
import org.jivesoftware.wildfire.muc.spi.MultiUserChatServerImpl;
import org.jivesoftware.wildfire.net.MulticastDNSService;
import org.jivesoftware.wildfire.net.SSLConfig;
import org.jivesoftware.wildfire.net.ServerTrafficCounter;
import org.jivesoftware.wildfire.pubsub.PubSubModule;
import org.jivesoftware.wildfire.roster.RosterManager;
import org.jivesoftware.wildfire.spi.*;
import org.jivesoftware.wildfire.transport.TransportHandler;
import org.jivesoftware.wildfire.update.UpdateManager;
import org.jivesoftware.wildfire.user.UserManager;
import org.jivesoftware.wildfire.vcard.VCardManager;
import org.xmpp.packet.JID;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.security.KeyStore;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* The main XMPP server that will load, initialize and start all the server's
* modules. The server is unique in the JVM and could be obtained by using the
* {@link #getInstance()} method.<p>
* <p/>
* The loaded modules will be initialized and may access through the server other
* modules. This means that the only way for a module to locate another module is
* through the server. The server maintains a list of loaded modules.<p>
* <p/>
* After starting up all the modules the server will load any available plugin.
* For more information see: {@link org.jivesoftware.wildfire.container.PluginManager}.<p>
* <p/>
* A configuration file keeps the server configuration. This information is required for the
* server to work correctly. The server assumes that the configuration file is named
* <b>wildfire.xml</b> and is located in the <b>conf</b> folder. The folder that keeps
* the configuration file must be located under the home folder. The server will try different
* methods to locate the home folder.
* <p/>
* <ol>
* <li><b>system property</b> - The server will use the value defined in the <i>wildfireHome</i>
* system property.</li>
* <li><b>working folder</b> - The server will check if there is a <i>conf</i> folder in the
* working directory. This is the case when running in standalone mode.</li>
* <li><b>wildfire_init.xml file</b> - Attempt to load the value from wildfire_init.xml which
* must be in the classpath</li>
* </ol>
*
* @author Gaston Dombiak
*/
public class XMPPServer {
private static XMPPServer instance;
private String name;
private Version version;
private Date startDate;
private Date stopDate;
private boolean initialized = false;
/**
* All modules loaded by this server
*/
private Map<Class, Module> modules = new LinkedHashMap<Class, Module>();
/**
* Listeners that will be notified when the server has started or is about to be stopped.
*/
private List<XMPPServerListener> listeners = new CopyOnWriteArrayList<XMPPServerListener>();
/**
* Location of the home directory. All configuration files should be
* located here.
*/
private File wildfireHome;
private ClassLoader loader;
private PluginManager pluginManager;
private InternalComponentManager componentManager;
/**
* True if in setup mode
*/
private boolean setupMode = true;
private static final String STARTER_CLASSNAME =
"org.jivesoftware.wildfire.starter.ServerStarter";
private static final String WRAPPER_CLASSNAME =
"org.tanukisoftware.wrapper.WrapperManager";
private HttpServerManager httpServerManager;
/**
* Returns a singleton instance of XMPPServer.
*
* @return an instance.
*/
public static XMPPServer getInstance() {
return instance;
}
/**
* Creates a server and starts it.
*/
public XMPPServer() {
// We may only have one instance of the server running on the JVM
if (instance != null) {
throw new IllegalStateException("A server is already running");
}
instance = this;
start();
}
/**
* Returns a snapshot of the server's status.
*
* @return the server information current at the time of the method call.
*/
public XMPPServerInfo getServerInfo() {
if (!initialized) {
throw new IllegalStateException("Not initialized yet");
}
return new XMPPServerInfoImpl(name, version, startDate, stopDate, getConnectionManager());
}
/**
* Returns true if the given address is local to the server (managed by this
* server domain). Return false even if the jid's domain matches a local component's
* service JID.
*
* @param jid the JID to check.
* @return true if the address is a local address to this server.
*/
public boolean isLocal(JID jid) {
boolean local = false;
if (jid != null && name != null && name.equals(jid.getDomain())) {
local = true;
}
return local;
}
/**
* Returns true if the given address does not match the local server hostname and does not
* match a component service JID.
*
* @param jid the JID to check.
* @return true if the given address does not match the local server hostname and does not
* match a component service JID.
*/
public boolean isRemote(JID jid) {
if (jid != null) {
if (!name.equals(jid.getDomain()) && componentManager.getComponent(jid) == null) {
return true;
}
}
return false;
}
/**
* Returns true if the given address matches a component service JID.
*
* @param jid the JID to check.
* @return true if the given address matches a component service JID.
*/
public boolean matchesComponent(JID jid) {
return jid != null && !name.equals(jid.getDomain()) &&
componentManager.getComponent(jid) != null;
}
/**
* Creates an XMPPAddress local to this server.
*
* @param username the user name portion of the id or null to indicate none is needed.
* @param resource the resource portion of the id or null to indicate none is needed.
* @return an XMPPAddress for the server.
*/
public JID createJID(String username, String resource) {
return new JID(username, name, resource);
}
/**
* Returns a collection with the JIDs of the server's admins. The collection may include
* JIDs of local users and users of remote servers.
*
* @return a collection with the JIDs of the server's admins.
*/
public Collection<JID> getAdmins() {
Collection<JID> admins = new ArrayList<JID>();
// Add the JIDs of the local users that are admins
String usernames = JiveGlobals.getXMLProperty("admin.authorizedUsernames");
if (usernames == null) {
// Fall back to old method for defining admins (i.e. using adminConsole prefix
usernames = JiveGlobals.getXMLProperty("adminConsole.authorizedUsernames");
}
usernames = (usernames == null || usernames.trim().length() == 0) ? "admin" : usernames;
StringTokenizer tokenizer = new StringTokenizer(usernames, ",");
while (tokenizer.hasMoreTokens()) {
String username = tokenizer.nextToken();
try {
admins.add(createJID(username.toLowerCase().trim(), null));
}
catch (IllegalArgumentException e) {
// Ignore usernames that when appended @server.com result in an invalid JID
Log.warn("Invalid username found in authorizedUsernames at wildfire.xml: " +
username, e);
}
}
// Add bare JIDs of users that are admins (may include remote users)
String jids = JiveGlobals.getXMLProperty("admin.authorizedJIDs");
jids = (jids == null || jids.trim().length() == 0) ? "" : jids;
tokenizer = new StringTokenizer(jids, ",");
while (tokenizer.hasMoreTokens()) {
String jid = tokenizer.nextToken().toLowerCase().trim();
try {
admins.add(new JID(jid));
}
catch (IllegalArgumentException e) {
Log.warn("Invalid JID found in authorizedJIDs at wildfire.xml: " + jid, e);
}
}
return admins;
}
/**
* Adds a new server listener that will be notified when the server has been started
* or is about to be stopped.
*
* @param listener the new server listener to add.
*/
public void addServerListener(XMPPServerListener listener) {
listeners.add(listener);
}
/**
* Removes a server listener that was being notified when the server was being started
* or was about to be stopped.
*
* @param listener the server listener to remove.
*/
public void removeServerListener(XMPPServerListener listener) {
listeners.remove(listener);
}
private void initialize() throws FileNotFoundException {
locateWildfire();
name = JiveGlobals.getProperty("xmpp.domain", "127.0.0.1").toLowerCase();
version = new Version(3, 2, 0, Version.ReleaseStatus.Alpha, 0);
if ("true".equals(JiveGlobals.getXMLProperty("setup"))) {
setupMode = false;
}
if (isStandAlone()) {
Runtime.getRuntime().addShutdownHook(new ShutdownHookThread());
}
loader = Thread.currentThread().getContextClassLoader();
componentManager = InternalComponentManager.getInstance();
httpServerManager = HttpServerManager.getInstance();
initialized = true;
}
/**
* Finish the setup process. Because this method is meant to be called from inside
* the Admin console plugin, it spawns its own thread to do the work so that the
* class loader is correct.
*/
public void finishSetup() {
if (!setupMode) {
return;
}
// Make sure that setup finished correctly.
if ("true".equals(JiveGlobals.getXMLProperty("setup"))) {
// Set the new server domain assigned during the setup process
name = JiveGlobals.getProperty("xmpp.domain").toLowerCase();
// Update certificates (if required)
try {
// Check if keystore already has certificates for current domain
KeyStore ksKeys = SSLConfig.getKeyStore();
boolean dsaFound = CertificateManager.isDSACertificate(ksKeys, name);
boolean rsaFound = CertificateManager.isRSACertificate(ksKeys, name);
// No certificates were found so create new self-signed certificates
if (!dsaFound) {
CertificateManager.createDSACert(ksKeys, SSLConfig.getKeyPassword(),
name + "_dsa", "cn=" + name, "cn=" + name, "*." + name);
}
if (!rsaFound) {
CertificateManager.createRSACert(ksKeys, SSLConfig.getKeyPassword(),
name + "_rsa", "cn=" + name, "cn=" + name, "*." + name);
}
// Save new certificates into the key store
if (!dsaFound || !rsaFound) {
SSLConfig.saveStores();
}
} catch (Exception e) {
Log.error("Error generating self-signed certificates", e);
}
Thread finishSetup = new Thread() {
public void run() {
try {
if (isStandAlone()) {
// Always restart the HTTP server manager. This covers the case
// of changing the ports, as well as generating self-signed certificates.
// Wait a short period before shutting down the admin console.
// Otherwise, the page that requested the setup finish won't
// render properly!
Thread.sleep(1000);
httpServerManager.shutdown();
httpServerManager.startup();
}
verifyDataSource();
// First load all the modules so that modules may access other modules while
// being initialized
loadModules();
// Initize all the modules
initModules();
// Start all the modules
startModules();
// Initialize component manager (initialize before plugins get loaded)
InternalComponentManager.getInstance().start();
}
catch (Exception e) {
e.printStackTrace();
Log.error(e);
shutdownServer();
}
}
};
// Use the correct class loader.
finishSetup.setContextClassLoader(loader);
finishSetup.start();
// We can now safely indicate that setup has finished
setupMode = false;
}
}
public void start() {
try {
initialize();
// Create PluginManager now (but don't start it) so that modules may use it
File pluginDir = new File(wildfireHome, "plugins");
pluginManager = new PluginManager(pluginDir);
// If the server has already been setup then we can start all the server's modules
if (!setupMode) {
verifyDataSource();
// First load all the modules so that modules may access other modules while
// being initialized
loadModules();
// Initize all the modules
initModules();
// Start all the modules
startModules();
// Initialize component manager (initialize before plugins get loaded)
InternalComponentManager.getInstance().start();
}
// Initialize statistics
ServerTrafficCounter.initStatistics();
// Load plugins (when in setup mode only the admin console will be loaded)
pluginManager.addPluginListener(new PluginListener() {
public void pluginCreated(String pluginName, Plugin plugin) {
if("admin".equals(pluginName)) {
httpServerManager.startup();
}
}
public void pluginDestroyed(String pluginName, Plugin plugin) {
if ("admin".equals(pluginName)) {
httpServerManager.shutdown();
}
}
});
pluginManager.start();
// Log that the server has been started
List<String> params = new ArrayList<String>();
params.add(version.getVersionString());
params.add(JiveGlobals.formatDateTime(new Date()));
String startupBanner = LocaleUtils.getLocalizedString("startup.name", params);
Log.info(startupBanner);
System.out.println(startupBanner);
startDate = new Date();
stopDate = null;
// Notify server listeners that the server has been started
for (XMPPServerListener listener : listeners) {
listener.serverStarted();
}
}
catch (Exception e) {
e.printStackTrace();
Log.error(e);
System.out.println(LocaleUtils.getLocalizedString("startup.error"));
shutdownServer();
}
}
private void loadModules() {
// Load boot modules
loadModule(RoutingTableImpl.class.getName());
loadModule(AuditManagerImpl.class.getName());
loadModule(RosterManager.class.getName());
loadModule(PrivateStorage.class.getName());
// Load core modules
loadModule(PresenceManagerImpl.class.getName());
loadModule(SessionManager.class.getName());
loadModule(PacketRouterImpl.class.getName());
loadModule(IQRouter.class.getName());
loadModule(MessageRouter.class.getName());
loadModule(PresenceRouter.class.getName());
loadModule(MulticastRouter.class.getName());
loadModule(PacketTransporterImpl.class.getName());
loadModule(PacketDelivererImpl.class.getName());
loadModule(TransportHandler.class.getName());
loadModule(OfflineMessageStrategy.class.getName());
loadModule(OfflineMessageStore.class.getName());
loadModule(VCardManager.class.getName());
// Load standard modules
loadModule(IQBindHandler.class.getName());
loadModule(IQSessionEstablishmentHandler.class.getName());
loadModule(IQAuthHandler.class.getName());
loadModule(IQPrivateHandler.class.getName());
loadModule(IQRegisterHandler.class.getName());
loadModule(IQRosterHandler.class.getName());
loadModule(IQTimeHandler.class.getName());
loadModule(IQvCardHandler.class.getName());
loadModule(IQVersionHandler.class.getName());
loadModule(IQLastActivityHandler.class.getName());
loadModule(PresenceSubscribeHandler.class.getName());
loadModule(PresenceUpdateHandler.class.getName());
loadModule(IQDiscoInfoHandler.class.getName());
loadModule(IQDiscoItemsHandler.class.getName());
loadModule(IQOfflineMessagesHandler.class.getName());
loadModule(MultiUserChatServerImpl.class.getName());
loadModule(MulticastDNSService.class.getName());
loadModule(IQSharedGroupHandler.class.getName());
loadModule(AdHocCommandHandler.class.getName());
loadModule(IQPrivacyHandler.class.getName());
loadModule(DefaultFileTransferManager.class.getName());
loadModule(FileTransferProxy.class.getName());
loadModule(PubSubModule.class.getName());
loadModule(UpdateManager.class.getName());
// Load this module always last since we don't want to start listening for clients
// before the rest of the modules have been started
loadModule(ConnectionManagerImpl.class.getName());
}
/**
* Loads a module.
*
* @param module the name of the class that implements the Module interface.
*/
private void loadModule(String module) {
try {
Class modClass = loader.loadClass(module);
Module mod = (Module) modClass.newInstance();
this.modules.put(modClass, mod);
}
catch (Exception e) {
e.printStackTrace();
Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
}
}
private void initModules() {
for (Module module : modules.values()) {
boolean isInitialized = false;
try {
module.initialize(this);
isInitialized = true;
}
catch (Exception e) {
e.printStackTrace();
// Remove the failed initialized module
this.modules.remove(module.getClass());
if (isInitialized) {
module.stop();
module.destroy();
}
Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
}
}
}
/**
* <p>Following the loading and initialization of all the modules
* this method is called to iterate through the known modules and
* start them.</p>
*/
private void startModules() {
for (Module module : modules.values()) {
boolean started = false;
try {
module.start();
}
catch (Exception e) {
if (started && module != null) {
module.stop();
module.destroy();
}
Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
}
}
}
/**
* Restarts the server and all it's modules only if the server is restartable. Otherwise do
* nothing.
*/
public void restart() {
if (isStandAlone() && isRestartable()) {
try {
Class wrapperClass = Class.forName(WRAPPER_CLASSNAME);
Method restartMethod = wrapperClass.getMethod("restart", (Class []) null);
restartMethod.invoke(null, (Object []) null);
}
catch (Exception e) {
Log.error("Could not restart container", e);
}
}
}
/**
* Stops the server only if running in standalone mode. Do nothing if the server is running
* inside of another server.
*/
public void stop() {
// Only do a system exit if we're running standalone
if (isStandAlone()) {
// if we're in a wrapper, we have to tell the wrapper to shut us down
if (isRestartable()) {
try {
Class wrapperClass = Class.forName(WRAPPER_CLASSNAME);
Method stopMethod = wrapperClass.getMethod("stop", Integer.TYPE);
stopMethod.invoke(null, 0);
}
catch (Exception e) {
Log.error("Could not stop container", e);
}
}
else {
shutdownServer();
stopDate = new Date();
Thread shutdownThread = new ShutdownThread();
shutdownThread.setDaemon(true);
shutdownThread.start();
}
}
else {
// Close listening socket no matter what the condition is in order to be able
// to be restartable inside a container.
shutdownServer();
stopDate = new Date();
}
}
public boolean isSetupMode() {
return setupMode;
}
public boolean isRestartable() {
boolean restartable;
try {
restartable = Class.forName(WRAPPER_CLASSNAME) != null;
}
catch (ClassNotFoundException e) {
restartable = false;
}
return restartable;
}
/**
* Returns if the server is running in standalone mode. We consider that it's running in
* standalone if the "org.jivesoftware.wildfire.starter.ServerStarter" class is present in the
* system.
*
* @return true if the server is running in standalone mode.
*/
public boolean isStandAlone() {
boolean standalone;
try {
standalone = Class.forName(STARTER_CLASSNAME) != null;
}
catch (ClassNotFoundException e) {
standalone = false;
}
return standalone;
}
/**
* Verify that the database is accessible.
*/
private void verifyDataSource() {
java.sql.Connection conn = null;
try {
conn = DbConnectionManager.getConnection();
PreparedStatement stmt = conn.prepareStatement("SELECT count(*) FROM jiveID");
ResultSet rs = stmt.executeQuery();
rs.next();
rs.close();
stmt.close();
}
catch (Exception e) {
System.err.println("Database setup or configuration error: " +
"Please verify your database settings and check the " +
"logs/error.log file for detailed error messages.");
Log.error("Database could not be accessed", e);
throw new IllegalArgumentException(e);
}
finally {
if (conn != null) {
try {
conn.close();
}
catch (SQLException e) {
Log.error(e);
}
}
}
}
/**
* Verifies that the given home guess is a real Wildfire home directory.
* We do the verification by checking for the Wildfire config file in
* the config dir of jiveHome.
*
* @param homeGuess a guess at the path to the home directory.
* @param jiveConfigName the name of the config file to check.
* @return a file pointing to the home directory or null if the
* home directory guess was wrong.
* @throws java.io.FileNotFoundException if there was a problem with the home
* directory provided
*/
private File verifyHome(String homeGuess, String jiveConfigName) throws FileNotFoundException {
File wildfireHome = new File(homeGuess);
File configFile = new File(wildfireHome, jiveConfigName);
if (!configFile.exists()) {
throw new FileNotFoundException();
}
else {
try {
return new File(wildfireHome.getCanonicalPath());
}
catch (Exception ex) {
throw new FileNotFoundException();
}
}
}
/**
* <p>Retrieve the jive home for the container.</p>
*
* @throws FileNotFoundException If jiveHome could not be located
*/
private void locateWildfire() throws FileNotFoundException {
String jiveConfigName = "conf" + File.separator + "wildfire.xml";
// First, try to load it wildfireHome as a system property.
if (wildfireHome == null) {
String homeProperty = System.getProperty("wildfireHome");
try {
if (homeProperty != null) {
wildfireHome = verifyHome(homeProperty, jiveConfigName);
}
}
catch (FileNotFoundException fe) {
// Ignore.
}
}
// If we still don't have home, let's assume this is standalone
// and just look for home in a standard sub-dir location and verify
// by looking for the config file
if (wildfireHome == null) {
try {
wildfireHome = verifyHome("..", jiveConfigName).getCanonicalFile();
}
catch (FileNotFoundException fe) {
// Ignore.
}
catch (IOException ie) {
// Ignore.
}
}
// If home is still null, no outside process has set it and
// we have to attempt to load the value from wildfire_init.xml,
// which must be in the classpath.
if (wildfireHome == null) {
InputStream in = null;
try {
in = getClass().getResourceAsStream("/wildfire_init.xml");
if (in != null) {
SAXReader reader = new SAXReader();
Document doc = reader.read(in);
String path = doc.getRootElement().getText();
try {
if (path != null) {
wildfireHome = verifyHome(path, jiveConfigName);
}
}
catch (FileNotFoundException fe) {
fe.printStackTrace();
}
}
}
catch (Exception e) {
System.err.println("Error loading wildfire_init.xml to find home.");
e.printStackTrace();
}
finally {
try {
if (in != null) {
in.close();
}
}
catch (Exception e) {
System.err.println("Could not close open connection");
e.printStackTrace();
}
}
}
if (wildfireHome == null) {
System.err.println("Could not locate home");
throw new FileNotFoundException();
}
else {
// Set the home directory for the config file
JiveGlobals.setHomeDirectory(wildfireHome.toString());
// Set the name of the config file
JiveGlobals.setConfigName(jiveConfigName);
}
}
/**
* <p>A thread to ensure the server shuts down no matter what.</p>
* <p>Spawned when stop() is called in standalone mode, we wait a few
* seconds then call system exit().</p>
*
* @author Iain Shigeoka
*/
private class ShutdownHookThread extends Thread {
/**
* <p>Logs the server shutdown.</p>
*/
public void run() {
shutdownServer();
Log.info("Server halted");
System.err.println("Server halted");
}
}
/**
* <p>A thread to ensure the server shuts down no matter what.</p>
* <p>Spawned when stop() is called in standalone mode, we wait a few
* seconds then call system exit().</p>
*
* @author Iain Shigeoka
*/
private class ShutdownThread extends Thread {
/**
* <p>Shuts down the JVM after a 5 second delay.</p>
*/
public void run() {
try {
Thread.sleep(5000);
// No matter what, we make sure it's dead
System.exit(0);
}
catch (InterruptedException e) {
// Ignore.
}
}
}
/**
* Makes a best effort attempt to shutdown the server
*/
private void shutdownServer() {
// Notify server listeners that the server is about to be stopped
for (XMPPServerListener listener : listeners) {
listener.serverStopping();
}
// If we don't have modules then the server has already been shutdown
if (modules.isEmpty()) {
return;
}
// Get all modules and stop and destroy them
for (Module module : modules.values()) {
module.stop();
module.destroy();
}
modules.clear();
// Stop all plugins
if (pluginManager != null) {
pluginManager.shutdown();
}
// Stop the Db connection manager.
DbConnectionManager.destroyConnectionProvider();
// hack to allow safe stopping
Log.info("Wildfire stopped");
}
/**
* Returns the <code>ConnectionManager</code> registered with this server. The
* <code>ConnectionManager</code> was registered with the server as a module while starting up
* the server.
*
* @return the <code>ConnectionManager</code> registered with this server.
*/
public ConnectionManager getConnectionManager() {
return (ConnectionManager) modules.get(ConnectionManagerImpl.class);
}
/**
* Returns the <code>RoutingTable</code> registered with this server. The
* <code>RoutingTable</code> was registered with the server as a module while starting up
* the server.
*
* @return the <code>RoutingTable</code> registered with this server.
*/
public RoutingTable getRoutingTable() {
return (RoutingTable) modules.get(RoutingTableImpl.class);
}
/**
* Returns the <code>PacketDeliverer</code> registered with this server. The
* <code>PacketDeliverer</code> was registered with the server as a module while starting up
* the server.
*
* @return the <code>PacketDeliverer</code> registered with this server.
*/
public PacketDeliverer getPacketDeliverer() {
return (PacketDeliverer) modules.get(PacketDelivererImpl.class);
}
/**
* Returns the <code>RosterManager</code> registered with this server. The
* <code>RosterManager</code> was registered with the server as a module while starting up
* the server.
*
* @return the <code>RosterManager</code> registered with this server.
*/
public RosterManager getRosterManager() {
return (RosterManager) modules.get(RosterManager.class);
}
/**
* Returns the <code>PresenceManager</code> registered with this server. The
* <code>PresenceManager</code> was registered with the server as a module while starting up
* the server.
*
* @return the <code>PresenceManager</code> registered with this server.
*/
public PresenceManager getPresenceManager() {
return (PresenceManager) modules.get(PresenceManagerImpl.class);
}
/**
* Returns the <code>OfflineMessageStore</code> registered with this server. The
* <code>OfflineMessageStore</code> was registered with the server as a module while starting up
* the server.
*
* @return the <code>OfflineMessageStore</code> registered with this server.
*/
public OfflineMessageStore getOfflineMessageStore() {
return (OfflineMessageStore) modules.get(OfflineMessageStore.class);
}
/**
* Returns the <code>OfflineMessageStrategy</code> registered with this server. The
* <code>OfflineMessageStrategy</code> was registered with the server as a module while starting
* up the server.
*
* @return the <code>OfflineMessageStrategy</code> registered with this server.
*/
public OfflineMessageStrategy getOfflineMessageStrategy() {
return (OfflineMessageStrategy) modules.get(OfflineMessageStrategy.class);
}
/**
* Returns the <code>PacketRouter</code> registered with this server. The
* <code>PacketRouter</code> was registered with the server as a module while starting up
* the server.
*
* @return the <code>PacketRouter</code> registered with this server.
*/
public PacketRouter getPacketRouter() {
return (PacketRouter) modules.get(PacketRouterImpl.class);
}
/**
* Returns the <code>IQRegisterHandler</code> registered with this server. The
* <code>IQRegisterHandler</code> was registered with the server as a module while starting up
* the server.
*
* @return the <code>IQRegisterHandler</code> registered with this server.
*/
public IQRegisterHandler getIQRegisterHandler() {
return (IQRegisterHandler) modules.get(IQRegisterHandler.class);
}
/**
* Returns the <code>IQAuthHandler</code> registered with this server. The
* <code>IQAuthHandler</code> was registered with the server as a module while starting up
* the server.
*
* @return the <code>IQAuthHandler</code> registered with this server.
*/
public IQAuthHandler getIQAuthHandler() {
return (IQAuthHandler) modules.get(IQAuthHandler.class);
}
/**
* Returns the <code>PluginManager</code> instance registered with this server.
*
* @return the PluginManager instance.
*/
public PluginManager getPluginManager() {
return pluginManager;
}
/**
* Returns the <code>PubSubModule</code> registered with this server. The
* <code>PubSubModule</code> was registered with the server as a module while starting up
* the server.
*
* @return the <code>PubSubModule</code> registered with this server.
*/
public PubSubModule getPubSubModule() {
return (PubSubModule) modules.get(PubSubModule.class);
}
/**
* Returns a list with all the modules registered with the server that inherit from IQHandler.
*
* @return a list with all the modules registered with the server that inherit from IQHandler.
*/
public List<IQHandler> getIQHandlers() {
List<IQHandler> answer = new ArrayList<IQHandler>();
for (Module module : modules.values()) {
if (module instanceof IQHandler) {
answer.add((IQHandler) module);
}
}
return answer;
}
/**
* Returns the <code>SessionManager</code> registered with this server. The
* <code>SessionManager</code> was registered with the server as a module while starting up
* the server.
*
* @return the <code>SessionManager</code> registered with this server.
*/
public SessionManager getSessionManager() {
return (SessionManager) modules.get(SessionManager.class);
}
/**
* Returns the <code>TransportHandler</code> registered with this server. The
* <code>TransportHandler</code> was registered with the server as a module while starting up
* the server.
*
* @return the <code>TransportHandler</code> registered with this server.
*/
public TransportHandler getTransportHandler() {
return (TransportHandler) modules.get(TransportHandler.class);
}
/**
* Returns the <code>PresenceUpdateHandler</code> registered with this server. The
* <code>PresenceUpdateHandler</code> was registered with the server as a module while starting
* up the server.
*
* @return the <code>PresenceUpdateHandler</code> registered with this server.
*/
public PresenceUpdateHandler getPresenceUpdateHandler() {
return (PresenceUpdateHandler) modules.get(PresenceUpdateHandler.class);
}
/**
* Returns the <code>PresenceSubscribeHandler</code> registered with this server. The
* <code>PresenceSubscribeHandler</code> was registered with the server as a module while
* starting up the server.
*
* @return the <code>PresenceSubscribeHandler</code> registered with this server.
*/
public PresenceSubscribeHandler getPresenceSubscribeHandler() {
return (PresenceSubscribeHandler) modules.get(PresenceSubscribeHandler.class);
}
/**
* Returns the <code>IQRouter</code> registered with this server. The
* <code>IQRouter</code> was registered with the server as a module while starting up
* the server.
*
* @return the <code>IQRouter</code> registered with this server.
*/
public IQRouter getIQRouter() {
return (IQRouter) modules.get(IQRouter.class);
}
/**
* Returns the <code>MessageRouter</code> registered with this server. The
* <code>MessageRouter</code> was registered with the server as a module while starting up
* the server.
*
* @return the <code>MessageRouter</code> registered with this server.
*/
public MessageRouter getMessageRouter() {
return (MessageRouter) modules.get(MessageRouter.class);
}
/**
* Returns the <code>PresenceRouter</code> registered with this server. The
* <code>PresenceRouter</code> was registered with the server as a module while starting up
* the server.
*
* @return the <code>PresenceRouter</code> registered with this server.
*/
public PresenceRouter getPresenceRouter() {
return (PresenceRouter) modules.get(PresenceRouter.class);
}
/**
* Returns the <code>MulticastRouter</code> registered with this server. The
* <code>MulticastRouter</code> was registered with the server as a module while starting up
* the server.
*
* @return the <code>MulticastRouter</code> registered with this server.
*/
public MulticastRouter getMulticastRouter() {
return (MulticastRouter) modules.get(MulticastRouter.class);
}
/**
* Returns the <code>UserManager</code> registered with this server. The
* <code>UserManager</code> was registered with the server as a module while starting up
* the server.
*
* @return the <code>UserManager</code> registered with this server.
*/
public UserManager getUserManager() {
return UserManager.getInstance();
}
/**
* Returns the <code>UpdateManager</code> registered with this server. The
* <code>UpdateManager</code> was registered with the server as a module while starting up
* the server.
*
* @return the <code>UpdateManager</code> registered with this server.
*/
public UpdateManager getUpdateManager() {
return (UpdateManager) modules.get(UpdateManager.class);
}
/**
* Returns the <code>AuditManager</code> registered with this server. The
* <code>AuditManager</code> was registered with the server as a module while starting up
* the server.
*
* @return the <code>AuditManager</code> registered with this server.
*/
public AuditManager getAuditManager() {
return (AuditManager) modules.get(AuditManagerImpl.class);
}
/**
* Returns a list with all the modules that provide "discoverable" features.
*
* @return a list with all the modules that provide "discoverable" features.
*/
public List<ServerFeaturesProvider> getServerFeaturesProviders() {
List<ServerFeaturesProvider> answer = new ArrayList<ServerFeaturesProvider>();
for (Module module : modules.values()) {
if (module instanceof ServerFeaturesProvider) {
answer.add((ServerFeaturesProvider) module);
}
}
return answer;
}
/**
* Returns a list with all the modules that provide "discoverable" items associated with
* the server.
*
* @return a list with all the modules that provide "discoverable" items associated with
* the server.
*/
public List<ServerItemsProvider> getServerItemsProviders() {
List<ServerItemsProvider> answer = new ArrayList<ServerItemsProvider>();
for (Module module : modules.values()) {
if (module instanceof ServerItemsProvider) {
answer.add((ServerItemsProvider) module);
}
}
return answer;
}
/**
* Returns the <code>IQDiscoInfoHandler</code> registered with this server. The
* <code>IQDiscoInfoHandler</code> was registered with the server as a module while starting up
* the server.
*
* @return the <code>IQDiscoInfoHandler</code> registered with this server.
*/
public IQDiscoInfoHandler getIQDiscoInfoHandler() {
return (IQDiscoInfoHandler) modules.get(IQDiscoInfoHandler.class);
}
/**
* Returns the <code>IQDiscoItemsHandler</code> registered with this server. The
* <code>IQDiscoItemsHandler</code> was registered with the server as a module while starting up
* the server.
*
* @return the <code>IQDiscoItemsHandler</code> registered with this server.
*/
public IQDiscoItemsHandler getIQDiscoItemsHandler() {
return (IQDiscoItemsHandler) modules.get(IQDiscoItemsHandler.class);
}
/**
* Returns the <code>PrivateStorage</code> registered with this server. The
* <code>PrivateStorage</code> was registered with the server as a module while starting up
* the server.
*
* @return the <code>PrivateStorage</code> registered with this server.
*/
public PrivateStorage getPrivateStorage() {
return (PrivateStorage) modules.get(PrivateStorage.class);
}
/**
* Returns the <code>MultiUserChatServer</code> registered with this server. The
* <code>MultiUserChatServer</code> was registered with the server as a module while starting up
* the server.
*
* @return the <code>MultiUserChatServer</code> registered with this server.
*/
public MultiUserChatServer getMultiUserChatServer() {
return (MultiUserChatServer) modules.get(MultiUserChatServerImpl.class);
}
/**
* Returns the <code>AdHocCommandHandler</code> registered with this server. The
* <code>AdHocCommandHandler</code> was registered with the server as a module while starting up
* the server.
*
* @return the <code>AdHocCommandHandler</code> registered with this server.
*/
public AdHocCommandHandler getAdHocCommandHandler() {
return (AdHocCommandHandler) modules.get(AdHocCommandHandler.class);
}
/**
* Returns the <code>FileTransferProxy</code> registered with this server. The
* <code>FileTransferProxy</code> was registered with the server as a module while starting up
* the server.
*
* @return the <code>FileTransferProxy</code> registered with this server.
*/
public FileTransferProxy getFileTransferProxy() {
return (FileTransferProxy) modules.get(FileTransferProxy.class);
}
/**
* Returns the <code>FileTransferManager</code> registered with this server. The
* <code>FileTransferManager</code> was registered with the server as a module while starting up
* the server.
*
* @return the <code>FileTransferProxy</code> registered with this server.
*/
public FileTransferManager getFileTransferManager() {
return (FileTransferManager) modules.get(DefaultFileTransferManager.class);
}
}
|
package edu.umd.cs.findbugs.annotations;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Mark a constructor or method as creating a resource
* which requires cleanup.
* The marked method must be a member of a class
* marked with the CleanupObligation annotation.
*
* @author David Hovemeyer
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.CONSTRUCTOR})
public @interface CreatesObligation {
}
|
package org.nuxeo.drive.listener;
import java.security.Principal;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;
import org.nuxeo.drive.adapter.FileSystemItem;
import org.nuxeo.drive.adapter.RootlessItemException;
import org.nuxeo.drive.service.FileSystemItemAdapterService;
import org.nuxeo.drive.service.NuxeoDriveEvents;
import org.nuxeo.ecm.core.api.ClientException;
import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.ecm.core.api.LifeCycleConstants;
import org.nuxeo.ecm.core.api.event.DocumentEventTypes;
import org.nuxeo.ecm.core.event.Event;
import org.nuxeo.ecm.core.event.EventListener;
import org.nuxeo.ecm.core.event.impl.DocumentEventContext;
import org.nuxeo.ecm.platform.audit.api.AuditLogger;
import org.nuxeo.ecm.platform.audit.api.ExtendedInfo;
import org.nuxeo.ecm.platform.audit.api.LogEntry;
import org.nuxeo.runtime.api.Framework;
/**
* Event listener to track events that should be mapped to file system item
* deletions in the the ChangeSummary computation.
*
* In particular this includes
*
* <li>Synchronization root unregistration (user specific)</li>
*
* <li>Simple document or root document lifecycle change to the 'deleted' state</li>
*
* <li>Simple document or root physical removal from the directory.</li>
*/
public class NuxeoDriveFileSystemDeletionListener implements EventListener {
@Override
public void handleEvent(Event event) throws ClientException {
DocumentEventContext ctx;
if (event.getContext() instanceof DocumentEventContext) {
ctx = (DocumentEventContext) event.getContext();
} else {
// not interested in event that are not related to documents
return;
}
DocumentModel doc = ctx.getSourceDocument();
if (DocumentEventTypes.ABOUT_TO_REMOVE.equals(event.getName())
&& LifeCycleConstants.DELETED_STATE.equals(doc.getCurrentLifeCycleState())) {
// Document deletion of document that are already in deleted state
// should not be marked as FS deletion to avoid duplicates
return;
}
String transition = (String) ctx.getProperty(LifeCycleConstants.TRANSTION_EVENT_OPTION_TRANSITION);
if (transition != null
&& !LifeCycleConstants.DELETE_TRANSITION.equals(transition)) {
// not interested in lifecycle transitions that are not related to
// document deletion
return;
}
// Some events will only impact a specific user (e.g. root
// unregistration)
String impactedUserName = (String) ctx.getProperty(NuxeoDriveEvents.IMPACTED_USERNAME_PROPERTY);
logDeletionEvent(doc, ctx.getPrincipal(), impactedUserName);
}
protected void logDeletionEvent(DocumentModel doc, Principal principal,
String impactedUserName) throws ClientException {
AuditLogger logger = Framework.getLocalService(AuditLogger.class);
if (logger == null) {
// The log is not deployed (probably in unittest)
return;
}
FileSystemItem fsItem = null;
try {
fsItem = Framework.getLocalService(
FileSystemItemAdapterService.class).getFileSystemItem(doc,
true);
} catch (RootlessItemException e) {
// can happen when deleting a folder under and unregistered root:
// nothing to do
return;
}
if (fsItem == null) {
return;
}
LogEntry entry = logger.newLogEntry();
entry.setEventId(NuxeoDriveEvents.DELETED_EVENT);
// XXX: shall we use the server local for the event date or UTC?
entry.setEventDate(Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTime());
entry.setCategory((String) NuxeoDriveEvents.EVENT_CATEGORY);
entry.setDocUUID(doc.getId());
entry.setDocPath(doc.getPathAsString());
entry.setPrincipalName(principal.getName());
entry.setDocType(doc.getType());
entry.setRepositoryId(doc.getRepositoryName());
entry.setDocLifeCycle(doc.getCurrentLifeCycleState());
Map<String, ExtendedInfo> extendedInfos = new HashMap<String, ExtendedInfo>();
if (impactedUserName != null) {
extendedInfos.put("impactedUserName",
logger.newExtendedInfo(impactedUserName));
}
// We do not serialize the whole object as it's too big to fit in a
// StringInfo column and
extendedInfos.put("fileSystemItemId",
logger.newExtendedInfo(fsItem.getId()));
extendedInfos.put("fileSystemItemName",
logger.newExtendedInfo(fsItem.getName()));
entry.setExtendedInfos(extendedInfos);
logger.addLogEntries(Collections.singletonList(entry));
}
}
|
package jsettlers.algorithms;
import jsettlers.common.material.ESearchType;
import jsettlers.common.position.ISPosition2D;
import jsettlers.common.position.ShortPoint2D;
import jsettlers.logic.algorithms.path.IPathCalculateable;
import jsettlers.logic.algorithms.path.Path;
import jsettlers.logic.algorithms.path.astar.HexAStar;
import jsettlers.logic.algorithms.path.dijkstra.DijkstraAlgorithm;
import jsettlers.logic.algorithms.path.dijkstra.IDijkstraPathMap;
import jsettlers.logic.algorithms.path.test.DummyEmptyAStarMap;
public class SimpleDijkstraTester {
private static final short WIDTH = (short) 200;
private static final short HEIGHT = (short) 200;
public static void main(String args[]) {
IDijkstraPathMap map = new IDijkstraPathMap() {
@Override
public boolean fitsSearchType(short x, short y, ESearchType type, IPathCalculateable requester) {
if (x == 120 && y == 100)
return true;
if (x == 110 && y == 110)
return true;
if (x == 118 && y == 115)
return true;
return false;
}
@Override
public void setDijkstraSearched(short x, short y) {
}
};
DummyEmptyAStarMap aStarMap = new DummyEmptyAStarMap(WIDTH, HEIGHT);
aStarMap.setBlocked(120, 100, true);
DijkstraAlgorithm dijkstra = new DijkstraAlgorithm(map, new HexAStar(aStarMap, WIDTH, HEIGHT), WIDTH, HEIGHT);
IPathCalculateable requester = new IPathCalculateable() {
@Override
public ISPosition2D getPos() {
return new ShortPoint2D(100, 100);
}
@Override
public byte getPlayer() {
// TODO Auto-generated method stub
return 0;
}
@Override
public boolean needsPlayersGround() {
return false;
}
};
Path path = dijkstra.find(requester, (short) 100, (short) 100, (short) 1, (short) 30, null);
System.out.println("path: " + path);
}
}
|
package org.nuxeo.ecm.platform.ec.notification;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.mail.MessagingException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuxeo.ecm.core.api.ClientException;
import org.nuxeo.ecm.core.api.CoreSession;
import org.nuxeo.ecm.core.api.DataModel;
import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.ecm.core.api.NuxeoGroup;
import org.nuxeo.ecm.core.api.NuxeoPrincipal;
import org.nuxeo.ecm.core.api.PathRef;
import org.nuxeo.ecm.core.event.Event;
import org.nuxeo.ecm.core.event.EventBundle;
import org.nuxeo.ecm.core.event.EventContext;
import org.nuxeo.ecm.core.event.PostCommitEventListener;
import org.nuxeo.ecm.core.event.impl.DocumentEventContext;
import org.nuxeo.ecm.platform.ec.notification.email.EmailHelper;
import org.nuxeo.ecm.platform.ec.notification.service.NotificationService;
import org.nuxeo.ecm.platform.ec.notification.service.NotificationServiceHelper;
import org.nuxeo.ecm.platform.notification.api.Notification;
import org.nuxeo.ecm.platform.url.DocumentViewImpl;
import org.nuxeo.ecm.platform.url.api.DocumentView;
import org.nuxeo.ecm.platform.url.api.DocumentViewCodecManager;
import org.nuxeo.ecm.platform.usermanager.UserManager;
import org.nuxeo.runtime.api.Framework;
public class NotificationEventListener implements PostCommitEventListener {
private static final Log log = LogFactory
.getLog(NotificationEventListener.class);
private DocumentViewCodecManager docLocator;
private UserManager userManager;
private EmailHelper emailHelper = new EmailHelper();
public void handleEvent(EventBundle events) throws ClientException {
NotificationService service = NotificationServiceHelper
.getNotificationService();
if (service == null) {
log.error("Unable to get NotificationService, exiting");
return;
}
for (Event event : events) {
List<Notification> notifs = service.getNotificationsForEvents(event
.getName());
if (notifs != null && !notifs.isEmpty()) {
try {
handleNotifications(event, notifs);
} catch (Exception e) {
log.error("Error during Notification processing for event "
+ event.getName(), e);
}
}
}
}
protected void handleNotifications(Event event, List<Notification> notifs)
throws Exception {
EventContext ctx = event.getContext();
DocumentEventContext docCtx = null;
if (ctx instanceof DocumentEventContext) {
docCtx = (DocumentEventContext) ctx;
} else {
log.warn("Can not handle notification on a event that is not bound to a DocumentEventContext");
return;
}
CoreSession coreSession = event.getContext().getCoreSession();
Map<String, Serializable> properties = event.getContext()
.getProperties();
Map<Notification, List<String>> targetUsers = new HashMap<Notification, List<String>>();
gatherConcernedUsersForDocument(coreSession,
docCtx.getSourceDocument(), notifs, targetUsers);
for (Notification notif : targetUsers.keySet()) {
if (!notif.getAutoSubscribed()) {
for (String user : targetUsers.get(notif)) {
sendNotificationSignalForUser(notif, user, event, docCtx);
}
} else {
String[] recipients = (String[]) properties
.get(NotificationConstants.RECIPIENTS_KEY);
if (recipients == null) {
return;
}
Set<String> users = new HashSet<String>();
for (String recipient : recipients) {
if (recipient == null) {
continue;
}
if (recipient.contains(NuxeoPrincipal.PREFIX)) {
users.add(recipient.replace(NuxeoPrincipal.PREFIX, ""));
} else if (recipient.contains(NuxeoGroup.PREFIX)) {
List<String> groupMembers = getGroupMembers(recipient
.replace(NuxeoGroup.PREFIX, ""));
for (String member : groupMembers) {
users.add(member);
}
} else {
users.add(recipient);
}
}
for (String user : users) {
sendNotificationSignalForUser(notif, user, event, docCtx);
}
}
}
}
protected UserManager getUserManager() {
if (userManager == null) {
try {
userManager = Framework.getService(UserManager.class);
} catch (Exception e) {
throw new IllegalStateException(
"UserManager service not deployed.", e);
}
}
return userManager;
}
protected List<String> getGroupMembers(String groupId)
throws ClientException {
return getUserManager().getUsersInGroup(groupId);
}
private void sendNotificationSignalForUser(Notification notification,
String subscriptor, Event event, DocumentEventContext ctx)
throws ClientException {
log.debug("Producing notification message.");
Map<String, Serializable> eventInfo = ctx.getProperties();
eventInfo.put(NotificationConstants.DESTINATION_KEY, subscriptor);
eventInfo.put(NotificationConstants.NOTIFICATION_KEY, notification);
eventInfo.put(NotificationConstants.DOCUMENT_ID_KEY, ctx
.getSourceDocument().getId());
eventInfo.put(NotificationConstants.DATE_TIME_KEY, new Date(event
.getTime()));
eventInfo.put(NotificationConstants.AUTHOR_KEY, ctx.getPrincipal()
.getName());
DocumentModel doc = ctx.getSourceDocument();
if (!isDeleteEvent(event.getName())) {
DocumentView docView = new DocumentViewImpl(doc);
eventInfo.put(NotificationConstants.DOCUMENT_URL_KEY,
getDocLocator().getUrlFromDocumentView(
docView,
true,
NotificationServiceHelper.getNotificationService()
.getServerUrlPrefix()));
eventInfo.put(NotificationConstants.DOCUMENT_TITLE_KEY, doc
.getTitle());
}
if (isInterestedInNotification(notification)) {
try {
sendNotification(event, ctx);
if (log.isDebugEnabled()) {
log.debug("notification " + notification.getName()
+ " sent to " + notification.getSubject());
}
} catch (ClientException e) {
log
.error(
"An error occurred while trying to send user notification",
e);
}
}
}
public void sendNotification(Event event, DocumentEventContext ctx)
throws ClientException {
String eventId = event.getName();
log.debug("Recieved a message for notification sender with eventId : "
+ eventId);
Map<String, Serializable> eventInfo = ctx.getProperties();
String userDest = (String) eventInfo
.get(NotificationConstants.DESTINATION_KEY);
NotificationImpl notif = (NotificationImpl) eventInfo
.get(NotificationConstants.NOTIFICATION_KEY);
// send email
NuxeoPrincipal recepient = NotificationServiceHelper.getUsersService()
.getPrincipal(userDest);
if (recepient == null) {
log.error("Couldn't find user: " + userDest
+ " to send her a mail.");
return;
}
// XXX hack, principals have only one model
DataModel model = recepient.getModel().getDataModels().values()
.iterator().next();
String email = (String) model.getData("email");
String subjectTemplate = notif.getSubjectTemplate();
String mailTemplate = notif.getTemplate();
log.debug("email: " + email);
log.debug("mail template: " + mailTemplate);
log.debug("subject template: " + subjectTemplate);
Map<String, Object> mail = new HashMap<String, Object>();
mail.put("mail.to", email);
String authorUsername = (String) eventInfo
.get(NotificationConstants.AUTHOR_KEY);
if (authorUsername != null) {
NuxeoPrincipal author = NotificationServiceHelper.getUsersService()
.getPrincipal(authorUsername);
mail.put(NotificationConstants.PRINCIPAL_AUTHOR_KEY, author);
}
mail.put(NotificationConstants.DOCUMENT_KEY, ctx.getSourceDocument());
String subject = notif.getSubject() == null ? NotificationConstants.NOTIFICATION_KEY
: notif.getSubject();
subject = NotificationServiceHelper.getNotificationService()
.getEMailSubjectPrefix()
+ subject;
mail.put("subject", subject);
mail.put("template", mailTemplate);
mail.put("subjectTemplate", subjectTemplate);
// Transferring all data from event to email
for (String key : eventInfo.keySet()) {
mail.put(key, eventInfo.get(key));
log.debug("Mail prop: " + key);
}
mail.put(NotificationConstants.EVENT_ID_KEY, eventId);
try {
emailHelper.sendmail(mail);
} catch (MessagingException e) {
log.error("Failed to send notification email to '" + email + "': "
+ e.getClass().getName() + ": " + e.getMessage());
} catch (Exception e) {
throw new ClientException("Failed to send notification email ", e);
}
}
private DocumentModel getDocFromPath(CoreSession coreSession, String path)
throws ClientException {
if (path == null) {
return null;
}
return coreSession.getDocument(new PathRef(path));
}
/**
* Adds the concerned users to the list of targeted users for these
* notifications.
*/
private void gatherConcernedUsersForDocument(CoreSession coreSession,
DocumentModel doc, List<Notification> notifs,
Map<Notification, List<String>> targetUsers) throws Exception {
if (doc.getPath().segmentCount() > 1) {
log.debug("Searching document: " + doc.getName());
getInterstedUsers(doc, notifs, targetUsers);
DocumentModel parent = getDocumentParent(coreSession, doc);
gatherConcernedUsersForDocument(coreSession, parent, notifs,
targetUsers);
}
}
private DocumentModel getDocumentParent(CoreSession coreSession,
DocumentModel doc) throws ClientException {
if (doc == null) {
return null;
}
return coreSession.getDocument(doc.getParentRef());
}
private void getInterstedUsers(DocumentModel doc,
List<Notification> notifs,
Map<Notification, List<String>> targetUsers) throws Exception {
for (Notification notification : notifs) {
if (!notification.getAutoSubscribed()) {
List<String> userGroup = NotificationServiceHelper
.getNotificationService().getSubscribers(
notification.getName(), doc.getId());
for (String subscriptor : userGroup) {
if (subscriptor != null) {
if (isUser(subscriptor)) {
storeUserForNotification(notification, subscriptor
.substring(5), targetUsers);
} else {
// it is a group - get all users and send
// notifications to them
List<String> usersOfGroup = NotificationServiceHelper
.getUsersService().getUsersInGroup(
subscriptor.substring(6));
if (usersOfGroup != null && !usersOfGroup.isEmpty()) {
for (String usr : usersOfGroup) {
storeUserForNotification(notification, usr,
targetUsers);
}
}
}
}
}
} else {
// An automatic notification happens
// should be sent to interested users
targetUsers.put(notification, new ArrayList<String>());
}
}
}
private void storeUserForNotification(Notification notification,
String user, Map<Notification, List<String>> targetUsers) {
List<String> subscribedUsers = targetUsers.get(notification);
if (subscribedUsers == null) {
targetUsers.put(notification, new ArrayList<String>());
}
if (!targetUsers.get(notification).contains(user)) {
targetUsers.get(notification).add(user);
}
}
private boolean isDeleteEvent(String eventId) {
List<String> deletionEvents = new ArrayList<String>();
deletionEvents.add("aboutToRemove");
deletionEvents.add("documentRemoved");
return deletionEvents.contains(eventId);
}
private boolean isUser(String subscriptor) {
return subscriptor != null && subscriptor.startsWith("user:");
}
public boolean isInterestedInNotification(Notification notif) {
return notif != null && "email".equals(notif.getChannel());
}
public DocumentViewCodecManager getDocLocator() {
if (docLocator == null) {
try {
docLocator = Framework
.getService(DocumentViewCodecManager.class);
} catch (Exception e) {
log.info("Could not get service for document view manager");
}
}
return docLocator;
}
public EmailHelper getEmailHelper() {
return emailHelper;
}
public void setEmailHelper(EmailHelper emailHelper) {
this.emailHelper = emailHelper;
}
}
|
package justaway.signinwithtwitter;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Locale;
import twitter4j.DirectMessage;
import twitter4j.MediaEntity;
import twitter4j.Status;
import twitter4j.User;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v4.util.LruCache;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.WebView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
public class TwitterAdapter extends ArrayAdapter<Row> {
private Context context;
private ArrayList<Row> statuses = new ArrayList<Row>();
private LayoutInflater inflater;
private int layout;
private LruCache<String, Bitmap> mMemoryCache;
private static int limit = 500;
public TwitterAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
this.inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.context = context;
this.layout = textViewResourceId;
// Get max available VM memory, exceeding this amount will throw an
// OutOfMemory exception. Stored in kilobytes as LruCache takes an
// int in its constructor.
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
// Use 1/8th of the available memory for this memory cache.
final int cacheSize = maxMemory / 2;
mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
@SuppressLint("NewApi")
@Override
protected int sizeOf(String key, Bitmap bitmap) {
// The cache size will be measured in kilobytes rather than
// number of items.
return bitmap.getByteCount() / 1024;
}
};
}
@Override
public void add(Row row) {
super.add(row);
this.statuses.add(row);
this.limitation();
}
@Override
public void insert(Row row, int index) {
super.insert(row, index);
this.statuses.add(index, row);
this.limitation();
}
public void limitation() {
int size = this.statuses.size();
if (size > limit) {
int count = size - limit;
for (int i = 0; i < count; i++) {
super.remove(this.statuses.remove(size - i - 1));
}
}
}
@Override
public void clear() {
super.clear();
this.statuses.clear();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
// null
view = inflater.inflate(this.layout, null);
}
Row row = (Row) statuses.get(position);
if (row.isDirectMessage()) {
DirectMessage message = row.getMessage();
if (message == null) {
return view;
}
renderMessage(view, message);
} else {
Status status = row.getStatus();
if (status == null) {
return view;
}
Status retweet = status.getRetweetedStatus();
if (row.isFavorite()) {
renderStatus(view, status, null, row.getSource());
} else if (retweet == null) {
renderStatus(view, status, null, null);
} else {
renderStatus(view, retweet, status, null);
}
}
if (position == 0) {
((MainActivity) context).showTopView();
}
return view;
}
private void renderMessage(View view, DirectMessage message) {
((TextView) view.findViewById(R.id.display_name)).setText(message
.getSender().getName());
((TextView) view.findViewById(R.id.screen_name)).setText("@"
+ message.getSender().getScreenName());
((TextView) view.findViewById(R.id.status)).setText("D "
+ message.getRecipientScreenName() + " " + message.getText());
SimpleDateFormat date_format = new SimpleDateFormat(
"MM'/'dd' 'hh':'mm':'ss", Locale.ENGLISH);
((TextView) view.findViewById(R.id.datetime)).setText(date_format
.format(message.getCreatedAt()));
view.findViewById(R.id.via).setVisibility(View.GONE);
view.findViewById(R.id.retweet).setVisibility(View.GONE);
view.findViewById(R.id.images).setVisibility(View.GONE);
ImageView icon = (ImageView) view.findViewById(R.id.icon);
ProgressBar wait = (ProgressBar) view.findViewById(R.id.WaitBar);
renderIcon(wait, icon, message.getSender().getBiggerProfileImageURL());
}
private void renderStatus(View view, Status status, Status retweet,
User favorite) {
((TextView) view.findViewById(R.id.display_name)).setText(status
.getUser().getName());
((TextView) view.findViewById(R.id.screen_name)).setText("@"
+ status.getUser().getScreenName());
((TextView) view.findViewById(R.id.status)).setText(status.getText());
SimpleDateFormat date_format = new SimpleDateFormat(
"MM'/'dd' 'hh':'mm':'ss", Locale.ENGLISH);
((TextView) view.findViewById(R.id.datetime)).setText(date_format
.format(status.getCreatedAt()));
((TextView) view.findViewById(R.id.via)).setText("via "
+ getClientName(status.getSource()));
view.findViewById(R.id.via).setVisibility(View.VISIBLE);
// fav
if (favorite != null) {
((TextView) view.findViewById(R.id.retweet_by))
.setText("favorited by " + favorite.getScreenName() + "("
+ favorite.getName() + ")");
ImageView icon = (ImageView) view.findViewById(R.id.retweet_icon);
ProgressBar wait = (ProgressBar) view
.findViewById(R.id.retweet_wait);
renderIcon(wait, icon, favorite.getMiniProfileImageURL());
view.findViewById(R.id.retweet).setVisibility(View.VISIBLE);
}
else if (retweet != null) {
((TextView) view.findViewById(R.id.retweet_by))
.setText("retweeted by "
+ retweet.getUser().getScreenName() + "("
+ retweet.getUser().getName() + ") and "
+ String.valueOf(status.getRetweetCount())
+ " others");
ImageView icon = (ImageView) view.findViewById(R.id.retweet_icon);
ProgressBar wait = (ProgressBar) view
.findViewById(R.id.retweet_wait);
renderIcon(wait, icon, retweet.getUser().getMiniProfileImageURL());
view.findViewById(R.id.retweet).setVisibility(View.VISIBLE);
} else {
view.findViewById(R.id.retweet).setVisibility(View.GONE);
}
ImageView icon = (ImageView) view.findViewById(R.id.icon);
ProgressBar wait = (ProgressBar) view.findViewById(R.id.WaitBar);
renderIcon(wait, icon, status.getUser().getBiggerProfileImageURL());
icon.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO: UserProfileActivity
System.out.println("icon touch!");
}
});
MediaEntity[] medias = retweet != null ? retweet.getMediaEntities()
: status.getMediaEntities();
LinearLayout images = (LinearLayout) view.findViewById(R.id.images);
images.removeAllViews();
if (medias.length > 0) {
for (final MediaEntity url : medias) {
ImageView image = new ImageView(context);
image.setScaleType(ImageView.ScaleType.CENTER_CROP);
images.addView(image, new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, 120));
renderIcon(null, image, url.getMediaURL());
// WebView
image.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
WebView webView = new WebView(context);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setBuiltInZoomControls(true);
String htmlData = "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"><style>html,body {margin:0;padding:0}img {max-width:100%}</style><img src=\"" + url.getMediaURL() + "\">";
webView.loadDataWithBaseURL("file:///android_asset/", htmlData, "text/html", "utf-8", null);
Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(webView);
dialog.show();
}
});
}
images.setVisibility(View.VISIBLE);
} else {
images.setVisibility(View.GONE);
}
}
private void renderIcon(ProgressBar wait, ImageView icon, String url) {
if (wait != null) {
wait.setVisibility(View.VISIBLE);
}
icon.setVisibility(View.GONE);
String tag = (String) icon.getTag();
if (tag != null && tag == url) {
} else {
icon.setTag(url);
Bitmap image = mMemoryCache.get(url);
if (image == null) {
ImageGetTask task = new ImageGetTask(icon, wait);
task.execute(url);
} else {
icon.setImageBitmap(image);
icon.setVisibility(View.VISIBLE);
if (wait != null) {
wait.setVisibility(View.GONE);
}
}
}
}
private String getClientName(String source) {
String[] tokens = source.split("[<>]");
if (tokens.length > 1) {
return tokens[2];
} else {
return tokens[0];
}
}
class ImageGetTask extends AsyncTask<String, Void, Bitmap> {
private ImageView image;
private String tag;
private ProgressBar bar;
public ImageGetTask(ImageView image, ProgressBar bar) {
this.image = image;
this.bar = bar;
this.tag = image.getTag().toString();
}
@Override
protected Bitmap doInBackground(String... params) {
// HttpBitmap
synchronized (context) {
try {
URL imageUrl = new URL(params[0]);
InputStream imageIs;
imageIs = imageUrl.openStream();
Bitmap bitmap = BitmapFactory.decodeStream(imageIs);
return bitmap;
} catch (MalformedURLException e) {
return null;
} catch (IOException e) {
return null;
}
}
}
@Override
protected void onPostExecute(Bitmap bitmap) {
// Tag
// Tag
if (tag.equals(image.getTag())) {
if (bitmap != null) {
mMemoryCache.put(tag, bitmap);
image.setImageBitmap(bitmap);
} else {
// image.setImageDrawable(context.getResources().getDrawable(
// R.drawable.x));
}
image.setVisibility(View.VISIBLE);
if (bar != null) {
bar.setVisibility(View.GONE);
}
}
}
}
}
|
package org.carewebframework.help;
import org.carewebframework.ui.command.CommandUtil;
import org.zkoss.zk.ui.Component;
import org.zkoss.zul.impl.XulElement;
/**
* Utility methods supporting context sensitive help.
*/
public class HelpCSH {
private static final String HELP_PREFIX = HelpCSH.class.getPackage().getName() + ".";
private static final String CSH_TARGET = HELP_PREFIX + "target";
/**
* Show help for the given module and optional topic.
*
* @param module The id of the help module.
* @param topic The id of the desired topic. If null, the home topic is shown.
* @param label The label to display for the topic. If null, the topic id is displayed as the
* label.
*/
public static void show(String module, String topic, String label) {
show(new HelpContext(module, topic, label));
}
/**
* Show help for the given help target.
*
* @param target The help target.
*/
public static void show(HelpContext target) {
HelpModule dx = HelpModuleRegistry.getInstance().get(target.module);
IHelpSet hs = dx == null ? null : HelpSetCache.getInstance().get(dx);
if (hs != null) {
String label = target.label == null && target.topic == null ? dx.getTitle() : target.label;
IHelpViewer viewer = HelpUtil.getViewer();
viewer.mergeHelpSet(hs);
viewer.show(hs, target.topic, label);
}
}
/**
* Displays the help viewer's table of contents.
*/
public static void showTOC() {
HelpUtil.getViewer().show(HelpViewType.TOC);
}
/**
* Display context-sensitive help associated with the specified component. If none is associated
* with the component, its parent is examined, and so on. If no help association is found, no
* action is taken.
*
* @param component Component whose CSH is to be displayed.
*/
public static void showCSH(Component component) {
while (component != null) {
HelpContext target = (HelpContext) component.getAttribute(CSH_TARGET);
if (target != null) {
show(target);
break;
}
component = component.getParent();
}
}
/**
* Associates context-sensitive help topic with a component. Any existing association is
* replaced.
*
* @param component Component to be associated.
* @param helpContext The help target.
* @param commandTarget The command target.
*/
public static void associateCSH(XulElement component, HelpContext helpContext, Component commandTarget) {
if (component != null) {
component.setAttribute(CSH_TARGET, helpContext);
CommandUtil.associateCommand("help", component, commandTarget);
}
}
/**
* Dissociates context-sensitive help from a component.
*
* @param component Component to dissociate.
*/
public static void dissociateCSH(XulElement component) {
if (component != null && component.hasAttribute(CSH_TARGET)) {
CommandUtil.dissociateCommand("help", component);
component.removeAttribute(CSH_TARGET);
}
}
/**
* Enforces static class.
*/
private HelpCSH() {
}
}
|
package org.wyona.yanel.impl.resources;
import org.wyona.yanel.core.Resource;
import org.wyona.yanel.core.api.attributes.ViewableV2;
import org.wyona.yanel.core.attributes.viewable.View;
import org.wyona.yanel.core.attributes.viewable.ViewDescriptor;
import org.wyona.yanel.core.navigation.Node;
import org.wyona.yanel.core.navigation.Sitetree;
import org.apache.log4j.Category;
public class DataRepoSitetreeResource extends Resource implements ViewableV2 {
private static Category log = Category.getInstance(DataRepoSitetreeResource.class);
public DataRepoSitetreeResource() {
}
public String getMimeType(String viewId) throws Exception {
if (viewId != null && viewId.equals("xml")) return "application/xml";
return "application/xhtml+xml";
}
public long getSize() throws Exception {
return -1;
}
public boolean exists() throws Exception {
return true;
}
public View getView(String viewId) throws Exception {
StringBuffer sb = new StringBuffer("<?xml version=\"1.0\"?>");
if (viewId != null && viewId.equals("xml")) {
sb.append(getSitetreeAsXML());
//sb.append(getSitetreeAsXML(getPath().toString()));
} else {
sb.append("<html xmlns=\"http:
}
View view = new View();
view.setMimeType(getMimeType(viewId));
view.setInputStream(new java.io.StringBufferInputStream(sb.toString()));
return view;
}
public ViewDescriptor[] getViewDescriptors() {
try {
ViewDescriptor[] vd = new ViewDescriptor[2];
vd[0] = new ViewDescriptor("default");
vd[0].setMimeType(getMimeType(null));
vd[1] = new ViewDescriptor("xml");
vd[1].setMimeType(getMimeType("xml"));
return vd;
} catch (Exception e) {
log.error(e.getMessage(), e);
return null;
}
}
/**
* Get sitetree as XML
*/
private String getSitetreeAsXML() {
StringBuffer sb = new StringBuffer("<sitetree>");
sb.append(getNodeAsXML("/"));
// TODO: Sitetree generated out of RDF resources and statements
/*
com.hp.hpl.jena.rdf.model.Resource rootResource = getRealm().getSitetreeRootResource();
sb.append(getNodeAsXML(rootResource));
*/
sb.append("</sitetree>");
return sb.toString();
}
/**
* Get node as XML
*/
private String getNodeAsXML(String path) {
//private String getNodeAsXML(com.hp.hpl.jena.rdf.model.Resource resource) {
//log.error("DEBUG: Path: " + path);
Sitetree sitetree = getRealm().getRepoNavigation();
Node node = sitetree.getNode(getRealm(), path);
StringBuffer sb = new StringBuffer("");
// TODO: Check for statements "parentOf" for this resource
/*
Statement[] st = resource.getStatements("parentOf");
if (st.length > 0) {
for (int i = 0; i < st.length; i++) {
Resource child = st.getObject();
URL url = getReal().getURLBuilder(child);
}
} else {
// Is not a collection, there are no children
}
*/
if (node != null) {
if (node.isCollection()) {
sb.append("<collection path=\"" + path + "\" name=\" " + node.getName() + "\">");
Node[] children = node.getChildren();
for (int i = 0; i < children.length; i++) {
if (children[i].isCollection()) {
sb.append(getNodeAsXML(children[i].getPath()));
} else if (children[i].isResource()) {
sb.append("<resource path=\"" + children[i].getPath() + "\" name=\"" + children[i].getName() + "\"/>");
} else {
sb.append("<neither-resource-nor-collection path=\"" + children[i].getPath() + "\" name=\"" + children[i].getName() + "\"/>");
}
}
sb.append("</collection>");
} else {
sb.append("<resource path=\"" + path + "\" name=\"" + node.getName() + "\"/>");
}
} else {
String errorMessage = "node is null for path: " + path;
sb.append("<exception>" + errorMessage + "</exception>");
log.error(errorMessage);
}
return sb.toString();
}
}
|
package com.demonwav.mcdev.platform.forge.inspections.sideonly;
import com.demonwav.mcdev.util.McPsiUtil;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiClassType;
import com.intellij.psi.PsiLocalVariable;
import com.intellij.psi.PsiModifierListOwner;
import com.intellij.psi.PsiType;
import com.siyeh.ig.BaseInspection;
import com.siyeh.ig.BaseInspectionVisitor;
import com.siyeh.ig.InspectionGadgetsFix;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class LocalVariableDeclarationSideOnlyInspection extends BaseInspection {
@Nls
@NotNull
@Override
public String getDisplayName() {
return "Invalid usage of local variable declaration annotated with @SideOnly";
}
@NotNull
@Override
protected String buildErrorString(Object... infos) {
final Error error = (Error) infos[0];
return error.getErrorString(SideOnlyUtil.getSubArray(infos));
}
@Nullable
@Override
public String getStaticDescription() {
return "A variable whose class declaration is annotated with @SideOnly for one side cannot be declared in a class" +
" or method that does not match the same side.";
}
@Nullable
@Override
protected InspectionGadgetsFix buildFix(Object... infos) {
PsiClass variableClass = (PsiClass) infos[2];
if (variableClass.isWritable()) {
return new RemoveAnnotationInspectionGadgetsFix() {
@Nullable
@Override
public PsiModifierListOwner getListOwner() {
return variableClass;
}
@Nls
@NotNull
@Override
public String getName() {
return "Remove @SideOnly annotation from variable class declaration";
}
};
} else {
return null;
}
}
@Override
public BaseInspectionVisitor buildVisitor() {
return new BaseInspectionVisitor() {
@Override
public void visitLocalVariable(PsiLocalVariable variable) {
final PsiClass psiClass = McPsiUtil.getClassOfElement(variable);
if (psiClass == null) {
return;
}
if (!SideOnlyUtil.beginningCheck(variable)) {
return;
}
final PsiType type = variable.getType();
if (!(type instanceof PsiClassType)) {
return;
}
final PsiClassType classType = (PsiClassType) type;
final PsiClass variableClass = classType.resolve();
if (variableClass == null) {
return;
}
final Side variableSide = SideOnlyUtil.getSideForClass(variableClass);
if (variableSide == Side.NONE || variableSide == Side.INVALID) {
return;
}
final Side containingClassSide = SideOnlyUtil.getSideForClass(psiClass);
final Side methodSide = SideOnlyUtil.checkElementInMethod(variable);
boolean classAnnotated = false;
if (containingClassSide != Side.NONE && containingClassSide != Side.INVALID) {
if (variableSide != containingClassSide) {
registerVariableError(
variable,
Error.VAR_CROSS_ANNOTATED_CLASS,
variableSide.getName(),
containingClassSide.getName(),
variableClass
);
}
classAnnotated = true;
}
if (methodSide == Side.INVALID) {
return;
}
if (variableSide != methodSide) {
if (methodSide == Side.NONE) {
if (!classAnnotated) {
registerVariableError(
variable,
Error.VAR_UNANNOTATED_METHOD,
variableSide.getName(),
methodSide.getName(),
variableClass
);
}
} else {
registerVariableError(
variable,
Error.VAR_CROSS_ANNOTATED_METHOD,
variableSide.getName(),
methodSide.getName(),
variableClass
);
}
}
}
};
}
enum Error {
VAR_CROSS_ANNOTATED_CLASS {
@Override
String getErrorString(Object... infos) {
return "A local variable whose class is annotated with " + infos[0] + " cannot be used in a class annotated with " + infos[1];
}
},
VAR_CROSS_ANNOTATED_METHOD {
@Override
String getErrorString(Object... infos) {
return "A local variable whose class is annotated with " + infos[0] + " cannot be used in a method annotated with " + infos[1];
}
},
VAR_UNANNOTATED_METHOD {
@Override
String getErrorString(Object... infos) {
return "A local variable whose class is annotated with " + infos[0] + " cannot be used in an un-annotated method.";
}
};
abstract String getErrorString(Object... infos);
}
}
|
package test;
import static org.fest.assertions.Assertions.assertThat;
import static play.test.Helpers.contentAsString;
import static play.test.Helpers.contentType;
import java.util.List;
import models.Contact;
import org.junit.Test;
import play.mvc.Content;
/**
*
* Simple (JUnit) tests that can call all parts of a play app. If you are interested in mocking a whole application, see
* the wiki for more details.
*
*/
public class ApplicationTest {
/**
* Illustrates a simple test.
*/
@Test
public void simpleCheck() {
int a = 1 + 1;
assertThat(a).isEqualTo(2);
}
/**
* Illustrates how to render a template for testing.
*/
@Test
public void renderTemplate() {
List<Contact> list = null;
Content html = views.html.Index.render(list, "Index", false, null);
assertThat(contentType(html)).isEqualTo("text/html");
assertThat(contentAsString(html)).contains("home page");
}
}
|
import java.util.Scanner;
public class Frustum {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.print("Enter R1: ");
int userR1 = userInput.nextInt();
System.out.print("Enter R2: ");
int userR2 = userInput.nextInt();
System.out.print("Enter h: ");
int h = userInput.nextInt();
System.out.println("The volume is: " + getVolume(userR1, userR2, h));
System.out.println("The surface is: " + getSurface(userR1, userR2, h));
}
public static double getVolume(int R1, int R2, int h) {
return (Math.PI*h*(Math.pow(R1, 2) + Math.pow(R2, 2) + R1*R2))/3;
}
public static double getSurface(int R1, int R2, int h) {
return Math.PI*(R1 + R2)*Math.sqrt(Math.pow(R2 - R1, 2) + Math.pow(h, 2)) + Math.PI*Math.pow(R1, 2);
}
}
|
package soot;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import soot.jimple.CaughtExceptionRef;
import soot.jimple.DefinitionStmt;
import soot.jimple.IdentityStmt;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.InvokeExpr;
import soot.jimple.InvokeStmt;
import soot.jimple.ParameterRef;
import soot.jimple.ThisRef;
import soot.options.Options;
import soot.tagkit.AbstractHost;
import soot.tagkit.CodeAttribute;
import soot.tagkit.Tag;
import soot.toolkits.exceptions.PedanticThrowAnalysis;
import soot.toolkits.exceptions.ThrowAnalysis;
import soot.toolkits.graph.ExceptionalUnitGraph;
import soot.toolkits.graph.UnitGraph;
import soot.toolkits.scalar.FlowSet;
import soot.toolkits.scalar.InitAnalysis;
import soot.toolkits.scalar.LocalDefs;
import soot.toolkits.scalar.SimpleLiveLocals;
import soot.toolkits.scalar.SmartLocalDefs;
import soot.util.Chain;
import soot.util.EscapedWriter;
import soot.util.HashChain;
/**
* Abstract base class that models the body (code attribute) of a Java method.
* Classes that implement an Intermediate Representation for a method body should subclass it.
* In particular the classes GrimpBody, JimpleBody and BafBody all extend this
* class. This class provides methods that are common to any IR, such as methods
* to get the body's units (statements), traps, and locals.
*
* @see soot.grimp.GrimpBody
* @see soot.jimple.JimpleBody
* @see soot.baf.BafBody
*/
public abstract class Body extends AbstractHost implements Serializable
{
/** The method associated with this Body. */
protected transient SootMethod method = null;
/** The chain of locals for this Body. */
protected Chain<Local> localChain = new HashChain<Local>();
/** The chain of traps for this Body. */
protected Chain<Trap> trapChain = new HashChain<Trap>();
/** The chain of units for this Body. */
protected PatchingChain<Unit> unitChain = new PatchingChain<Unit>(new HashChain<Unit>());
/** Creates a deep copy of this Body. */
abstract public Object clone();
/** Creates a Body associated to the given method. Used by subclasses during initialization.
* Creation of a Body is triggered by e.g. Jimple.v().newBody(options).
*/
protected Body(SootMethod m)
{
this.method = m;
}
/** Creates an extremely empty Body. The Body is not associated to any method. */
protected Body()
{
}
/**
* Returns the method associated with this Body.
* @return the method that owns this body.
*/
public SootMethod getMethod()
{
if(method == null)
throw new RuntimeException("no method associated w/ body");
return method;
}
/**
* Sets the method associated with this Body.
* @param method the method that owns this body.
*
*/
public void setMethod(SootMethod method)
{
this.method = method;
}
/** Returns the number of locals declared in this body. */
public int getLocalCount()
{
return localChain.size();
}
/** Copies the contents of the given Body into this one. */
public Map<Object, Object> importBodyContentsFrom(Body b)
{
HashMap<Object, Object> bindings = new HashMap<Object, Object>();
{
Iterator<Unit> it = b.getUnits().iterator();
// Clone units in body's statement list
while(it.hasNext()) {
Unit original = it.next();
Unit copy = (Unit) original.clone();
copy.addAllTagsOf(original);
// Add cloned unit to our unitChain.
unitChain.addLast(copy);
// Build old <-> new map to be able to patch up references to other units
// within the cloned units. (these are still refering to the original
// unit objects).
bindings.put(original, copy);
}
}
{
// Clone trap units.
Iterator<Trap> it = b.getTraps().iterator();
while(it.hasNext()) {
Trap original = it.next();
Trap copy = (Trap) original.clone();
// Add cloned unit to our trap list.
trapChain.addLast(copy);
// Store old <-> new mapping.
bindings.put(original, copy);
}
}
{
// Clone local units.
Iterator<Local> it = b.getLocals().iterator();
while(it.hasNext()) {
Local original = it.next();
Local copy = (Local) original.clone();
// Add cloned unit to our trap list.
localChain.addLast(copy);
// Build old <-> new mapping.
bindings.put(original, copy);
}
}
{
// Patch up references within units using our (old <-> new) map.
Iterator<UnitBox> it = getAllUnitBoxes().iterator();
while(it.hasNext()) {
UnitBox box = it.next();
Unit newObject, oldObject = box.getUnit();
// if we have a reference to an old object, replace it
// it's clone.
if( (newObject = (Unit) bindings.get(oldObject)) != null )
box.setUnit(newObject);
}
}
{
// backpatching all local variables.
Iterator<ValueBox> it = getUseBoxes().iterator();
while(it.hasNext()) {
ValueBox vb = it.next();
if(vb.getValue() instanceof Local)
vb.setValue((Value) bindings.get(vb.getValue()));
}
it = getDefBoxes().iterator();
while(it.hasNext()) {
ValueBox vb = it.next();
if(vb.getValue() instanceof Local)
vb.setValue((Value) bindings.get(vb.getValue()));
}
}
return bindings;
}
/** Verifies a few sanity conditions on the contents on this body. */
public void validate()
{
//System.out.println("body: "+this.getUnits());
validateLocals();
validateTraps();
validateUnitBoxes();
if (Options.v().debug() || Options.v().validate()) {
validateUses();
validateValueBoxes();
checkInit();
checkTypes();
checkLocals();
}
}
/** Verifies that a ValueBox is not used in more than one place. */
public void validateValueBoxes()
{
List<ValueBox> l = getUseAndDefBoxes();
for( int i = 0; i < l.size(); i++ ) {
for( int j = 0; j < l.size(); j++ ) {
if( i == j ) continue;
if( l.get(i) == l.get(j) ) {
System.err.println("Aliased value box : "+l.get(i)+" in "+getMethod());
for( Iterator<Unit> uIt = getUnits().iterator(); uIt.hasNext(); ) {
final Unit u = uIt.next();
System.err.println(""+u);
}
throw new RuntimeException("Aliased value box : "+l.get(i)+" in "+getMethod());
}
}
}
}
/** Verifies that each Local of getUseAndDefBoxes() is in this body's locals Chain. */
public void validateLocals()
{
Iterator<ValueBox> it = getUseBoxes().iterator();
while(it.hasNext()){
validateLocal( it.next() );
}
it = getDefBoxes().iterator();
while(it.hasNext()){
validateLocal( it.next() );
}
}
private void validateLocal( ValueBox vb ) {
Value value;
if( (value = vb.getValue()) instanceof Local) {
//System.out.println("localChain: "+localChain);
if(!localChain.contains(value))
throw new RuntimeException("Local not in chain : "+value+" in "+getMethod());
}
}
/** Verifies that the begin, end and handler units of each trap are in this body. */
public void validateTraps()
{
Iterator<Trap> it = getTraps().iterator();
while (it.hasNext())
{
Trap t = it.next();
if (!unitChain.contains(t.getBeginUnit()))
throw new RuntimeException("begin not in chain"+" in "+getMethod());
if (!unitChain.contains(t.getEndUnit()))
throw new RuntimeException("end not in chain"+" in "+getMethod());
if (!unitChain.contains(t.getHandlerUnit()))
throw new RuntimeException("handler not in chain"+" in "+getMethod());
}
}
/** Verifies that the UnitBoxes of this Body all point to a Unit contained within this body. */
public void validateUnitBoxes()
{
Iterator<UnitBox> it = getAllUnitBoxes().iterator();
while (it.hasNext())
{
UnitBox ub = it.next();
if (!unitChain.contains(ub.getUnit()))
throw new RuntimeException
("Unitbox points outside unitChain! to unit : "+ub.getUnit()+" in "+getMethod());
}
}
/** Verifies that each use in this Body has a def. */
public void validateUses()
{
// Conservative validation of uses: add edges to exception handlers
// even if they are not reachable.
// class C {
// int a;
// public void m() {
// try {
// a = 2;
// } catch (Exception e) {
// System.out.println("a: "+ a);
// In a graph generated from the Jimple representation there would
// be no edge from "a = 2;" to "catch..." because "a = 2" can only
// generate an Error, a subclass of Throwable and not of Exception.
// Use of 'a' in "System.out.println" would thus trigger a 'no defs
// for value' RuntimeException.
// To avoid this we create an ExceptionalUnitGraph that considers all
// exception handlers (even unreachable ones as the one in the code
// snippet above) by using a PedanticThrowAnalysis and setting the
// parameter 'omitExceptingUnitEdges' to false.
// Note that unreachable traps can be removed by setting jb.uce's
// "remove-unreachable-traps" option to true.
ThrowAnalysis throwAnalysis = PedanticThrowAnalysis.v();
UnitGraph g = new ExceptionalUnitGraph(this, throwAnalysis, false);
LocalDefs ld = new SmartLocalDefs(g, new SimpleLiveLocals(g));
for (Unit u : getUnits()) {
Iterator<ValueBox> useBoxIt = u.getUseBoxes().iterator();
while (useBoxIt.hasNext())
{
Value v = (useBoxIt.next()).getValue();
if (v instanceof Local)
{
// This throws an exception if there is
// no def already; we check anyhow.
List<Unit> l = ld.getDefsOfAt((Local)v, u);
if (l.size() == 0){
for( Iterator<Unit> uuIt = getUnits().iterator(); uuIt.hasNext(); ) {
final Unit uu = uuIt.next();
System.err.println(""+uu);
}
throw new RuntimeException("("+ getMethod() +") no defs for value: " + v + "!\n" + this);
}
}
}
}
}
/** Returns a backed chain of the locals declared in this Body. */
public Chain<Local> getLocals() {return localChain;}
/** Returns a backed view of the traps found in this Body. */
public Chain<Trap> getTraps() {return trapChain;}
/** Return LHS of the first identity stmt assigning from \@this. **/
public Local getThisLocal()
{
Iterator<Unit> unitsIt = getUnits().iterator();
while (unitsIt.hasNext())
{
Unit s = unitsIt.next();
if (s instanceof IdentityStmt &&
((IdentityStmt)s).getRightOp() instanceof ThisRef)
return (Local)(((IdentityStmt)s).getLeftOp());
}
throw new RuntimeException("couldn't find identityref!"+" in "+getMethod());
}
/** Return LHS of the first identity stmt assigning from \@parameter i. **/
public Local getParameterLocal(int i)
{
Iterator<Unit> unitsIt = getUnits().iterator();
while (unitsIt.hasNext())
{
Unit s = unitsIt.next();
if (s instanceof IdentityStmt &&
((IdentityStmt)s).getRightOp() instanceof ParameterRef)
{
IdentityStmt is = (IdentityStmt)s;
ParameterRef pr = (ParameterRef)is.getRightOp();
if (pr.getIndex() == i)
return (Local)is.getLeftOp();
}
}
throw new RuntimeException("couldn't find parameterref" + i +"! in "+getMethod());
}
/**
* Get all the LHS of the identity statements assigning from parameter references.
*
* @return a list of size as per <code>getMethod().getParameterCount()</code> with all elements ordered as per the parameter index.
* @throws RuntimeException if a parameterref is missing
*/
public List<Local> getParameterLocals(){
final int numParams = getMethod().getParameterCount();
final List<Local> retVal = new ArrayList<Local>(numParams);
//Parameters are zero-indexed, so the keeping of the index is safe
for (Unit u : getUnits()){
if (u instanceof IdentityStmt){
IdentityStmt is = ((IdentityStmt)u);
if (is.getRightOp() instanceof ParameterRef){
ParameterRef pr = (ParameterRef) is.getRightOp();
retVal.add(pr.getIndex(), (Local) is.getLeftOp());
}
}
}
if (retVal.size() != numParams)
throw new RuntimeException("couldn't find parameterref! in " + getMethod());
return retVal;
}
/**
* Returns the list of parameter references used in this body. The list is as long as
* the number of parameters declared in the associated method's signature.
* The list may have <code>null</code> entries for parameters not referenced in the body.
* The returned list is of fixed size.
*/
public List<Value> getParameterRefs()
{
Value[] res = new Value[getMethod().getParameterCount()];
Iterator<Unit> unitsIt = getUnits().iterator();
while (unitsIt.hasNext())
{
Unit s = unitsIt.next();
if (s instanceof IdentityStmt) {
Value rightOp = ((IdentityStmt)s).getRightOp();
if (rightOp instanceof ParameterRef) {
ParameterRef parameterRef = (ParameterRef) rightOp;
res[parameterRef.getIndex()] = parameterRef;
}
}
}
return Arrays.asList(res);
}
/**
* Returns the Chain of Units that make up this body. The units are
* returned as a PatchingChain. The client can then manipulate the chain,
* adding and removing units, and the changes will be reflected in the body.
* Since a PatchingChain is returned the client need <i>not</i> worry about removing exception
* boundary units or otherwise corrupting the chain.
*
* @return the units in this Body
*
* @see PatchingChain
* @see Unit
*/
public PatchingChain<Unit> getUnits()
{
return unitChain;
}
/**
* Returns the result of iterating through all Units in this body
* and querying them for their UnitBoxes. All UnitBoxes thus
* found are returned. Branching Units and statements which use
* PhiExpr will have UnitBoxes; a UnitBox contains a Unit that is
* either a target of a branch or is being used as a pointer to
* the end of a CFG block.
*
* <p> This method is typically used for pointer patching, eg when
* the unit chain is cloned.
*
* @return A list of all the UnitBoxes held by this body's units.
* @see UnitBox
* @see #getUnitBoxes(boolean)
* @see Unit#getUnitBoxes()
* @see soot.shimple.PhiExpr#getUnitBoxes()
**/
public List<UnitBox> getAllUnitBoxes()
{
ArrayList<UnitBox> unitBoxList = new ArrayList<UnitBox>();
{
Iterator<Unit> it = unitChain.iterator();
while(it.hasNext()) {
Unit item = it.next();
unitBoxList.addAll(item.getUnitBoxes());
}
}
{
Iterator<Trap> it = trapChain.iterator();
while(it.hasNext()) {
Trap item = it.next();
unitBoxList.addAll(item.getUnitBoxes());
}
}
{
Iterator<Tag> it = getTags().iterator();
while(it.hasNext()) {
Tag t = it.next();
if( t instanceof CodeAttribute)
unitBoxList.addAll(((CodeAttribute) t).getUnitBoxes());
}
}
return unitBoxList;
}
/**
* If branchTarget is true, returns the result of iterating
* through all branching Units in this body and querying them for
* their UnitBoxes. These UnitBoxes contain Units that are the
* target of a branch. This is useful for, say, labeling blocks
* or updating the targets of branching statements.
*
* <p> If branchTarget is false, returns the result of iterating
* through the non-branching Units in this body and querying them
* for their UnitBoxes. Any such UnitBoxes (typically from
* PhiExpr) contain a Unit that indicates the end of a CFG block.
*
* @return a list of all the UnitBoxes held by this body's
* branching units.
*
* @see UnitBox
* @see #getAllUnitBoxes()
* @see Unit#getUnitBoxes()
* @see soot.shimple.PhiExpr#getUnitBoxes()
**/
public List<UnitBox> getUnitBoxes(boolean branchTarget)
{
ArrayList<UnitBox> unitBoxList = new ArrayList<UnitBox>();
{
Iterator<Unit> it = unitChain.iterator();
while(it.hasNext()) {
Unit item = it.next();
if(branchTarget){
if(item.branches())
unitBoxList.addAll(item.getUnitBoxes());
}
else{
if(!item.branches())
unitBoxList.addAll(item.getUnitBoxes());
}
}
}
{
Iterator<Trap> it = trapChain.iterator();
while(it.hasNext()) {
Trap item = it.next();
unitBoxList.addAll(item.getUnitBoxes());
}
}
{
Iterator<Tag> it = getTags().iterator();
while(it.hasNext()) {
Tag t = it.next();
if( t instanceof CodeAttribute)
unitBoxList.addAll(((CodeAttribute) t).getUnitBoxes());
}
}
return unitBoxList;
}
/**
* Returns the result of iterating through all Units in this
* body and querying them for ValueBoxes used.
* All of the ValueBoxes found are then returned as a List.
*
* @return a list of all the ValueBoxes for the Values used this body's units.
*
* @see Value
* @see Unit#getUseBoxes
* @see ValueBox
* @see Value
*
*/
public List<ValueBox> getUseBoxes()
{
ArrayList<ValueBox> useBoxList = new ArrayList<ValueBox>();
Iterator<Unit> it = unitChain.iterator();
while(it.hasNext()) {
Unit item = it.next();
useBoxList.addAll(item.getUseBoxes());
}
return useBoxList;
}
/**
* Returns the result of iterating through all Units in this
* body and querying them for ValueBoxes defined.
* All of the ValueBoxes found are then returned as a List.
*
* @return a list of all the ValueBoxes for Values defined by this body's units.
*
* @see Value
* @see Unit#getDefBoxes
* @see ValueBox
* @see Value
*/
public List<ValueBox> getDefBoxes()
{
ArrayList<ValueBox> defBoxList = new ArrayList<ValueBox>();
Iterator<Unit> it = unitChain.iterator();
while(it.hasNext()) {
Unit item = it.next();
defBoxList.addAll(item.getDefBoxes());
}
return defBoxList;
}
/**
* Returns a list of boxes corresponding to Values
* either used or defined in any unit of this Body.
*
* @return a list of ValueBoxes for held by the body's Units.
*
* @see Value
* @see Unit#getUseAndDefBoxes
* @see ValueBox
* @see Value
*/
public List<ValueBox> getUseAndDefBoxes()
{
ArrayList<ValueBox> useAndDefBoxList = new ArrayList<ValueBox>();
Iterator<Unit> it = unitChain.iterator();
while(it.hasNext()) {
Unit item = it.next();
useAndDefBoxList.addAll(item.getUseBoxes());
useAndDefBoxList.addAll(item.getDefBoxes());
}
return useAndDefBoxList;
}
private void checkLocals() {
Chain<Local> locals=getLocals();
Iterator<Local> it=locals.iterator();
while(it.hasNext()) {
Local l=it.next();
if(l.getType() instanceof VoidType)
throw new RuntimeException("Local "+l+" in "+method+" defined with void type");
}
}
private void checkTypes() {
Chain<Unit> units=getUnits();
Iterator<Unit> it=units.iterator();
while(it.hasNext()) {
Unit stmt=(it.next());
InvokeExpr iexpr=null;
String errorSuffix=" at "+stmt+" in "+getMethod();
if(stmt instanceof DefinitionStmt) {
DefinitionStmt astmt=(DefinitionStmt) stmt;
if( !(astmt.getRightOp() instanceof CaughtExceptionRef ) ) {
Type leftType=Type.toMachineType(astmt.getLeftOp().getType());
Type rightType=Type.toMachineType(astmt.getRightOp().getType());
checkCopy(leftType,rightType,errorSuffix);
if(astmt.getRightOp() instanceof InvokeExpr)
iexpr=(InvokeExpr) (astmt.getRightOp());
}
}
if(stmt instanceof InvokeStmt) iexpr=((InvokeStmt) stmt).getInvokeExpr();
if(iexpr!=null) {
SootMethodRef called=iexpr.getMethodRef();
if(iexpr instanceof InstanceInvokeExpr) {
InstanceInvokeExpr iiexpr=(InstanceInvokeExpr) iexpr;
checkCopy(called.declaringClass().getType(),
iiexpr.getBase().getType(),
" in receiver of call"+errorSuffix);
}
if(called.parameterTypes().size() != iexpr.getArgCount())
throw new RuntimeException("Warning: Argument count doesn't match up with signature in call"+errorSuffix+" in "+getMethod());
else
for(int i=0;i<iexpr.getArgCount();i++)
checkCopy(Type.toMachineType(called.parameterType(i)),
Type.toMachineType(iexpr.getArg(i).getType()),
" in argument "+i+" of call"+errorSuffix);
}
}
}
private void checkCopy(Type leftType,Type rightType,String errorSuffix) {
if(leftType instanceof PrimType || rightType instanceof PrimType) {
if(leftType instanceof IntType && rightType instanceof IntType) return;
if(leftType instanceof LongType && rightType instanceof LongType) return;
if(leftType instanceof FloatType && rightType instanceof FloatType) return;
if(leftType instanceof DoubleType && rightType instanceof DoubleType) return;
throw new RuntimeException("Warning: Bad use of primitive type"+errorSuffix+" in "+getMethod());
}
if(rightType instanceof NullType) return;
if(leftType instanceof RefType &&
((RefType) leftType).getClassName().equals("java.lang.Object")) return;
if(leftType instanceof ArrayType || rightType instanceof ArrayType) {
if(leftType instanceof ArrayType && rightType instanceof ArrayType) return;
if(rightType instanceof ArrayType) {
if(leftType.equals(RefType.v("java.io.Serializable")) ||
leftType.equals(RefType.v("java.lang.Cloneable")) ||
leftType.equals(RefType.v("java.lang.Object")))
return;
}
throw new RuntimeException("Warning: Bad use of array type"+errorSuffix+" in "+getMethod());
}
if(leftType instanceof RefType && rightType instanceof RefType) {
SootClass leftClass=((RefType) leftType).getSootClass();
SootClass rightClass=((RefType) rightType).getSootClass();
if(leftClass.isPhantom() || rightClass.isPhantom()) {
return;
}
if(leftClass.isInterface()) {
if(rightClass.isInterface()) {
if(!(leftClass.getName().equals(rightClass.getName()) ||
Scene.v().getActiveHierarchy().isInterfaceSubinterfaceOf(rightClass,leftClass)))
throw new RuntimeException("Warning: Bad use of interface type"+errorSuffix+" in "+getMethod());
} else {
// No quick way to check this for now.
}
} else {
if(rightClass.isInterface()) {
throw new RuntimeException("Warning: trying to use interface type where non-Object class expected"
+errorSuffix+" in "+getMethod());
} else {
if(!Scene.v().getActiveHierarchy().isClassSubclassOfIncluding(rightClass,leftClass))
throw new RuntimeException("Warning: Bad use of class type"+errorSuffix+" in "+getMethod());
}
}
return;
}
throw new RuntimeException("Warning: Bad types"+errorSuffix+" in "+getMethod());
}
@SuppressWarnings("unchecked")
public void checkInit() {
ExceptionalUnitGraph g = new ExceptionalUnitGraph
(this, PedanticThrowAnalysis.v(), false);
InitAnalysis analysis=new InitAnalysis(g);
for (Unit s : getUnits()) {
FlowSet init=(FlowSet) analysis.getFlowBefore(s);
for (ValueBox vBox : s.getUseBoxes()) {
Value v=vBox.getValue();
if(v instanceof Local) {
Local l=(Local) v;
if(!init.contains(l))
throw new RuntimeException("Warning: Local variable "+l
+" not definitely defined at "+s
+" in "+method);
}
}
}
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
ByteArrayOutputStream streamOut = new ByteArrayOutputStream();
PrintWriter writerOut = new PrintWriter(new EscapedWriter(new OutputStreamWriter(streamOut)));
try {
Printer.v().printTo(this, writerOut);
} catch (RuntimeException e) {
e.printStackTrace(writerOut);
}
writerOut.flush();
writerOut.close();
return streamOut.toString();
}
}
|
package Hardware;
import edu.wpi.first.wpilibj.PIDOutput;
import edu.wpi.first.wpilibj.SerialPort;
import edu.wpi.first.wpilibj.SpeedController;
import edu.wpi.first.wpilibj.visa.VisaException;
/**
*
* @author Aidan
*/
public class SabertoothSpeedController implements SpeedController {
private static SerialPort _PORT = null; //Serial port shared by all Sabertooths
//TODO: Keep list of assigned motors (address/motor pairs) and throw an error when we overwrite one?
// Motor specification //
private int _address;
private int _motorNumber;
private double _currentSpeed;
public SabertoothSpeedController(int address, int motorNumber) {
if (_PORT == null) throw new IllegalStateException("Serial port not initialized, call initializeSerialPort(baudRate)");
if (address < 128 || address > 135) throw new IllegalArgumentException("Sabertooth address out of range");
if (motorNumber < 1 || motorNumber > 2) throw new IllegalArgumentException("Sabertooth motor number out of range");
_address = address;
_motorNumber = motorNumber;
_currentSpeed = 0.0;
}
public static void initializeSerialPort(int baudRate) {
System.out.println("Initializing the serial port...");
if(_PORT != null) throw new IllegalStateException("Serial port already initialized");
try {
_PORT = new SerialPort(baudRate);
// send the baud rate character //
byte[] baudChar = { (byte) 170 };
_PORT.write(baudChar, baudChar.length);
} catch(VisaException e) {
throw new RuntimeException("Error creating serial port: " + e.getMessage());
}
}
private void writeSerialPacket(int command, int data) throws VisaException {
byte addr = (byte) _address;
byte com = (byte) command;
byte dat = (byte) data;
byte checksum = (byte) ((addr + com + dat) & 0x7F);
byte[] packet = { addr, com, dat, checksum };
_PORT.write(packet, packet.length);
}
public void pidWrite(double output) {
set(output);
}
public double get() {
return _currentSpeed;
}
public void set(double speed, byte syncGroup) {
set(speed); //Not sure if I'll ever need to implement sync groups for this
}
public void set(double speed) { //Speed should be between -1.0 and 1.0
double spd = Math.abs(speed);
if (spd > 1.0) throw new IllegalArgumentException("Speed must be between -1.0 and 1.0");
_currentSpeed = speed;
// Set command byte... TODO: Make this more readable? //
int command = (_motorNumber == 1) ? 0 : 4; //Command is 0/1 for motor 1, 4/5 for motor 2
if (speed < 0.0) command++;
// Set data byte //
int data = (int) Math.floor(spd * 127.0);
// Write data //
try {
writeSerialPacket(command, data);
} catch (VisaException e) {
throw new RuntimeException("Error writing serial data: " + e.getMessage());
}
}
public void disable() {
set(0.0);
}
public static boolean isSerialSet() { //Has the serial port been set yet?
return !(_PORT == null);
}
}
|
package cgeo.geocaching;
import cgeo.geocaching.apps.cache.navi.NavigationAppFactory;
import cgeo.geocaching.geopoint.Geopoint;
import cgeo.geocaching.geopoint.Units;
import cgeo.geocaching.ui.CacheDetailsCreator;
import cgeo.geocaching.utils.Log;
import org.apache.commons.lang3.StringUtils;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
public class WaypointPopup extends AbstractPopupActivity {
private int waypointId = 0;
private Waypoint waypoint = null;
private TextView waypointDistance = null;
public WaypointPopup() {
super("c:geo-waypoint-info", R.layout.waypoint_popup);
}
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// get parameters
final Bundle extras = getIntent().getExtras();
if (extras != null) {
waypointId = extras.getInt(Intents.EXTRA_WAYPOINT_ID);
}
}
@Override
public void onUpdateGeoData(IGeoData geo) {
if (geo.getCoords() != null && waypoint != null && waypoint.getCoords() != null) {
waypointDistance.setText(Units.getDistanceFromKilometers(geo.getCoords().distanceTo(waypoint.getCoords())));
waypointDistance.bringToFront();
}
}
@Override
protected void init() {
super.init();
waypoint = cgData.loadWaypoint(waypointId);
try {
if (StringUtils.isNotBlank(waypoint.getName())) {
setTitle(waypoint.getName());
} else {
setTitle(waypoint.getGeocode());
}
// actionbar icon
((TextView) findViewById(R.id.actionbar_title)).setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(waypoint.getWaypointType().markerId), null, null, null);
//Start filling waypoint details
details = new CacheDetailsCreator(this, (LinearLayout) findViewById(R.id.waypoint_details_list));
//Waypoint geocode
details.add(R.string.cache_geocode, waypoint.getPrefix() + waypoint.getGeocode().substring(2));
details.addDistance(waypoint, waypointDistance);
waypointDistance = details.getValueView();
details.add(R.string.waypoint_note, waypoint.getNote());
// Edit Button
final Button buttonEdit = (Button) findViewById(R.id.edit);
buttonEdit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
EditWaypointActivity.startActivityEditWaypoint(WaypointPopup.this, waypoint.getId());
finish();
}
});
//Start filling cache details
details = new CacheDetailsCreator(this, (LinearLayout) findViewById(R.id.details_list));
details.add(R.string.cache_name, cache.getName());
addCacheDetails();
} catch (Exception e) {
Log.e("cgeopopup.init", e);
}
}
@Override
protected void navigateTo() {
NavigationAppFactory.startDefaultNavigationApplication(1, this, waypoint);
}
/**
* Tries to navigate to the {@link Geocache} of this activity.
*/
@Override
protected void startDefaultNavigation2() {
if (waypoint == null || waypoint.getCoords() == null) {
showToast(res.getString(R.string.cache_coordinates_no));
return;
}
NavigationAppFactory.startDefaultNavigationApplication(2, this, waypoint);
finish();
}
public static void startActivity(final Context context, final int waypointId, final String geocode) {
final Intent popupIntent = new Intent(context, WaypointPopup.class);
popupIntent.putExtra(Intents.EXTRA_WAYPOINT_ID, waypointId);
popupIntent.putExtra(Intents.EXTRA_GEOCODE, geocode);
context.startActivity(popupIntent);
}
@Override
protected void showNavigationMenu() {
NavigationAppFactory.showNavigationMenu(this, null, waypoint, null);
}
@Override
protected Geopoint getCoordinates() {
if (waypoint == null) {
return null;
}
return waypoint.getCoords();
}
}
|
package cgeo.geocaching.ui;
import cgeo.geocaching.Intents;
import cgeo.geocaching.R;
import cgeo.geocaching.apps.navi.NavigationAppFactory;
import cgeo.geocaching.enumerations.WaypointType;
import cgeo.geocaching.location.Geopoint;
import cgeo.geocaching.models.Geocache;
import cgeo.geocaching.models.Image;
import cgeo.geocaching.models.Waypoint;
import cgeo.geocaching.network.HtmlImage;
import cgeo.geocaching.storage.LocalStorage;
import cgeo.geocaching.utils.AndroidRxUtils;
import cgeo.geocaching.utils.Log;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.util.SparseArray;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.core.content.FileProvider;
import androidx.core.text.HtmlCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Collection;
import java.util.LinkedList;
import com.drew.imaging.ImageMetadataReader;
import com.drew.lang.GeoLocation;
import com.drew.metadata.Metadata;
import com.drew.metadata.exif.GpsDirectory;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.internal.disposables.CancellableDisposable;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
public class ImagesList {
private ImageView currentView;
private Image currentImage;
public enum ImageType {
LogImages(R.string.cache_log_images_title), SpoilerImages(R.string.cache_spoiler_images_title);
@StringRes private final int titleResId;
ImageType(@StringRes final int title) {
this.titleResId = title;
}
@StringRes
public int getTitle() {
return titleResId;
}
}
private LayoutInflater inflater = null;
private final Activity activity;
// We could use a Set here, but we will insert no duplicates, so there is no need to check for uniqueness.
private final Collection<Bitmap> bitmaps = new LinkedList<>();
/**
* map image view id to image
*/
private final SparseArray<Image> images = new SparseArray<>();
private final SparseArray<Geopoint> geoPoints = new SparseArray<>();
private final String geocode;
private final Geocache geocache;
private LinearLayout imagesView;
public ImagesList(final Activity activity, final String geocode, final Geocache geocache) {
this.activity = activity;
this.geocode = geocode;
this.geocache = geocache;
inflater = activity.getLayoutInflater();
}
/**
* Load images into a view.
*
* @param parentView
* a view to load the images into
* @param images
* the images to load
* @return a disposable which, when disposed, interrupts the loading and clears up resources
*/
public Disposable loadImages(final View parentView, final Collection<Image> images) {
// Start with a fresh disposable because of this method can be called several times if the
// enclosing activity is stopped/restarted.
final CompositeDisposable disposables = new CompositeDisposable(new CancellableDisposable(this::removeAllViews));
imagesView = parentView.findViewById(R.id.spoiler_list);
imagesView.removeAllViews();
final HtmlImage imgGetter = new HtmlImage(geocode, true, false, false);
for (final Image img : images) {
final LinearLayout rowView = (LinearLayout) inflater.inflate(R.layout.cache_image_item, imagesView, false);
assert rowView != null;
if (StringUtils.isNotBlank(img.getTitle())) {
final TextView titleView = rowView.findViewById(R.id.title);
titleView.setText(HtmlCompat.fromHtml(img.getTitle(), HtmlCompat.FROM_HTML_MODE_LEGACY));
}
if (StringUtils.isNotBlank(img.getDescription())) {
final TextView descView = rowView.findViewById(R.id.description);
descView.setText(HtmlCompat.fromHtml(img.getDescription(), HtmlCompat.FROM_HTML_MODE_LEGACY), TextView.BufferType.SPANNABLE);
descView.setVisibility(View.VISIBLE);
}
final RelativeLayout imageView = (RelativeLayout) inflater.inflate(R.layout.image_item, rowView, false);
assert imageView != null;
rowView.addView(imageView);
imagesView.addView(rowView);
disposables.add(AndroidRxUtils.bindActivity(activity, imgGetter.fetchDrawable(img.getUrl())).subscribe(image -> display(imageView, image, img, rowView)));
}
return disposables;
}
private void display(final RelativeLayout imageViewLayout, final BitmapDrawable image, final Image img, final LinearLayout view) {
final ImageView imageView = (ImageView) imageViewLayout.findViewById(R.id.map_image);
// In case of a failed download happening fast, the imageView seems to not have been added to the layout yet
if (image != null && imageView != null) {
bitmaps.add(image.getBitmap());
final Rect bounds = image.getBounds();
imageView.setImageResource(R.drawable.image_not_loaded);
imageView.setClickable(true);
imageView.setOnClickListener(view1 -> viewImageInStandardApp(img, image));
activity.registerForContextMenu(imageView);
imageView.setImageDrawable(image);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new RelativeLayout.LayoutParams(bounds.width(), bounds.height()));
view.findViewById(R.id.progress_bar).setVisibility(View.GONE);
imageView.setId(image.hashCode());
images.put(imageView.getId(), img);
final Geopoint geoPoint = getImageLocation(img);
if (geoPoint != null) {
addGeoOverlay(imageViewLayout, geoPoint);
geoPoints.put(imageView.getId(), geoPoint);
}
view.invalidate();
}
}
@Nullable
private Geopoint getImageLocation(final Image image) {
try {
final File file = LocalStorage.getGeocacheDataFile(geocode, image.getUrl(), true, false);
final Metadata metadata = ImageMetadataReader.readMetadata(file);
final Collection<GpsDirectory> gpsDirectories = metadata.getDirectoriesOfType(GpsDirectory.class);
if (gpsDirectories == null) {
return null;
}
for (final GpsDirectory gpsDirectory : gpsDirectories) {
// Try to read out the location, making sure it's non-zero
final GeoLocation geoLocation = gpsDirectory.getGeoLocation();
if (geoLocation != null && !geoLocation.isZero()) {
return new Geopoint(geoLocation.getLatitude(), geoLocation.getLongitude());
}
}
} catch (final Exception e) {
Log.i("ImagesList.getImageLocation", e);
}
return null;
}
private void addGeoOverlay(final RelativeLayout imageViewLayout, final Geopoint gpt) {
final ImageView geoOverlay = (ImageView) imageViewLayout.findViewById(R.id.geo_overlay);
geoOverlay.setVisibility(View.VISIBLE);
geoOverlay.setOnClickListener(wpNavView -> {
wpNavView.setOnClickListener(v -> NavigationAppFactory.startDefaultNavigationApplication(1, activity, gpt));
wpNavView.setOnLongClickListener(v -> {
NavigationAppFactory.startDefaultNavigationApplication(2, activity, gpt);
return true;
});
});
}
private void removeAllViews() {
for (final Bitmap b : bitmaps) {
b.recycle();
}
bitmaps.clear();
images.clear();
geoPoints.clear();
imagesView.removeAllViews();
}
public void onCreateContextMenu(final ContextMenu menu, final View v) {
activity.getMenuInflater().inflate(R.menu.images_list_context, menu);
final Resources res = activity.getResources();
menu.setHeaderTitle(res.getString(R.string.cache_image));
currentView = (ImageView) v;
currentImage = images.get(currentView.getId());
final boolean hasCoordinates = geoPoints.get(currentView.getId()) != null;
menu.findItem(R.id.image_add_waypoint).setVisible(hasCoordinates && geocache != null);
menu.findItem(R.id.menu_navigate).setVisible(hasCoordinates);
}
public boolean onContextItemSelected(final MenuItem item) {
final BitmapDrawable currentDrawable = (BitmapDrawable) currentView.getDrawable();
final int itemId = item.getItemId();
if (itemId == R.id.image_open_file) {
viewImageInStandardApp(currentImage, currentDrawable);
} else if (itemId == R.id.image_open_browser) {
if (currentImage != null) {
currentImage.openInBrowser(activity);
}
} else if (itemId == R.id.image_add_waypoint) {
final Geopoint coords = geoPoints.get(currentView.getId());
if (geocache != null && coords != null) {
final Waypoint waypoint = new Waypoint(currentImage.getTitle(), WaypointType.WAYPOINT, true);
waypoint.setCoords(coords);
geocache.addOrChangeWaypoint(waypoint, true);
final Intent intent = new Intent(Intents.INTENT_CACHE_CHANGED);
intent.putExtra(Intents.EXTRA_WPT_PAGE_UPDATE, true);
LocalBroadcastManager.getInstance(activity).sendBroadcast(intent);
}
} else if (itemId == R.id.menu_navigate) {
final Geopoint geopoint = geoPoints.get(currentView.getId());
if (geopoint != null) {
NavigationAppFactory.showNavigationMenu(activity, null, null, geopoint);
}
} else {
return false;
}
return true;
}
private static String mimeTypeForUrl(final String url) {
|
package de.fzi.cjunit.jpf.outside;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import gov.nasa.jpf.Config;
import gov.nasa.jpf.JPF;
import gov.nasa.jpf.report.Publisher;
import de.fzi.cjunit.jpf.inside.TestWrapper;
import de.fzi.cjunit.jpf.outside.TestObserver;
import de.fzi.cjunit.jpf.util.ArgumentCreator;
import de.fzi.cjunit.jpf.util.OnFailurePublisher;
public class JPFInvoker {
protected Config conf;
protected JPF jpf;
protected TestObserver testObserver;
public JPFInvoker() {
testObserver = new TestObserver();
}
public void run(Object target, Method method,
Class<? extends Throwable> exceptionClass)
throws Throwable {
runJPF(createJPFArgs(target, method, exceptionClass));
checkResult();
}
public void checkResult() throws Throwable {
if (testObserver.getTestResult() == false) {
throw testObserver.getException();
}
}
protected void runJPF(String[] args) {
conf = JPF.createConfig(args);
jpf = new JPF(conf);
jpf.addPropertyListener(testObserver);
registerTestObserverAtPublisher();
jpf.run();
}
protected void registerTestObserverAtPublisher() {
for (Publisher p : jpf.getReporter().getPublishers()) {
if (p instanceof OnFailurePublisher) {
((OnFailurePublisher) p).setTestObserver(
testObserver);
}
}
}
protected String[] createJPFArgs(Object target, Method method,
Class<? extends Throwable> exceptionClass) {
List<String> testArgs = new ArrayList<String>();
testArgs.add("--testclass=" + target.getClass().getName());
testArgs.add("--testmethod=" + method.getName());
if (exceptionClass != null) {
testArgs.add("--expectedexception=" +
exceptionClass.getName());
}
return new ArgumentCreator()
.publisher(OnFailurePublisher.class)
.jpfArgs(new String[] {
"+jpf.report.console.start=",
"+jpf.report.console.finished=result",
"+jpf.report.console.show_steps=true"
})
.app(TestWrapper.class)
.appArgs(testArgs)
.getArgs();
}
}
|
package cn.imaq.cerdns.core;
import cn.imaq.cerdns.util.CIDR;
import cn.imaq.cerdns.util.Config;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.xbill.DNS.Message;
import org.xbill.DNS.Record;
import org.xbill.DNS.Section;
import org.xbill.DNS.Type;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutorService;
@Slf4j
@AllArgsConstructor
public class ForwardTask implements Runnable {
private DatagramChannel channel;
private SocketAddress client;
private Message reqMessage;
private ExecutorService queryPool;
@Override
public void run() {
log.info("Query: " + reqMessage.getQuestion());
Message result = null;
if (reqMessage.getQuestion().getType() == Type.A) {
log.info("> A type query, use chain");
// Use chain
List<Config.ChainNode> chain = Config.getChain();
try {
long endTime = System.currentTimeMillis() + Config.getTimeout();
int size = chain.size();
// Send requests
Selector selector = Selector.open();
DatagramChannel[] channels = new DatagramChannel[size];
for (int i = 0; i < size; i++) {
DatagramChannel channel = DatagramChannel.open();
channels[i] = channel;
channel.configureBlocking(false);
channel.connect(chain.get(i).getServer());
channel.register(selector, SelectionKey.OP_READ, i);
channel.socket().setSoTimeout(Config.getTimeout());
channel.write(ByteBuffer.wrap(reqMessage.toWire()));
}
// Receive responses
Message[] responses = new Message[size];
ByteBuffer byteBuf = ByteBuffer.allocate(4096);
int currentIndex = 0, lastIndex = 0;
while (true) {
int count = selector.select(endTime - System.currentTimeMillis());
if (count <= 0) {
break;
}
Iterator<SelectionKey> keyIter = selector.selectedKeys().iterator();
while (keyIter.hasNext()) {
SelectionKey key = keyIter.next();
keyIter.remove();
if (key.isReadable()) {
int keyIndex = (int) key.attachment();
byteBuf.clear();
((DatagramChannel) key.channel()).read(byteBuf);
byteBuf.flip();
responses[keyIndex] = new Message(byteBuf);
log.info("Got result from server " + chain.get(keyIndex).getServer());
if (keyIndex >= lastIndex) {
lastIndex = keyIndex;
result = responses[keyIndex];
}
}
}
boolean matches = false;
while (currentIndex < size && responses[currentIndex] != null) {
Message respMessage = responses[currentIndex];
Record[] answer = respMessage.getSectionArray(Section.ANSWER);
if (answer != null && answer.length > 0) {
Config.ChainNode node = chain.get(currentIndex);
matches = true;
if (node.getMatchPrefixes() != null) {
for (Record record : answer) {
if (record.getType() == Type.A) {
boolean match = false;
int ip = CIDR.toInt(record.rdataToString());
for (byte len = 0; len < 32; len++) {
if (node.getMatchPrefixes().contains(new CIDR.Prefix(ip >> (32 - len), len))) {
match = true;
break;
}
}
if (!match) {
matches = false;
break;
}
}
}
}
if (matches) {
log.info(node.getServer() + " result matches!");
result = respMessage;
break;
} else {
log.info(node.getServer() + " result doesn't match");
}
}
currentIndex++;
}
if (matches) {
break;
}
}
// Close channels
for (int i = 0; i < size; i++) {
channels[i].disconnect();
channels[i].close();
}
selector.close();
} catch (IOException e) {
log.warn("Failed to forward (chain): " + e);
}
} else {
SocketAddress server;
if (reqMessage.getQuestion().getType() == Type.AAAA) {
log.info("> AAAA type query, use v6 server");
server = Config.getV6Server();
} else {
log.info("> Other type query, use default");
server = Config.getDefaultServer();
}
// Query from server
try {
DatagramSocket socket = new DatagramSocket();
socket.setSoTimeout(Config.getTimeout());
byte[] data = reqMessage.toWire();
socket.send(new DatagramPacket(data, data.length, server));
DatagramPacket packet = new DatagramPacket(new byte[4096], 4096);
socket.receive(packet);
socket.close();
result = new Message(packet.getData());
} catch (Exception e) {
log.warn("Failed to forward (single): " + e);
}
}
if (result != null) {
try {
channel.send(ByteBuffer.wrap(result.toWire()), client);
} catch (Exception e) {
log.error("Error replying to " + client, e);
}
}
}
}
|
package customer;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Scanner;
public class Search_Customer {
public void search_Customer(){
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:@192.168.10.21:1521:orcl";
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
String sql;
Statement fstmt = null;
ResultSet frs = null;
String fsql;
try{
con = DriverManager.getConnection(url, "dvd","1111");
Scanner scan = new Scanner(System.in);
System.out.println("");
System.out.print(" : ");
String phone_num = scan.next();
sql = "SELECT * FROM member"; //WHERE phone_num LIKE '"+phone_num+"$'";
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
fsql = "SELECT * FROM family";
fstmt = con.createStatement();
frs = fstmt.executeQuery(fsql);
while(rs.next()){
if (rs.getString(5).equals(phone_num)){
System.out.println("\t\t\t\t\t\t\t()");
System.out.print(rs.getInt(1)+"\t\t");
System.out.print(rs.getString(2)+"\t\t");
System.out.print(rs.getString(3)+"\t\t");
System.out.print(rs.getInt(4)+"\t");
System.out.print(rs.getString(5)+"\t");
while(frs.next()){
if(rs.getInt(1)==frs.getInt(1)){
System.out.print(frs.getString(2)+"(");
System.out.print(frs.getString(3)+")\t");
}else
break;
}
System.out.println("");
}
else {
System.out.println(" .");
}
}
}
catch(Exception err){
err.printStackTrace();
}
finally{
if(frs != null) try{frs.close();}catch(Exception err){}
if(rs != null) try{rs.close();}catch(Exception err){}
if(fstmt != null) try{fstmt.close();}catch(Exception err){}
if(stmt != null) try{stmt.close();}catch(Exception err){}
if(con != null) try{con.close();}catch(Exception err){}
}
return;
}
}
|
package com.bio4j.exporter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.codehaus.groovy.tools.shell.Groovysh;
import org.codehaus.groovy.tools.shell.IO;
import com.tinkerpop.gremlin.process.Traversal;
import com.tinkerpop.gremlin.structure.Edge;
import com.tinkerpop.gremlin.structure.Graph;
import com.tinkerpop.gremlin.structure.Vertex;
import com.tinkerpop.gremlin.structure.io.graphml.GraphMLWriter;
import com.tinkerpop.gremlin.structure.io.graphson.GraphSONWriter;
public class ExporterCore {
private static final String DEFAULT_JSON_NAME = "bio4j.json";
private static final String DEFAULT_XML_NAME = "bio4j.xml";
public static void exportGraphson(Groovysh shell, IO io, String query, String path) throws IOException {
// prepare to export
path = resolvePath(path, DEFAULT_JSON_NAME);
File file = new File(path);
FileOutputStream f = new FileOutputStream(file);
GraphSONWriter w = GraphSONWriter.build().create();
// execute the given query
shell.execute("t = " + query + ";null");
Traversal<?, Vertex> traversal = (Traversal<?, Vertex>) shell.getInterp().getContext().getProperty("t");
// try exporting
try {
w.writeVertices(f, traversal);
} catch (ClassCastException e){
shell.execute("t = " + query + ";null");
Traversal<?, Edge> edgeTraversal = (Traversal<?, Edge>) shell.getInterp().getContext().getProperty("t");
while (edgeTraversal.hasNext()){
Edge edge = edgeTraversal.next();
w.writeEdge(f, edge);
}
}
// done
f.close();
io.out.println("==> exported to " + path);
}
public static void exportGraphml(Groovysh shell, IO io, String graphName, String path) throws IOException {
// prepare to export
path = resolvePath(path, DEFAULT_XML_NAME);
File file = new File(path);
FileOutputStream f = new FileOutputStream(file);
GraphMLWriter w = GraphMLWriter.build().create();
// get the graph and export it to file
Graph graph = (Graph) shell.getInterp().getContext().getProperty(graphName);
w.writeGraph(f, graph);
// done
f.close();
io.out.println("==> exported to " + path);
}
/**
* @param path
* @return
*/
public static String resolvePath(String path, String defaultFileName) {
if(path == null){
//default path
path = defaultFileName;
} else if (path.endsWith(".json") || (path.endsWith(".xml"))) {
return path;
} else if (path.endsWith("/")){
path = path + defaultFileName;
} else {
path = path + "/" + defaultFileName;
}
return path;
}
public static String returnRelString(Relationship rel){
switch(rel){
case IS_A:
return "com.bio4j.titan.model.go.relationships.TitanIsA.TitanIsAType";
case PART_OF:
return "com.bio4j.titan.model.go.relationships.TitanPartOf.TitanPartOfType";
case HAS_PART_OF:
return "com.bio4j.titan.model.go.relationships.TitanHasPartOf.TitanHasPartOfType";
case REGULATES:
return "com.bio4j.titan.model.go.relationships.TitanPositivelyRegulates.TitanRegulatesType";
case POSITIVELY_REGULATES:
return "com.bio4j.titan.model.go.relationships.TitanPositivelyRegulates.TitanPositivelyRegulatesType";
case NEGATIVELY_REGULATES:
return "com.bio4j.titan.model.go.relationships.TitanNegativelyRegulates.TitanNegativelyRegulatesType";
case SUB_ONTOLOGY:
return "com.bio4j.titan.model.go.relationships.TitanSubOntology.TitanSubOntologyType";
case GO_SLIM:
return "com.bio4j.titan.model.go.relationships.TitanGoSlim.TitanGoSlimType";
}
throw new IllegalArgumentException("Unknown relationship: " + rel);
}
}
|
package com.cx.client.rest;
import com.cx.client.CxPluginHelper;
import com.cx.client.dto.LoginRequest;
import com.cx.client.dto.OSAFile;
import com.cx.client.exception.CxClientException;
import com.cx.client.rest.dto.*;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.client.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.security.KeyManagementException;
import java.util.ArrayList;
import java.util.List;
public class CxRestClient {
private final String username;
private final String password;
private Client client;
private WebTarget root;
public static final String OSA_SCAN_PROJECT_PATH = "osa/scans";
public static final String OSA_SCAN_STATUS_PATH = "osa/scans/{scanId}";
public static final String OSA_SCAN_SUMMARY_PATH = "osa/reports";
public static final String OSA_SCAN_LIBRARIES_PATH = "/osa/libraries";
public static final String OSA_SCAN_VULNERABILITIES_PATH = "/osa/vulnerabilities";
private static final String AUTHENTICATION_PATH = "auth/login";
private static final String ROOT_PATH = "CxRestAPI";
public static final String CSRF_TOKEN_HEADER = "CXCSRFToken";
public static final long MAX_ITEMS = 1000000;
private ArrayList<Object> cookies;
private String csrfToken;
private ObjectMapper mapper = new ObjectMapper();
private static final Logger log = LoggerFactory.getLogger(CxRestClient.class);
private ClientResponseFilter clientResponseFilter = new ClientResponseFilter() {
public void filter(ClientRequestContext clientRequestContext, ClientResponseContext clientResponseContext) throws IOException {
// copy cookies
if (clientResponseContext.getCookies() != null) {
if (cookies == null) {
cookies = new ArrayList<Object>();
}
//cookies.clear();
cookies.addAll(clientResponseContext.getCookies().values());
if (clientResponseContext.getCookies().get(CSRF_TOKEN_HEADER) != null) {
csrfToken = clientResponseContext.getCookies().get(CSRF_TOKEN_HEADER).getValue();
}
}
}
};
private ClientRequestFilter clientRequestFilter = new ClientRequestFilter() {
public void filter(ClientRequestContext clientRequestContext) throws IOException {
if (cookies != null) {
clientRequestContext.getHeaders().put("Cookie", cookies);
}
if (csrfToken != null) {
clientRequestContext.getHeaders().putSingle(CSRF_TOKEN_HEADER, csrfToken);
}
}
};
public CxRestClient(String hostname, String username, String password) {
this.username = username;
this.password = password;
client = ClientBuilder.newBuilder().register(clientRequestFilter).register(clientResponseFilter).build();
root = client.target(hostname).path(ROOT_PATH);
}
public void destroy() {
client.close();
}
public void disableCertificateValidation() {
try {
client.getSslContext().init(null, CxPluginHelper.createFakeTrustManager(), null);
} catch (KeyManagementException e) {
log.warn("Failed to disable SSL/TLS certificate validation");
}
}
public void login() throws CxClientException {
cookies = null;
csrfToken = null;
LoginRequest credentials = new LoginRequest(username, password);
Response response = root.path(AUTHENTICATION_PATH).request().post(Entity.entity(credentials, MediaType.APPLICATION_JSON));
validateResponse(response, Response.Status.OK, "Failed to login");
}
public CreateOSAScanResponse createOSAScan(long projectId, List<OSAFile> sha1s) throws CxClientException {
CreateOSAScanRequest requestBody = new CreateOSAScanRequest(projectId, "Maven", sha1s);
Response response = root.path(OSA_SCAN_PROJECT_PATH).request()
.post(Entity.entity(requestBody, MediaType.APPLICATION_JSON_TYPE));
validateResponse(response, Response.Status.ACCEPTED, "Failed to create OSA scan");
return convertToObject(response, CreateOSAScanResponse.class);
}
public OSAScanStatus getOSAScanStatus(String scanId) throws CxClientException {
Response response = root.path(OSA_SCAN_STATUS_PATH).resolveTemplate("scanId", scanId).request().get();
validateResponse(response, Response.Status.OK, "Failed to get OSA scan status");
return convertToObject(response, OSAScanStatus.class);
}
public OSASummaryResults getOSAScanSummaryResults(String scanId) throws CxClientException {
Response response = root.path(OSA_SCAN_SUMMARY_PATH).queryParam("scanId", scanId).request(MediaType.APPLICATION_JSON).get();
validateResponse(response, Response.Status.OK, "Failed to get OSA scan summary results");
return convertToObject(response, OSASummaryResults.class);
}
public String getOSAScanHtmlResults(String scanId) throws CxClientException {
Response response = root.path(OSA_SCAN_SUMMARY_PATH).queryParam("scanId", scanId).request(MediaType.TEXT_HTML).get();
validateResponse(response, Response.Status.OK, "Failed to get OSA scan HTML results");
return response.readEntity(String.class);
}
public List<Library> getOSALibraries(String scanId) throws CxClientException {
Response response = root.path(OSA_SCAN_LIBRARIES_PATH).queryParam("scanId", scanId)
.queryParam("itemsPerPage", MAX_ITEMS).request(MediaType.APPLICATION_JSON).get();
validateResponse(response, Response.Status.OK, "Failed to get OSA libraries");
return convertToObject(response, TypeFactory.defaultInstance().constructCollectionType(List.class, Library.class));
}
public List<CVE> getOSAVulnerabilities(String scanId) throws CxClientException {
Response response = root.path(OSA_SCAN_VULNERABILITIES_PATH).queryParam("scanId", scanId)
.queryParam("itemsPerPage", MAX_ITEMS).request(MediaType.APPLICATION_JSON).get();
validateResponse(response, Response.Status.OK, "Failed to get OSA vulnerabilities");
return convertToObject(response, TypeFactory.defaultInstance().constructCollectionType(List.class, CVE.class));
}
public byte[] getOSAScanPDFResults(String scanId) throws CxClientException {
Response response = root.path(OSA_SCAN_SUMMARY_PATH).queryParam("scanId", scanId).request("application/pdf").get();
validateResponse(response, Response.Status.OK, "Failed to get OSA scan PDF results");
return response.readEntity(byte[].class);
}
private void validateResponse(Response response, Response.Status expectedStatus, String message) throws CxClientException {
if (response.getStatus() != expectedStatus.getStatusCode()) {
String responseBody = response.readEntity(String.class);
responseBody = responseBody.replace("{", "").replace("}", "").replace(System.lineSeparator(), " ").replace(" ", "");
throw new CxClientException(message + ": " + "status code: " + response.getStatus() + ". error:" + responseBody);
}
}
private <T> T convertToObject(Response response, Class<T> valueType) throws CxClientException {
String json = response.readEntity(String.class);
T ret = null;
try {
ret = mapper.readValue(json, valueType);
} catch (IOException e) {
log.debug("Failed to parse JSON response: [" + json + "]", e);
throw new CxClientException("Failed to parse JSON response: " + e.getMessage());
}
return ret;
}
private <T> T convertToObject(Response response, JavaType javaType) throws CxClientException {
String json = response.readEntity(String.class);
T ret = null;
try {
ret = mapper.readValue(json, javaType);
} catch (IOException e) {
log.debug("Failed to parse JSON response: [" + json + "]", e);
throw new CxClientException("Failed to parse JSON response: " + e.getMessage());
}
return ret;
}
}
|
package com.fishercoder.solutions;
import java.util.ArrayList;
import java.util.List;
/**
* 1002. Find Common Characters
*
* Given an array A of strings made only from lowercase letters,
* return a list of all characters that show up in all strings within the list (including duplicates).
* For example, if a character occurs 3 times in all strings but not 4 times, you need to include that character three times in the final answer.
*
* You may return the answer in any order.
*
* Example 1:
* Input: ["bella","label","roller"]
* Output: ["e","l","l"]
*
* Example 2:
* Input: ["cool","lock","cook"]
* Output: ["c","o"]
*
* Note:
* 1 <= A.length <= 100
* 1 <= A[i].length <= 100
* A[i][j] is a lowercase letter
*/
public class _1002 {
public static class Solution1 {
public List<String> commonChars(String[] A) {
int[][] charCount = new int[A.length][26];
for (int i = 0; i < A.length; i++) {
for (char c : A[i].toCharArray()) {
charCount[i][c - 'a']++;
}
}
List<String> result = new ArrayList<>();
for (int i = 0; i < 26; i++) {
while (charCount[0][i] != 0) {
char c = (char) (i + 'a');
boolean valid = true;
charCount[0][i]
for (int j = 1; j < A.length; j++) {
if (charCount[j][i] == 0) {
valid = false;
break;
} else {
charCount[j][i]
}
}
if (!valid) {
break;
} else {
result.add("" + c);
}
}
}
return result;
}
}
}
|
package com.fishercoder.solutions;
import java.util.Arrays;
public class _1196 {
public static class Solution1 {
public int maxNumberOfApples(int[] arr) {
Arrays.sort(arr);
int sum = 0;
int i = 0;
for (; i < arr.length; i++) {
sum += arr[i];
if (sum > 5000) {
break;
}
}
return i;
}
}
}
|
package com.github.fjdbc.op;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import com.github.fjdbc.FjdbcException;
import com.github.fjdbc.PreparedStatementBinder;
import com.github.fjdbc.util.FjdbcUtil;
import com.github.fjdbc.util.PreparedStatementEx;
/**
* Wraps either a {@link java.sql.PreparedStatement} or a {@link java.sql.Statement}.
*/
public class StatementOp implements DbOp {
private final String sql;
private final PreparedStatementBinder binder;
public StatementOp(String sql, PreparedStatementBinder binder) {
assert sql != null;
this.sql = sql;
this.binder = binder;
}
private boolean isPrepared() {
return binder != null;
}
@Override
public int execute(Connection cnx) throws SQLException {
assert cnx != null;
return isPrepared() ? execute_preparedStatement(cnx) : execute_regularStatement(cnx);
}
private int execute_regularStatement(Connection cnx) throws SQLException {
try (Statement st = cnx.createStatement()) {
final int modifiedRows = st.executeUpdate(sql);
return modifiedRows;
}
}
private int execute_preparedStatement(Connection cnx) throws SQLException {
try (PreparedStatement ps = cnx.prepareStatement(sql)) {
final PreparedStatementEx psx = new PreparedStatementEx(ps);
binder.bind(psx);
if (psx.isBatch()) {
final int[] nRows = ps.executeBatch();
return getNRowsModifiedByBatch(nRows);
} else {
final int nRows = psx.executeUpdate();
return nRows;
}
}
}
private int getNRowsModifiedByBatch(int[] modifiedRows) {
int sum = 0;
for (final int r : modifiedRows) {
if (r == PreparedStatement.SUCCESS_NO_INFO) {
return PreparedStatement.SUCCESS_NO_INFO;
} else if (r == PreparedStatement.EXECUTE_FAILED) {
return PreparedStatement.EXECUTE_FAILED;
} else {
sum += r;
}
}
return sum;
}
@Override
public int executeAndCommit(Connection cnx) {
try {
final int modifiedRows = execute(cnx);
cnx.commit();
return modifiedRows;
} catch (final SQLException e) {
throw new FjdbcException(e);
} finally {
FjdbcUtil.closeConnection(cnx);
}
}
}
|
package com.google.sps.data;
/** Class representing a MapLocation as a coordinate **/
public class MapLocation {
public double lat;
public double lng;
/** Creates a new MapLocation
* @param lat latitude value
* @param lng longitude value
* @return MapLocation object
**/
public MapLocation (double lat, double lng) {
this.lat = lat;
this.lng = lng;
}
}
|
package com.kurento.kmf.media;
import com.kurento.kms.api.MediaObject;
import com.kurento.kms.api.MixerType;
public class MainMixer extends Mixer {
private static final long serialVersionUID = 1L;
static final MixerType mixerType = MixerType.MAIN_MIXER;
MainMixer(MediaObject mainMixer) {
super(mainMixer);
}
}
|
package com.logsentinel.api;
import com.logsentinel.ApiException;
import com.logsentinel.ApiClient;
import com.logsentinel.ApiResponse;
import com.logsentinel.Configuration;
import com.logsentinel.Pair;
import javax.ws.rs.core.GenericType;
import com.logsentinel.model.APICredentialsOrganization;
import com.logsentinel.model.OrganizationDto;
import com.logsentinel.model.RegistrationResponse;
import java.util.UUID;
import com.logsentinel.model.UserRegistrationRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class PartnersApi {
private ApiClient apiClient;
public PartnersApi() {
this(Configuration.getDefaultApiClient());
}
public PartnersApi(ApiClient apiClient) {
this.apiClient = apiClient;
}
public ApiClient getApiClient() {
return apiClient;
}
public void setApiClient(ApiClient apiClient) {
this.apiClient = apiClient;
}
/**
* Cancels organization by Id and deletes all users
*
* @param organizationId organizationId (required)
* @throws ApiException if fails to make API call
*/
public void cancelOrganization(UUID organizationId) throws ApiException {
cancelOrganizationWithHttpInfo(organizationId);
}
/**
* Cancels organization by Id and deletes all users
*
* @param organizationId organizationId (required)
* @throws ApiException if fails to make API call
*/
public ApiResponse<Void> cancelOrganizationWithHttpInfo(UUID organizationId) throws ApiException {
Object localVarPostBody = null;
// verify the required parameter 'organizationId' is set
if (organizationId == null) {
throw new ApiException(400, "Missing the required parameter 'organizationId' when calling cancelOrganization");
}
// create path and map variables
String localVarPath = "/api/partner/organizations/cancel";
// query params
List<Pair> localVarQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
localVarQueryParams.addAll(apiClient.parameterToPairs("", "organizationId", organizationId));
final String[] localVarAccepts = {
"application/xml", "application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
final String[] localVarContentTypes = {
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
String[] localVarAuthNames = new String[] { "basicAuth" };
return apiClient.invokeAPI(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null);
}
/**
* Fetch all organizations
*
* @return List<UUID>
* @throws ApiException if fails to make API call
*/
public List<UUID> fetchAllOrganizations() throws ApiException {
return fetchAllOrganizationsWithHttpInfo().getData();
}
/**
* Fetch all organizations
*
* @return ApiResponse<List<UUID>>
* @throws ApiException if fails to make API call
*/
public ApiResponse<List<UUID>> fetchAllOrganizationsWithHttpInfo() throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/api/partner/organizations";
// query params
List<Pair> localVarQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/xml", "application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
final String[] localVarContentTypes = {
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
String[] localVarAuthNames = new String[] { "basicAuth" };
GenericType<List<UUID>> localVarReturnType = new GenericType<List<UUID>>() {};
return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType);
}
/**
* API credentials per organization from organizations owned by partner
*
* @return Map<String, List<APICredentialsOrganization>>
* @throws ApiException if fails to make API call
*/
public Map<String, List<APICredentialsOrganization>> getApiCredentials() throws ApiException {
return getApiCredentialsWithHttpInfo().getData();
}
/**
* API credentials per organization from organizations owned by partner
*
* @return ApiResponse<Map<String, List<APICredentialsOrganization>>>
* @throws ApiException if fails to make API call
*/
public ApiResponse<Map<String, List<APICredentialsOrganization>>> getApiCredentialsWithHttpInfo() throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/api/partner/organizations/apiCredentials";
// query params
List<Pair> localVarQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/xml", "application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
final String[] localVarContentTypes = {
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
String[] localVarAuthNames = new String[] { "basicAuth" };
GenericType<Map<String, List<APICredentialsOrganization>>> localVarReturnType = new GenericType<Map<String, List<APICredentialsOrganization>>>() {};
return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType);
}
/**
* Get the organization for the supplied email
*
* @param email email (required)
* @return OrganizationDto
* @throws ApiException if fails to make API call
*/
public OrganizationDto getOrganizationByUserEmail(String email) throws ApiException {
return getOrganizationByUserEmailWithHttpInfo(email).getData();
}
/**
* Get the organization for the supplied email
*
* @param email email (required)
* @return ApiResponse<OrganizationDto>
* @throws ApiException if fails to make API call
*/
public ApiResponse<OrganizationDto> getOrganizationByUserEmailWithHttpInfo(String email) throws ApiException {
Object localVarPostBody = null;
// verify the required parameter 'email' is set
if (email == null) {
throw new ApiException(400, "Missing the required parameter 'email' when calling getOrganizationByUserEmail");
}
// create path and map variables
String localVarPath = "/api/partner/organizationByUserEmail";
// query params
List<Pair> localVarQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
localVarQueryParams.addAll(apiClient.parameterToPairs("", "email", email));
final String[] localVarAccepts = {
"application/xml", "application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
final String[] localVarContentTypes = {
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
String[] localVarAuthNames = new String[] { "basicAuth" };
GenericType<OrganizationDto> localVarReturnType = new GenericType<OrganizationDto>() {};
return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType);
}
/**
* Register a user
*
* @param request request (required)
* @return RegistrationResponse
* @throws ApiException if fails to make API call
*/
public RegistrationResponse registerUser(UserRegistrationRequest request) throws ApiException {
return registerUserWithHttpInfo(request).getData();
}
/**
* Register a user
*
* @param request request (required)
* @return ApiResponse<RegistrationResponse>
* @throws ApiException if fails to make API call
*/
public ApiResponse<RegistrationResponse> registerUserWithHttpInfo(UserRegistrationRequest request) throws ApiException {
Object localVarPostBody = request;
// verify the required parameter 'request' is set
if (request == null) {
throw new ApiException(400, "Missing the required parameter 'request' when calling registerUser");
}
// create path and map variables
String localVarPath = "/api/partner/user/register";
// query params
List<Pair> localVarQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/xml", "application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
final String[] localVarContentTypes = {
"application/json", "*/*"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
String[] localVarAuthNames = new String[] { "basicAuth" };
GenericType<RegistrationResponse> localVarReturnType = new GenericType<RegistrationResponse>() {};
return apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType);
}
}
|
package com.lovi.puppy.message;
import com.lovi.puppy.exceptions.UICallerException;
public interface UICaller {
/**
* listener address format -> {appName}.{address}.
* @param address
* @param message
* @throws ServiceCallerException
*/
void call(String listenerAddress,Object message) throws UICallerException;
}
|
package com.maestrano.net;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
public class MnoHttpClient {
private String defaultUserAgent;
public MnoHttpClient() {
this.defaultUserAgent = "maestrano-java/" + System.getProperty("java.version");
}
/**
* Perform a GET request on the specified endpoint
* @param url
* @return response body
* @throws IOException
*/
public String get(String url) throws IOException {
return performRequest(url,"GET",null);
}
/**
* Perform a GET request on the specified endpoint
* @param url
* @return response body
* @throws IOException
*/
public String get(String url, Map<String,String> header) throws IOException {
return performRequest(url,"GET",header);
}
/**
* Perform a POST request on the specified endpoint
* @param url
* @param header
* @param payload
* @return response body
* @throws IOException
*/
public String post(String url, Map<String,String> header, String payload) throws IOException {
return performRequest(url,"POST",header,payload);
}
/**
* Perform a PUT request on the specified endpoint
* @param url
* @param header
* @param payload
* @return response body
* @throws IOException
*/
public String put(String url, Map<String,String> header, String payload) throws IOException {
return performRequest(url,"PUT",header,payload);
}
/**
* Perform a PUT request on the specified endpoint
* @param url
* @param header
* @param payload
* @return response body
* @throws IOException
*/
public String delete(String url, Map<String,String> header, String payload) throws IOException {
return performRequest(url,"DELETE",header,payload);
}
/**
* Perform a request to the remote endpoint
* @param url the remote endpoint to contact
* @param method such as 'GET', 'PUT', 'POST' or 'DELETE'
* @return response body
* @throws IOException
*/
protected String performRequest(String url, String method) throws IOException {
return performRequest(url,method,null);
}
/**
* Perform a request to the remote endpoint
* @param url the remote endpoint to contact
* @param method such as 'GET', 'PUT', 'POST' or 'DELETE'
* @param header values
* @return response body
* @throws IOException
*/
protected String performRequest(String url, String method, Map<String,String> header) throws IOException {
return performRequest(url,method,header,null);
}
/**
* Perform a request to the remote endpoint
* @param url the remote endpoint to contact
* @param method such as 'GET', 'PUT', 'POST' or 'DELETE'
* @param header values
* @param payload data to send
* @return response body
* @throws IOException
*/
protected String performRequest(String url, String method, Map<String,String> header, String payload) throws IOException {
// Prepare header
if (header == null) {
header = new HashMap<String,String>();
}
// Set method
header.put("method",method.toUpperCase());
// Set user agent
if (header.get("User-Agent") == null || header.get("User-Agent").isEmpty()) {
header.put("User-Agent",defaultUserAgent);
}
// Get connection
HttpURLConnection conn = openConnection(url,header);
// Send Data if PUT/POST
if (payload != null) {
if (method.equalsIgnoreCase("PUT") || method.equalsIgnoreCase("POST")) {
OutputStream output = null;
try {
output = conn.getOutputStream();
output.write(payload.getBytes());
} finally {
if (output != null) {
output.close();
}
}
}
}
// Parse response
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer html = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
html.append(inputLine);
}
in.close();
return html.toString();
}
/**
* Open a connection and follow the redirect
* @param String url
* @param header contain
* @return HttpURLConnection connection
* @throws IOException
*/
protected HttpURLConnection openConnection(String url, Map<String,String> header) throws IOException {
// Initialize connection
URL urlObj = null;
HttpURLConnection conn = null;
int redirectCount = 0;
boolean redirect = true;
while (redirect) {
if (redirectCount > 10) {
throw new ProtocolException("Too many redirects: " + redirectCount);
}
if (conn == null) {
urlObj = new URL(url);
} else {
// get redirect url from "location" header field
urlObj = new URL(conn.getHeaderField("Location"));
}
// open the new connection again
conn = (HttpURLConnection) urlObj.openConnection();
conn.setRequestMethod(header.get("method"));
conn.addRequestProperty("User-Agent", header.get("User-Agent"));
conn.setInstanceFollowRedirects(true);
// Check if redirect
redirect = false;
int status = conn.getResponseCode();
if (status != HttpURLConnection.HTTP_OK) {
if (status == HttpURLConnection.HTTP_MOVED_TEMP
|| status == HttpURLConnection.HTTP_MOVED_PERM
|| status == HttpURLConnection.HTTP_SEE_OTHER)
redirect = true;
redirectCount ++;
}
}
return conn;
}
}
|
package com.metaweb.gridworks.model;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Map.Entry;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonToken;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONWriter;
import com.metaweb.gridworks.Jsonizable;
import com.metaweb.gridworks.expr.CellTuple;
import com.metaweb.gridworks.expr.HasFields;
public class Row implements HasFields, Jsonizable {
public boolean flagged;
public boolean starred;
final public List<Cell> cells;
transient public int recordIndex = -1; // -1 for rows that are not main record rows
transient public List<Integer> contextRows;
transient public int[] contextRowSlots;
transient public int[] contextCellSlots;
private static final String FLAGGED = "flagged";
private static final String STARRED = "starred";
public Row(int cellCount) {
cells = new ArrayList<Cell>(cellCount);
}
protected Row(List<Cell> cells, boolean flagged, boolean starred) {
this.cells = cells;
this.flagged = flagged;
this.starred = starred;
}
public Row dup() {
Row row = new Row(cells.size());
row.flagged = flagged;
row.starred = starred;
row.cells.addAll(cells);
return row;
}
public Object getField(String name, Properties bindings) {
if (FLAGGED.equals(name)) {
return flagged;
} else if (STARRED.equals(name)) {
return starred;
}
return null;
}
public boolean fieldAlsoHasFields(String name) {
return "cells".equals(name) || "record".equals(name);
}
public boolean isEmpty() {
for (Cell cell : cells) {
if (cell != null && cell.value != null && !isValueBlank(cell.value)) {
return false;
}
}
return true;
}
public Cell getCell(int cellIndex) {
if (cellIndex < cells.size()) {
return cells.get(cellIndex);
} else {
return null;
}
}
public Object getCellValue(int cellIndex) {
if (cellIndex < cells.size()) {
Cell cell = cells.get(cellIndex);
if (cell != null) {
return cell.value;
}
}
return null;
}
public boolean isCellBlank(int cellIndex) {
return isValueBlank(getCellValue(cellIndex));
}
protected boolean isValueBlank(Object value) {
return value == null || !(value instanceof String) || ((String) value).trim().length() == 0;
}
public void setCell(int cellIndex, Cell cell) {
if (cellIndex < cells.size()) {
cells.set(cellIndex, cell);
} else {
while (cellIndex > cells.size()) {
cells.add(null);
}
cells.add(cell);
}
}
public CellTuple getCellTuple(Project project) {
return new CellTuple(project, this);
}
public void write(JSONWriter writer, Properties options)
throws JSONException {
writer.object();
writer.key(FLAGGED); writer.value(flagged);
writer.key(STARRED); writer.value(starred);
writer.key("cells"); writer.array();
for (Cell cell : cells) {
if (cell != null) {
cell.write(writer, options);
} else {
writer.value(null);
}
}
writer.endArray();
if (!"save".equals(options.getProperty("mode"))) {
if (recordIndex >= 0) {
writer.key("j"); writer.value(recordIndex);
}
if (options.containsKey("rowIndex")) {
writer.key("i"); writer.value(options.get("rowIndex"));
}
if (options.containsKey("extra")) {
Properties extra = (Properties) options.get("extra");
if (extra != null) {
for (Entry<Object,Object> e : extra.entrySet()) {
writer.key((String) e.getKey());
writer.value(e.getValue());
}
}
}
}
writer.endObject();
}
public void save(Writer writer, Properties options) {
JSONWriter jsonWriter = new JSONWriter(writer);
try {
write(jsonWriter, options);
} catch (JSONException e) {
e.printStackTrace();
}
}
static public Row load(String s, Map<Long, Recon> reconCache) throws Exception {
return s.length() == 0 ? null :
//load(ParsingUtilities.evaluateJsonStringToObject(s), reconCache);
loadStreaming(s, reconCache);
}
static public Row load(JSONObject obj, Map<Long, Recon> reconCache) throws Exception {
JSONArray a = obj.getJSONArray("cells");
int count = a.length();
Row row = new Row(count);
for (int i = 0; i < count; i++) {
if (!a.isNull(i)) {
JSONObject o = a.getJSONObject(i);
row.setCell(i, Cell.load(o, reconCache));
}
}
if (obj.has(STARRED)) {
row.starred = obj.getBoolean(STARRED);
}
if (obj.has(FLAGGED)) {
row.flagged = obj.getBoolean(FLAGGED);
}
return row;
}
static public Row loadStreaming(String s, Map<Long, Recon> reconCache) throws Exception {
JsonFactory jsonFactory = new JsonFactory();
JsonParser jp = jsonFactory.createJsonParser(s);
if (jp.nextToken() != JsonToken.START_OBJECT) {
return null;
}
List<Cell> cells = new ArrayList<Cell>();
boolean starred = false;
boolean flagged = false;
while (jp.nextToken() != JsonToken.END_OBJECT) {
String fieldName = jp.getCurrentName();
jp.nextToken();
if (STARRED.equals(fieldName)) {
starred = jp.getBooleanValue();
} else if (FLAGGED.equals(fieldName)) {
flagged = jp.getBooleanValue();
} else if ("cells".equals(fieldName)) {
if (jp.getCurrentToken() != JsonToken.START_ARRAY) {
return null;
}
while (jp.nextToken() != JsonToken.END_ARRAY) {
Cell cell = Cell.loadStreaming(jp, reconCache);
cells.add(cell);
}
}
}
return (cells.size() > 0) ? new Row(cells, flagged, starred) : null;
}
}
|
package com.pardot.rhombus;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.utils.UUIDs;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.pardot.rhombus.cobject.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Map;
import java.util.UUID;
public class ObjectMapper {
private static Logger logger = LoggerFactory.getLogger(ObjectMapper.class);
private static final int reasonableStatementLimit = 20;
private boolean logCql = false;
private Session session;
private CKeyspaceDefinition keyspaceDefinition;
private CObjectCQLGenerator cqlGenerator;
public ObjectMapper(Session session, CKeyspaceDefinition keyspaceDefinition) {
this.session = session;
this.keyspaceDefinition = keyspaceDefinition;
this.cqlGenerator = new CObjectCQLGenerator(keyspaceDefinition.getDefinitions(),null);
}
/**
* Build the tables contained in the keyspace definition.
* This method assumes that its keyspace exists and
* does not contain any tables.
*/
public void buildKeyspace() {
//First build the shard index
String cql = CObjectCQLGenerator.makeCQLforShardIndexTableCreate();
executeCql(cql);
//Now build the tables for each object
for(CDefinition definition : keyspaceDefinition.getDefinitions().values()) {
CQLStatementIterator statementIterator = cqlGenerator.makeCQLforCreate(definition.getName());
while(statementIterator.hasNext()) {
cql = statementIterator.next();
executeCql(cql);
}
}
}
private void executeCql(String cql) {
if(logCql) {
logger.debug("Executing CQL: {}", cql);
}
session.execute(cql);
}
private UUID insert(String objectType, Map<String, String> values, UUID key) throws CQLGenerationException {
logger.debug("Insert {}", objectType);
if(key == null) {
key = UUIDs.timeBased();
}
long timestamp = System.currentTimeMillis();
CQLStatementIterator statementIterator = cqlGenerator.makeCQLforInsert(objectType, values, key, timestamp);
while(statementIterator.hasNext()) {
String cql = statementIterator.next();
executeCql(cql);
}
return key;
}
/**
* Insert a new objectType with values
* @param objectType
* @param values
* @return UUID of inserted object
* @throws CQLGenerationException
*/
public UUID insert(String objectType, Map<String, String> values) throws CQLGenerationException {
return insert(objectType, values, null);
}
/**
* Delete objecttype with id key
* @param objectType
* @param key
*/
public void delete(String objectType, UUID key) {
CDefinition def = keyspaceDefinition.getDefinitions().get(objectType);
Map<String, String> values = getByKey(objectType, key);
CQLStatementIterator statementIterator = cqlGenerator.makeCQLforDelete(objectType, key, values, null);
mapResults(statementIterator, def, 0L);
}
/**
* Update objectType with key using values
* @param objectType
* @param key
* @param values
* @return new UUID of the object
* @throws CQLGenerationException
*/
public UUID update(String objectType, UUID key, Map<String, String> values) throws CQLGenerationException {
//Make a new key
UUID newKey = UUIDs.startOf(UUIDs.unixTimestamp(key));
//Delete
delete(objectType, key);
//Insert
return insert(objectType, values, newKey);
}
/**
*
* @param objectType
* @param key
* @return Object of type with key or null if it does not exist
*/
public Map<String, String> getByKey(String objectType, UUID key) {
CDefinition def = keyspaceDefinition.getDefinitions().get(objectType);
CQLStatementIterator statementIterator = cqlGenerator.makeCQLforGet(objectType, key);
List<Map<String, String>> results = mapResults(statementIterator, def, 1L);
if(results.size() > 0) {
return results.get(0);
} else {
return null;
}
}
/**
* @param objectType
* @param criteria
* @return List of objects that match the specified type and criteria
* @throws CQLGenerationException
*/
public List<Map<String, String>> list(String objectType, Criteria criteria) throws CQLGenerationException {
CDefinition def = keyspaceDefinition.getDefinitions().get(objectType);
CQLStatementIterator statementIterator = cqlGenerator.makeCQLforGet(objectType, criteria);
List<Map<String, String>> results = mapResults(statementIterator, def, criteria.getLimit());
return results;
}
/**
* Iterates through cql statements executing them in sequence and mapping the results until limit is reached
* @param statementIterator
* @param definition
* @return Ordered resultset concatenating results from statements in statement iterator.
*/
private List<Map<String, String>> mapResults(CQLStatementIterator statementIterator, CDefinition definition, Long limit) {
List<Map<String, String>> results = Lists.newArrayList();
int statementNumber = 0;
int resultNumber = 0;
while(statementIterator.hasNext(resultNumber) ) {
String cql = statementIterator.next();
logger.debug("Executing CQL: " + cql);
ResultSet resultSet = session.execute(cql);
for(Row row : resultSet) {
Map<String, String> result = mapResult(row, definition);
results.add(result);
resultNumber++;
}
statementNumber++;
if((limit > 0 && resultNumber >= limit) || statementNumber > reasonableStatementLimit) {
logger.debug("Breaking from mapping results");
break;
}
}
return results;
}
/**
* @param row
* @param definition
* @return Data contained in a row mapped to the object described in definition.
*/
private Map<String, String> mapResult(Row row, CDefinition definition) {
Map<String, String> result = Maps.newHashMap();
for(CField field : definition.getFields().values()) {
result.put(field.getName(), getFieldValue(row, field));
}
return result;
}
private String getFieldValue(Row row, CField field) {
Object fieldValue;
switch(field.getType()) {
case ASCII:
case VARCHAR:
case TEXT:
fieldValue = row.getString(field.getName());
break;
case BIGINT:
case COUNTER:
fieldValue = row.getLong(field.getName());
break;
case BLOB:
fieldValue = row.getBytes(field.getName());
break;
case BOOLEAN:
fieldValue = row.getBool(field.getName());
break;
case DECIMAL:
fieldValue = row.getDecimal(field.getName());
break;
case DOUBLE:
fieldValue = row.getDouble(field.getName());
break;
case FLOAT:
fieldValue = row.getFloat(field.getName());
break;
case INT:
fieldValue = row.getInt(field.getName());
break;
case TIMESTAMP:
fieldValue = row.getDate(field.getName());
break;
case UUID:
case TIMEUUID:
fieldValue = row.getUUID(field.getName());
break;
case VARINT:
fieldValue = row.getVarint(field.getName());
break;
default:
fieldValue = null;
}
return fieldValue.toString();
}
public boolean getLogCql() {
return logCql;
}
public void setLogCql(boolean logCql) {
this.logCql = logCql;
}
public void teardown() {
session.shutdown();
}
}
|
package com.perimeterx.models;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.perimeterx.api.additionalContext.AdditionalContext;
import com.perimeterx.api.providers.CustomParametersProvider;
import com.perimeterx.api.providers.HostnameProvider;
import com.perimeterx.api.providers.IPProvider;
import com.perimeterx.internals.cookie.AbstractPXCookie;
import com.perimeterx.internals.cookie.DataEnrichmentCookie;
import com.perimeterx.internals.cookie.RawCookieData;
import com.perimeterx.internals.cookie.cookieparsers.CookieHeaderParser;
import com.perimeterx.internals.cookie.cookieparsers.HeaderParser;
import com.perimeterx.internals.cookie.cookieparsers.MobileCookieHeaderParser;
import com.perimeterx.models.configuration.ModuleMode;
import com.perimeterx.models.configuration.PXConfiguration;
import com.perimeterx.models.risk.*;
import com.perimeterx.utils.*;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.ServletRequest;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.perimeterx.utils.Constants.BREACHED_ACCOUNT_KEY_NAME;
@Data
public class PXContext {
private static final PXLogger logger = PXLogger.getLogger(PXContext.class);
/**
* Original HTTP request
*/
private final HttpServletRequest request;
private String pxCookieRaw;
/**
* Original Captcha cookie
*/
private String pxCaptcha;
/**
* Request IP as extracted with IPProvider.
*
* @see com.perimeterx.api.providers.IPProvider#getRequestIP(HttpServletRequest)
*/
private String ip;
private PXConfiguration pxConfiguration;
// Additional fields extracted from the original HTTP request
private String vid;
private String uuid;
private Map<String, String> headers;
private String hostname;
private String uri;
private String userAgent;
private String fullUrl;
private String httpMethod;
private String httpVersion;
// PerimeterX computed data on the request
private String riskCookie;
private final String appId;
private String cookieHmac;
/**
* Score for the current request - if riskScore is above configured blockingScore on
* PXConfiguration then the {@link com.perimeterx.models.PXContext#verified} is set to false
*/
private int riskScore;
/**
* Reason for calling PX Service
*
* @see com.perimeterx.models.risk.S2SCallReason
*/
private String s2sCallReason;
private boolean madeS2SApiCall;
/**
* Which action to take after being blocked
*/
private BlockAction blockAction;
/**
* if true - calling risk_api to verified request even if cookie data is valid
*/
private boolean sensitiveRoute;
/**
* Reason for request being verified
*
* @see com.perimeterx.models.risk.PassReason
*/
private PassReason passReason;
/**
* Reason for s2s_error if occurred
*
* @see com.perimeterx.models.risk.S2SErrorReasonInfo
*/
private S2SErrorReasonInfo s2sErrorReasonInfo;
/**
* Risk api timing
*/
private long riskRtt;
/**
* Request verification status - if {@link com.perimeterx.models.PXContext#verified} is true, the request is safe to pass to server.
*/
private boolean verified;
/**
* Reason for why request should be blocked - relevant when request is not verified, meaning - verified {@link com.perimeterx.models.PXContext#verified} is false
*/
private BlockReason blockReason;
/**
* Contains the data that would be rendered on the response when score exceeds the threshold
*/
private String blockActionData;
/**
* Marks is the origin of the request comes from mobile client
*/
private boolean isMobileToken;
/**
* Marks the origin of the pxCookie
*/
private String cookieOrigin = Constants.COOKIE_HEADER_NAME;
/**
* Custom parameters from the requests, cusotm parameters are set via {@link com.perimeterx.api.providers.CustomParametersProvider#buildCustomParameters(PXConfiguration, PXContext)}
* if exist, the custom parameters will be set when risk api is triggered
*/
private CustomParameters customParameters;
/**
* Simmilar to {@link com.perimeterx.models.PXContext#verified}, flags if to continue the filter chain or return
* This will be set to true when the module will handle the request though proxy mode
*/
private boolean firstPartyRequest;
/**
* The original uuid of the request.
*/
private String originalUuid;
/**
* The original token decoded.
*/
private String decodedOriginalToken;
/**
* Errors encountered during the creation process of the cookie
*/
private String originalTokenError;
/**
* The original token cookie.
*/
private String originalTokenCookie;
/**
* The risk mode (monitor / active_blocking) of the request
*/
private String riskMode;
private List<RawCookieData> tokens;
private List<RawCookieData> originalTokens;
private String cookieVersion;
/**
* PerimeterX data enrichment cookie payload
*/
private JsonNode pxde;
private boolean pxdeVerified = false;
/**
* All the names of the cookies in the request
*/
private String[] requestCookieNames;
/**
* the source of the vid
*/
private VidSource vidSource = VidSource.NONE;
/**
* the pxhd cookie
*/
private String pxhd;
private String responsePxhd;
private boolean isMonitoredRequest;
private AdditionalContext additionalContext;
private UUID requestId;
public PXContext(final HttpServletRequest request, final IPProvider ipProvider, final HostnameProvider hostnameProvider, PXConfiguration pxConfiguration) {
this.pxConfiguration = pxConfiguration;
logger.debug(PXLogger.LogReason.DEBUG_REQUEST_CONTEXT_CREATED);
this.appId = pxConfiguration.getAppId();
this.ip = ipProvider.getRequestIP(request);
this.hostname = hostnameProvider.getHostname(request);
this.request = request;
initContext(request, pxConfiguration);
}
private void initContext(final HttpServletRequest request, PXConfiguration pxConfiguration) {
this.headers = PXCommonUtils.getHeadersFromRequest(request);
if (headers.containsKey(Constants.MOBILE_SDK_AUTHORIZATION_HEADER) || headers.containsKey(Constants.MOBILE_SDK_TOKENS_HEADER)) {
logger.debug(PXLogger.LogReason.DEBUG_MOBILE_SDK_DETECTED);
this.isMobileToken = true;
this.cookieOrigin = Constants.HEADER_ORIGIN;
}
parseCookies(request, isMobileToken);
this.firstPartyRequest = false;
this.userAgent = request.getHeader("user-agent");
this.uri = request.getRequestURI();
this.fullUrl = extractURL(request); //full URL with query string
this.blockReason = BlockReason.NONE;
this.passReason = PassReason.NONE;
this.s2sErrorReasonInfo = new S2SErrorReasonInfo();
this.madeS2SApiCall = false;
this.riskRtt = 0;
this.httpMethod = request.getMethod();
this.isMonitoredRequest = !shouldBypassMonitor() && shouldMonitorRequest();
this.requestId = UUID.randomUUID();
String protocolDetails[] = request.getProtocol().split("/");
this.httpVersion = protocolDetails.length > 1 ? protocolDetails[1] : StringUtils.EMPTY;
this.sensitiveRoute = checkSensitiveRoute(pxConfiguration.getSensitiveRoutes(), uri)
|| checkSensitiveRouteRegex(pxConfiguration.getSensitiveRoutesRegex(), uri);
CustomParametersProvider customParametersProvider = pxConfiguration.getCustomParametersProvider();
this.customParameters = customParametersProvider.buildCustomParameters(pxConfiguration, this);
}
private boolean isRoutesContainUri(Set<String> routes, String uri) {
Pattern pattern;
Matcher matcher;
for (String routeExpression : routes) {
pattern = Pattern.compile(routeExpression, Pattern.CASE_INSENSITIVE);
matcher = pattern.matcher(uri);
if (matcher.matches()) {
return true;
}
}
return false;
}
private boolean shouldMonitorRequest() {
return ((pxConfiguration.getModuleMode().equals(ModuleMode.MONITOR) &&
!isRoutesContainUri(this.pxConfiguration.getEnforcedRoutes(), this.getUri())) ||
isRoutesContainUri(this.pxConfiguration.getMonitoredRoutes(), this.getUri()));
}
private boolean shouldBypassMonitor() {
String bypassHeader = this.pxConfiguration.getBypassMonitorHeader();
return !StringUtils.isEmpty(bypassHeader) && this.getHeaders().containsKey(bypassHeader.toLowerCase())
&& this.getHeaders().get(bypassHeader.toLowerCase()).equals("1");
}
private String extractURL(ServletRequest request) {
StringBuffer requestURL = ((HttpServletRequest) request).getRequestURL();
if (((HttpServletRequest) request).getQueryString() != null) {
requestURL.append("?").append(((HttpServletRequest) request).getQueryString());
}
return requestURL.toString();
}
private void parseCookies(HttpServletRequest request, boolean isMobileToken) {
HeaderParser headerParser = new CookieHeaderParser();
List<RawCookieData> tokens = new ArrayList<>();
List<RawCookieData> originalTokens = new ArrayList<>();
if (isMobileToken) {
headerParser = new MobileCookieHeaderParser();
String tokensHeader = request.getHeader(Constants.MOBILE_SDK_TOKENS_HEADER);
tokens.addAll(headerParser.createRawCookieDataList(tokensHeader));
String authCookieHeader = request.getHeader(Constants.MOBILE_SDK_AUTHORIZATION_HEADER);
tokens.addAll(headerParser.createRawCookieDataList(authCookieHeader));
String originalTokensHeader = request.getHeader(Constants.MOBILE_SDK_ORIGINAL_TOKENS_HEADER);
originalTokens.addAll(headerParser.createRawCookieDataList(originalTokensHeader));
String originalTokenHeader = request.getHeader(Constants.MOBILE_SDK_ORIGINAL_TOKEN_HEADER);
originalTokens.addAll(headerParser.createRawCookieDataList(originalTokenHeader));
this.tokens = tokens;
if (!originalTokens.isEmpty()) {
this.originalTokens = originalTokens;
}
ObjectMapper mapper = new ObjectMapper();
this.pxde = mapper.createObjectNode();
this.pxdeVerified = true;
} else {
Cookie[] cookies = request.getCookies();
String cookieHeader = request.getHeader(Constants.COOKIE_HEADER_NAME);
this.requestCookieNames = CookieNamesExtractor.extractCookieNames(cookies);
setVidAndPxhd(cookies);
tokens.addAll(headerParser.createRawCookieDataList(cookieHeader));
this.tokens = tokens;
DataEnrichmentCookie deCookie = headerParser.getRawDataEnrichmentCookie(this.tokens, this.pxConfiguration.getCookieKey());
this.pxde = deCookie.getJsonPayload();
this.pxdeVerified = deCookie.isValid();
}
}
private void setVidAndPxhd(Cookie[] cookies) {
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("_pxvid") || cookie.getName().equals("pxvid")) {
this.vid = cookie.getValue();
this.vidSource = VidSource.VID_COOKIE;
}
if (cookie.getName().equals("_pxhd")) {
try {
this.pxhd = URLDecoder.decode(cookie.getValue(), "UTF-8");
} catch (UnsupportedEncodingException e) {
logger.error("Failed while decoding the pxhd value");
}
}
}
}
}
public String getPxOriginalTokenCookie() {
return originalTokenCookie;
}
public Boolean isMonitoredRequest() {
return this.isMonitoredRequest;
}
public String getRiskMode() {
return this.isMonitoredRequest() ? "monitor" : "active_blocking";
}
public void setOriginalTokenCookie(String originalTokenCookie) {
this.originalTokenCookie = originalTokenCookie;
}
public void setRiskCookie(AbstractPXCookie riskCookie) {
this.riskCookie = riskCookie.getDecodedCookie().toString();
}
public void setBlockAction(String blockAction) {
switch (blockAction) {
case Constants.CAPTCHA_ACTION_CAPTCHA:
this.blockAction = BlockAction.CAPTCHA;
break;
case Constants.BLOCK_ACTION_CAPTCHA:
this.blockAction = BlockAction.BLOCK;
break;
case Constants.BLOCK_ACTION_CHALLENGE:
this.blockAction = BlockAction.CHALLENGE;
break;
case Constants.BLOCK_ACTION_RATE:
this.blockAction = BlockAction.RATE;
break;
default:
this.blockAction = BlockAction.CAPTCHA;
break;
}
}
/**
* Check if request is verified or not
*
* @return true if request is valid, false otherwise
* @deprecated - Use {@link PXContext#isHandledResponse}
*/
@Deprecated
public boolean isVerified() {
return verified;
}
/**
* Check if request is verified or not, this method should not be used as a condition if to pass the request to
* the application, instead use {@link PXContext#isHandledResponse} for the reason that its not
* handling a case where we already responded if this is a first party request
* <p>
* The {@link PXContext#isRequestLowScore} only indicates if the request was verified and should
* called only if more details about the request is needed (like knowing the reason why shouldn't be passed)
*
* @return true if request is valid, false otherwise
*/
public boolean isRequestLowScore() {
return verified;
}
/**
* Check if PerimeterX already handled the response thus the request should not be passed to the application
* In case true, you can check if {@link PXContext#isRequestLowScore()} or {@link PXContext#isFirstPartyRequest()}
* for more information if the response was handled by first party or score was lower than the configured threshold
*
* @return true if response was handled
*/
public boolean isHandledResponse() {
return !verified || firstPartyRequest;
}
private boolean checkSensitiveRoute(Set<String> sensitiveRoutes, String uri) {
for (String sensitiveRoutePrefix : sensitiveRoutes) {
if (uri.startsWith(sensitiveRoutePrefix)) {
return true;
}
}
return false;
}
private boolean checkSensitiveRouteRegex(Set<String> sensitiveRoutes, String uri) {
Pattern pattern;
Matcher matcher;
for (String sensitiveRouteRegex : sensitiveRoutes) {
pattern = Pattern.compile(sensitiveRouteRegex);
matcher = pattern.matcher(uri);
if (matcher.find()) {
return true;
}
}
return false;
}
public String getCollectorURL() {
return String.format("%s%s%s", Constants.API_COLLECTOR_PREFIX, appId, Constants.API_COLLECTOR_POSTFIX);
}
public void setCookieVersion(String cookieVersion) {
this.cookieVersion = cookieVersion;
}
public boolean isAdvancedBlockingResponse() {
return pxConfiguration.isAdvancedBlockingResponse();
}
public boolean isBreachedAccount() {
return this.pxde != null && this.pxdeVerified && this.pxde.has(BREACHED_ACCOUNT_KEY_NAME);
}
public boolean isContainCredentialsIntelligence() {
return this.getAdditionalContext() != null && this.getAdditionalContext().getLoginCredentials() != null;
}
}
|
package com.s24.redjob.lock;
import java.util.concurrent.TimeUnit;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.Assert;
import com.s24.redjob.AbstractDao;
/**
* Default implementation of {@link LockDao}.
*/
public class LockDaoImpl extends AbstractDao {
/**
* Redis key part for locks.
*/
public static final String LOCK = "lock";
/**
* Redis access.
*/
private RedisTemplate<String, ?> redis;
@Override
public void afterPropertiesSet() {
super.afterPropertiesSet();
redis = new RedisTemplate<>();
redis.setConnectionFactory(connectionFactory);
redis.setKeySerializer(strings);
redis.afterPropertiesSet();
}
/**
* Try to acquire a lock.
*
* @param lock
* Name of the lock.
* @param holder
* Holder for the lock.
* @param timeout
* Timeout for the lock. Should be >= 100 ms.
* @param unit
* Unit of the timeout.
* @return Lock has been acquired.
*/
public boolean tryLock(final String lock, final String holder, final int timeout, final TimeUnit unit) {
Assert.notNull(lock, "Pre-condition violated: lock != null.");
Assert.notNull(holder, "Pre-condition violated: holder != null.");
Assert.isTrue(timeout > 0, "Pre-condition violated: timeout > 0.");
Assert.notNull(unit, "Pre-condition violated: unit != null.");
return redis.execute((RedisConnection connection) -> {
byte[] key = key(LOCK, lock);
byte[] value = value(holder);
return doTryLock(connection, key, value, timeout, unit);
});
}
/**
* Try to acquire a lock.
*
* @param connection
* Connection.
* @param key
* Name of the lock.
* @param value
* Holder for the lock.
* @param timeout
* Timeout for the lock. Should be >= 100 ms.
* @param unit
* Unit of the timeout.
* @return Lock has been acquired.
*/
private boolean doTryLock(RedisConnection connection, byte[] key, byte[] value, int timeout, TimeUnit unit) {
Assert.notNull(connection, "Pre-condition violated: connection != null.");
Assert.notNull(key, "Pre-condition violated: key != null.");
Assert.notNull(value, "Pre-condition violated: value != null.");
Assert.isTrue(timeout > 0, "Pre-condition violated: timeout > 0.");
Assert.notNull(unit, "Pre-condition violated: unit != null.");
long timeoutMillis = unit.toMillis(timeout);
Assert.isTrue(timeoutMillis >= 100, "Pre-condition violated: timeoutMillis >= 100.");
// Try to extend existing lock.
if (value.equals(connection.get(key))) {
if (connection.expire(key, timeout) && value.equals(connection.get(key))) {
// Expiration has successfully been set and we are the new holder -> We got the lock.
return true;
}
}
// Try to acquire lock.
if (!connection.setNX(key, value)) {
// Key exists and is not set to our holder (see above) -> Lock is hold by someone else.
return false;
}
if (!connection.pExpire(key, timeoutMillis)) {
// Failed to set expiration -> Maybe someone else deleted our key? -> Lock cannot be acquired now.
return false;
}
// Lock has successfully been acquired if we are finally the new holder.
return value.equals(connection.get(key));
}
/**
* Release a lock.
*
* @param lock
* Name of the lock.
* @param holder
* Holder for the lock.
*/
public void releaseLock(final String lock, final String holder) {
Assert.notNull(lock, "Pre-condition violated: lock != null.");
Assert.notNull(holder, "Pre-condition violated: holder != null.");
redis.execute((RedisConnection connection) -> {
byte[] key = key(LOCK, lock);
byte[] value = value(holder);
// Try to acquire lock first to avoid race conditions.
if (connection.exists(key) && doTryLock(connection, key, value, 1, TimeUnit.SECONDS)) {
connection.del(key);
}
return null;
});
}
}
|
package de.fe1k.game9;
import de.fe1k.game9.commands.Console;
import de.fe1k.game9.components.ComponentPlayer;
import de.fe1k.game9.entities.Entity;
import de.fe1k.game9.events.Event;
import de.fe1k.game9.events.EventBeforeRender;
import de.fe1k.game9.events.EventUpdate;
import de.fe1k.game9.map.MapLoader;
import de.fe1k.game9.network.Network;
import de.fe1k.game9.systems.*;
import de.nerogar.noise.Noise;
import de.nerogar.noise.render.GLWindow;
import de.nerogar.noise.render.OrthographicCamera;
import de.nerogar.noise.render.RenderHelper;
import de.nerogar.noise.render.deferredRenderer.DeferredRenderer;
import de.nerogar.noise.util.Timer;
import java.util.ArrayList;
import java.util.List;
public class Game {
private static final float ZOOM = 1/32f;
public static GLWindow window;
public static DeferredRenderer renderer;
private OrthographicCamera camera;
private static Timer timer; // TODO properly distinguish between static and non-static stuff
private long lastFpsUpdate;
private List<GameSystem> systems;
private Console console;
public Game() {
timer = new Timer();
systems = new ArrayList<>();
Noise.init();
setUpWindow();
setUpCamera();
setUpRenderer();
setUpSystems();
console = new Console(window);
start();
}
private void start() {
MapLoader.loadMap(renderer, "res/map/map_dungeon0");
}
private void setUpSystems() {
systems.add(new SystemPhysics());
systems.add(new SystemCallbacks());
systems.add(new SystemDeathAnimation(renderer));
systems.add(new SystemKillOnCollision());
systems.add(new SystemParticles(renderer));
systems.forEach(GameSystem::start);
}
private void setUpRenderer() {
renderer = new DeferredRenderer(window.getWidth(), window.getHeight());
renderer.setSunLightBrightness(0);
renderer.setAmbientOcclusionEnabled(false);
renderer.setMinAmbientBrightness(0.1f);
}
private void setUpWindow() {
window = new GLWindow("Game-9", 1280, 720, true, 0, null, null);
window.setSizeChangeListener((int width, int height) -> {
renderer.setFrameBufferResolution(width, height);
camera.setAspect((float) width / height);
camera.setHeight((float) height * ZOOM);
console.updateProjectionMatrix(width, height);
});
}
private void setUpCamera() {
camera = new OrthographicCamera((float) window.getHeight() * ZOOM, (float) window.getWidth() / window.getHeight(), 100, -100);
camera.setXYZ(10, 10, 10);
}
private void displayFPS() {
if (System.nanoTime() - lastFpsUpdate > 1_000_000_000 / 5) {
lastFpsUpdate = System.nanoTime();
float fps = Math.round(timer.getFrequency() * 10f) / 10f;
float time = Math.round(timer.getCalcTime() * 1000000f) / 1000f;
window.setTitle("FPS: " + fps + " -> frame time: " + time);
}
}
private void mainloop() {
GLWindow.updateAll();
float targetDelta = 1 / 60f;
timer.update(targetDelta);
displayFPS();
boolean shouldUpdate = Network.isStarted() && (!Network.isServer() || Network.getClients().size() > 0);
shouldUpdate = true;
Event.trigger(new EventUpdate(shouldUpdate ? targetDelta : 0));
Event.trigger(new EventBeforeRender(targetDelta, timer.getRuntime()));
ComponentPlayer player = Entity.getFirstComponent(ComponentPlayer.class);
if (player != null) {
camera.setX(player.getOwner().getPosition().getX());
camera.setY(player.getOwner().getPosition().getY());
}
renderer.render(camera);
console.render();
window.bind();
RenderHelper.blitTexture(renderer.getColorOutput());
}
public void run() {
while (!window.shouldClose()) {
mainloop();
}
shutdown();
}
private void shutdown() {
if (Network.isStarted()) Network.shutdown();
//Entity.despawnAll(); // too slow
systems.forEach(GameSystem::stop);
}
public static double getRunTime() {
return timer.getRuntime();
}
}
|
package com.socrata.datasync.job;
import com.google.common.collect.ImmutableMap;
import com.socrata.api.SodaImporter;
import com.socrata.datasync.PublishMethod;
import com.socrata.datasync.SMTPMailer;
import com.socrata.datasync.SocrataConnectionInfo;
import com.socrata.datasync.Utils;
import com.socrata.datasync.VersionProvider;
import com.socrata.datasync.config.CommandLineOptions;
import com.socrata.datasync.config.controlfile.ControlFile;
import com.socrata.datasync.config.userpreferences.UserPreferences;
import com.socrata.datasync.config.userpreferences.UserPreferencesJava;
import com.socrata.datasync.validation.GISJobValidity;
import com.socrata.exceptions.SodaError;
import com.socrata.model.importer.GeoDataset;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.*;
import java.net.URLEncoder;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
@JsonIgnoreProperties(ignoreUnknown=true)
@JsonSerialize(include= JsonSerialize.Inclusion.NON_NULL)
public class GISJob extends Job {
private final Logger logging = Logger.getLogger(GISJob.class.getName());
static AtomicInteger jobCounter = new AtomicInteger(0);
int jobNum = jobCounter.getAndIncrement();
private String defaultJobName = "Unsaved GIS Job" + " (" + jobNum + ")";
// Anytime a @JsonProperty is added/removed/updated in this class add 1 to this value
private static final long fileVersionUID = 4L;
private UserPreferences userPrefs;
private String datasetID = "";
private String fileToPublish = "";
private PublishMethod publishMethod = PublishMethod.replace;
private boolean fileToPublishHasHeaderRow = true;
private ControlFile controlFile = null;
private String ticket = "";
private String userAgent = "datasync";
private String userAgentNameClient = "Client";
private String userAgentNameCli = "CLI";
private String userAgentNameSijFile = ".gij File";
private ObjectMapper controlFileMapper =
new ObjectMapper().enable(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
public GISJob() {
userPrefs = new UserPreferencesJava();
}
/*
* This is a method that enables DataSync preferences to be established
* directly when DataSync is used in "library mode" or "command-line mode"
* (rather than being loaded from Preferences class)
*/
public GISJob(UserPreferences userPrefs) {
this.userPrefs = userPrefs;
}
/**
* Loads GIS job data from a file and
* uses the saved data to populate the fields
* of this object
*/
public GISJob(String pathToFile) throws IOException, ControlDisagreementException {
this(pathToFile, false);
setUserAgentSijFile();
}
/**
* Loads GIS job data from a file and
* uses the saved data to populate the fields
* of this object
*/
public GISJob(String pathToFile, boolean ignoreControlInconsistencies) throws IOException, ControlDisagreementException {
userPrefs = new UserPreferencesJava();
// first try reading the 'current' format
ObjectMapper mapper = new ObjectMapper();
GISJob loadedJob;
try {
loadedJob = mapper.readValue(new File(pathToFile), GISJob.class);
} catch (IOException e) {
// if reading new format fails...try reading old format into this object
loadOldSijFile(pathToFile);
return;
}
setDatasetID(loadedJob.getDatasetID());
setFileToPublish(loadedJob.getFileToPublish());
setPublishMethod(loadedJob.getPublishMethod());
setPathToSavedFile(pathToFile);
}
@JsonProperty("fileVersionUID")
public long getFileVersionUID() { return fileVersionUID; }
public ControlFile getControlFile() { return controlFile; }
public void setControlFile(ControlFile cf) { controlFile = cf; }
@JsonProperty("datasetID")
public void setDatasetID(String newDatasetID) { datasetID = newDatasetID; }
@JsonProperty("datasetID")
public String getDatasetID() {
return datasetID;
}
@JsonProperty("fileToPublish")
public void setFileToPublish(String newFileToPublish) { fileToPublish = newFileToPublish; }
@JsonProperty("fileToPublish")
public String getFileToPublish() {
return fileToPublish;
}
@JsonProperty("publishMethod")
public void setPublishMethod(PublishMethod newPublishMethod) {
publishMethod = newPublishMethod.replace;
}
@JsonProperty("publishMethod")
public PublishMethod getPublishMethod() {
return publishMethod;
}
public String getDefaultJobName() { return defaultJobName; }
public void setUserAgent(String usrAgentName) {
userAgent = Utils.getUserAgentString(usrAgentName);
}
public void setUserAgentClient() {
userAgent = Utils.getUserAgentString(userAgentNameClient);
}
public void setUserAgentSijFile() {
userAgent = Utils.getUserAgentString(userAgentNameSijFile);
}
/**
* Checks that the command line arguments are sensible
* NB: it is expected that this is run before 'configure'.
* @param cmd the commandLine object constructed from the user's options
* @return true if the commandLine is approved, false otherwise
*/
public boolean validateArgs(CommandLine cmd) {
return GISJobValidity.validateArgs(cmd);
}
/**
* Configures an integration job prior to running it; in particular, the fields we need are
* set from the cmd line and the controlFile contents are deserialized
* NB: This should be run after 'validateArgs' and before 'run'
* @param cmd the commandLine object constructed from the user's options
*/
public void configure(CommandLine cmd) {
CommandLineOptions options = new CommandLineOptions();
String method = cmd.getOptionValue(options.PUBLISH_METHOD_FLAG);
setDatasetID(cmd.getOptionValue(options.DATASET_ID_FLAG));
setFileToPublish(cmd.getOptionValue(options.FILE_TO_PUBLISH_FLAG));
if(method != null)
setPublishMethod(PublishMethod.valueOf(method));
String userAgentName = cmd.getOptionValue(options.USER_AGENT_FLAG);
if(Utils.nullOrEmpty(userAgentName)) {
userAgentName = userAgentNameCli;
}
setUserAgent(userAgentName);
}
/**
* Runs an GIS job. It is expected that 'configure' was run beforehand.
* @return
* @throws IOException
*/
public JobStatus run() {
SocrataConnectionInfo connectionInfo = userPrefs.getConnectionInfo();
GeoDataset result = null;
String publishExceptions = "";
JobStatus runStatus = JobStatus.SUCCESS;
JobStatus validationStatus = GISJobValidity.validateJobParams(connectionInfo, this);
if (validationStatus.isError()) {
runStatus = validationStatus;
} else {
try {
File fileToPublishFile = new File(fileToPublish);
System.out.println("Uploading " + fileToPublish);
// attach a requestId to all Producer API calls (for error tracking purposes)
String jobRequestId = Utils.generateRequestId();
final SodaImporter importer = SodaImporter.newImporter(connectionInfo.getUrl(), connectionInfo.getUser(), connectionInfo.getPassword(), connectionInfo.getToken());
switch (publishMethod) {
case replace:
boolean status = replaceGeo(fileToPublishFile, connectionInfo);
logging.log(Level.INFO,String.valueOf(status));
if(status){
runStatus = JobStatus.SUCCESS;
}
else {
runStatus = JobStatus.PUBLISH_ERROR;
}
break;
default:
runStatus = JobStatus.INVALID_PUBLISH_METHOD;
}
} catch (Exception e) {
publishExceptions = e.getMessage();
e.printStackTrace();
}
}
if (publishExceptions.length() > 0) {
runStatus = JobStatus.PUBLISH_ERROR;
runStatus.setMessage(publishExceptions);
}
emailAdmin(runStatus);
return runStatus;
}
private void sendErrorNotificationEmail(final String adminEmail, final SocrataConnectionInfo connectionInfo, final JobStatus runStatus, final String runErrorMessage, final String logDatasetID) {
String errorEmailMessage = "";
String urlToLogDataset = connectionInfo.getUrl() + "/d/" + logDatasetID;
if(runStatus.isError()) {
errorEmailMessage += "There was an error updating a dataset.\n"
+ "\nDataset: " + connectionInfo.getUrl() + "/d/" + getDatasetID()
+ "\nFile to publish: " + fileToPublish
+ "\nFile to publish has header row: " + fileToPublishHasHeaderRow
+ "\nPublish method: " + publishMethod
+ "\nJob File: " + pathToSavedJobFile
+ "\nError message: " + runErrorMessage
+ "\nLog dataset: " + urlToLogDataset + "\n\n";
}
if(runStatus.isError()) {
try {
SMTPMailer.send(adminEmail, "Socrata DataSync Error", errorEmailMessage);
} catch (Exception e) {
System.out.println("Error sending email to: " + adminEmail + "\n" + e.getMessage());
}
}
}
private String logRunResults(JobStatus runStatus, GeoDataset result) {
String logDatasetID = userPrefs.getLogDatasetID();
String logPublishingErrorMessage = null;
SocrataConnectionInfo connectionInfo = userPrefs.getConnectionInfo();
return logPublishingErrorMessage;
}
private void emailAdmin(JobStatus status) {
String adminEmail = userPrefs.getAdminEmail();
String logDatasetID = userPrefs.getLogDatasetID();
SocrataConnectionInfo connectionInfo = userPrefs.getConnectionInfo();
if(userPrefs.emailUponError() && adminEmail != null && !adminEmail.equals("")) {
sendErrorNotificationEmail(
adminEmail, connectionInfo, status, status.getMessage(), logDatasetID);
}
}
public class ControlDisagreementException extends Exception {
public ControlDisagreementException(String msg) {
super(msg);
}
}
/**
* This allows backward compatability with DataSync 0.1 .sij file format
*
* @param pathToFile .sij file that uses old serialization format (Java native)
* @throws IOException
*/
private void loadOldSijFile(String pathToFile) throws IOException {
try {
InputStream file = new FileInputStream(pathToFile);
InputStream buffer = new BufferedInputStream(file);
ObjectInput input = new ObjectInputStream (buffer);
try{
com.socrata.datasync.IntegrationJob loadedJobOld = (com.socrata.datasync.IntegrationJob) input.readObject();
setDatasetID(loadedJobOld.getDatasetID());
setFileToPublish(loadedJobOld.getFileToPublish());
setPublishMethod(loadedJobOld.getPublishMethod());
setPathToSavedFile(pathToFile);
}
finally{
input.close();
}
} catch(Exception e) {
// TODO add log entry?
throw new IOException(e.toString());
}
}
private boolean replaceGeo(File file, SocrataConnectionInfo connectionInfo) {
String scan_url = makeUri(connectionInfo.getUrl(), "scan");
String blueprint = "";
boolean status = true;
try {
blueprint = postRawFile(scan_url, file, connectionInfo);
status = replaceGeoFile(blueprint, file, connectionInfo);
} catch (IOException e) {
e.printStackTrace();
return false;
}
return status;
}
private boolean replaceGeoFile(String blueprint, File file, SocrataConnectionInfo connectionInfo) {
boolean status = true;
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(blueprint);
JSONObject array = (JSONObject)obj;
String fileId = array.get("fileId").toString();
String name = file.getName();
String bluepr = array.get("summary").toString();
String query = "";
String url = makeUri(connectionInfo.getUrl(),"replace");
query = query + "&fileId="+URLEncoder.encode(fileId,"UTF-8");
query = query + "&name="+URLEncoder.encode(name,"UTF-8");
query = query + "&blueprint=" + URLEncoder.encode(bluepr,"UTF-8");
query = query + "&viewUid=" + URLEncoder.encode(datasetID,"UTF-8");
url = url + query;
//logging.log(Level.INFO,url);
status = postReplaceGeoFile(url, connectionInfo);
} catch(ParseException | UnsupportedEncodingException e) {
e.printStackTrace();
return false;
}
return status;
}
private boolean postReplaceGeoFile(String url, SocrataConnectionInfo connectionInfo) {
boolean status = true;
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
logging.log(Level.INFO, url);
HttpPost httpPost = new HttpPost(url);
String to_encode = connectionInfo.getUser() + ":" + connectionInfo.getPassword();
byte[] bytes = Base64.encodeBase64(to_encode.getBytes());
String auth = new String(bytes);
httpPost.setHeader("Authorization","Basic "+auth);
httpPost.setHeader("X-App-Token", connectionInfo.getToken());
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
String result = EntityUtils.toString(resEntity);
JSONParser parser = new JSONParser();
JSONObject resJson = (JSONObject) parser.parse(result);
logging.log(Level.INFO, result);
boolean error = (boolean) resJson.get("error");
if(error) {
return false;
}
ticket = resJson.get("ticket").toString();
try {
logging.log(Level.INFO,"Polling for Status...");
status = pollForStatus(ticket, connectionInfo,false);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException | ParseException e) {
e.printStackTrace();
return false;
}
return status;
}
private boolean pollForStatus(String ticket, SocrataConnectionInfo connectionInfo, boolean complete) throws InterruptedException {
String status_url = makeUri(connectionInfo.getUrl(),"status") + ticket;
String[] status = new String[2];
if(!complete)
{
status = getStatus(status_url,connectionInfo);
logging.log(Level.INFO,status[1]);
Thread.sleep(1000);
if (status[0] == "Complete") {
return true;
}
if (status[0] == "Error"){
return false;
}
pollForStatus(ticket,connectionInfo,false);
}
return true;
}
private String[] getStatus(String url, SocrataConnectionInfo connectionInfo) {
String[] status = new String[2];
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
String to_encode = connectionInfo.getUser() + ":" + connectionInfo.getPassword();
byte[] bytes = Base64.encodeBase64(to_encode.getBytes());
String auth = new String(bytes);
httpGet.setHeader("Authorization","Basic "+auth);
httpGet.setHeader("X-App-Token", connectionInfo.getToken());
HttpResponse response = httpClient.execute(httpGet);
HttpEntity resEntity = response.getEntity();
String result = EntityUtils.toString(resEntity);
JSONParser parser = new JSONParser();
JSONObject resJson = (JSONObject) parser.parse(result);
try {
boolean error = (boolean) resJson.get("error");
JSONObject details = (JSONObject) resJson.get("details");
if(error){
status[0] = "Error";
status[1] = resJson.get("message").toString()+" with code: "+resJson.get("code").toString();
return status;
}
else {
try {
status[0] = "Progress";
status[1] = details.get("status").toString() + ": " + details.get("progress").toString() + " features completed";
} catch (NullPointerException e) {
status[0] = "Progress";
status[1] = details.get("stage").toString();
return status;
}
}
} catch (NullPointerException e) {
// For once the ticket is complete
status[0] = "Complete";
status[1] = "Complete";
return status;
}
return status;
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
status[0] = "Complete";
status[1] = "Complete";
return status;
}
return status;
}
private String postRawFile(String uri, File file, SocrataConnectionInfo connectionInfo) throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(uri);
String to_encode = connectionInfo.getUser() + ":" + connectionInfo.getPassword();
byte[] bytes = Base64.encodeBase64(to_encode.getBytes());
String auth = new String(bytes);
httpPost.setHeader("Authorization","Basic "+auth);
httpPost.setHeader("X-App-Token", connectionInfo.getToken());
logging.log(Level.INFO, "Posting file...");
HttpEntity httpEntity = MultipartEntityBuilder.create()
.addBinaryBody(file.getName(), file, ContentType.APPLICATION_OCTET_STREAM,file.getName())
.build();
httpPost.setEntity(httpEntity);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
String result = EntityUtils.toString(resEntity);
logging.log(Level.INFO,result);
return result;
}
private String makeUri(String domain,String method) {
switch(method) {
case "scan":
return domain + "/api/imports2?method=scanShape";
case "replace":
return domain + "/api/imports2?method=replaceShapefile";
case "status":
return domain + "/api/imports2?ticket=";
default:
return "Method Required";
}
}
}
|
package com.sybit.airtable;
import com.google.gson.internal.LinkedTreeMap;
import com.sybit.airtable.vo.Thumbnail;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.converters.AbstractConverter;
/**
*
* org.apache.commons.beanutils.Converter implementaion
* that handles conversion to and from Map<String,T> objects.
*
* <p>This implementation converts Map<String,T> to Map<String,mapClass>.
* The mapClass can be set to the Class that is needed.</p>
*
* @author fzr
*/
public class MapConverter extends AbstractConverter{
private Class mapClass;
/**
* Converts the Input Object into a Map.
*
*
* @param type The type of the Input Object
* @param value The value of the Input Object
* @return A Map
* @throws Throwable
*/
@Override
protected <T> T convertToType(Class<T> type, Object value) throws Throwable {
Class<T> sourceType = (Class<T>) value.getClass();
Map<String, Object> returnMap = new HashMap<>();
if(value instanceof LinkedTreeMap){
for (String key : ((LinkedTreeMap<String, Object>) value).keySet()) {
Object instanz = this.mapClass.newInstance();
Object val = ((LinkedTreeMap) value).get(key);
BeanUtils.setProperty(instanz,"name",key);
for (String key2 : ((LinkedTreeMap<String, Object>) val).keySet()) {
Object val2 = ((LinkedTreeMap) val).get(key2);
BeanUtils.setProperty(instanz,key2,val2);
}
returnMap = toClassMap(sourceType,instanz,returnMap);
}
return (T) returnMap;
}
if(value instanceof String){
return (T) toStringMap(sourceType,value.toString(),returnMap);
}
final String stringValue = value.toString().trim();
if (stringValue.length() == 0) {
return handleMissing(type);
}
return (T) toStringMap(sourceType,stringValue,returnMap);
}
/**
*
* Default Conversion to specified Class.
*
* @param type The Class of the type
* @param value The value of the Object
* @param returnMap A Map of all currently converted Objects
* @return A Map
*/
private Map<String,Object> toClassMap(final Class type, final Object value,Map<String, Object> returnMap) {
if (type.equals(LinkedTreeMap.class)) {
if (value.getClass().equals(Thumbnail.class)) {
returnMap.put(((Thumbnail)value).getName(),value);
}
return returnMap;
}
return toStringMap(type,value.toString(),returnMap);
}
/**
*
* Default toString Conversion.
*
* @param type The Class of the type
* @param value The String value
* @param returnMap A Map of all currently converted Objects
* @return A Map
*/
private Map<String,Object> toStringMap(final Class type, final String value,Map<String, Object> returnMap) {
if (type.equals(String.class)) {
returnMap.put(value,value);
return returnMap;
}
returnMap.put(value,value);
return returnMap;
}
@Override
protected Class<?> getDefaultType() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Set-Method for the MapClass
*
* @param aClass The Parameter that is used
*/
public void setMapClass(Class<Thumbnail> aClass) {
this.mapClass = aClass;
}
}
|
package com.tinkerrocks.storage;
import com.google.common.base.Preconditions;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.tinkerrocks.structure.RocksGraph;
import com.tinkerrocks.structure.Utils;
import org.apache.tinkerpop.gremlin.structure.Element;
import org.rocksdb.ColumnFamilyDescriptor;
import org.rocksdb.ColumnFamilyHandle;
import org.rocksdb.RocksDB;
import org.rocksdb.RocksDBException;
import org.rocksdb.RocksIterator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
public class IndexDB extends StorageAbstractClass implements IndexStorage {
public <T extends Element> void removeIndex(Class<T> indexClass, String key, Object value, byte[] id) {
try {
this.rocksDB.remove((getIndexClass(indexClass) + Byte.toString(StorageConstants.PROPERTY_SEPARATOR) +
key + Byte.toString(StorageConstants.PROPERTY_SEPARATOR) + value + Byte.toString(StorageConstants.PROPERTY_SEPARATOR)
+ new String(id)).getBytes());
} catch (RocksDBException e) {
e.printStackTrace();
}
}
public void createIndex(Class indexClass, String key) {
cache.invalidate(indexClass);
try {
put(getColumn(INDEX_COLUMNS.INDEX_KEYS), (getIndexClass(indexClass) +
Byte.toString(StorageConstants.PROPERTY_SEPARATOR) + key).getBytes(), "".getBytes());
} catch (RocksDBException e) {
e.printStackTrace();
}
}
public enum INDEX_COLUMNS {
INDEX_KEYS("INDEX_KEYS");
String value;
INDEX_COLUMNS(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
Cache<Class, Set<String>> cache;
public IndexDB(RocksGraph rocksGraph) throws RocksDBException {
super(rocksGraph);
RocksDB.loadLibrary();
columnFamilyDescriptors = new ArrayList<>(INDEX_COLUMNS.values().length);
columnFamilyHandleList = new ArrayList<>(INDEX_COLUMNS.values().length);
columnFamilyDescriptors.add(new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY, StorageConfigFactory.getColumnFamilyOptions()));
for (INDEX_COLUMNS vertex_columns : INDEX_COLUMNS.values()) {
columnFamilyDescriptors.add(new ColumnFamilyDescriptor(vertex_columns.getValue().getBytes(),
StorageConfigFactory.getColumnFamilyOptions()));
}
rocksDB = RocksDB.open(StorageConfigFactory.getDBOptions(), getDbPath() + "/indexes", columnFamilyDescriptors, columnFamilyHandleList);
this.rocksDB.enableFileDeletions(true);
cache = CacheBuilder.newBuilder()
.maximumSize(1000)
.concurrencyLevel(1000)
.build();
}
public ColumnFamilyHandle getColumn(INDEX_COLUMNS edge_column) {
return columnFamilyHandleList.get(edge_column.ordinal() + 1);
}
private String getIndexClass(Class _class) {
return _class.getSimpleName();
}
@SuppressWarnings("unchecked")
public <T extends Element> void putIndex(Class<T> indexClass, String key, Object value, byte[] id) throws Exception {
Preconditions.checkNotNull(indexClass);
Preconditions.checkNotNull(id);
Preconditions.checkNotNull(key);
String className = getIndexClass(indexClass);
byte[] key1 = (className +
Byte.toString(StorageConstants.PROPERTY_SEPARATOR) + key + StorageConstants.PROPERTY_SEPARATOR + value).getBytes();
HashSet<byte[]> hashSet = (HashSet<byte[]>) deserialize(get(key1), HashSet.class);
if (hashSet == null) {
hashSet = new HashSet<>();
}
hashSet.add(id);
put(key1, serialize(hashSet));
}
@SuppressWarnings("unchecked")
public <T extends Element> List<byte[]> getIndex(Class<T> indexClass, String key, Object value) {
List<byte[]> results = new ArrayList<>();
try {
byte[] key1 = (getIndexClass(indexClass) +
Byte.toString(StorageConstants.PROPERTY_SEPARATOR) + key + StorageConstants.PROPERTY_SEPARATOR + value).getBytes();
HashSet<byte[]> hashSet = (HashSet<byte[]>) deserialize(get(key1), HashSet.class);
if (hashSet == null) {
hashSet = new HashSet<>();
}
return hashSet.stream().collect(Collectors.toList());
} catch (RocksDBException ex) {
ex.printStackTrace();
}
return results;
}
public <T extends Element> void dropIndex(Class<T> indexClass, String key) throws RocksDBException {
byte[] seek_key = (getIndexClass(indexClass) + Byte.toString(StorageConstants.PROPERTY_SEPARATOR) + key).getBytes();
this.rocksDB.remove(getColumn(INDEX_COLUMNS.INDEX_KEYS), seek_key);
}
public <T extends Element> Set<String> getIndexedKeys(Class<T> indexClass) {
try {
return cache.get(indexClass, () -> {
Set<String> indexes = new HashSet<>();
RocksIterator iterator = rocksDB.newIterator(getColumn(INDEX_COLUMNS.INDEX_KEYS));
byte[] seek_key = (getIndexClass(indexClass) + Byte.toString(StorageConstants.PROPERTY_SEPARATOR)).getBytes();
try {
Utils.RocksIterUtil(iterator, seek_key, (key, value) -> {
indexes.add(new String(Utils.slice(key, seek_key.length)));
return true;
});
} catch (Exception ex) {
ex.printStackTrace();
}
return indexes;
});
} catch (ExecutionException e) {
e.printStackTrace();
}
return Collections.emptySet();
}
}
|
package com.unitvectory.shak.jarvis;
import java.io.File;
import java.util.Scanner;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.daemon.Daemon;
import org.apache.commons.daemon.DaemonContext;
import org.apache.commons.daemon.DaemonInitException;
import org.apache.log4j.Logger;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;
/**
* The main application.
*
* @author Jared Hatfield
*
*/
public class App implements Daemon {
/**
* the log
*/
private static Logger log = Logger.getLogger(App.class);
/**
* the main thread
*/
private static MainThread mainThread;
/**
* the app config
*/
private static AppConfig config;
/**
* The main application.
*
* @param args
* the args
*/
public static void main(String[] args) {
// create the parser
org.apache.commons.cli.CommandLineParser parser = new BasicParser();
try {
// The required options
Options options = new Options();
@SuppressWarnings("static-access")
Option configOption =
OptionBuilder.withArgName("config").hasArg()
.withDescription("path to config file")
.isRequired().create("config");
options.addOption(configOption);
// Parse the command line arguments
CommandLine line = parser.parse(options, args);
String configPath = line.getOptionValue("config");
// Load the config
Serializer serializer = new Persister();
try {
config = serializer.read(AppConfig.class, new File(configPath));
} catch (Exception e) {
log.error("Unable to load config file.", e);
return;
}
// Start the app
App app = new App();
try {
app.start();
} catch (Exception e) {
log.error("Failed to start app.", e);
}
// Wait for input to exit
@SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
while (!sc.nextLine().equals("")) {
}
// Exit the app
try {
app.stop();
} catch (Exception e) {
log.error("Failed to stop app.", e);
}
} catch (ParseException exp) {
System.err.println("Parsing failed. Reason: " + exp.getMessage());
}
}
public void destroy() {
}
public void init(DaemonContext arg0)
throws DaemonInitException, Exception {
Serializer serializer = new Persister();
String configPath = "/etc/shak-jarvis/config.xml";
config = serializer.read(AppConfig.class, new File(configPath));
}
public void start()
throws Exception {
mainThread = new MainThread(config);
mainThread.start();
}
public void stop()
throws Exception {
mainThread.done();
}
}
|
package com.zenplanner.sql;
import com.google.common.base.Charsets;
import com.google.common.io.Resources;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.*;
public class DbComparator {
private static final String filterCol = "partitionId";
private static final int maxKeys = 1999; // jtds driver limit
public enum ChangeType {
INSERT, UPDATE, DELETE, NONE
}
public DbComparator() {
}
public static void Syncronize(Connection scon, Connection dcon, String filterValue) {
try {
Map<String, Table> srcTables = filterTables(getTables(scon));
Map<String, Table> dstTables = getTables(dcon);
try {
setConstraints(dcon, dstTables.values(), false);
for (Table srcTable : srcTables.values()) {
if (!dstTables.containsKey(srcTable.getName())) {
continue;
}
Table dstTable = dstTables.get(srcTable.getName());
System.out.println("Comparing table: " + srcTable.getName());
syncTables(scon, dcon, srcTable, dstTable, filterValue);
}
} catch (Exception ex) {
throw ex;
} finally {
setConstraints(dcon, dstTables.values(), true);
}
} catch (Exception ex) {
throw new RuntimeException("Error comparing databases!", ex);
}
}
private static void setConstraints(Connection con, Collection<Table> tables, boolean enabled) {
for (Table table : tables) {
table.setConstraints(con, false);
}
}
/**
* Retrieves a map of Tables from the database schema
*
* @param con The connection to use to query the DB for its schema
* @return A map of Tables from the database schema
* @throws Exception
*/
private static Map<String, Table> getTables(Connection con) throws Exception {
Map<String, Table> tables = new HashMap<>();
try (Statement stmt = con.createStatement()) {
String sql = Resources.toString(Resources.getResource("GetTables.sql"), Charsets.UTF_8);
try (ResultSet rs = stmt.executeQuery(sql)) {
while (rs.next()) {
String tableName = rs.getString("table_name");
if (!tables.containsKey(tableName)) {
tables.put(tableName, new Table(tableName));
}
Table table = tables.get(tableName);
Column col = new Column();
String colName = rs.getString("column_name");
col.setColumnName(colName);
col.setDataType(rs.getString("data_type"));
col.setPrimaryKey(rs.getBoolean("primary_key"));
table.put(colName, col);
}
}
}
return tables;
}
/**
* Compares two tables and syncronizes the results
*
* @param scon The source connection
* @param dcon The destination connection
* @param srcTable The source table
* @param dstTable The destination table
* @param filterValue A partitionId
* @throws Exception
*/
private static void syncTables(Connection scon, Connection dcon, Table srcTable, Table dstTable,
String filterValue) throws Exception {
Table lcd = findLcd(srcTable, dstTable);
String sql = lcd.writeHashedQuery(filterCol);
//int i = 0; // TODO: Threading and progress indicator
try (PreparedStatement stmt = scon.prepareStatement(sql); PreparedStatement dtmt = dcon.prepareStatement(sql)) {
if (lcd.hasColumn(filterCol)) {
stmt.setObject(1, filterValue);
dtmt.setObject(1, filterValue);
}
try (ResultSet srs = stmt.executeQuery(); ResultSet drs = dtmt.executeQuery()) {
srs.next();
drs.next();
Map<ChangeType, Set<Key>> changes = new HashMap<>();
changes.put(ChangeType.INSERT, new HashSet<>());
changes.put(ChangeType.UPDATE, new HashSet<>());
changes.put(ChangeType.DELETE, new HashSet<>());
while (srs.getRow() > 0 || drs.getRow() > 0) {
ChangeType change = detectChange(lcd, srs, drs);
Key key = getPk(lcd, srs, drs);
Set<Key> changeset = changes.get(change);
if (changeset == null) {
continue;
}
changeset.add(key);
advance(srcTable, dstTable, srs, drs);
}
insertRows(scon, dcon, lcd, changes.get(ChangeType.INSERT));
} catch (Exception ex) {
throw new RuntimeException("Error selecting hashed rows!", ex);
}
}
}
private static void insertRows(Connection scon, Connection dcon, Table table, Set<Key> keys) throws Exception {
if (keys.size() <= 0) {
return;
}
table.setIdentityInsert(dcon, true);
List<Column> pk = table.getPk();
int rowLimit = (int) Math.floor(maxKeys / pk.size());
for (int rowIndex = 0; rowIndex < keys.size(); ) {
int count = Math.min(keys.size() - rowIndex, rowLimit);
System.out.println("Inserting " + count + " rows into " + table.getName());
try (PreparedStatement selectStmt = createSelectQuery(scon, table, keys, count)) {
try (ResultSet rs = selectStmt.executeQuery()) {
String sql = table.writeInsertQuery();
try (PreparedStatement insertStmt = dcon.prepareStatement(sql)) {
while (rs.next()) {
insertRow(insertStmt, table, rs);
}
try {
insertStmt.executeBatch();
} catch (Exception ex) {
throw new RuntimeException("Error inserting rows!", ex);
}
}
}
}
rowIndex += count;
}
}
/**
* Adds the values from a given row to the PreparedStatement
*
* @param stmt The PreparedStatement to help prepare
* @param table The table definition
* @param rs The ResultSet to pull values from
* @throws Exception
*/
private static void insertRow(PreparedStatement stmt, Table table, ResultSet rs) throws Exception {
stmt.clearParameters();
int i = 0;
for (Column col : table.values()) {
String colName = col.getColumnName();
Object val = rs.getObject(colName);
stmt.setObject(++i, val);
}
stmt.addBatch();
}
/**
* Takes two RecordSets, and advances one cursor, or the other, or both to keep the PKs in sync
*
* @param srcTable The source table
* @param dstTable The destination table
* @param srs The source RecordSet
* @param drs The destination RecordSet
* @throws Exception
*/
private static void advance(Table srcTable, Table dstTable, ResultSet srs, ResultSet drs) throws Exception {
Key spk = srcTable.getPk(srs);
Key dpk = dstTable.getPk(drs);
int val = Key.compare(spk, dpk);
if (val < 0) {
srs.next();
return;
}
if (val > 0) {
drs.next();
return;
}
srs.next();
drs.next();
}
/**
* Gets the primary key from whichever row exists
*
* @param table The table definition
* @param srs The source RecordSet
* @param drs The destination RecordSet
* @return The primary key of the row
* @throws Exception
*/
private static Key getPk(Table table, ResultSet srs, ResultSet drs) throws Exception {
ChangeType change = detectChange(table, srs, drs);
if (change == ChangeType.DELETE) {
return table.getPk(drs);
}
return table.getPk(srs);
}
/**
* Creates a virtual table that contains the intersection of the columns of two other real tables
*
* @param srcTable The source table
* @param dstTable The destination table
* @return a virtual table that contains the intersection of the columns of two other real tables
*/
private static Table findLcd(Table srcTable, Table dstTable) {
Table table = new Table(srcTable.getName());
Set<String> colNames = new HashSet<>();
colNames.addAll(srcTable.keySet());
colNames.addAll(dstTable.keySet());
for (String colName : colNames) {
if (!srcTable.containsKey(colName) || !dstTable.containsKey(colName)) {
continue;
}
table.put(colName, srcTable.get(colName));
}
return table;
}
/**
* Creates a PreparedStatement that returns all of the rows for the given set of keys.
* Don't forget to close the statement!
*
* @param con The connection to use to query the DB for its schema
* @param table The table definition
* @param keys The keys of the rows for which to query
* @return A PreparedStatement that returns all the rows for the given set of keys.
* @throws Exception
*/
// TODO: Break this monster out into separate methods for SQL and values
private static PreparedStatement createSelectQuery(Connection con, Table table, Set<Key> keys, int count) {
List<Object> parms = new ArrayList<>();
List<Column> pk = table.getPk();
StringBuilder sb = new StringBuilder();
int rowIndex = 0;
for (Key key : new HashSet<>(keys)) {
keys.remove(key); // Remove as we go
if (sb.length() > 0) {
sb.append("\tor ");
}
sb.append("(");
for (int pkIdx = 0; pkIdx < pk.size(); pkIdx++) {
if (pkIdx > 0) {
sb.append(" and ");
}
Column col = pk.get(pkIdx);
sb.append("[");
sb.append(col.getColumnName());
sb.append("]=?");
// Grab the value of the parameter
Object val = key.get(pkIdx);
parms.add(val);
}
sb.append(")\n");
if (rowIndex++ >= count) {
break;
}
}
String sql = String.format("select\n\t*\nfrom [%s]\nwhere %s", table.getName(), sb.toString());
try {
PreparedStatement stmt = con.prepareStatement(sql);
for (int i = 0; i < parms.size(); i++) {
stmt.setObject(i + 1, parms.get(i));
}
return stmt;
} catch (Exception ex) {
throw new RuntimeException("Error creating select query!", ex);
}
}
/**
* Filters a map of database tables and returns only the ones that are sync-able
*
* @param in The map to filter
* @return The filtered map
*/
private static Map<String, Table> filterTables(Map<String, Table> in) {
Map<String, Table> out = new HashMap<>();
for (Map.Entry<String, Table> entry : in.entrySet()) {
boolean hasPk = false;
String name = entry.getKey();
Table table = entry.getValue();
for (Column col : table.values()) {
if (col.isPrimaryKey()) {
hasPk = true;
}
}
if (hasPk) {
out.put(name, table);
}
}
return out;
}
/**
* Basically this is the join logic. It compares the two rows presently under the cursors, and returns an action
* that needs to be taken based on whether the row is in left but not right, right but not left, or in both but
* changes are present. As usual for join code, this method assumes that the ResultSets are ordered, and the
* Key.compare() method exhibits the same ordering as the database engine.
*
* @param table The table definition
* @param srs The source RecordSet
* @param drs The destination RecordSet
* @return A ChangeType indicating what action should be taken to sync the two databases
* @throws Exception
*/
public static ChangeType detectChange(Table table, ResultSet srs, ResultSet drs) throws Exception {
// Verify we're on the same row
Key srcPk = table.getPk(srs);
Key dstPk = table.getPk(drs);
int eq = Key.compare(srcPk, dstPk);
/*
Left Right
ACD BDE
A B Left < right, insert A into right
C B Left > right, delete B from right
D D Left = right, update D in right
null E Left > right, delete E from right
*/
if (eq < 0) {
// Left < right, insert
return ChangeType.INSERT;
}
if (eq > 0) {
// Left > right, delete
return ChangeType.DELETE;
}
// Keys match, check hashes
byte[] shash = getHash(srs);
byte[] dhash = getHash(drs);
if (shash == null && dhash == null) {
throw new RuntimeException("Both rows are null!");
}
if (shash == null) {
return ChangeType.DELETE;
}
if (dhash == null) {
return ChangeType.INSERT;
}
if (shash.equals(dhash)) {
return ChangeType.NONE;
}
return ChangeType.UPDATE;
}
/**
* Get the Hash from a ResultSet, or returns null if the ResultSet is exhausted
*
* @param rs The ResultSet
* @return The Hash, or null
*/
private static byte[] getHash(ResultSet rs) throws Exception {
if (rs == null || rs.isBeforeFirst() || rs.isAfterLast() || rs.getRow() == 0) {
return null;
}
return rs.getBytes("Hash");
}
}
|
package de.lalo5.simplecoins;
import org.jetbrains.annotations.Nullable;
import java.sql.*;
import static de.lalo5.simplecoins.SimpleCoins.*;
import static de.lalo5.simplecoins.SimpleCoins.LOGGER;
/**
* Helper-class to interact with the MySQL Database.
*/
class SqlManager {
/** The database host. */
private String host;
/** The database port. */
private int port;
/** The database name to create tables in. Usually "<b>minecraft</b>". */
private String databaseName;
/** The table name to store the data in. */
private String tableName;
/** A user having modify access to the database. */
private String username;
/** The password for the user. */
private String password;
/** Connection instance. */
private Connection conn;
/**
* Default constructor with all connection relevant fields.
*
* @param host The database host.
* @param port The database port.
* @param databaseName The database name to create tables in.
* @param tableName The table name to store the data in.
* @param username A user having modify access to the database.
* @param password The password for the user.
*/
SqlManager(String host, int port, String databaseName, String tableName, String username, String password) {
this.host = host;
this.port = port;
this.databaseName = databaseName;
this.tableName = tableName;
this.username = username;
this.password = password;
}
/**
* Tries to open a connection to the database.
*
* @throws SQLException If an exception occurs while trying to connect.
*/
void connect() throws SQLException {
String url = "jdbc:mysql://" + host + ":" + port + "/" + databaseName;
conn = DriverManager.getConnection(url, username, password);
LOGGER.info(CONSOLEPREFIX + "Successfully connected to the MySQL database.");
}
/**
* Creates a new table with the specified name (see {@link #tableName} and structure required for storing the account data.
*
* @throws SQLException If an exception occurs while trying to create the table.
*/
void createTable() throws SQLException {
executeStatement(
"CREATE TABLE IF NOT EXISTS `minecraft`.`" + tableName + "` " +
"( `UUID` TEXT NOT NULL COMMENT 'Players UUID' , " +
"`Name` TEXT NOT NULL COMMENT 'Players Name' , " +
"`Coins` DOUBLE NOT NULL COMMENT 'Players amount of coins' , " +
"UNIQUE `UUID` (`UUID`(36))) " +
"ENGINE = InnoDB CHARSET=utf8 COLLATE utf8_general_ci COMMENT = 'SimpleCoins account storage';"
);
LOGGER.info("Created table " + tableName + ".");
}
/**
* Closes the connection.
*
* @throws SQLException If an exception occurs while trying to close the connection.
*/
void closeConnection() throws SQLException {
conn.close();
LOGGER.info(CONSOLEPREFIX + "Successfully disconnected from the MySQL database.");
}
/**
* Executes an SQL statement on the database.
* <br>
* Returns nothing. Useful for <b>INSERT</b> or <b>UPDATE</b> statements.
*
* @param command The command (or query) to execute.
*
* @throws SQLException If an exception occurs while trying to execute the command (or query).
*/
void executeStatement(String command) throws SQLException {
conn.createStatement().execute(command);
}
/**
* Executes an SQL statement on the database.
* <br>
* Returns nothing. Useful for <b>SELECT</b> statements.
*
* @param command The command (or query) to execute.
*
* @return A {@link ResultSet} containing the returned data.
*/
@Nullable
ResultSet returnValue(String command) {
try {
return conn.prepareStatement(command).executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}
|
package editor.views;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import xml.Element;
public class RepresentationView extends JFrame {
private final String TAG_STR = "Tag";
private final String ATTRIBUTE_VALUE_STR = "Attribute Value";
private class RepComboBoxActionListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String repChoice = (String) repComboBox.getSelectedItem();
boolean attBoxVisible = attributeComboBox.isVisible();
if (repChoice.equals(ATTRIBUTE_VALUE_STR) && !attBoxVisible) {
attributeComboBox.setVisible(true);
} else if (!repChoice.equals(ATTRIBUTE_VALUE_STR)) {
attributeComboBox.setVisible(false);
}
}
}
private JComboBox<String> repComboBox;
private JComboBox<String> attributeComboBox;
public RepresentationView(Element elem) {
setTitle("Element Representation");
setSize(300, 200);
setLayout(new FlowLayout());
add(new JLabel("Element"));
JTextField elemField = new JTextField(elem.getTag(), 20);
elemField.setEditable(false);
add(new JLabel("Representation"));
String[] repChoices = {TAG_STR, ATTRIBUTE_VALUE_STR};
repComboBox = new JComboBox<String>(repChoices);
RepComboBoxActionListener listener = new RepComboBoxActionListener();
repComboBox.addActionListener(listener);
if (elem.getNumberOfAttributes() == 0) {
repComboBox.setEnabled(false);
}
add(repComboBox);
add(new JLabel("Set for all of this type of element"));
JCheckBox setForAllCheckBox = new JCheckBox();
add(setForAllCheckBox);
String[] atts = new String[elem.getNumberOfAttributes()];
int idx = 0;
for (String att : elem.attributeNames()) {
atts[idx] = att;
idx++;
}
attributeComboBox = new JComboBox<String>(atts);
attributeComboBox.setVisible(false);
add(attributeComboBox);
JButton okButton = new JButton("OK");
add(okButton);
setVisible(true);
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.mayo.ve.VCFParser;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.mongodb.*;
import com.mongodb.util.JSON;
import com.tinkerpop.pipes.Pipe;
import com.tinkerpop.pipes.transform.IdentityPipe;
import com.tinkerpop.pipes.util.Pipeline;
import edu.mayo.TypeAhead.TypeAheadCollection;
import edu.mayo.TypeAhead.TypeAheadInterface;
import edu.mayo.concurrency.exceptions.ProcessTerminatedException;
import edu.mayo.concurrency.workerQueue.Task;
import edu.mayo.index.Index;
import edu.mayo.parsers.ParserInterface;
import edu.mayo.pipes.MergePipe;
import edu.mayo.pipes.ReplaceAllPipe;
import edu.mayo.pipes.UNIX.CatPipe;
import edu.mayo.pipes.bioinformatics.SampleDefinition;
import edu.mayo.pipes.bioinformatics.VCF2VariantPipe;
import edu.mayo.pipes.history.HistoryInPipe;
import edu.mayo.pipes.iterators.Compressor;
import edu.mayo.senders.FileSender;
import edu.mayo.senders.Sender;
import edu.mayo.util.MongoConnection;
import edu.mayo.util.SystemProperties;
import edu.mayo.util.Tokens;
import edu.mayo.ve.resources.MetaData;
import edu.mayo.ve.resources.SampleMeta;
import java.io.File;
import java.io.IOException;
import java.io.LineNumberReader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
//import edu.mayo.cli.CommandPlugin; TO DO! get this to work :(
/**
*
* @author m102417
*/
public class VCFParser implements ParserInterface {
private int cacheSize = 50000;
private Mongo m = MongoConnection.getMongo();
/** testingCollection contains all of the objects placed into the workspace from parsing the VCF */
HashMap<Integer,String> testingCollection = new HashMap<Integer,String>();
JsonObject json = null;
/** @param context - the execution context (so we can kill the process if needed) -- can be null */
private Task context = null;
/** @param typeAhead - the implementation for where value sets will be stored for providing type-ahead functionality. */
private TypeAheadInterface typeAhead = new TypeAheadCollection();
/** @param testing -- populate in-memoryt testingCollection instead of Mongo. */
private boolean testing = false;
/** @param reporting - if verbose output is desired (much slower and not for production use, use when debugging) */
private boolean reporting = false;
private Double initialLinePerformance = 0.0;
private Double averageLinePerformance = 0.0;
public static void usage(){
System.out.println("This program will parse a VCF file, obtain the 'schema' for that VCF and populate a MongoDB database with the variants in the VCF.");
System.out.println("");
System.out.println("Make sure to check your sys.properties file fo the MongoDB IP/Port combination, otherwised this script may fail");
System.out.println("usage: VCFParser <input.vcf> <workspace_id>");
}
public static void main(String[] args) throws IOException, ProcessTerminatedException {
SystemProperties sysprops = new SystemProperties();
String mongoPort = sysprops.get("mongo_port");
VCFParser parser = new VCFParser();
if( args.length != 2 ) {
usage();
System.exit(1);
}
String infile = args[0];
String workspace = args[1];
// String infile = "/data/VCFExamples/BATCH4.vcf";
// String outfile = "/data/VCFExamples/BATCH4.json";
// String workspace = "w7ee29742ff80d61953d5e6f84e1686957fbe36f7";
System.out.println("#Input File: " + infile);
System.out.println("#Workspace: " + workspace);
System.out.println("#mongo_server: " + sysprops.get("mongo_server") );
System.out.println("#mongo port: " + new Integer(sysprops.get("mongo_port")));
parser.setReporting(true);
int datalines = parser.parse(null, infile, workspace, 50000, false, true);
parser.checkAndUpdateLoadStatus(workspace, datalines, true);
parser.m.close();
//note the following will only work if you have a document in mongo like:
//{ "_id" : { "$oid" : "51afa2710364d3ebd97b533a"} , "owner" : "steve" , "alias" : "foo" , "key" : "w7ee29742ff80d61953d5e6f84e1686957fbe36f7"}
//parser.updateMetadata(workspace, "{ \"hosting\" : \"hostA\" , \"clients\" : \"888\" , \"type\" : \"vps\"}");
}
/**
*
* @return The path to an error file that will show all errors with the load
*/
public String getErrorFile(String workspace){
try {
SystemProperties sysprops = new SystemProperties();
String tmp = sysprops.get("TEMPDIR");
return tmp + File.separator + workspace + ".errors";
}catch (Exception e){
throw new RuntimeException(e);
}
}
/** legacy interface, keep it in place for testing */
public int parse(Task context, String infile, String workspace, int typeAheadCacheSize) throws ProcessTerminatedException {
return parse(context, infile, workspace, typeAheadCacheSize, false, false);
}
/** legacy interface, keep it in place for testing */
public int parse(Task context, String infile, String workspace, int typeAheadCacheSize, boolean testing) throws ProcessTerminatedException{
return parse(context, infile, workspace, typeAheadCacheSize, testing, false);
}
/** legacy interface, keep it in place for testing */
public int parse(Task context, String infile, String workspace, int typeAheadCacheSize, boolean testing, boolean reporting) throws ProcessTerminatedException {
typeAhead = new TypeAheadCollection();
this.reporting = reporting;
this.testing = testing;
return parse(infile, workspace);
}
/**
* This method makes it easier to test the logic in the VCF file by enabling testing methods
* to directly get the parsing pipeline.
* @return
*/
public Pipe getPipeline(VCF2VariantPipe vcf, String infile){
Pipe p = new Pipeline(new CatPipe(),
new ReplaceAllPipe("\\{",""),
new ReplaceAllPipe("\\}",""),
new HistoryInPipe(),
vcf,
new MergePipe("\t"),
new ReplaceAllPipe("^.*\t\\{", "{"),
new ReplaceAllPipe("\"_id\":","\"_ident\":"),
new ReplaceAllPipe("Infinity","2147483648"),
//new PrintPipe(),
new IdentityPipe()
);
p.setStarts(Arrays.asList(infile));
return p;
}
/**
* This is the simple direct interface that just works when we need a simple parser.
* parse the infile, which is a raw vcf and put it into the mongo workspace
* @param infile - the raw complete (cononical) path to the file we want to parse as a string.
* @param workspace - the key for the workspace where we will put the data
* @return lines processed.
*/
public int parse(String infile, String workspace) throws ProcessTerminatedException{
Sender sender = new FileSender(getErrorFile(workspace));
if(reporting){ System.out.println("Getting the vcf-miner database from mongo"); }
DB db = MongoConnection.getDB();
if(reporting){ System.out.println("Getting the workspace collection from mongo"); }
DBCollection col = db.getCollection(workspace);
if(reporting){
System.out.println("Setting up Pipeline,\n input file: " + infile);
System.out.println("Workspace: " + workspace);
System.out.println("TypeAhead: " + typeAhead);
System.out.println("Testing: " + testing);
System.out.println("Reporting: " + reporting);
}
//make sure we have type-ahead indexed before wo go-ahead and do the load:
typeAhead.index(workspace, reporting);
VCF2VariantPipe vcf = new VCF2VariantPipe(sender, true, false);
Pipe p = getPipeline(vcf, infile);
int i;
long starttime = System.currentTimeMillis();
DBObject jsonmeta = null;
boolean storedVariantCount = false;
if(reporting) System.out.println("Processing Data....");
try {
for(i=0; p.hasNext(); i++){
if(context!=null){ if(context.isTerminated()) throw new ProcessTerminatedException(); }
if (!storedVariantCount) {
try {
storeVariantCount(new File(infile), vcf.getHeaderLineCount(), workspace);
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
storedVariantCount = true;
}
// if the line # is equally divisble by 256 (power of 2)
if (fastModulus(i, 256) == 0) {
storeCurrentVariantCount(i, workspace);
}
if(reporting) System.out.println(col.count());
String s = (String) p.next();
//System.out.println(s);
BasicDBObject bo = (BasicDBObject) JSON.parse(s);
//for type-ahead, we need access to the metadata inside the loop, try to force that here
if(jsonmeta == null){
//System.out.println(vcf.getJSONMetadata().toString());
jsonmeta = (DBObject) JSON.parse(vcf.getJSONMetadata().toString());
jsonmeta = removeDots(jsonmeta, reporting);
}
if(reporting){
System.out.println("row before removing dots:"); System.out.println(s); }
if(testing){
testingCollection.put(new Integer(i), s);
}else {//production
//System.out.println(bo.toString());
col.save(removeDots(bo, reporting));
addToTypeAhead(bo, workspace,jsonmeta);
}
if(reporting){
System.out.println("i:" + i + "\ts:" + s.length());
}
long curtime = System.currentTimeMillis();
averageLinePerformance = 1.0*(curtime-starttime)/(i+1);
if(i<50){
//consider burn in, this is the initial reading(s)...
initialLinePerformance = averageLinePerformance;
}
}
// final time, update current count
storeCurrentVariantCount(i, workspace);
} finally {
// close the FileSender so that all messages are flushed to disk
sender.close();
}
try {
addPoundSamples(vcf.getSampleDefinitions(), workspace);
}catch (IOException e){
//this exception happens when the configuration file, sys.properties is not set up correctly.
throw new ProcessTerminatedException();
}
json = vcf.getJSONMetadata();
//do some small fixes to the metadata before continuing...
//if(reporting){System.out.println("Updating metadata with type-ahead informaton");}
//DEPRICATED!!!
//json = updateMetadataWTypeAhead(json, typeAhead.getOverunFields());
if(reporting){System.out.println("Changing the structure of the FORMAT metadata");}
metadata = this.fixFormat((DBObject)JSON.parse(json.toString()));
if(!testing){
if(reporting){System.out.println("Updating metadata in database...");}
updateMetadata(workspace, metadata.toString(), reporting);
if(reporting){System.out.println("indexing...");}
index(workspace, vcf, reporting);
if(reporting){System.out.println("saving type-ahead results to the database");}
typeAhead.index(workspace, reporting);
}
if(reporting){ System.out.println("done!");}
return i; //the number of records processed
}
/**
* Stores the TOTAL variant count in the 'meta' collection
* @param vcf
* @param headerLineCount
* @param workspaceID
* @throws IOException
*/
private void storeVariantCount(File vcf, int headerLineCount, String workspaceID) throws IOException {
long timestamp = System.currentTimeMillis();
int variantCount = getLineCount(vcf) - headerLineCount;
long delta = System.currentTimeMillis() - timestamp;
int totalLines = variantCount + headerLineCount;
System.out.println("Took " + delta + "ms to get line count for file " + vcf.getAbsolutePath());
// store to mongo meta collection
BasicDBObject query = new BasicDBObject().append(Tokens.KEY, workspaceID);
BasicDBObject update = new BasicDBObject();
update.append("$set", new BasicDBObject().append("variant_count_total", variantCount));
MongoConnection.getDB().getCollection(Tokens.METADATA_COLLECTION).update(query, update);
}
/**
* Stores the CURRENT variant count in the 'meta' collection.
* @param currentLineNum
* @param workspaceID
*/
private void storeCurrentVariantCount(int currentLineNum, String workspaceID){
// store to mongo meta collection
BasicDBObject query = new BasicDBObject().append(Tokens.KEY, workspaceID);
BasicDBObject update = new BasicDBObject();
update.append("$set", new BasicDBObject().append("variant_count_current", currentLineNum));
MongoConnection.getDB().getCollection(Tokens.METADATA_COLLECTION).update(query, update);
}
/**
* Faster implementation to the Java language modulus "%" operator, which internally uses
* slow division calculations. NOTE: this only works if the divisor is a power of 2 (e.g. 2, 4, 8, 16, etc...)
*
* @param dividend
* @param divisor
* @return
*/
private int fastModulus(int dividend, int divisor) {
return dividend & (divisor - 1);
}
/**
* Gets the total line count for the given file.
* @param f
* The file to be inspected.
* @return
* The line count for the given file.
* @throws IOException
*/
private int getLineCount(File f) throws IOException {
// use compressor to figure out how to handle .zip, .gz, .bz2, etc...
File fakeOutFile = File.createTempFile("fake", "fake");
Compressor compressor = new Compressor(f, fakeOutFile);
LineNumberReader reader = null;
try {
reader = new LineNumberReader(compressor.getReader());
reader.skip(Long.MAX_VALUE);
return reader.getLineNumber();
} finally {
reader.close();
fakeOutFile.delete();
}
}
/**
* Checks whether the given INFO field has a metadata type of String or Character.
*
* @param infoField
* The INFO field to be checked.
* @param metadata
* VCF metadata.
*/
private boolean isStringOrCharacter(String infoField, DBObject metadata) {
Map headerMap = (Map) metadata.get("HEADER");
Map infoMap = (Map) headerMap.get("INFO");
if (infoMap.containsKey(infoField)) {
Map fieldMetadata = (Map) infoMap.get(infoField);
String type = (String) fieldMetadata.get("type");
if(type.equals("String") || type.equals("Character")) {
return true;
} else {
return false;
}
} else {
// no matching ##INFO metadata for this field
// it's possible the ##INFO is missing completely or not well-formed
return false;
}
}
/**
*
* @param vcfLine
* @param workspace
* @param metadata - what the header says about the field (e.g. is it a number, if so, then don't do a type-ahead!)
*/
private void addToTypeAhead(DBObject vcfLine, String workspace, DBObject metadata){
DBObject info = (DBObject) vcfLine.get("INFO"); //only care about info field for type-ahead
if(info != null){
for(String key : info.keySet()) {
String ikey = "INFO." + key;
if(isStringOrCharacter(key,metadata)) { //check to see if its a String or Character
Object o = info.get(key);
if (o instanceof BasicDBList) {
//it is a list of String or Character
addArrToTypeAhead((BasicDBList) o, workspace, ikey);
} else {
// it is a single String or Character value
typeAhead.put(workspace, ikey, String.valueOf(o));
}
}
}
}
}
/**
* ##SAMPLE LINES need to be added to their own collection so that later code can query it.
* DBObject metadata
*/
public void addPoundSamples(Iterator<SampleDefinition> iter, String workspace) throws IOException {
SampleMeta sm = new SampleMeta();
SystemProperties sysprop = new SystemProperties();
String poundsamplecol = sysprop.get(SampleMeta.sample_meta_collection);
DB db = MongoConnection.getDB();
DBCollection col = db.getCollection(poundsamplecol);
Gson gson = new Gson();
//First, get a curser to the ##SAMPLE objects.
while(iter.hasNext()){
SampleDefinition sdef = (SampleDefinition) iter.next();
String json = gson.toJson(sdef);
BasicDBObject bo = (BasicDBObject) JSON.parse(json);
bo.append(SampleMeta.sample_meta_key, workspace);
System.out.println(json);
col.save(bo);
}
sm.indexSampleDocuments();
}
/**
*
* @param values - a list of strings, doubles or ints.
* @param workspace - string, workspace we
*/
private void addArrToTypeAhead(BasicDBList values, String workspace, String ikey){
//System.out.println("Adding Array: " + ikey);
for(Object o : values){
if (o instanceof String) {
typeAhead.put(workspace, ikey, o.toString());
//System.out.println(ikey + ((String) o));
} else if (o instanceof Integer) {
typeAhead.put(workspace, ikey, String.valueOf((Integer) o));
} else if (o instanceof Double) {
typeAhead.put(workspace, ikey, String.valueOf((Double) o));
}
}
}
/**
* Adds the {@link SampleDefinition} values of type string to the typeahead backend.
* @param def
* The {@link SampleDefinition} to be used.
* @param workspace
* The workspace key.
*/
public void addToTypeAhead(SampleDefinition def, String workspace) {
for (String stringMetaKey: def.getStringKeys()) {
final String ikey = "META." + stringMetaKey;
for (String value: def.getStringValues(stringMetaKey)) {
typeAhead.put(workspace, ikey, value);
}
}
}
private DBObject metadata = null;
/**
* for testing...
*/
public DBObject getMetadata(){
return metadata;
}
public int parse(Task task, String inputVCFFile, String workspace, TypeAheadInterface typeAhead, boolean testing) throws ProcessTerminatedException {
if(task != null)
context = task;
if(typeAhead != null){
this.typeAhead = typeAhead;
}
this.testing = testing;
this.reporting = reporting;
return parse(inputVCFFile, workspace);
}
/**
* This needs to be called after a parse to ensure that the load gets correctly registered by the UI
* checks to see if the load worked or if it failed
* @param workspace - the key for the workspace
* @param datalines - the number of lines of data in the load file
* @param force - force the status as successful
* @return true if it worked, false if it failed.
*/
public boolean checkAndUpdateLoadStatus(String workspace, int datalines, boolean force){
MetaData metaData = new MetaData();
if(force){
if(reporting) System.out.println("Force flag set, the workspace will be flagged as ready!");
metaData.flagAsReady(workspace);
}
if(reporting) System.out.println("Checking the status of the load");
//the first way the load could have failed is if the number of records in the workspace != the number of data lines
BasicDBObject query = new BasicDBObject(); //empty for all
DB db = MongoConnection.getDB();
DBCollection col = db.getCollection(workspace);
long linesLoaded = col.count(query);
if(linesLoaded != datalines){
metaData.flagAsFailed(workspace, "The load failed, the number of records in the workspace (" + linesLoaded + ") does not equal the number of data lines in the original file (" + datalines +")" );
return false;
}
//are there other ways we could check / need to check that a load failed?
//everything looks ok,
//now flag the workspace as ready so the UI knows
if(reporting) System.out.println("Flagging the workspace as ready");
//requested change by patrick
//metaData.flagAsReady(workspace);
return true;
}
private class TrackNode {
public TrackNode(DBObject node, boolean discovered){
this.node = node;
this.discovered = discovered;
}
public DBObject node; // the position in the JSON structure where the dfs is pointing
public DBObject shaddow; // shaddow is the new node in the copy structure
public boolean discovered = false;
}
/**
* removeDots uses Depth First Search to traverse the json object hiarchy and replace any keys with a dot (.) in them
* with keys that have an underscore (_). This way mongo can load the key.
* @param bo
* @param reporting
* @return
*/
public DBObject removeDots(DBObject bo, boolean reporting){
if(bo == null) return bo;
if(bo.keySet().size() < 1) return bo;
//Generic non-recursive DFS algorithm is:
// 1 procedure DFS-iterative(G,v):
// 2 let S be a stack
// 3 S.push(v)
// 4 while S is not empty
// 6 if v is not labeled as discovered:
// 7 label v as discovered
// 8 for all edges from v to w in G.adjacentEdges(v) do
// 9 S.push(w)
Stack<TrackNode> s = new Stack<TrackNode>();
TrackNode v = new TrackNode(bo, false);
s.push(v);
while( s.size() > 0){
v = s.pop();
if(v.discovered == false){
v.discovered = true;
ArrayList<String> keyset = new ArrayList<String>();
for(String key : v.node.keySet()){
//System.out.println(key);
keyset.add(key);
Object o = v.node.get(key);
if(o instanceof DBObject){
DBObject d = (DBObject) o;
s.push(new TrackNode(d,false));
}//else it is data
}
for(String key : keyset){
if(key.contains(".")){
Object o = v.node.get(key);
v.node = fixDBObjectDotKey(key, v.node);
}
}
}
}
if(reporting){
System.out.println("removedDotsResult");
System.out.println(bo.toString());
System.out.println("end");
}
return bo;
}
public String getNth(String prefix, Set<String> keys, int index){
int count =0;
for(String key : keys){
if(index == count) return key;
count++;
}
return null;
}
public DBObject removeDots2(DBObject bo, boolean reporting){
if(reporting) System.out.println("removeDots");
//first, check to see if the top level directory has any dots
for(String key : bo.keySet()){
//first, check all the leafs (one dir down only)!
Object o = bo.get(key);
if(o instanceof BasicDBObject){
BasicDBObject dboo = (BasicDBObject) o;
//deal with this concurent modification problem...
List<String> keys = new ArrayList();
for(String zkey : dboo.keySet()){
keys.add(zkey);
}
for(String k2 : keys){
if(k2.contains(".")){
fixDBObjectDotKey(k2,dboo);
}
}
}
}
//now fix and check the branches (can't do in the same loop because of this concurency bug
for(String key : bo.keySet()){
//then check the branch
if(key.contains(".")){
fixDBObjectDotKey(key, bo);
}
}
if(null != bo.get(".")){
bo.removeField(".");
}
if(null != bo.get("INFO")){
Object o = bo.get("INFO");
if(o instanceof DBObject){
if( ((DBObject)o).get(".") != null ){
((DBObject)o).removeField(".");
if( ((DBObject)o).keySet().size() == 0 ){
bo.put("INFO", ".");
}
}
}
}
if(reporting){
System.out.println("removedDotsResult");
System.out.println(bo.toString());
System.out.println("end");
}
return bo;
}
public DBObject fixDBObjectDotKey(String key, DBObject dbo){
String newkey = key.replaceAll("\\.", "_");
Object o = dbo.get(key);
if(o instanceof String){
String value = (String) o;
dbo.removeField(key);
dbo.put(newkey, value);
return dbo;
}
if(o instanceof BasicDBObject){
BasicDBObject value = (BasicDBObject) o;
dbo.removeField(key);
dbo.put(newkey, value);
return dbo;
}
if(o instanceof Integer){
Integer value = (Integer) o;
dbo.removeField(key);
dbo.put(newkey, value);
return dbo;
}
if(o instanceof Double){
Double value = (Double) o;
dbo.removeField(key);
dbo.put(newkey, value);
return dbo;
}
if(o instanceof Boolean){
Boolean value = (Boolean) o;
dbo.removeField(key);
dbo.put(newkey,value);
return dbo;
}
if(o instanceof BasicDBList){
BasicDBList value = (BasicDBList) o;
dbo.removeField(key);
dbo.put(newkey,value);
return dbo;
}
return dbo;
}
public void index(String workspace, VCF2VariantPipe vcf, boolean reporting){
JsonObject json = vcf.getJSONMetadata();
if(json == null){
return;
}
DB db = MongoConnection.getDB();
DBCollection col = db.getCollection(workspace);
//auto-index all reserved columns (as needed by the app)
indexReserved(col, reporting);
//auto-index all SNPEFF columns
indexSNPEFF(col, json, reporting);
//index format
indexFormat(vcf.getFormatKeys(), col, reporting);
}
/**
* index the reserved fields that we already know about...
* @param col
* @param reporting
*/
private void indexReserved(DBCollection col, boolean reporting){
indexField("FORMAT.GenotypePostitiveCount", col, reporting);
indexField("FORMAT.GenotypePositiveList",col, reporting); //don't need to index this as soon as the query is refactored
indexField("FORMAT.HeterozygousList",col, reporting);
indexField("FORMAT.HomozygousList",col, reporting);
}
private void indexSNPEFF(DBCollection col, JsonObject json, boolean reporting){
//indexField("INFO.SNPEFF_GENE_NAME", col);
for(String key: getSNPEFFColsFromJsonObj(json)){
indexField("INFO." + key, col, reporting);
}
}
/**
*
* @param json - the json metadata object
* @return
*/
public List<String> getSNPEFFColsFromJsonObj(JsonObject json){
ArrayList<String> a = new ArrayList<String>();
JsonObject header = json.getAsJsonObject("HEADER");
if(header == null) return a;
JsonObject info = header.getAsJsonObject("INFO");
if(info == null) return a;
Iterator<Map.Entry<String,JsonElement>> itter =info.entrySet().iterator();
while(itter.hasNext()){
Map.Entry<String, JsonElement> next = itter.next();
String key = next.getKey();
//System.out.println(key); //all keys in info
if(key.contains("SNPEFF")){
a.add(key);
}
}
return a;
}
/**
*
* @param formatFields - a list of fields to index (all format fields)
* @param col - the collection/workspace
* @param reporting - if we want to show what is going on in the tomcat log
*/
private void indexFormat(Set<String> formatFields, DBCollection col, boolean reporting){
for(String field : formatFields){
// FORMAT + . + . + field
String ikey = "FORMAT." + "min." + field;
String xkey = "FORMAT." + "max." + field;
if(reporting){ System.out.println( "Trying to index: " + ikey); }
indexField(ikey, col, reporting);
if(reporting){ System.out.println( "Trying to index: " + xkey); }
indexField(xkey, col, reporting);
}
}
private void indexFieldReplacingDot(String field, DBCollection col, boolean reporting){ //don't think this is ever used...
if(field.contains(".")){
field = field.replace(".","_");
}
indexField(field, col, reporting);
}
private Index indexUtil = new Index(); //use the indexUtil instead of the raw interface to prevent duplicate indexes!
private void indexField(String field, DBCollection col, boolean reporting){
if(reporting) System.out.println("index: " + field);
DBObject status = indexUtil.indexField(field,col);
if(reporting) System.out.println(status.toString());
}
public void updateMetadata(String workspace, String jsonUpdate, boolean reporting){
if(reporting) System.out.println("Saving Metadata to Workspace: " + workspace);
DB db = MongoConnection.getDB();
DBCollection col = db.getCollection(Tokens.METADATA_COLLECTION);
String query = "{\"key\":\""+workspace+"\"}";
BasicDBObject bo = (BasicDBObject) JSON.parse(query); //JSON2BasicDBObject
DBCursor dbc = col.find(bo);
DBObject result = null;
while(dbc.hasNext()){
result = dbc.next();
break; //there will only be one that matches!
}
String owner = result.get(Tokens.OWNER).toString();
String id = result.get("_id").toString();
String alias = result.get(Tokens.WORKSPACE_ALIAS).toString();
//key = workspace, passed in so we have that!
col.remove(bo);
//System.out.println("result: " + result.toString());
//note, we want to destroy whatever was in there with the new data (in case they try to load multiple times)
//but we have to keep owner, id, and key.
BasicDBObject replace = (BasicDBObject) JSON.parse(jsonUpdate);
//we need to remove any dot keys before we save the metadata to mongo.
DBObject replaceWODots = removeDots(replace, reporting);
// carry forward ALL existing keys/value pairs (owner, key, _id, alias, ready, status)
replaceWODots.putAll(result);
//now add the new keys
replaceWODots.put("timestamp", getISONow()); //The last time the workspace was touched.
if(reporting) System.out.println(replaceWODots.toString());
col.save(replaceWODots);
}
/**
* In the metadata returned, the format field from the vcf-variant pipe looks something like this:
*
* "FORMAT": {
* "PL": 1,
* "AD": 1,
* "GT": 1,
* "GQ": 1,
* "DP": 1,
* "MLPSAF": 1,
* "MLPSAC": 1
* }
*
* This method transforms it into this (which is what mongodb will store):
* "FORMAT": {
* "min": {
* "PL": 1,
* "AD": 1,
* "GT": 1,
* "GQ": 1,
* "DP": 1,
* "MLPSAF": 1,
* "MLPSAC": 1
* }
* "max": {
* "PL": 1,
* "AD": 1,
* "GT": 1,
* "GQ": 1,
* "DP": 1,
* "MLPSAF": 1,
* "MLPSAC": 1
* }
* }
*
* @param input
* @return
*/
public DBObject fixFormat(DBObject input){
DBObject output = input;
DBObject oldformat = (DBObject) input.removeField("FORMAT");
if(oldformat != null){
DBObject min = new BasicDBObject();
DBObject max = new BasicDBObject();
for(String s : oldformat.keySet()){
min.put(s,1);
max.put(s,1);
}
DBObject format = new BasicDBObject();
if(min.keySet().size() > 0 && max.keySet().size()>0){
format.put("min", min);
format.put("max", max);
}
output.put("FORMAT", format);
}
return output;
}
/**
*
* @return the current time in iso format
*/
public String getISONow(){
TimeZone tz = TimeZone.getTimeZone("UTC");
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mmZ");
df.setTimeZone(tz);
String nowAsISO = df.format(new Date());
return nowAsISO;
}
public HashMap<Integer, String> getTestingCollection() {
return testingCollection;
}
public void setTestingCollection(HashMap<Integer, String> testingCollection) {
this.testingCollection = testingCollection;
}
public JsonObject getJson() {
return json;
}
public void setJson(JsonObject json) {
this.json = json;
}
public Mongo getM() {
return m;
}
public void setM(Mongo m) {
this.m = m;
}
public int getCacheSize() {
return cacheSize;
}
public void setCacheSize(int cacheSize) {
this.cacheSize = cacheSize;
}
public Task getContext() {
return context;
}
public void setContext(Task context) {
this.context = context;
}
public boolean isTesting() {
return testing;
}
public void setTesting(boolean testing) {
this.testing = testing;
}
@Override
public void setTypeAhead(TypeAheadInterface typeAheadInterface) {
this.typeAhead = typeAheadInterface;//To change body of implemented methods use File | Settings | File Templates.
}
public TypeAheadInterface getTypeAhead(){
return typeAhead;
}
public boolean isReporting() {
return reporting;
}
public void setReporting(boolean reporting) {
this.reporting = reporting;
}
public void setMetadata(DBObject metadata) {
this.metadata = metadata;
}
public Index getIndexUtil() {
return indexUtil;
}
public void setIndexUtil(Index indexUtil) {
this.indexUtil = indexUtil;
}
public Double getInitialLinePerformance() {
return initialLinePerformance;
}
public void setInitialLinePerformance(Double initialLinePerformance) {
this.initialLinePerformance = initialLinePerformance;
}
public Double getAverageLinePerformance() {
return averageLinePerformance;
}
public void setAverageLinePerformance(Double averageLinePerformance) {
this.averageLinePerformance = averageLinePerformance;
}
}
|
package ezvcard.util;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;
import java.util.TimeZone;
/**
* Helper class that formats and parses vCard dates. vCard dates adhere to the
* ISO8601 date format standard.
* @author Michael Angstadt
*/
public class VCardDateFormatter {
/**
* Formats a date for inclusion in a vCard.
* @param date the date to format
* @param format the format to use
* @return the formatted date
*/
public static String format(Date date, ISOFormat format) {
return format(date, format, TimeZone.getDefault());
}
/**
* Formats a date for inclusion in a vCard.
* @param date the date to format
* @param format the format to use
* @param timeZone the time zone to format the date in. This will be ignored
* if the specified ISOFormat is a "UTC" format
* @return the formatted date
*/
public static String format(Date date, ISOFormat format, TimeZone timeZone) {
switch (format) {
case UTC_TIME_BASIC:
case UTC_TIME_EXTENDED:
timeZone = TimeZone.getTimeZone("UTC");
break;
}
DateFormat df = format.getFormatDateFormat();
df.setTimeZone(timeZone);
String str = df.format(date);
switch (format) {
case TIME_EXTENDED:
//add a colon to the timezone
//example: converts "2012-07-05T22:31:41-0400" to "2012-07-05T22:31:41-04:00"
str = str.replaceAll("([-\\+]\\d{2})(\\d{2})$", "$1:$2");
break;
}
return str;
}
public static Date parse(String dateStr) {
//find out what ISOFormat the date is in
ISOFormat format = null;
for (ISOFormat f : ISOFormat.values()) {
if (f.matches(dateStr)) {
format = f;
break;
}
}
if (format == null) {
throw new IllegalArgumentException("Date string is not in a valid ISO-8601 format.");
}
//tweak the date string to make it work with SimpleDateFormat
switch (format) {
case TIME_EXTENDED:
case HCARD_TIME_TAG:
//SimpleDateFormat doesn't recognize timezone offsets that have colons
//so remove the colon from the timezone offset
dateStr = dateStr.replaceAll("([-\\+]\\d{2}):(\\d{2})$", "$1$2");
break;
case UTC_TIME_BASIC:
case UTC_TIME_EXTENDED:
//SimpleDateFormat doesn't recognize "Z"
dateStr = dateStr.replace("Z", "+0000");
break;
}
//parse the date
DateFormat df = format.getParseDateFormat();
try {
return df.parse(dateStr);
} catch (ParseException e) {
//should never be thrown because the string is checked against a regex
throw new RuntimeException(e);
}
}
private VCardDateFormatter() {
//hide constructor
}
}
|
package gov.nrel.bacnet.consumer;
import gov.nrel.bacnet.Config;
import gov.nrel.bacnet.consumer.beans.JsonAllFilters;
import gov.nrel.bacnet.consumer.beans.JsonObjectData;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
import java.util.Collection;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import java.util.Timer;
import com.serotonin.bacnet4j.LocalDevice;
import com.serotonin.bacnet4j.event.DefaultExceptionListener;
import com.serotonin.bacnet4j.type.primitive.UnsignedInteger;
import com.serotonin.util.queue.ByteQueue;
import org.apache.commons.cli.*;
public class BACnet {
private static final Logger logger = Logger.getLogger(Main.class.getName());
private ScheduledThreadPoolExecutor schedSvc; //used for broadcast and polling
private ExecutorService execSvc; //used by databus meta loading/writing and by Oid discovery
private Timer slaveDeviceTimer;
// private OurExecutor exec;
private DatabusDataWriter writer;
private ScheduledFuture<?> backgroundDiscoverer;
private Config config;
private LocalDevice localDevice;
private JsonAllFilters filters;
private LogHandler logHandler;
private BACnetDatabase database;
private TaskTracker tracker;
public BACnet(Config t_config)
{
config = t_config;
tracker = new TaskTracker();
localDevice = null;
filters = null;
logHandler = null;
try {
logger.info("starting. Loading logging.properties first to log to a file in logs directory");
FileInputStream configFile = new FileInputStream(config.getLoggingPropertiesFileName());
LogManager.getLogManager().readConfiguration(configFile);
if (config.getVerboseLogging())
{
logger.setLevel(Level.INFO);
}
if (config.getVeryVerboseLogging())
{
logger.setLevel(Level.ALL);
}
logger.info("Starting now that logger properties are loaded");
LocalDevice.setExceptionListener(new MyExceptionListener());
initialize(config);
} catch(Throwable e) {
logger.log(Level.WARNING, "exception starting", e);
}
}
public void setDatabase(BACnetDatabase d)
{
logger.info("Setting new database");
database = d;
}
public BACnetDatabase getDatabase()
{
return database;
}
public TaskTracker getTaskTracker()
{
return tracker;
}
public void setLogger(LogHandler h)
{
logger.info("Setting new loghandler");
if (logHandler != null)
{
Logger.getLogger("gov.nrel.bacnet").removeHandler(logHandler);
}
logHandler = h;
Logger.getLogger("gov.nrel.bacnet").addHandler(logHandler);
}
public ExecutorService getExecSvc(){
return execSvc;
}
public ScheduledThreadPoolExecutor getSchedSvc(){
return schedSvc;
}
public LogHandler getLogger()
{
return logHandler;
}
public LocalDevice getLocalDevice()
{
return localDevice;
}
public JsonAllFilters getFilters()
{
return filters;
}
public JsonAllFilters parseFilters(String filters)
{
com.google.gson.Gson gson = new com.google.gson.Gson();
return gson.fromJson(filters, JsonAllFilters.class);
}
public Collection<BACnetDataWriter> getDefaultWriters()
{
java.util.List<BACnetDataWriter> writerlist = new java.util.ArrayList();
if (getDatabusDataWriter() != null)
{
writerlist.add(getDatabusDataWriter());
}
if (database != null)
{
writerlist.add(database);
}
return writerlist;
}
private void initialize(Config config) throws IOException {
LinkedBlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>(1000);
RejectedExecutionHandler rejectedExec = new RejectedExecHandler();
execSvc = new ThreadPoolExecutor(20, 20, 120, TimeUnit.SECONDS, queue, rejectedExec );
schedSvc = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(config.getNumThreads());
// execSvc = Executors.newFixedThreadPool(config.getNumThreads());
// exec = new OurExecutor(svc, execSvc, recorderSvc);
String devname = config.getNetworkDevice();
int device_id = config.getDeviceId();
NetworkInterface networkinterface = null;
try {
networkinterface = java.net.NetworkInterface.getByName(devname);
} catch (Exception ex) {
System.out.println("Unable to open device: " + devname);
System.exit(-1);
}
if (networkinterface == null) {
System.out.println("Unable to open device: " + devname);
System.exit(-1);
}
List<InterfaceAddress> addresses = networkinterface.getInterfaceAddresses();
String sbroadcast = null;
String saddress = null;
//InterfaceAddress ifaceaddr = null;
for (InterfaceAddress address : addresses) {
logger.fine("Evaluating address: " + address.toString());
if (address.getAddress().getAddress().length == 4) {
logger.info("Address is ipv4, selecting: " + address.toString());
sbroadcast = address.getBroadcast().toString().substring(1);
saddress = address.getAddress().toString().substring(1);
//ifaceaddr = address;
break;
} else {
logger.info("Address is not ipv4, not selecting: "
+ address.toString());
}
}
logger.info("Binding to: " + saddress + " " + sbroadcast);
localDevice = new LocalDevice(device_id, sbroadcast);
localDevice.setPort(LocalDevice.DEFAULT_PORT);
localDevice.setTimeout(localDevice.getTimeout() * 3);
localDevice.setSegTimeout(localDevice.getSegTimeout() * 3);
try {
localDevice.initialize();
localDevice.setRetries(0); //don't retry as it seems to really be a waste.
} catch (IOException e) {
e.printStackTrace();
return;
}
if (config.getSlaveDeviceEnabled())
{
slaveDeviceTimer = new Timer();
slaveDeviceTimer.schedule(new gov.nrel.bacnet.SlaveDevice(localDevice, config), 1000, config.getSlaveDeviceUpdateInterval() * 1000);
}
String file = config.getFilterFileName();
String filterfile = readFile(file, Charset.forName("US-ASCII"));
logger.info("using filter file:" + file);
filters = parseFilters(filterfile);
int counter = 0;
for(JsonObjectData d : filters.getFilters()) {
if(d.getInterval() == 0) {
throw new IllegalArgumentException("Filter cannot have interval value of 0 or null. It must be less than 0 to disable and greater than 0 to enable in seconds");
} else if(d.getInterval() > 0 && d.getInterval() < 15) {
throw new IllegalArgumentException("Scan interval cannot be less than 15 seconds");
}
logger.info("filter"+counter+"="+d.getInterval()+" devId="+d.getDeviceId()+" objId="+d.getObjectId()+" objType="+d.getObjectType());
//initialize regular expression matchers...
d.init();
}
String streamTable = config.getDatabusStreamTable();
String deviceTable = config.getDatabusDeviceTable();
String username = config.getDatabusUserName();
String key = config.getDatabusKey();
logger.info("user="+username+" key="+key);
DatabusSender sender = null;
if (config.getDatabusEnabled())
{
sender = new DatabusSender(username, key, deviceTable, streamTable, execSvc, config.getDatabusUrl(), config.getDatabusPort(), true);
}
logger.info("databus sender: "+sender);
writer = new DatabusDataWriter(new DataPointWriter(sender));
logger.info("databus writer" + writer);
}
public static String readFile(String file, Charset cs) throws IOException {
// No real need to close the BufferedReader/InputStreamReader
// as they're only wrapping the stream
FileInputStream stream = new FileInputStream(file);
try {
Reader reader = new BufferedReader(
new InputStreamReader(stream, cs));
StringBuilder builder = new StringBuilder();
char[] buffer = new char[8192];
int read;
while ((read = reader.read(buffer, 0, buffer.length)) > 0) {
builder.append(buffer, 0, read);
}
return builder.toString();
} finally {
// Potential issue here: if this throws an IOException,
// it will mask any others. Normally I'd use a utility
// method which would log exceptions and swallow them
stream.close();
}
}
public BACnetDataWriter getDatabusDataWriter()
{
return writer;
}
public static Config parseOptions(String[] args) throws Exception {
int min_id = -1;
int max_id = -1;
int device_id = 11234;
int scanInterval = 168;
int broadcastInterval = 1;
int range = 100;
int numThreads = 10;
String databusStreamTable = "bacnetstreamMeta";
String databusDeviceTable = "bacnetdeviceMeta";
String databusUserName = "";
String databusKey = "";
String databusURL = "";
int databusPort = 1;
String devname = "eth0";
String filterFile = "conf/example_filter.json";
String slaveDeviceConfigFile = "conf/example_oid.json";
int slaveDeviceUpdateInterval = 10;
boolean scan = true;
boolean slaveDeviceEnabled = false;
String loggingPropertiesFile = "../conf/logging.properties";
boolean verboseLogging = false;
boolean veryVerboseLogging = false;
boolean databusEnabled = true;
CommandLineParser parser = new PosixParser();
Options options = new Options();
options.addOption("m", "min-device-id", true,
"Minimum device ID to scan for, default: " + min_id);
options.addOption("M", "max-device-id", true,
"Maximum device ID to scan for, default: " + max_id);
options.addOption("i", "id", true,
"Device ID of this software, default: " + device_id);
options.addOption("D", "device-id", true,
"device ID to scan, exclusive of min-device-id and max-device-id");
options.addOption("f", "filter-file", true,
"JSON filter file to use during scanning, default: " + filterFile);
options.addOption("d", "dev", true,
"Network device to use for broadcasts, default: " + devname);
options.addOption("s", "scan", false, "Enable scanning feature, default: " + scan);
options.addOption("S", "slave-device", false,
"Enable slave device feature, default: " + slaveDeviceEnabled);
options.addOption("T", "slave-device-interval", true,
"Number of seconds between updates to slave device values, default: " + slaveDeviceUpdateInterval);
options.addOption(
"t",
"scan-interval",
true,
"Amount of time (in ms) to wait between finishing one scan and starting another. default: " + scanInterval);
options.addOption("F", "oid-file", true,
"JSON oid file to use for the slave device configuration, default: " + slaveDeviceConfigFile);
options.addOption("v", "verbose", false,
"Verbose logging (Info Level). Default is warning and error logging. default: " + verboseLogging);
options.addOption("vv", "very-verbose", false,
"Very verbose logging (All Levels). Default is warning and error logging. default: " + veryVerboseLogging);
options.addOption("u", "databus-url", true,
"Databus URL to send data to, default: " + databusURL);
options.addOption("k", "databus-key", true,
"Key for sending to Databus, default: " + databusKey);
options.addOption("U", "databus-user", true,
"Databus username for sending to Database, default: " + databusUserName);
options.addOption("p", "databus-port", true,
"Databus port for sending to Database, default: " + databusPort);
options.addOption("l", "logging-properties-file", true,
"File for loading logger configuration, default: " + loggingPropertiesFile);
options.addOption("databus", "databus-enabled", true, "Enable writing to databus. default: " + databusEnabled);
try {
CommandLine line = parser.parse(options, args);
scanInterval = Integer.parseInt(line.getOptionValue("t",
"168"));
device_id = Integer.parseInt(line.getOptionValue("i", "1234"));
scan = line.hasOption("s");
slaveDeviceEnabled = line.hasOption("S");
min_id = Integer.parseInt(line.getOptionValue("m", "-1"));
max_id = min_id;
max_id = Integer.parseInt(line.getOptionValue("M", "-1"));
if (min_id == -1) {
min_id = 0;
}
if (max_id == -1)
{
max_id = 4000000;
}
if (line.hasOption("m") && !line.hasOption("M")) {
HelpFormatter hp = new HelpFormatter();
hp.printHelp(
"Syntax:",
"Error: a max-device-id must be specified if a min-device-id is specified",
options, "", true);
System.exit(-1);
}
if (max_id < min_id) {
HelpFormatter hp = new HelpFormatter();
hp.printHelp(
"Syntax:",
"Error: max-device-id cannot be less than min-device-id",
options, "", true);
System.exit(-1);
}
if (line.hasOption("D")
&& (line.hasOption("m") || line.hasOption("M"))) {
HelpFormatter hp = new HelpFormatter();
hp.printHelp(
"Syntax:",
"Error: you cannot specify both a specific device-id and a min-device-id or max-device-id",
options, "", true);
System.exit(-1);
}
if (line.hasOption("D")) {
min_id = max_id = Integer.parseInt(line.getOptionValue("D"));
}
if (line.hasOption("f")) {
filterFile = line.getOptionValue("f");
}
if (line.hasOption("F")) {
slaveDeviceConfigFile = line.getOptionValue("F");
}
devname = line.getOptionValue("dev", "eth0");
if (line.hasOption("v")) {
verboseLogging = true;
}
if (line.hasOption("vv")) {
veryVerboseLogging = true;
}
if (line.hasOption("u")) {
databusURL = line.getOptionValue("u");
}
if (line.hasOption("k")) {
databusKey = line.getOptionValue("k");
}
if (line.hasOption("U")) {
databusUserName = line.getOptionValue("U");
}
if (line.hasOption("p")) {
databusPort = Integer.parseInt(line.getOptionValue("p"));
}
if (line.hasOption("l")) {
loggingPropertiesFile = line.getOptionValue("l");
}
if (line.hasOption("databus-enabled")) {
databusEnabled = Boolean.parseBoolean(line.getOptionValue("databus-enabled"));
}
} catch (Exception e) {
HelpFormatter hp = new HelpFormatter();
logger.log(Level.SEVERE, "Commmand Line Parsing Error: ", e);
hp.printHelp("Syntax:", options, true);
System.exit(-1);
}
Config config = new Config(scanInterval, broadcastInterval, range, numThreads, devname, verboseLogging,
veryVerboseLogging, device_id, filterFile, loggingPropertiesFile, databusEnabled,
databusDeviceTable, databusStreamTable, databusUserName, databusKey,
databusURL, databusPort, slaveDeviceEnabled, slaveDeviceConfigFile, slaveDeviceUpdateInterval,
min_id, max_id);
return config;
}
static class MyExceptionListener extends DefaultExceptionListener {
@Override
public void unimplementedVendorService(UnsignedInteger vendorId,
UnsignedInteger serviceNumber, ByteQueue queue) {
if (vendorId.intValue() == 8 && serviceNumber.intValue() == 1) {
// do nothing
logger.info("do nothing...unimplemented vendor service="+vendorId+" service="+serviceNumber);
} else {
logger.info("Received unimplemented vendor service: vendor id=" + vendorId + ", service number="
+ serviceNumber + ", bytes (with context id)=" + queue);
}
}
public void receivedException(Exception e) {
logger.log(Level.WARNING, "Exception", e);
}
public void receivedThrowable(Throwable t) {
logger.log(Level.WARNING, "Exc", t);
}
}
}
|
package hudson.plugins.git;
import hudson.EnvVars;
import hudson.Extension;
import hudson.FilePath;
import hudson.FilePath.FileCallable;
import hudson.Launcher;
import hudson.Util;
import hudson.matrix.MatrixAggregatable;
import hudson.matrix.MatrixAggregator;
import hudson.matrix.MatrixBuild;
import hudson.matrix.MatrixRun;
import hudson.model.AbstractBuild;
import hudson.model.AbstractDescribableImpl;
import hudson.model.AbstractProject;
import hudson.model.BuildListener;
import hudson.model.Descriptor;
import hudson.model.Result;
import hudson.plugins.git.opt.PreBuildMergeOptions;
import hudson.remoting.VirtualChannel;
import hudson.scm.SCM;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.BuildStepMonitor;
import hudson.tasks.Publisher;
import hudson.tasks.Recorder;
import hudson.util.FormValidation;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import org.apache.commons.lang.StringUtils;
import org.eclipse.jgit.transport.RemoteConfig;
import org.kohsuke.stapler.AncestorInPath;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
public class GitPublisher extends Recorder implements Serializable, MatrixAggregatable {
private static final long serialVersionUID = 1L;
/**
* Store a config version so we're able to migrate config on various
* functionality upgrades.
*/
private Long configVersion;
private boolean pushMerge;
private boolean pushOnlyIfSuccess;
private List<TagToPush> tagsToPush;
// Pushes HEAD to these locations
private List<BranchToPush> branchesToPush;
// notes support
private List<NoteToPush> notesToPush;
@DataBoundConstructor
public GitPublisher(List<TagToPush> tagsToPush,
List<BranchToPush> branchesToPush,
List<NoteToPush> notesToPush,
boolean pushOnlyIfSuccess,
boolean pushMerge) {
this.tagsToPush = tagsToPush;
this.branchesToPush = branchesToPush;
this.notesToPush = notesToPush;
this.pushMerge = pushMerge;
this.pushOnlyIfSuccess = pushOnlyIfSuccess;
this.configVersion = 2L;
}
public boolean isPushOnlyIfSuccess() {
return pushOnlyIfSuccess;
}
public boolean isPushMerge() {
return pushMerge;
}
public boolean isPushTags() {
if (tagsToPush == null) {
return false;
}
return !tagsToPush.isEmpty();
}
public boolean isPushBranches() {
if (branchesToPush == null) {
return false;
}
return !branchesToPush.isEmpty();
}
public boolean isPushNotes() {
if (notesToPush == null) {
return false;
}
return !notesToPush.isEmpty();
}
public List<TagToPush> getTagsToPush() {
if (tagsToPush == null) {
tagsToPush = new ArrayList<TagToPush>();
}
return tagsToPush;
}
public List<BranchToPush> getBranchesToPush() {
if (branchesToPush == null) {
branchesToPush = new ArrayList<BranchToPush>();
}
return branchesToPush;
}
public List<NoteToPush> getNotesToPush() {
if (notesToPush == null) {
notesToPush = new ArrayList<NoteToPush>();
}
return notesToPush;
}
public BuildStepMonitor getRequiredMonitorService() {
return BuildStepMonitor.BUILD;
}
/**
* For a matrix project, push should only happen once.
*/
public MatrixAggregator createAggregator(MatrixBuild build, Launcher launcher, BuildListener listener) {
return new MatrixAggregator(build,launcher,listener) {
@Override
public boolean endBuild() throws InterruptedException, IOException {
return GitPublisher.this.perform(build,launcher,listener);
}
};
}
@Override
public boolean perform(AbstractBuild<?, ?> build,
Launcher launcher, final BuildListener listener)
throws InterruptedException {
// during matrix build, the push back would happen at the very end only once for the whole matrix,
// not for individual configuration build.
if (build instanceof MatrixRun) {
return true;
}
SCM scm = build.getProject().getScm();
if (!(scm instanceof GitSCM)) {
return false;
}
final GitSCM gitSCM = (GitSCM) scm;
if(gitSCM.getUseShallowClone()) {
listener.getLogger().println("GitPublisher disabled while using shallow clone.");
return true;
}
final String projectName = build.getProject().getName();
final FilePath workspacePath = build.getWorkspace();
final int buildNumber = build.getNumber();
final Result buildResult = build.getResult();
// If pushOnlyIfSuccess is selected and the build is not a success, don't push.
if (pushOnlyIfSuccess && buildResult.isWorseThan(Result.SUCCESS)) {
listener.getLogger().println("Build did not succeed and the project is configured to only push after a successful build, so no pushing will occur.");
return true;
}
else {
final String gitExe = gitSCM.getGitExe(build.getBuiltOn(), listener);
EnvVars tempEnvironment;
try {
tempEnvironment = build.getEnvironment(listener);
} catch (IOException e) {
e.printStackTrace(listener.error("Failed to build up environment"));
tempEnvironment = new EnvVars();
}
String confName = gitSCM.getGitConfigNameToUse();
if ((confName != null) && (!confName.equals(""))) {
tempEnvironment.put("GIT_COMMITTER_NAME", confName);
tempEnvironment.put("GIT_AUTHOR_NAME", confName);
}
String confEmail = gitSCM.getGitConfigEmailToUse();
if ((confEmail != null) && (!confEmail.equals(""))) {
tempEnvironment.put("GIT_COMMITTER_EMAIL", confEmail);
tempEnvironment.put("GIT_AUTHOR_EMAIL", confEmail);
}
final EnvVars environment = tempEnvironment;
final FilePath workingDirectory = gitSCM.workingDirectory(workspacePath,environment);
boolean pushResult = true;
// If we're pushing the merge back...
if (pushMerge) {
boolean mergeResult;
try {
mergeResult = workingDirectory.act(new FileCallable<Boolean>() {
private static final long serialVersionUID = 1L;
public Boolean invoke(File workspace,
VirtualChannel channel) throws IOException {
IGitAPI git = new GitAPI(
gitExe, new FilePath(workspace),
listener, environment);
// We delete the old tag generated by the SCM plugin
String buildnumber = "jenkins-" + projectName + "-" + buildNumber;
git.deleteTag(buildnumber);
// And add the success / fail state into the tag.
buildnumber += "-" + buildResult.toString();
git.tag(buildnumber, "Jenkins Build #" + buildNumber);
PreBuildMergeOptions mergeOptions = gitSCM.getMergeOptions();
if (mergeOptions.doMerge() && buildResult.isBetterOrEqualTo(Result.SUCCESS)) {
RemoteConfig remote = mergeOptions.getMergeRemote();
listener.getLogger().println("Pushing HEAD to branch " + mergeOptions.getMergeTarget() + " of " + remote.getName() + " repository");
git.push(remote, "HEAD:" + mergeOptions.getMergeTarget());
} else {
//listener.getLogger().println("Pushing result " + buildnumber + " to origin repository");
//git.push(null);
}
return true;
}
});
} catch (Throwable e) {
e.printStackTrace(listener.error("Failed to push merge to origin repository"));
build.setResult(Result.FAILURE);
mergeResult = false;
}
if (!mergeResult) {
pushResult = false;
}
}
if (isPushTags()) {
boolean allTagsResult = true;
for (final TagToPush t : tagsToPush) {
boolean tagResult = true;
if (t.getTagName() == null) {
listener.getLogger().println("No tag to push defined");
tagResult = false;
}
if (t.getTargetRepoName() == null) {
listener.getLogger().println("No target repo to push to defined");
tagResult = false;
}
if (tagResult) {
final String tagName = environment.expand(t.getTagName());
final String tagMessage = hudson.Util.fixNull(environment.expand(t.getTagMessage()));
final String targetRepo = environment.expand(t.getTargetRepoName());
try {
tagResult = workingDirectory.act(new FileCallable<Boolean>() {
private static final long serialVersionUID = 1L;
public Boolean invoke(File workspace,
VirtualChannel channel) throws IOException {
IGitAPI git = new GitAPI(gitExe, new FilePath(workspace),
listener, environment);
RemoteConfig remote = gitSCM.getRepositoryByName(targetRepo);
if (remote == null) {
listener.getLogger().println("No repository found for target repo name " + targetRepo);
return false;
}
if (t.isCreateTag()) {
if (git.tagExists(tagName)) {
listener.getLogger().println("Tag " + tagName + " already exists and Create Tag is specified, so failing.");
return false;
}
if (tagMessage.isEmpty()) {
git.tag(tagName, "Jenkins Git plugin tagging with " + tagName);
} else {
git.tag(tagName, tagMessage);
}
}
else if (!git.tagExists(tagName)) {
listener.getLogger().println("Tag " + tagName + " does not exist and Create Tag is not specified, so failing.");
return false;
}
listener.getLogger().println("Pushing tag " + tagName + " to repo "
+ targetRepo);
git.push(remote, tagName);
return true;
}
});
} catch (Throwable e) {
e.printStackTrace(listener.error("Failed to push tag " + tagName + " to " + targetRepo));
build.setResult(Result.FAILURE);
tagResult = false;
}
}
if (!tagResult) {
allTagsResult = false;
}
}
if (!allTagsResult) {
pushResult = false;
}
}
if (isPushBranches()) {
boolean allBranchesResult = true;
for (final BranchToPush b : branchesToPush) {
boolean branchResult = true;
if (b.getBranchName() == null) {
listener.getLogger().println("No branch to push defined");
return false;
}
if (b.getTargetRepoName() == null) {
listener.getLogger().println("No branch repo to push to defined");
return false;
}
final String branchName = environment.expand(b.getBranchName());
final String targetRepo = environment.expand(b.getTargetRepoName());
if (branchResult) {
try {
branchResult = workingDirectory.act(new FileCallable<Boolean>() {
private static final long serialVersionUID = 1L;
public Boolean invoke(File workspace,
VirtualChannel channel) throws IOException {
IGitAPI git = new GitAPI(gitExe, new FilePath(workspace),
listener, environment);
RemoteConfig remote = gitSCM.getRepositoryByName(targetRepo);
if (remote == null) {
listener.getLogger().println("No repository found for target repo name " + targetRepo);
return false;
}
listener.getLogger().println("Pushing HEAD to branch " + branchName + " at repo "
+ targetRepo);
git.push(remote, "HEAD:" + branchName);
return true;
}
});
} catch (Throwable e) {
e.printStackTrace(listener.error("Failed to push branch " + branchName + " to " + targetRepo));
build.setResult(Result.FAILURE);
branchResult = false;
}
}
if (!branchResult) {
allBranchesResult = false;
}
}
if (!allBranchesResult) {
pushResult = false;
}
}
if (isPushNotes()) {
boolean allNotesResult = true;
for (final NoteToPush b : notesToPush) {
boolean noteResult = true;
if (b.getnoteMsg() == null) {
listener.getLogger().println("No note to push defined");
return false;
}
b.setEmptyTargetRepoToOrigin();
final String noteMsg = environment.expand(b.getnoteMsg());
final String noteNamespace = environment.expand(b.getnoteNamespace());
final String targetRepo = environment.expand(b.getTargetRepoName());
final boolean noteReplace = b.getnoteReplace();
if (noteResult) {
try {
noteResult = workingDirectory.act(new FileCallable<Boolean>() {
private static final long serialVersionUID = 1L;
public Boolean invoke(File workspace,
VirtualChannel channel) throws IOException {
IGitAPI git = new GitAPI(gitExe, new FilePath(workspace),
listener, environment);
RemoteConfig remote = gitSCM.getRepositoryByName(targetRepo);
if (remote == null) {
listener.getLogger().println("No repository found for target repo name " + targetRepo);
return false;
}
listener.getLogger().println("Adding note \"" + noteMsg + "\" to namespace \""+noteNamespace +"\"" );
if ( noteReplace )
git.addNote( noteMsg, noteNamespace );
else
git.appendNote( noteMsg, noteNamespace );
/**
* Handles migration from earlier version - if we were pushing merges, we'll be
* instantiated but tagsToPush will be null rather than empty.
* @return This.
*/
private Object readResolve() {
// Default unspecified to v0
if(configVersion == null)
this.configVersion = 0L;
if (this.configVersion < 1L) {
if (tagsToPush == null) {
this.pushMerge = true;
}
}
return this;
}
@Extension(ordinal=-1)
public static class DescriptorImpl extends BuildStepDescriptor<Publisher> {
public String getDisplayName() {
return "Git Publisher";
}
@Override
public String getHelpFile() {
return "/plugin/git/gitPublisher.html";
}
/**
* Performs on-the-fly validation on the file mask wildcard.
*
* I don't think this actually ever gets called, but I'm modernizing it anyway.
*
*/
public FormValidation doCheck(@AncestorInPath AbstractProject project, @QueryParameter String value)
throws IOException {
return FilePath.validateFileMask(project.getSomeWorkspace(),value);
}
public FormValidation doCheckTagName(@QueryParameter String value) {
return checkFieldNotEmpty(value, "Tag Name");
}
public FormValidation doCheckBranchName(@QueryParameter String value) {
return checkFieldNotEmpty(value, "Branch Name");
}
public FormValidation doCheckNoteMsg(@QueryParameter String value) {
return checkFieldNotEmpty(value, "Note");
}
public FormValidation doCheckRemote(
@AncestorInPath AbstractProject project, StaplerRequest req)
throws IOException, ServletException {
String remote = req.getParameter("value");
boolean isMerge = req.getParameter("isMerge") != null;
// Added isMerge because we don't want to allow empty remote names
// for tag/branch pushes.
if (remote.length() == 0 && isMerge)
return FormValidation.ok();
FormValidation validation = checkFieldNotEmpty(remote,
"Remote Name");
if (validation.kind != FormValidation.Kind.OK)
return validation;
GitSCM scm = (GitSCM) project.getScm();
if (scm.getRepositoryByName(remote) == null)
return FormValidation
.error("No remote repository configured with name '"
+ remote + "'");
return FormValidation.ok();
}
public boolean isApplicable(Class<? extends AbstractProject> jobType) {
return true;
}
private FormValidation checkFieldNotEmpty(String value, String field) {
value = StringUtils.strip(value);
if (value == null || value.equals("")) {
return FormValidation.error(field + " is required.");
}
return FormValidation.ok();
}
}
public static abstract class PushConfig extends AbstractDescribableImpl<PushConfig> implements Serializable {
private static final long serialVersionUID = 1L;
private String targetRepoName;
public PushConfig(String targetRepoName) {
this.targetRepoName = Util.fixEmptyAndTrim(targetRepoName);
}
public String getTargetRepoName() {
return targetRepoName;
}
public void setTargetRepoName() {
this.targetRepoName = targetRepoName;
}
public void setEmptyTargetRepoToOrigin(){
if (targetRepoName == null || targetRepoName.trim().isEmpty() ){
targetRepoName = "origin";
}
}
}
public static final class BranchToPush extends PushConfig {
private String branchName;
public String getBranchName() {
return branchName;
}
@DataBoundConstructor
public BranchToPush(String targetRepoName, String branchName) {
super(targetRepoName);
this.branchName = Util.fixEmptyAndTrim(branchName);
}
@Extension
public static class DescriptorImpl extends Descriptor<PushConfig> {
@Override
public String getDisplayName() {
return "";
}
}
}
public static final class TagToPush extends PushConfig {
private String tagName;
private String tagMessage;
private boolean createTag;
public String getTagName() {
return tagName;
}
public String getTagMessage() {
return tagMessage;
}
public boolean isCreateTag() {
return createTag;
}
@DataBoundConstructor
public TagToPush(String targetRepoName, String tagName, String tagMessage, boolean createTag) {
super(targetRepoName);
this.tagName = Util.fixEmptyAndTrim(tagName);
this.tagMessage = tagMessage;
this.createTag = createTag;
}
@Extension
public static class DescriptorImpl extends Descriptor<PushConfig> {
@Override
public String getDisplayName() {
return "";
}
}
}
public static final class NoteToPush extends PushConfig {
private String noteMsg;
private String noteNamespace;
private boolean noteReplace;
public String getnoteMsg() {
return noteMsg;
}
public String getnoteNamespace() {
return noteNamespace;
}
public boolean getnoteReplace() {
return noteReplace;
}
@DataBoundConstructor
public NoteToPush( String targetRepoName, String noteMsg, String noteNamespace, boolean noteReplace ) {
super(targetRepoName);
this.noteMsg = Util.fixEmptyAndTrim(noteMsg);
this.noteReplace = noteReplace;
if ( noteNamespace != null && !noteNamespace.trim().isEmpty() )
this.noteNamespace = Util.fixEmptyAndTrim(noteNamespace);
else
this.noteNamespace = "master";
// throw new GitException("Toimii2 " + this.noteMsg + " namespace: "+this.noteNamespace );
}
@Extension
public static class DescriptorImpl extends Descriptor<PushConfig> {
@Override
public String getDisplayName() {
return "";
}
}
}
}
|
package i5.las2peer.testing;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Hashtable;
import i5.las2peer.api.Service;
import i5.las2peer.persistency.DecodingFailedException;
import i5.las2peer.persistency.EncodingFailedException;
import i5.las2peer.persistency.Envelope;
import i5.las2peer.persistency.EnvelopeException;
import i5.las2peer.persistency.MalformedXMLException;
import i5.las2peer.security.L2pSecurityException;
/**
* Simple test service for connectors to have a service with methods to call.
*/
public class TestService extends Service {
private int iCounter = 0;
private String sStorage = "";
/**
* a simple counter, returns the number fo calls within each session.
*
* @return an int
*/
public int counter() {
iCounter++;
return iCounter;
}
/**
* returns the stored string
*
* @return a String
*/
public String getStoredString() {
return sStorage;
}
/**
* Stores a String in the service instance
*
* @param s a String
*/
public void setStoredString(String s) {
sStorage = s;
}
/**
* Throws an Exception
*
* @exception Exception on each call
*/
public void exceptionThrower() throws Exception {
throw new Exception("An Exception to deal with!");
}
/**
* Throws a RuntimeException
*
* @exception RuntimeException on each call
*/
public void runtimeExceptionThrower() throws RuntimeException {
throw new RuntimeException("A RuntimeException to deal with!");
}
/**
* throws an exception that shouldn't be kown at the client.
*
* @exception MyOwnException
*/
public void myExceptionThrower() throws MyOwnException {
throw new MyOwnException("This is an exception not kown to the client!");
}
/**
* returns the sum of an bytearray
*
* @param bytes a byte[]
* @return a long
*/
public long byteAdder(byte[] bytes) {
long result = 0;
for (int i = 0; i < bytes.length; i++)
result += bytes[i];
return result;
}
/**
* returns a Hashtable with one entry to test complex result types
*
* @return a Hashtable
*/
public Hashtable<String, String> getAHash() {
Hashtable<String, String> hsResult = new Hashtable<String, String>();
hsResult.put("x", "y");
return hsResult;
}
/**
* Returns a fixed array with strings.
*
* @return a String[]
*/
public String[] stringArrayReturner() {
return new String[] { "This", "is an", "array", "with Strings" };
}
/**
* Returns a reverted version of the given string array
*
* @param ar a String[]
* @return a String[]
*/
public String[] stringArrayReturner(String[] ar) {
String[] asResult = new String[ar.length];
for (int i = 0; i < asResult.length; i++)
asResult[asResult.length - i - 1] = ar[i];
return asResult;
}
/**
* @return an empty array of strings
*/
public String[] emptyStringArrayReturner() {
return new String[0];
}
/**
* A method with multiple arguments returning a string summary over the argument
*
* @param i an int
* @param s a String
* @param l a long
* @param b a boolean
* @return a String
*/
public String multipleArguments(int i, String s, long l, boolean b) {
return "The method has been called with the following arguments:\n" + "an Integer: " + i + "\n" + "a String: "
+ s + "\n" + "a long: " + l + "\n" + "a boolean: " + b + "\n";
}
/**
* A method with multiple arguments returning a string summary over the argument
*
* @param i an int
* @param s a String
* @param l a long
* @param b a boolean
* @return a String
*/
public String multipleArguments2(Integer i, String s, Long l, Boolean b) {
return "The method has been called with the following arguments:\n" + "an Integer: " + i + "\n" + "a String: "
+ s + "\n" + "a long: " + l + "\n" + "a boolean: " + b + "\n";
}
/**
* throws an Exception indication, that the access (for the current user) has been denied.
*
* @exception L2pSecurityException
*/
public void accessForbidden() throws L2pSecurityException {
throw new L2pSecurityException("access forbidden!");
}
/**
* concats an array of String to one single String. Basically for testing array of Strings as invocation parameter.
*
* @param strings a String[]
* @return a String
*/
public String concatStrings(String[] strings) {
if (strings == null)
return "";
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < strings.length; i++)
buffer.append(strings[i]);
return buffer.toString();
}
/**
* simply returns the given byte array for connector coding tests
*
* @param ab a byte[]
* @return a byte[]
*/
public byte[] byteArrayReturner(byte[] ab) {
return ab;
}
/**
* simply returns the given long array for connector coding testing
*
* @param al a long[]
* @return a long[]
*/
public long[] longArrayReturner(long[] al) {
return al;
}
/**
* simply returns the given long value for connector coding testing
*
* @param l a long
* @return a long
*/
public long longReturner(long l) {
return l;
}
/**
* Returns the given date increased by one day. This may be used as test for delivering Serializables in connectors.
*
* @param input a Date
* @return a Date
*/
public java.util.Date addADay(java.util.Date input) {
long time = input.getTime();
time += 1000 * 60 * 60 * 24;
java.util.Date result = new java.util.Date(time);
return result;
}
/**
* access to the property file
*
* @return hashtable with properties
*/
public Hashtable<String, String> getProps() {
return getProperties();
}
private Envelope cache = null;
/**
* test for envelopes: store a string in an envelope
*
* @return previously stored string
* @throws EnvelopeException
* @throws L2pSecurityException
*/
public String getEnvelopeString() throws EnvelopeException, L2pSecurityException {
if (cache == null)
return "nothing stored!";
cache.open();
String result = cache.getContentAsString();
cache.close();
return result;
}
/**
* test for envelopes: get stored String
*
* @param s
* @throws UnsupportedEncodingException
* @throws EncodingFailedException
* @throws DecodingFailedException
*/
public void storeEnvelopeString(String s)
throws UnsupportedEncodingException, EncodingFailedException, DecodingFailedException {
cache = new Envelope((String) s, getContext().getMainAgent());
cache.close();
}
private Envelope groupCache = null;
/**
* get a string stored for the Group1
*
* @return a simple stored string
* @throws L2pSecurityException
* @throws EnvelopeException
*/
public String getGroupEnvelopeString() throws L2pSecurityException, EnvelopeException {
if (groupCache == null)
return "nothing stored";
groupCache.open();
String result = groupCache.getContentAsString();
groupCache.close();
return result;
}
/**
* store a simple string encrypted for the group
*
* @param store a string to store for the group
* @throws EncodingFailedException
* @throws IOException
* @throws MalformedXMLException
* @throws DecodingFailedException
* @throws UnsupportedEncodingException
*/
public void storeGroupEnvelopeString(String store) throws EncodingFailedException, UnsupportedEncodingException,
DecodingFailedException, MalformedXMLException, IOException {
groupCache = new Envelope(store, MockAgentFactory.getGroup1());
groupCache.close();
}
}
|
package io.github.ssoloff.secret;
import java.lang.reflect.Method;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.function.Consumer;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.security.auth.DestroyFailedException;
import javax.security.auth.Destroyable;
/**
* A container for a value that must be kept secret and only disclosed for as
* short of a time as possible.
*
* <p>
* This class is not thread safe.
* </p>
*/
public final class Secret implements AutoCloseable {
private static final String ALGORITHM = "AES";
private static final int ALGORITHM_KEY_SIZE_IN_BITS = 128;
private final byte[] ciphertext;
private final SecretKey key;
private Secret(final SecretKey key, final byte[] ciphertext) {
this.ciphertext = ciphertext;
this.key = key;
}
private static byte[] cipher(final int opmode, final SecretKey key, final byte[] input) throws SecretException {
try {
final Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(opmode, key);
return cipher.doFinal(input);
} catch (final GeneralSecurityException e) {
throw new SecretException("failed to apply cipher", e);
}
}
@Override
public void close() throws Exception {
scrub(ciphertext);
scrub(key);
}
private static byte[] decrypt(final SecretKey key, final byte[] ciphertext) throws SecretException {
return cipher(Cipher.DECRYPT_MODE, key, ciphertext);
}
private static byte[] encrypt(final SecretKey key, final byte[] plaintext) throws SecretException {
return cipher(Cipher.ENCRYPT_MODE, key, plaintext);
}
public static Secret fromPlaintext(final byte[] plaintext) throws SecretException {
final SecretKey key = generateSecretKey();
final byte[] ciphertext = encrypt(key, plaintext);
return new Secret(key, ciphertext);
}
private static SecretKey generateSecretKey() throws SecretException {
try {
final KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
keyGenerator.init(ALGORITHM_KEY_SIZE_IN_BITS);
return keyGenerator.generateKey();
} catch (final GeneralSecurityException e) {
throw new SecretException("failed to generate secret key", e);
}
}
private static boolean isDestroyable(final Destroyable destroyable) {
try {
final Method destroyMethod = destroyable.getClass().getMethod("destroy");
return !destroyMethod.isDefault();
} catch (final NoSuchMethodException e) {
throw new AssertionError("should never happen", e);
}
}
private static void scrub(final byte[] bytes) {
Arrays.fill(bytes, (byte) 0);
}
private static void scrub(final SecretKey key) throws DestroyFailedException {
if (!key.isDestroyed() && isDestroyable(key)) {
key.destroy();
}
}
/**
* Allows the specified consumer to perform an operation on the plaintext
* secret value.
*
* @param consumer
* The consumer to receive the plaintext secret value.
*
* @throws SecretException
* If an error occurs decrypting the secret or the secret has
* been closed.
*/
public void use(final Consumer<byte[]> consumer) throws SecretException {
final byte[] plaintext = decrypt(key, ciphertext);
try {
consumer.accept(plaintext);
} finally {
scrub(plaintext);
}
}
}
|
package io.herrmann.generator;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* This class allows specifying Python generator-like sequences. For examples,
* see the JUnit test case.
*
* The implementation uses a separate Thread to produce the sequence items. This
* is certainly not as fast as eg. a for-loop, but not horribly slow either. On
* a machine with a dual core i5 CPU @ 2.67 GHz, 1000 items can be produced in
* < 0.03s.
*
* By overriding finalize(), the class takes care not to leave any Threads
* running longer than necessary.
*/
public abstract class Generator<T> implements Iterable<T> {
private class Condition {
private boolean isSet;
public synchronized void set() {
isSet = true;
notify();
}
public synchronized void await() throws InterruptedException {
try {
if (isSet)
return;
wait();
} finally {
isSet = false;
}
}
}
static ThreadGroup THREAD_GROUP;
Thread producer;
private boolean hasFinished;
private final Condition itemAvailableOrHasFinished = new Condition();
private final Condition itemRequested = new Condition();
private T nextItem;
private boolean nextItemAvailable;
private RuntimeException exceptionRaisedByProducer;
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
@Override
public boolean hasNext() {
return waitForNext();
}
@Override
public T next() {
if (!waitForNext())
throw new NoSuchElementException();
nextItemAvailable = false;
return nextItem;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
private boolean waitForNext() {
if (nextItemAvailable)
return true;
if (hasFinished)
return false;
if (producer == null)
startProducer();
itemRequested.set();
try {
itemAvailableOrHasFinished.await();
} catch (InterruptedException e) {
hasFinished = true;
}
if (exceptionRaisedByProducer != null)
throw exceptionRaisedByProducer;
return !hasFinished;
}
};
}
protected abstract void run() throws InterruptedException;
protected void yield(T element) throws InterruptedException {
nextItem = element;
nextItemAvailable = true;
itemAvailableOrHasFinished.set();
itemRequested.await();
}
private void startProducer() {
assert producer == null;
if (THREAD_GROUP == null)
THREAD_GROUP = new ThreadGroup("generatorfunctions");
producer = new Thread(THREAD_GROUP, new Runnable() {
@Override
public void run() {
try {
itemRequested.await();
Generator.this.run();
} catch (InterruptedException e) {
// No need to do anything here; Remaining steps in run()
// will cleanly shut down the thread.
} catch (RuntimeException e) {
exceptionRaisedByProducer = e;
}
hasFinished = true;
itemAvailableOrHasFinished.set();
}
});
producer.setDaemon(true);
producer.start();
}
@Override
protected void finalize() throws Throwable {
producer.interrupt();
producer.join();
super.finalize();
}
}
|
package io.nats.client;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static io.nats.client.Constants.*;
abstract class SubscriptionImpl implements Subscription {
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
final Lock mu = new ReentrantLock();
long sid; //int64 in Go
// Subject that represents this subscription. This can be different
// than the received subject inside a Msg if this is a wildcard.
String subject = null;
// Optional queue group name. If present, all subscriptions with the
// same name will form a distributed queue, and each message will
// only be processed by one member of the group.
String queue;
// Number of messages delivered on this subscription
long msgs;
AtomicLong delivered = new AtomicLong(); // uint64
long bytes; // uint64
// int pendingMax; // uint64 in Go, int here due to underlying data structure
long max; // AutoUnsubscribe max
protected boolean closed;
protected boolean connClosed;
// slow consumer flag
boolean sc;
ConnectionImpl conn = null;
Channel<Message> mch;
// Pending stats, async subscriptions, high-speed etc.
int pMsgs;
int pBytes;
int pMsgsMax; // highest number of pending msgs
int pBytesMax; // highest number of pending bytes
int pMsgsLimit = 65536;
long pBytesLimit = pMsgsLimit * 1024;
int dropped;
SubscriptionImpl(ConnectionImpl conn, String subject, String queue, int maxPendingMsgs,
long maxPendingBytes) {
this.conn = conn;
this.subject = subject;
this.queue = queue;
// if (conn != null) {
// this.pendingMax = conn.getOptions().getMaxPendingMsgs();
this.setMaxPendingMsgs(maxPendingMsgs);
this.mch = new Channel<Message>();
}
void closeChannel() {
mu.lock();
try {
if (mch != null) {
mch.close();
mch = null;
}
} finally {
mu.unlock();
}
}
@Override
public String getSubject() {
return subject;
}
public String getQueue() {
// if (queue==null)
// return "";
return queue;
}
public Channel<Message> getChannel() {
return this.mch;
}
public void setChannel(Channel<Message> ch) {
this.mch = ch;
}
public boolean tallyMessage(long length) {
mu.lock();
try
{
// logger.trace("getMax()={}, msgs={}",
// max, msgs);
if (max > 0 && msgs > max)
return true;
this.msgs++;
this.bytes += bytes;
} finally {
mu.unlock();
}
return false;
}
protected void handleSlowConsumer(Message msg) {
dropped++;
conn.processSlowConsumer(this);
pMsgs
if (msg.getData() != null) {
pBytes -= msg.getData().length;
}
}
protected long tallyDeliveredMessage(Message msg) {
delivered.incrementAndGet();
if (msg.getData() != null) {
pBytes -= msg.getData().length;
}
pMsgs
return delivered.get();
}
// returns false if the message could not be added because
// the channel is full, true if the message was added
// to the channel.
boolean addMessage(Message m)
{
// logger.trace("Entered addMessage({}, count={} max={}",
// mch.getCount(),
// max);
// Subscription internal stats
pMsgs++;
if (pMsgs > pMsgsMax) {
pMsgsMax = pMsgs;
}
if (m.getData() != null) {
pBytes += m.getData().length;
}
if (pBytes > pBytesMax) {
pBytesMax = pBytes;
}
// Check for a Slow Consumer
if (pMsgs > pMsgsLimit || pBytes > pBytesLimit) {
handleSlowConsumer(m);
return false;
}
if (mch != null)
{
if (mch.getCount() >= getMaxPendingMsgs())
{
handleSlowConsumer(m);
// logger.trace("MAXIMUM COUNT ({}) REACHED FOR SID: {}",
// max, getSid());
return false;
}
else
{
sc = false;
mch.add(m);
// logger.trace("Added message to channel: " + m);
}
} // mch != null
return true;
}
public boolean isValid() {
mu.lock();
try {
return (conn != null);
} finally {
mu.unlock();
}
}
@Override
public void unsubscribe() throws IOException
{
ConnectionImpl c;
mu.lock();
try
{
c = this.conn;
} finally {
mu.unlock();
}
if (c == null)
throw new IllegalStateException(ERR_BAD_SUBSCRIPTION);
c.unsubscribe(this, 0);
}
@Override
public void autoUnsubscribe(int max) throws IOException {
ConnectionImpl c = null;
mu.lock();
try {
if (conn == null)
throw new IllegalStateException(ERR_BAD_SUBSCRIPTION);
c = conn;
} finally {
mu.unlock();
}
c.unsubscribe(this, max);
}
@Override
public void close() {
try {
logger.trace("Calling unsubscribe from AutoCloseable.close()");
unsubscribe();
} catch (Exception e) {
// Just ignore. This is for AutoCloseable.
}
}
protected long getSid() {
return sid;
}
protected void setSid(long id) {
this.sid = id;
}
/**
* @return the maxPendingMsgs
*/
@Override
public int getMaxPendingMsgs() {
return this.pMsgsLimit;
}
/**
* @return the maxPendingBytes
*/
@Override
public long getMaxPendingBytes() {
return this.pBytesLimit;
}
/**
* @param pending the pending to set
*/
@Override
public void setMaxPendingMsgs(int pending) {
pMsgsLimit = pending;
if (pending<=0) {
pMsgsLimit = ConnectionFactory.DEFAULT_MAX_PENDING_MSGS;
}
}
/**
* @param pending the pending to set
*/
@Override
public void setMaxPendingBytes(long pending) {
this.pBytesLimit = pending;
if (pending<=0) {
pBytesLimit = ConnectionFactory.DEFAULT_MAX_PENDING_BYTES;
}
}
protected Connection getConnection() {
return (Connection)this.conn;
}
protected void setConnection(ConnectionImpl conn) {
this.conn = conn;
}
public int getQueuedMessageCount() {
if (this.mch != null)
return this.mch.getCount();
else
return 0;
}
public String toString() {
String s = String.format("{subject=%s, queue=%s, sid=%d, max=%d, delivered=%d, queued=%d, maxPendingMsgs=%d, maxPendingBytes=%d, valid=%b}",
getSubject(),
getQueue()==null ? "null" : getQueue(),
getSid(),
getMax(),
delivered.get(),
getQueuedMessageCount(),
getMaxPendingMsgs(),
getMaxPendingBytes(),
isValid());
return s;
}
protected void setSlowConsumer(boolean sc) {
this.sc = sc;
}
protected boolean isSlowConsumer() {
return this.sc;
}
protected boolean processMsg(Message msg) {
return true;
}
protected void setMax(long max) {
this.max = max;
}
protected long getMax() {
return max;
}
Lock getLock() {
return this.mu;
}
}
|
package kr.ac.ajou.dsd.kda.model;
import javax.persistence.Embeddable;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
@Embeddable
public class Rating {
private int numUsersRated = 0;
private int rating = 0;
public Rating () {
}
@JsonCreator
public Rating(int rating){
setRating(rating);
}
@JsonValue
public int getRating() {
return rating;
}
public void setRating(int ratingNew) {
if (ratingNew > 5 || ratingNew < 0) return;
this.rating = (rating * numUsersRated + ratingNew) / (numUsersRated + 1);
this.numUsersRated++;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + numUsersRated;
result = prime * result + rating;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Rating other = (Rating) obj;
if (numUsersRated != other.numUsersRated)
return false;
if (rating != other.rating)
return false;
return true;
}
}
|
package ljfa.tntutils.proxy;
import ljfa.tntutils.Config;
import ljfa.tntutils.TNTUtils;
import ljfa.tntutils.blocks.BlockReplacedTNT;
import ljfa.tntutils.handlers.EntityJoinHandler;
import ljfa.tntutils.handlers.ExplosionHandler;
import ljfa.tntutils.util.LogHelper;
import ljfa.tntutils.util.ReflectionHelper;
import ljfa.tntutils.util.Utils;
import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.util.ObjectIntIdentityMap;
import net.minecraft.util.RegistryNamespaced;
import net.minecraft.util.RegistrySimple;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.registry.GameData;
import com.google.common.collect.BiMap;
public class CommonProxy {
public void preInit(FMLPreInitializationEvent event) {
Config.loadConfig(event.getSuggestedConfigurationFile());
if(Config.preventChainExpl) {
TNTUtils.replaced_tnt = new BlockReplacedTNT().setHardness(0.0F).setStepSound(Block.soundTypeGrass).setUnlocalizedName("tnt");
replaceVanillaTNT();
}
}
public void init(FMLInitializationEvent event) {
MinecraftForge.EVENT_BUS.register(new ExplosionHandler());
if(Config.disableTNT || Config.disableTNTMinecart)
MinecraftForge.EVENT_BUS.register(new EntityJoinHandler());
}
public void postInit(FMLPostInitializationEvent event) {
}
@SuppressWarnings("unchecked")
private void replaceVanillaTNT() {
try {
LogHelper.info("About to replace Vanilla TNT");
//Get TNT object to replace
Block oldTNT = (Block)Block.blockRegistry.getObject("tnt");
int tntID = Block.blockRegistry.getIDForObject(oldTNT);
//Replace it in the "underlyingIntegerMap"
Block.blockRegistry.underlyingIntegerMap.put(TNTUtils.replaced_tnt, tntID);
//Replace it in the "registryObjects"
BiMap<ResourceLocation, Block> regMap = (BiMap)Block.blockRegistry.registryObjects;
regMap.forcePut(new ResourceLocation("minecraft:tnt"), TNTUtils.replaced_tnt);
//Replace it in the associated ItemBlock
ItemBlock tntItem = (ItemBlock)Item.itemRegistry.getObjectById(tntID);
tntItem.block = TNTUtils.replaced_tnt;
//Add it to the Block -> Item map
GameData.getBlockItemMap().put(TNTUtils.replaced_tnt, tntItem);
//Replace it in the Blocks class
Blocks.tnt = TNTUtils.replaced_tnt;
LogHelper.info("Replaced Vanilla TNT");
} catch(Exception ex) {
throw new RuntimeException("Failed to replace Vanilla TNT!", ex);
}
}
}
|
package mcjty.rftools.items;
import mcjty.lib.varia.Logging;
import mcjty.rftools.GeneralConfiguration;
import mcjty.rftools.RFTools;
import mcjty.rftools.varia.EntityTools;
import net.minecraft.client.renderer.ItemMeshDefinition;
import net.minecraft.client.renderer.block.model.ModelBakery;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityList;
import net.minecraft.entity.MultiPartEntityPart;
import net.minecraft.entity.boss.EntityDragon;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ActionResult;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumHand;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.world.World;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.fml.common.registry.ForgeRegistries;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.lwjgl.input.Keyboard;
import java.util.List;
//import net.minecraft.entity.monster.SkeletonType;
public class SyringeItem extends GenericRFToolsItem {
public SyringeItem() {
super("syringe");
setMaxStackSize(1);
}
@Override
@SideOnly(Side.CLIENT)
public void initModel() {
for (int i = 0 ; i <= 5 ; i++) {
String domain = getRegistryName().getResourceDomain();
String path = getRegistryName().getResourcePath();
ModelBakery.registerItemVariants(this, new ModelResourceLocation(new ResourceLocation(domain, path + i), "inventory"));
}
ModelLoader.setCustomMeshDefinition(this, new ItemMeshDefinition() {
@Override
public ModelResourceLocation getModelLocation(ItemStack stack) {
NBTTagCompound tagCompound = stack.getTagCompound();
int level = 0;
if (tagCompound != null) {
level = tagCompound.getInteger("level");
}
if (level <= 0) {
level = 0;
} else if (level >= GeneralConfiguration.maxMobInjections) {
level = 5;
} else {
level = ((level-1) * 4 / (GeneralConfiguration.maxMobInjections-1)) + 1;
}
String domain = getRegistryName().getResourceDomain();
String path = getRegistryName().getResourcePath();
return new ModelResourceLocation(new ResourceLocation(domain, path + level), "inventory");
}
});
}
@Override
public int getMaxItemUseDuration(ItemStack stack) {
return 1;
}
@Override
public ActionResult<ItemStack> onItemRightClick(World world, EntityPlayer player, EnumHand hand) {
ItemStack stack = player.getHeldItem(hand);
if (!world.isRemote) {
NBTTagCompound tagCompound = stack.getTagCompound();
if (tagCompound != null) {
String mobName = getMobName(stack);
if (mobName != null) {
Logging.message(player, TextFormatting.BLUE + "Mob: " + mobName);
}
int level = tagCompound.getInteger("level");
level = level * 100 / GeneralConfiguration.maxMobInjections;
Logging.message(player, TextFormatting.BLUE + "Essence level: " + level + "%");
}
return new ActionResult<>(EnumActionResult.SUCCESS, stack);
}
return new ActionResult<>(EnumActionResult.SUCCESS, stack);
}
@Override
public boolean onLeftClickEntity(ItemStack stack, EntityPlayer player, Entity entity) {
Class<? extends Entity> clazz = findSelectedMobClass(entity);
if (clazz != null) {
String prevMobId = null;
NBTTagCompound tagCompound = stack.getTagCompound();
if (tagCompound != null) {
prevMobId = EntityTools.fixEntityId(tagCompound.getString("mobId"));
} else {
tagCompound = new NBTTagCompound();
stack.setTagCompound(tagCompound);
}
String id = findSelectedMobId(clazz, entity);
if (id != null && !id.isEmpty()) {
if (prevMobId == null || !prevMobId.equals(id)) {
tagCompound.setString("mobName", findSelectedMobName(entity));
tagCompound.setString("mobId", id);
tagCompound.setInteger("level", 1);
} else {
int level = tagCompound.getInteger("level");
level++;
if (level > GeneralConfiguration.maxMobInjections) {
level = GeneralConfiguration.maxMobInjections;
}
tagCompound.setInteger("level", level);
}
}
}
return super.onLeftClickEntity(stack, player, entity);
}
private String findSelectedMobId(Class<? extends Entity> clazz, Entity entity) {
ResourceLocation key = EntityList.getKey(clazz);
if (key != null) {
return key.toString();
}
if (clazz.isAssignableFrom(MultiPartEntityPart.class)) {
MultiPartEntityPart mp = (MultiPartEntityPart) entity;
if (mp.parent instanceof EntityDragon) {
return "minecraft:ender_dragon";
}
}
return null;
}
private Class<? extends Entity> findSelectedMobClass(Entity entity) {
// First try to find an exact matching class.
return entity.getClass();
}
private String findSelectedMobName(Entity entity) {
return entity.getName();
}
@SideOnly(Side.CLIENT)
@Override
public void addInformation(ItemStack itemStack, World player, List<String> list, ITooltipFlag whatIsThis) {
super.addInformation(itemStack, player, list, whatIsThis);
NBTTagCompound tagCompound = itemStack.getTagCompound();
if (tagCompound != null) {
String mobName = getMobName(itemStack);
if (mobName != null) {
list.add(TextFormatting.BLUE + "Mob: " + mobName);
}
int level = tagCompound.getInteger("level");
level = level * 100 / GeneralConfiguration.maxMobInjections;
list.add(TextFormatting.BLUE + "Essence level: " + level + "%");
}
if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT)) {
list.add(TextFormatting.WHITE + "Use this to extract essence from mobs");
} else {
list.add(TextFormatting.WHITE + RFTools.SHIFT_MESSAGE);
}
}
public static ItemStack createMobSyringe(Class<? extends Entity> mobClass) {
String id = EntityTools.findEntityIdByClass(mobClass);
// String name = EntityTools.findEntityLocNameByClass(mobClass);
String name = ForgeRegistries.ENTITIES.getValue(new ResourceLocation(id)).getName();
return createMobSyringe(id, name);
}
private static ItemStack createMobSyringe(String id, String name) {
ItemStack syringe = new ItemStack(ModItems.syringeItem);
NBTTagCompound tagCompound = new NBTTagCompound();
tagCompound.setString("mobId", id);
if (name == null || name.isEmpty()) {
name = id;
}
tagCompound.setString("mobName", name);
tagCompound.setInteger("level", GeneralConfiguration.maxMobInjections);
syringe.setTagCompound(tagCompound);
return syringe;
}
public static String getMobId(ItemStack stack) {
NBTTagCompound tagCompound = stack.getTagCompound();
if (tagCompound != null) {
String mob = tagCompound.getString("mobId");
if (mob == null) {
// For compatibility only!
return tagCompound.getString("mobName");
} else {
mob = EntityTools.fixEntityId(mob);
}
return mob;
}
return null;
}
public static String getMobName(ItemStack stack) {
NBTTagCompound tagCompound = stack.getTagCompound();
if (tagCompound != null) {
String mob = tagCompound.getString("mobName");
if (mob == null || "unknown".equals(mob)) {
if (tagCompound.hasKey("mobId")) {
String mobId = tagCompound.getString("mobId");
mobId = EntityTools.fixEntityId(mobId);
return mobId;
} else {
return "?";
}
}
return mob;
}
return null;
}
}
|
package net.ilexiconn.magister;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import net.ilexiconn.magister.adapter.*;
import net.ilexiconn.magister.container.*;
import net.ilexiconn.magister.container.sub.Privilege;
import net.ilexiconn.magister.exeption.PrivilegeException;
import net.ilexiconn.magister.handler.*;
import net.ilexiconn.magister.util.AndroidUtil;
import net.ilexiconn.magister.util.HttpUtil;
import net.ilexiconn.magister.util.LogUtil;
import org.apache.http.auth.InvalidCredentialsException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.security.InvalidParameterException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* The main API class. You can get a new instance by running {@link Magister#login(School, String, String)}.
*
* @since 0.1.0
* @author iLexiconn
*/
public class Magister {
public static final String VERSION = "0.1.0-SNAPSHOT";
public Gson gson = new GsonBuilder()
.registerTypeAdapter(Profile.class, new ProfileAdapter())
.registerTypeAdapter(Study[].class, new StudyAdapter())
.create();
public School school;
public Version version;
public Session session;
public Profile profile;
public Study[] studies;
public Study currentStudy;
private List<IHandler> handlerList = new ArrayList<IHandler>();
private Magister() {
handlerList.add(new GradeHandler(this));
handlerList.add(new PresenceHandler(this));
handlerList.add(new ContactHandler(this));
handlerList.add(new MessageHandler(this));
handlerList.add(new AppointmentHandler(this));
handlerList.add(new ELOHandler(this));
}
/**
* Create a new {@link Magister} instance by logging in. Will return null if login fails.
*
* @param school the {@link School} instance. Can't be null.
* @param username the username of the profile. Can't be null.
* @param password the password of the profile. Can't be null.
* @return the new {@link Magister} instance, null if login fails.
* @throws IOException if there is no active internet connection.
* @throws ParseException if parsing the date fails.
* @throws InvalidParameterException if one of the arguments is null.
*/
public static Magister login(School school, String username, String password) throws IOException, ParseException, InvalidParameterException {
if (school == null || username == null || username.isEmpty() || password == null || password.isEmpty()) {
throw new InvalidParameterException("Parameters can't be null or empty!");
}
Magister magister = new Magister();
AndroidUtil.checkAndroid();
magister.school = school;
magister.version = magister.gson.fromJson(HttpUtil.httpGet(school.url + "/api/versie"), Version.class);
HttpUtil.httpDelete(school.url + "/api/sessies/huidige");
Map<String, String> nameValuePairMap = new HashMap<String, String>();
nameValuePairMap.put("Gebruikersnaam", username);
nameValuePairMap.put("Wachtwoord", password);
magister.session = magister.gson.fromJson(HttpUtil.httpPost(school.url + "/api/sessies", nameValuePairMap), Session.class);
if (!magister.session.state.equals("active")) {
LogUtil.printError("Invalid credentials", new InvalidCredentialsException());
return null;
}
magister.profile = magister.gson.fromJson(HttpUtil.httpGet(school.url + "/api/account"), Profile.class);
magister.studies = magister.gson.fromJson(HttpUtil.httpGet(school.url + "/api/personen/" + magister.profile.id + "/aanmeldingen"), Study[].class);
DateFormat format = new SimpleDateFormat("y-m-d", Locale.ENGLISH);
Date now = new Date();
for (Study study : magister.studies) {
if (format.parse(study.endDate.substring(0, 10)).after(now)) {
magister.currentStudy = study;
}
}
return magister;
}
/**
* Check if this user has the following privilege.
*
* @param privilege the privilege name.
* @return true if the profile has the privilege.
*/
public boolean hasPrivilege(String privilege) {
for (Privilege p : profile.privileges) {
if (p.name.equals(privilege)) {
return true;
}
}
return false;
}
/**
* Get the current profile picture in the default size.
*
* @return the current profile picture in the default size.
* @throws IOException if there is no active internet connection.
*/
public BufferedImage getImage() throws IOException {
return getImage(42, 64, false);
}
/**
* Get the current profile picture.
*
* @param width the width.
* @param height the height.
* @param crop true if not in default ratio.
* @return the current profile picture.
* @throws IOException if there is no active internet connection.
*/
public BufferedImage getImage(int width, int height, boolean crop) throws IOException {
HttpGet get = new HttpGet(school.url + "/api/personen/" + profile.id + "/foto" + (width != 42 || height != 64 || crop ? "?width=" + width + "&height=" + height + "&crop=" + crop : ""));
CloseableHttpResponse responseGet = HttpUtil.getHttpClient().execute(get);
return ImageIO.read(responseGet.getEntity().getContent());
}
/**
* Change the password of the current profile.
*
* @param oldPassword the current password.
* @param newPassword the new password.
* @param newPassword2 the new password.
* @return a String with the response. 'Successful' if the password changed successfully.
* @throws IOException if there is no active internet connection.
* @throws InvalidParameterException if one of the parameters is null or empty, or when the two new passwords aren't
* the same.
* @throws PrivilegeException if the profile doesn't have the privilege to perform this action.
*/
public String changePassword(String oldPassword, String newPassword, String newPassword2) throws IOException, InvalidParameterException, PrivilegeException {
if (!hasPrivilege("WachtwoordWijzigen")) {
throw new PrivilegeException();
}
if (oldPassword == null || oldPassword.isEmpty() || newPassword == null || newPassword.isEmpty() || newPassword2 == null || newPassword2.isEmpty()) {
throw new InvalidParameterException("Parameters can't be null or empty!");
} else if (!newPassword.equals(newPassword2)) {
throw new InvalidParameterException("New passwords don't match!");
}
Map<String, String> nameValuePairMap = new HashMap<String, String>();
nameValuePairMap.put("HuidigWachtwoord", oldPassword);
nameValuePairMap.put("NieuwWachtwoord", newPassword);
nameValuePairMap.put("PersoonId", profile.id + "");
nameValuePairMap.put("WachtwoordBevestigen", newPassword2);
Response response = gson.fromJson(HttpUtil.httpPost(school.url + "/api/personen/account/wachtwoordwijzigen?persoonId=" + profile.id, nameValuePairMap), Response.class);
if (response == null) {
return "Successful";
} else {
LogUtil.printError(response.message, new InvalidParameterException());
return response.message;
}
}
public <T extends IHandler> T getHandler(Class<T> type) throws PrivilegeException {
for (IHandler handler : handlerList) {
if (handler.getClass() == type) {
if (!hasPrivilege(handler.getPrivilege())) {
throw new PrivilegeException();
}
return (T) handler;
}
}
return null;
}
}
|
package net.jforum.search;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.IOException;
import java.util.*;
import net.jforum.dao.AttachmentDAO;
import net.jforum.dao.DataAccessDriver;
import net.jforum.entities.Attachment;
import net.jforum.entities.AttachmentInfo;
import net.jforum.entities.Post;
import net.jforum.exceptions.SearchException;
import net.jforum.util.preferences.ConfigKeys;
import net.jforum.util.preferences.SystemGlobals;
import org.apache.log4j.Logger;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Field.Index;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.metadata.Property;
import org.apache.tika.metadata.TikaCoreProperties;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.sax.BodyContentHandler;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.Parser;
import org.xml.sax.ContentHandler;
/**
* @author Rafael Steil
* @version $Id$
*/
public class LuceneIndexer
{
private static final Logger LOGGER = Logger.getLogger(LuceneIndexer.class);
private LuceneSettings settings;
private Directory ramDirectory;
private IndexWriter ramWriter;
private int ramNumDocs;
private List<NewDocumentAdded> newDocumentAddedList = new ArrayList<NewDocumentAdded>();
private boolean indexAttachments = SystemGlobals.getBoolValue(ConfigKeys.LUCENE_INDEX_ATTACHMENTS);
private AttachmentDAO attachDAO;
private String attachDir = SystemGlobals.getValue(ConfigKeys.ATTACHMENTS_STORE_DIR);
public LuceneIndexer(final LuceneSettings settings)
{
this.settings = settings;
this.createRAMWriter();
this.attachDAO = DataAccessDriver.getInstance().newAttachmentDAO();
}
public void watchNewDocuDocumentAdded(NewDocumentAdded newDoc)
{
this.newDocumentAddedList.add(newDoc);
}
public void batchCreate(final Post post)
{
synchronized (LOGGER) {
try {
final Document document = this.createDocument(post);
this.ramWriter.addDocument(document);
this.flushRAMDirectoryIfNecessary();
}
catch (IOException e) {
throw new SearchException(e);
}
}
}
private void createRAMWriter()
{
try {
if (this.ramWriter != null) {
this.ramWriter.close();
}
this.ramDirectory = new RAMDirectory();
final IndexWriterConfig conf = new IndexWriterConfig(LuceneSettings.version, this.settings.analyzer()).setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);
this.ramWriter = new IndexWriter(this.ramDirectory, conf);
this.ramNumDocs = SystemGlobals.getIntValue(ConfigKeys.LUCENE_INDEXER_RAM_NUMDOCS);
}
catch (IOException e) {
throw new SearchException(e);
}
}
private void flushRAMDirectoryIfNecessary()
{
if (this.ramWriter.maxDoc() >= this.ramNumDocs) {
this.flushRAMDirectory();
}
}
public void flushRAMDirectory()
{
synchronized (LOGGER) {
IndexWriter writer = null;
try {
final IndexWriterConfig conf = new IndexWriterConfig(LuceneSettings.version, this.settings.analyzer()).setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);
writer = new IndexWriter(this.settings.directory(), conf);
this.ramWriter.commit();
this.ramWriter.close();
writer.addIndexes(new Directory[] { this.ramDirectory });
writer.forceMergeDeletes();
this.createRAMWriter();
}
catch (IOException e) {
throw new SearchException(e);
}
finally {
if (writer != null) {
try {
writer.commit();
writer.close();
this.notifyNewDocumentAdded();
}
catch (Exception e) {
LOGGER.error(e.toString(), e);
}
}
}
}
}
public void create(final Post post)
{
synchronized (LOGGER) {
IndexWriter writer = null;
try {
final IndexWriterConfig conf = new IndexWriterConfig(LuceneSettings.version, this.settings.analyzer()).setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);
writer = new IndexWriter(this.settings.directory(), conf);
final Document document = this.createDocument(post);
writer.addDocument(document);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Indexed " + document);
}
}
catch (Exception e) {
LOGGER.error(e.toString(), e);
}
finally {
if (writer != null) {
try {
writer.commit();
writer.close();
this.notifyNewDocumentAdded();
}
catch (Exception e) {
LOGGER.error(e.toString(), e);
}
}
}
}
}
public void update(final Post post)
{
if (this.performDelete(post)) {
this.create(post);
}
}
private Document createDocument(final Post post)
{
Document doc = new Document();
doc.add(new Field(SearchFields.Keyword.POST_ID, String.valueOf(post.getId()), Store.YES, Index.NOT_ANALYZED));
doc.add(new Field(SearchFields.Keyword.FORUM_ID, String.valueOf(post.getForumId()), Store.YES, Index.NOT_ANALYZED));
doc.add(new Field(SearchFields.Keyword.TOPIC_ID, String.valueOf(post.getTopicId()), Store.YES, Index.NOT_ANALYZED));
doc.add(new Field(SearchFields.Keyword.USER_ID, String.valueOf(post.getUserId()), Store.YES, Index.NOT_ANALYZED));
doc.add(new Field(SearchFields.Keyword.DATE, this.settings.formatDateTime(post.getTime()), Store.YES, Index.NOT_ANALYZED));
doc.add(new Field(SearchFields.Indexed.SUBJECT, post.getSubject(), Store.NO, Index.ANALYZED));
doc.add(new Field(SearchFields.Indexed.CONTENTS, post.getText(), Store.NO, Index.ANALYZED));
if (indexAttachments && post.hasAttachments()) {
for (Attachment att : attachDAO.selectAttachments(post.getId())) {
AttachmentInfo info = att.getInfo();
doc.add(new Field(SearchFields.Indexed.CONTENTS, info.getComment(), Field.Store.NO, Field.Index.ANALYZED));
File f = new File(attachDir + File.separatorChar + info.getPhysicalFilename());
LOGGER.debug("indexing "+f.getName());
InputStream is = null;
try {
Metadata metadata = new Metadata();
metadata.set(Metadata.RESOURCE_NAME_KEY, f.getName());
is = new FileInputStream(f);
Parser parser = new AutoDetectParser();
ContentHandler handler = new BodyContentHandler(-1);
//-1 disables the character size limit; otherwise only the first 100.000 characters are indexed
ParseContext context = new ParseContext();
context.set(Parser.class, parser);
Set<String> textualMetadataFields = new HashSet<String>();
textualMetadataFields.add(TikaCoreProperties.TITLE.getName());
textualMetadataFields.add(TikaCoreProperties.COMMENTS.getName());
textualMetadataFields.add(TikaCoreProperties.KEYWORDS.getName());
textualMetadataFields.add(TikaCoreProperties.DESCRIPTION.getName());
textualMetadataFields.add(TikaCoreProperties.KEYWORDS.getName());
parser.parse(is, handler, metadata, context);
doc.add(new Field(SearchFields.Indexed.CONTENTS, handler.toString(), Field.Store.NO, Field.Index.ANALYZED));
String[] names = metadata.names();
for (int j=0; j<names.length; j++) {
String value = metadata.get(names[j]);
if (textualMetadataFields.contains(names[j])) {
doc.add(new Field(SearchFields.Indexed.CONTENTS, value, Field.Store.NO, Field.Index.ANALYZED));
}
}
} catch (Exception ex) {
LOGGER.info("error indexing "+f.getName()+": " + ex.getMessage());
} finally {
try {
is.close();
} catch (Exception e) {
LOGGER.error("error closing FileInputStream " +f.getName() + ": " + e.getMessage());
}
}
}
}
return doc;
}
private void notifyNewDocumentAdded()
{
for (Iterator<NewDocumentAdded> iter = this.newDocumentAddedList.iterator(); iter.hasNext(); ) {
iter.next().newDocumentAdded();
}
}
public void delete(final Post post)
{
this.performDelete(post);
}
private boolean performDelete(final Post post)
{
synchronized (LOGGER) {
IndexWriter writer = null;
boolean status = false;
try {
final IndexWriterConfig conf = new IndexWriterConfig(LuceneSettings.version, this.settings.analyzer()).setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);
writer = new IndexWriter(this.settings.directory(), conf);
writer.deleteDocuments(new Term(SearchFields.Keyword.POST_ID, String.valueOf(post.getId())));
status = true;
}
catch (IOException e) {
LOGGER.error(e.toString(), e);
}
finally {
if (writer != null) {
try {
writer.commit();
writer.close();
this.flushRAMDirectory();
}
catch (IOException e) {
LOGGER.error(e.toString(), e);
}
}
}
return status;
}
}
}
|
package net.sf.webdav;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Principal;
import java.util.Enumeration;
import java.util.HashMap;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.webdav.exceptions.UnauthenticatedException;
import net.sf.webdav.exceptions.WebdavException;
import net.sf.webdav.fromcatalina.MD5Encoder;
import net.sf.webdav.locking.ResourceLocks;
import net.sf.webdav.methods.DoCopy;
import net.sf.webdav.methods.DoDelete;
import net.sf.webdav.methods.DoGet;
import net.sf.webdav.methods.DoHead;
import net.sf.webdav.methods.DoLock;
import net.sf.webdav.methods.DoMkcol;
import net.sf.webdav.methods.DoMove;
import net.sf.webdav.methods.DoNotImplemented;
import net.sf.webdav.methods.DoOptions;
import net.sf.webdav.methods.DoPropfind;
import net.sf.webdav.methods.DoProppatch;
import net.sf.webdav.methods.DoPut;
import net.sf.webdav.methods.DoUnlock;
public class WebDavServletBean extends HttpServlet {
private static org.slf4j.Logger LOG = org.slf4j.LoggerFactory
.getLogger(WebDavServletBean.class);
/**
* MD5 message digest provider.
*/
protected static MessageDigest MD5_HELPER;
/**
* The MD5 helper object for this class.
*/
protected static final MD5Encoder MD5_ENCODER = new MD5Encoder();
private static final boolean READ_ONLY = false;
protected ResourceLocks _resLocks;
protected IWebdavStore _store;
private HashMap<String, IMethodExecutor> _methodMap = new HashMap<String, IMethodExecutor>();
public WebDavServletBean() {
_resLocks = new ResourceLocks();
try {
MD5_HELPER = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException();
}
}
public void init(IWebdavStore store, String dftIndexFile,
String insteadOf404, int nocontentLenghHeaders,
boolean lazyFolderCreationOnPut) throws ServletException {
_store = store;
IMimeTyper mimeTyper = new IMimeTyper() {
public String getMimeType(ITransaction transaction, String path) {
String retVal= _store.getStoredObject(transaction, path).getMimeType();
if ( retVal== null) {
retVal= getServletContext().getMimeType( path);
}
return retVal;
}
};
register("GET", new DoGet(store, dftIndexFile, insteadOf404, _resLocks,
mimeTyper, nocontentLenghHeaders));
register("HEAD", new DoHead(store, dftIndexFile, insteadOf404,
_resLocks, mimeTyper, nocontentLenghHeaders));
DoDelete doDelete = (DoDelete) register("DELETE", new DoDelete(store,
_resLocks, READ_ONLY));
DoCopy doCopy = (DoCopy) register("COPY", new DoCopy(store, _resLocks,
doDelete, READ_ONLY));
register("LOCK", new DoLock(store, _resLocks, READ_ONLY));
register("UNLOCK", new DoUnlock(store, _resLocks, READ_ONLY));
register("MOVE", new DoMove(_resLocks, doDelete, doCopy, READ_ONLY));
register("MKCOL", new DoMkcol(store, _resLocks, READ_ONLY));
register("OPTIONS", new DoOptions(store, _resLocks));
register("PUT", new DoPut(store, _resLocks, READ_ONLY,
lazyFolderCreationOnPut));
register("PROPFIND", new DoPropfind(store, _resLocks, mimeTyper));
register("PROPPATCH", new DoProppatch(store, _resLocks, READ_ONLY));
register("*NO*IMPL*", new DoNotImplemented(READ_ONLY));
}
@Override
public void destroy() {
if(_store != null)
_store.destroy();
super.destroy();
}
protected IMethodExecutor register(String methodName, IMethodExecutor method) {
_methodMap.put(methodName, method);
return method;
}
/**
* Handles the special WebDAV methods.
*/
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String methodName = req.getMethod();
ITransaction transaction = null;
boolean needRollback = false;
if (LOG.isTraceEnabled())
debugRequest(methodName, req);
try {
Principal userPrincipal = getUserPrincipal(req);
transaction = _store.begin(userPrincipal);
needRollback = true;
_store.checkAuthentication(transaction);
resp.setStatus(WebdavStatus.SC_OK);
try {
IMethodExecutor methodExecutor = (IMethodExecutor) _methodMap
.get(methodName);
if (methodExecutor == null) {
methodExecutor = (IMethodExecutor) _methodMap
.get("*NO*IMPL*");
}
methodExecutor.execute(transaction, req, resp);
_store.commit(transaction);
/** Clear not consumed data
*
* Clear input stream if available otherwise later access
* include current input. These cases occure if the client
* sends a request with body to an not existing resource.
*/
if (req.getContentLength() != 0 && req.getInputStream().available() > 0) {
if (LOG.isTraceEnabled()) { LOG.trace("Clear not consumed data!"); }
while (req.getInputStream().available() > 0) {
req.getInputStream().read();
}
}
needRollback = false;
} catch (IOException e) {
java.io.StringWriter sw = new java.io.StringWriter();
java.io.PrintWriter pw = new java.io.PrintWriter(sw);
e.printStackTrace(pw);
LOG.error("IOException: " + sw.toString());
resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
_store.rollback(transaction);
throw new ServletException(e);
}
} catch (UnauthenticatedException e) {
resp.sendError(WebdavStatus.SC_FORBIDDEN);
} catch (WebdavException e) {
java.io.StringWriter sw = new java.io.StringWriter();
java.io.PrintWriter pw = new java.io.PrintWriter(sw);
e.printStackTrace(pw);
LOG.error("WebdavException: " + sw.toString());
throw new ServletException(e);
} catch (Exception e) {
java.io.StringWriter sw = new java.io.StringWriter();
java.io.PrintWriter pw = new java.io.PrintWriter(sw);
e.printStackTrace(pw);
LOG.error("Exception: " + sw.toString());
} finally {
if (needRollback)
_store.rollback(transaction);
}
}
/**
* Method that permit to customize the way
* user information are extracted from the request, default use JAAS
* @param req
* @return
*/
protected Principal getUserPrincipal(HttpServletRequest req) {
return req.getUserPrincipal();
}
private void debugRequest(String methodName, HttpServletRequest req) {
LOG.trace("
LOG.trace("WebdavServlet\n request: methodName = " + methodName);
LOG.trace("time: " + System.currentTimeMillis());
LOG.trace("path: " + req.getRequestURI());
LOG.trace("
Enumeration<?> e = req.getHeaderNames();
while (e.hasMoreElements()) {
String s = (String) e.nextElement();
LOG.trace("header: " + s + " " + req.getHeader(s));
}
e = req.getAttributeNames();
while (e.hasMoreElements()) {
String s = (String) e.nextElement();
LOG.trace("attribute: " + s + " " + req.getAttribute(s));
}
e = req.getParameterNames();
while (e.hasMoreElements()) {
String s = (String) e.nextElement();
LOG.trace("parameter: " + s + " " + req.getParameter(s));
}
}
}
|
package net.wizardsoflua.block;
import javax.annotation.Nullable;
import net.minecraft.block.state.IBlockState;
import net.minecraft.inventory.IInventory;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
public class WolBlock {
private IBlockState blockState;
private final @Nullable NBTTagCompound nbt;
public WolBlock(IBlockState blockState, NBTTagCompound nbt) {
this.blockState = blockState;
this.nbt = nbt;
}
public WolBlock(IBlockState blockState, @Nullable TileEntity tileEntity) {
this.blockState = blockState;
if (tileEntity != null) {
NBTTagCompound tagCompound = new NBTTagCompound();
tileEntity.writeToNBT(tagCompound);
nbt = tagCompound;
} else {
nbt = null;
}
}
public IBlockState getBlockState() {
return blockState;
}
public void setBlockState(IBlockState blockState) {
this.blockState = blockState;
}
public NBTTagCompound getNbt() {
return nbt;
}
public void setBlock(World world, BlockPos pos) {
TileEntity oldTileEntity = world.getTileEntity(pos);
if (oldTileEntity != null) {
if (oldTileEntity instanceof IInventory) {
((IInventory) oldTileEntity).clear();
}
}
if (world.setBlockState(pos, blockState)) {
if (nbt != null) {
// TODO remove this side effect
// however, it does not hurt
nbt.setInteger("x", pos.getX());
nbt.setInteger("y", pos.getY());
nbt.setInteger("z", pos.getZ());
TileEntity tileEntity = world.getTileEntity(pos);
if (tileEntity != null) {
tileEntity.readFromNBT(nbt);
tileEntity.markDirty();
} else {
throw new IllegalStateException(String.format("Missing tile entity for %s at %s %s %s",
blockState.getBlock().getRegistryName().getResourcePath(), pos.getX(), pos.getY(),
pos.getZ()));
}
int flags = 3; // Do a block update (1) and send it to all clients (2)
world.notifyBlockUpdate(pos, blockState, blockState, flags);
}
}
}
}
|
package no.hyper.imagecrop;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.media.ExifInterface;
import android.support.v4.view.GestureDetectorCompat;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import no.hyper.imagecrop.R;
public class ImageCropper extends View {
private Context context;
private Bitmap picture;
private Bitmap bitmapOverlay;
private Bitmap support;
private Point middle;
private Rect cropRect;
private Paint bitmapPaint;
private Paint bitmapOverlayPaint;
private Paint maskPaint;
private Paint overlayRectPaint;
private Paint cropRectPaint;
private float cropSize;
private String picturePath;
private int screenWidth;
private int screenHeight;
private float left;
private float top;
private ScaleGestureDetector mScaleDetector;
private GestureDetectorCompat mGestureDetector;
private float mScaleFactor = 1.f;
public ImageCropper(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
mScaleDetector = new ScaleGestureDetector(context, mScaleGestureListener);
mGestureDetector = new GestureDetectorCompat(context, mGestureListener);
TypedArray array = context.getTheme().obtainStyledAttributes(
attrs, R.styleable.ImageCropper, 0, 0);
try {
cropSize = (float) array.getInt(R.styleable.ImageCropper_crop_size, 500);
} finally {
array.recycle();
}
init();
}
private void init() {
bitmapPaint = new Paint(Paint.FILTER_BITMAP_FLAG);
bitmapOverlayPaint = new Paint(Paint.FILTER_BITMAP_FLAG);
bitmapOverlayPaint.setAlpha(120);
maskPaint = new Paint();
maskPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
overlayRectPaint = new Paint();
overlayRectPaint.setColor(Color.BLACK);
overlayRectPaint.setStyle(Paint.Style.FILL_AND_STROKE);
cropRectPaint = new Paint();
cropRectPaint.setStyle(Paint.Style.STROKE);
cropRectPaint.setColor(Color.WHITE);
middle = new Point(Utils.ScreenSize.getWidth(getContext()) / 2,
Utils.ScreenSize.getHeight(getContext()) / 2);
screenHeight = Utils.ScreenSize.getHeight(context);
screenWidth = Utils.ScreenSize.getWidth(context);
if(screenWidth < cropSize || screenHeight < cropSize) {
cropSize = Math.min((float)screenWidth - 5, (float)screenHeight - 5);
}
cropRect = new Rect();
bitmapOverlay = setBitmapOverlay();
picture = Bitmap.createBitmap(
Math.round(screenWidth / mScaleFactor) + 5,
Math.round(screenHeight / mScaleFactor) + 5, Bitmap.Config.ARGB_8888);
}
public void setPicture(Bitmap picture) {
this.picture = picture;
left = middle.x - picture.getWidth() / 2;
top = middle.y - picture.getHeight() / 2;
mScaleFactor = 1f;
while(picture.getWidth()*mScaleFactor < cropSize ||
picture.getHeight()*mScaleFactor < cropSize) {
mScaleFactor += 0.1;
}
invalidate();
}
public void setBottomPanelSize(int size) {
middle.y -= size;
int[] dimens = getCropSquareDimens();
cropRect.set(dimens[0], dimens[1], dimens[2], dimens[3]);
bitmapOverlay = setBitmapOverlay();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.save();
canvas.scale(mScaleFactor, mScaleFactor);
canvas.drawBitmap(picture, left, top, bitmapPaint);
canvas.drawBitmap(bitmapOverlay, 0, 0, bitmapOverlayPaint);
canvas.drawRect(cropRect.left, cropRect.top, cropRect.right, cropRect.bottom, cropRectPaint);
canvas.restore();
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
boolean retVal = mScaleDetector.onTouchEvent(ev);
retVal = mGestureDetector.onTouchEvent(ev) || retVal;
return retVal || super.onTouchEvent(ev);
}
public Bitmap createSafeBitmap(String picturePath) {
this.picturePath = picturePath;
int[] dimens = Utils.Image.getImageInfo(picturePath);
int rotation = getRotationValue();
float pictureWidth = (rotation != 0 && rotation != 270) ? dimens[1] : dimens[0];
float scaleFactor = screenWidth / pictureWidth;
float newX = dimens[0] * scaleFactor;
float newY = dimens[1] * scaleFactor;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = calculateInSampleSize(dimens[0], dimens[1],
screenWidth, screenHeight);
picturePath = null;
Bitmap original = BitmapFactory.decodeFile(picturePath, options);
if(original != null) {
original = Bitmap.createScaledBitmap(original, Math.round(newX), Math.round(newY), true);
return Bitmap.createBitmap(original, 0, 0, original.getWidth(), original.getHeight(),
getRotationMatrix(), true);
} else {
return null;
}
}
public Bitmap getCroppedPicture() {
int x = (Math.round(cropRect.left) - Math.round(left));
int y = Math.round(cropRect.top) - Math.round(top);
Bitmap newBitmap = Bitmap.createBitmap(picture, (x > 0) ? x : 0, (y > 0) ? y : 0,
Math.round(cropSize / mScaleFactor), Math.round(cropSize / mScaleFactor));
return Bitmap.createScaledBitmap(newBitmap, Math.round(cropSize),
Math.round(cropSize), true);
}
private final ScaleGestureDetector.OnScaleGestureListener mScaleGestureListener
= new ScaleGestureDetector.SimpleOnScaleGestureListener() {
@Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
return super.onScaleBegin(detector);
}
@Override
public boolean onScale(ScaleGestureDetector detector) {
float scale = detector.getScaleFactor();
float scaledWidth = picture.getWidth() * scale;
float scaledHeight = picture.getHeight() * scale;
float scaledRightSide = (left * scale) + scaledWidth;
float scaledBottomSide = (top * scale) + scaledHeight;
float fx = detector.getFocusX();
float fy = detector.getFocusY();
float dx = scaledRightSide - (left + picture.getWidth());
float dy = scaledBottomSide - (top + picture.getHeight());
float temp = mScaleFactor*scale;
if(temp >= 0.6f && temp <= 3.0f) {
mScaleFactor *= scale;
mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 3.0f));
left = left - (fx / (picture.getWidth()*mScaleFactor))*dx;
top = top - (fy / (picture.getHeight()*mScaleFactor))*dy;
int[] dimens = getCropSquareDimens();
cropRect.set(dimens[0], dimens[1], dimens[2], dimens[3]);
bitmapOverlay = setBitmapOverlay();
invalidate();
}
return true;
}
@Override
public void onScaleEnd(ScaleGestureDetector detector) {
super.onScaleEnd(detector);
float scaledWidth = picture.getWidth() * mScaleFactor;
float scaledHeight = picture.getHeight() * mScaleFactor;
if(left > cropRect.left) {
left = cropRect.left;
}
if(top > cropRect.top) {
top = cropRect.top;
}
if(left + picture.getWidth() < cropRect.right) {
left += cropRect.right - (left + picture.getWidth());
}
if(top + picture.getHeight() < cropRect.bottom) {
top += cropRect.bottom - (top + picture.getHeight());
}
if(scaledWidth < cropSize || scaledHeight < cropSize) {
while (scaledWidth < cropSize || scaledHeight < cropSize) {
mScaleFactor += 0.05f;
scaledWidth = picture.getWidth() * mScaleFactor;
scaledHeight = picture.getHeight() * mScaleFactor;
}
int[] dimens = getCropSquareDimens();
cropRect.set(dimens[0], dimens[1], dimens[2], dimens[3]);
left = middle.x - picture.getWidth() / 2;
top = cropRect.top;
bitmapOverlay = setBitmapOverlay();
}
invalidate();
}
};
private final GestureDetector.SimpleOnGestureListener mGestureListener
= new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onDown(MotionEvent e) {
return true;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
if(!mScaleDetector.isInProgress()) {
float newX = left - distanceX/mScaleFactor;
float newY = top - distanceY/mScaleFactor;
float minX = (middle.x + cropSize /2)/mScaleFactor
- picture.getWidth();
float maxX = (middle.x - cropSize /2)/mScaleFactor;
float minY = (middle.y + cropSize/2)/mScaleFactor
- picture.getHeight();
float maxY = (middle.y - cropSize/2)/mScaleFactor;
if(newX > minX && newX < maxX) {
left = newX;
}
if(newY > minY && newY < maxY) {
top = newY;
}
invalidate();
}
return true;
}
};
private int[] getCropSquareDimens() {
return new int[]{
Math.round((middle.x - cropSize/2)/mScaleFactor),
Math.round((middle.y - cropSize/2)/mScaleFactor),
Math.round((middle.x + cropSize/2)/mScaleFactor),
Math.round((middle.y + cropSize/2)/mScaleFactor)
};
}
private Bitmap setBitmapOverlay() {
if(support != null) {
support.recycle();
}
support = Bitmap.createBitmap(
Math.round(screenWidth / mScaleFactor)+5,
Math.round(screenHeight / mScaleFactor)+5, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(support);
canvas.drawRect(0, 0,
Math.round(screenWidth/mScaleFactor)+5, Math.round(screenHeight/mScaleFactor)+5,
overlayRectPaint);
canvas.drawRect(cropRect.left, cropRect.top, cropRect.right, cropRect.bottom, maskPaint);
return support;
}
private int getRotationValue() {
int rotate = 0;
try {
ExifInterface exif = new ExifInterface(picturePath);
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
}
} catch (Exception e) {
e.printStackTrace();
}
return rotate;
}
private Matrix getRotationMatrix() {
Matrix matrix = new Matrix();
matrix.postRotate(getRotationValue());
return matrix;
}
private static int calculateInSampleSize(int width, int height,
int reqWidth, int reqHeight) {
int inSampleSize = 1;
while ((height / inSampleSize) > reqHeight
&& (width / inSampleSize) > reqWidth) {
inSampleSize += 1;
}
return inSampleSize;
}
}
|
package org.basex.gui.editor;
import static org.basex.util.Token.*;
import org.basex.gui.editor.Editor.SearchDir;
import org.basex.util.*;
import org.basex.util.list.*;
public final class EditorText {
/** Tab width. */
static final int TAB = 2;
/** Search context. */
private SearchContext search;
/** Start and end positions of search terms. */
IntList[] spos = { new IntList(), new IntList() };
/** Text array to be written. */
private byte[] text = EMPTY;
/** Current cursor position. */
private int pc;
/** Start position of a token. */
private int ps;
/** End position of a token. */
private int pe;
/** Start position of a text selection. */
private int ms = -1;
/** End position of a text selection (+1). */
private int me = -1;
/** Start position of an error highlighting. */
private int es = -1;
/** Current search position. */
private int sp;
/**
* Constructor.
* @param t text
*/
EditorText(final byte[] t) {
text = t;
}
/**
* Initializes the iterator.
*/
void init() {
ps = 0;
pe = 0;
sp = 0;
}
/**
* Sets a new text.
* @param t new text
*/
void text(final byte[] t) {
text = t;
noSelect();
if(search != null) spos = search.search(t);
}
/**
* Checks if the text contains more words.
* @return result of check
*/
boolean moreTokens() {
// quit if text has ended
final byte[] txt = text;
final int tl = txt.length;
int ppe = pe;
if(ppe >= tl) return false;
ps = ppe;
// find next token boundary
int ch = cp(txt, ppe);
ppe += cl(txt, ppe);
if(ftChar(ch)) {
while(ppe < tl) {
ch = cp(txt, ppe);
if(!ftChar(ch)) break;
ppe += cl(txt, ppe);
}
}
pe = ppe;
return true;
}
/**
* Returns the token as string.
* @return string
*/
public String nextString() {
final byte[] txt = text;
final int ppe = pe;
final int pps = ps;
return ppe <= txt.length ? string(txt, pps, ppe - pps) : "";
}
/**
* Moves one character forward.
* @param select selection flag
* @return character
*/
int next(final boolean select) {
return noSelect(select, true) ? curr() : next();
}
/**
* Sets a new search processor.
* @param sc search processor
*/
void search(final SearchContext sc) {
// skip search if criteria have not changed
if(sc.equals(search)) {
sc.nr = search.nr;
sc.panel.refresh(sc);
} else {
spos = sc.search(text);
search = sc;
}
}
/**
* Replaces the text.
* @param rc replace context
* @return selection offsets
*/
int[] replace(final ReplaceContext rc) {
final int start = selected() ? Math.min(ms, me) : 0;
final int end = selected() ? Math.max(ms, me) : text.length;
return rc.replace(search, text, start, end);
}
/**
* Moves one token forward.
* @param select selection flag
*/
void nextToken(final boolean select) {
int ch = next(select);
if(ch == '\n') return;
if(Character.isLetterOrDigit(ch)) {
while(Character.isLetterOrDigit(ch)) ch = next();
while(ch != '\n' && Character.isWhitespace(ch)) ch = next();
} else if(Character.isWhitespace(ch)) {
while(ch != '\n' && Character.isWhitespace(ch)) ch = next();
} else {
while(ch != '\n' && !Character.isLetterOrDigit(ch) &&
!Character.isWhitespace(ch)) ch = next();
while(ch != '\n' && Character.isWhitespace(ch)) ch = next();
}
if(ps != text.length) prev();
}
/**
* Moves one token back.
* @param select selection flag
*/
void prevToken(final boolean select) {
int ch = prev(select);
if(ch == '\n') return;
if(Character.isLetterOrDigit(ch)) {
while(Character.isLetterOrDigit(ch)) ch = prev();
} else if(Character.isWhitespace(ch)) {
while(ch != '\n' && Character.isWhitespace(ch)) ch = prev();
while(Character.isLetterOrDigit(ch)) ch = prev();
} else {
while(ch != '\n' && !Character.isLetterOrDigit(ch) &&
!Character.isWhitespace(ch)) ch = prev();
}
if(ps != 0) next();
}
/**
* Checks if the character position equals the word end.
* @return result of check
*/
boolean more() {
return ps < pe && ps < text.length;
}
/**
* Returns the current character.
* @return current character
*/
public int curr() {
return ps < 0 || ps >= text.length ? '\n' : cp(text, ps);
}
/**
* Returns the original text array.
* @return text
*/
public byte[] text() {
return text;
}
/**
* Moves one character forward.
* @return current character
*/
int next() {
final int c = curr();
if(ps < text.length) ps += cl(text, ps);
return c;
}
/**
* Sets the iterator position.
* @param p iterator position
*/
void pos(final int p) {
ps = p;
}
/**
* Returns the iterator position.
* @return iterator position
*/
int pos() {
return ps;
}
/**
* Moves to the beginning of the line.
* @param select selection flag
* @return number of passed characters
*/
int bol(final boolean select) {
if(ps == 0) return 0;
int c = 0;
do c += curr() == '\t' ? TAB : 1; while(prev(select) != '\n');
if(ps != 0 || curr() == '\n') next(select);
return c;
}
/**
* Moves to the first character or the beginning of the line.
* @param select selection flag
*/
void home(final boolean select) {
final int p = ps;
boolean s = true;
// find beginning of line
while(prev(select) != '\n') s &= ws(curr());
if(ps != 0 || curr() == '\n') next(select);
// move to first non-whitespace character
if(p == ps || !s) while(ws(curr()) && curr() != '\n') next(select);
}
/**
* Moves to the end of the line.
* @param select selection flag
*/
void eol(final boolean select) {
forward(Integer.MAX_VALUE, select);
}
/**
* Moves one character back and returns the found character.
* @param select selection flag
* @return character
*/
int prev(final boolean select) {
return noSelect(select, false) ? curr() : prev();
}
/**
* Moves one character back and returns the found character. A newline character is
* returned if the cursor is placed at the beginning of the text.
* @return character
*/
int prev() {
if(ps == 0) return '\n';
while(--ps > 0 && text[ps] < -64 && text[ps] >= -128);
return curr();
}
/**
* Moves to the specified position of to the of the line.
* @param p position to move to
* @param select selection flag
*/
void forward(final int p, final boolean select) {
int nc = 0;
while(curr() != '\n') {
nc += curr() == '\t' ? TAB : 1;
if(nc >= p) return;
next(select);
}
}
/**
* Adds a string at the current position.
* @param str string
*/
void add(final String str) {
final TokenBuilder tb = new TokenBuilder(str.length() << 1);
final int cl = str.length();
for(int c = 0; c < cl; ++c) {
// ignore invalid characters
int ch = str.charAt(c);
if(ch == '\r') continue;
if(ch < ' ' && !ws(ch)) {
ch = '\n';
} else if(Character.isHighSurrogate((char) ch) && c + 1 < cl) {
ch = Character.toCodePoint((char) ch, str.charAt(++c));
}
tb.add(ch);
}
final int tl = text.length;
final int ts = tb.size();
final byte[] tmp = new byte[tl + ts];
System.arraycopy(text, 0, tmp, 0, ps);
System.arraycopy(tb.finish(), 0, tmp, ps, ts);
System.arraycopy(text, ps, tmp, ps + ts, tl - ps);
text(tmp);
ps += ts;
}
/**
* Indents lines.
* @param s start position
* @param e end position
* @param sh shift flag
*/
void indent(final int s, final int e, final boolean sh) {
// extend selection to match whole lines
pos(s);
bol(true);
startSelect();
pos(e);
forward(Integer.MAX_VALUE, true);
next(true);
finishSelect();
// decide if to use tab or spaces
boolean tab = false;
for(final byte t : text) tab |= t == '\t';
byte[] add = { '\t' };
if(!tab) {
add = new byte[TAB];
for(int a = 0; a < TAB; a++) add[a] = ' ';
}
// build new text
final TokenBuilder tb = new TokenBuilder();
tb.add(text, 0, ms);
final int pl = text.length;
for(int p = ms; p < ps; p += cl(text, p)) {
if(p == 0 || text[p - 1] == '\n') {
if(sh) {
// remove indentation
if(text[p] == '\t') {
me
continue;
}
if(text[p] == ' ') {
me
for(int i = 1; i < TAB && p + i < pl && text[p + i] == ' '; i++) {
me
p++;
}
continue;
}
} else {
// add new indentation
tb.add(add);
me += add.length;
}
}
tb.add(cp(text, p));
}
tb.add(text, ps, text.length);
ps = me;
final int ss = ms;
text(tb.finish());
ms = ss;
me = ps;
}
/**
* (Un)comments highlighted text or line.
* @param syntax syntax highlighter
*/
void comment(final Syntax syntax) {
final byte[] st = syntax.commentOpen();
final byte[] en = syntax.commentEnd();
boolean add = true;
int min = ps;
int max = ps;
if(selected()) {
min = ps < ms ? ps : ms;
max = ps > ms ? ps : ms;
if(max > min && text[max - 1] == '\n') max
// selected
final int mn = Math.max(min + st.length, max - en.length);
// check if selected area already has a comment
if(indexOf(text, st, min) == min && indexOf(text, en, mn) == mn) {
final TokenBuilder tb = new TokenBuilder();
tb.add(text, 0, min);
tb.add(text, min + st.length, max - en.length);
tb.add(text, max, text.length);
text(tb.finish());
ms = min;
me = max - st.length - en.length;
ps = me;
add = false;
}
} else {
while(min > 0 && text[min - 1] != '\n') --min;
while(max < size() && text[max] != '\n') ++max;
}
if(add) {
pos(max);
add(string(en));
pos(min);
add(string(st));
ms = min;
me = max + st.length + en.length;
ps = me;
}
}
/**
* Indents the current line or text.
* @param sb typed in string
* @param shift shift key
* @return indentation flag
*/
boolean indent(final StringBuilder sb, final boolean shift) {
// no selection, shift pressed: select current character
if(!selected() && shift && text.length != 0) select(ps + 1, ps);
// check if something is selected
boolean i = false;
if(selected()) {
// check if lines are to be indented
final int s = Math.min(ps, start());
final int l = Math.max(ps, start()) - 1;
int p = s;
for(; p <= l && p < text.length; p++) i |= text[p] != '\n';
i |= p == text.length;
if(i) {
indent(s, l, shift);
sb.setLength(0);
}
} else {
boolean c = ps > 0;
for(int p = ps - 1; p >= 0 && c; p
final byte b = text[p];
c = ws(b);
if(b == '\n') break;
}
if(c) {
sb.setLength(0);
sb.append(" ");
}
}
return i;
}
/**
* Processes the enter key and checks for opening brackets.
* @param sb typed in string
*/
void open(final StringBuilder sb) {
// adopt indentation from previous line
int s = 0;
for(int p = ps - 1; p >= 0; p
final byte b = text[p];
if(b == '\n') break;
if(b == '\t') {
s += EditorText.TAB;
} else if(b == ' ') {
s++;
} else {
s = 0;
}
}
// indent after opening bracket
if(ps > 0) {
final int l = text[ps - 1];
if(l == '(' || l == '{' || l == '[') s += EditorText.TAB;
}
// unindent before closing bracket
if(ps < text.length) {
final int l = text[ps];
if(l == ')' || l == '}' || l == ']') s -= EditorText.TAB;
}
for(int p = 0; p < s; p++) sb.append(' ');
}
/**
* Closes a bracket.
*/
void close() {
int p = ps - 1;
for(; p >= 0; p
final byte b = text[p];
if(b == '\n') break;
if(!ws(b)) return;
}
if(++p >= ps) return;
ms = Math.max(ps - TAB, p);
me = Math.max(ps, p);
if(ms != me) delete();
}
/**
* Deletes the current character or selection.
* Assumes that the current position allows a deletion.
*/
void delete() {
final int tl = text.length;
if(tl == 0) return;
final int s = selected() ? Math.min(ms, me) : ps;
final int e = selected() ? Math.max(ms, me) : ps + cl(text, ps);
final byte[] tmp = new byte[tl - e + s];
System.arraycopy(text, 0, tmp, 0, s);
System.arraycopy(text, e, tmp, s, tl - e);
text(tmp);
ps = s;
}
/**
* Deletes the current line.
*/
void deleteLine() {
bol(false);
startSelect();
eol(true);
next(true);
finishSelect();
delete();
}
/**
* Jumps to the maximum/minimum position and resets the selection.
* @param select selection flag
* @param max maximum/minimum flag
* @return true if selection was reset
*/
private boolean noSelect(final boolean select, final boolean max) {
final boolean rs = !select && selected();
if(rs) {
ps = max ^ ms < me ? ms : me;
noSelect();
}
return rs;
}
/**
* Resets the selection.
*/
void noSelect() {
ms = -1;
me = -1;
}
/**
* Sets the start of a text selection.
*/
void startSelect() {
ms = ps;
me = ps;
}
/**
* Extends the text selection.
*/
void extendSelect() {
me = ps;
}
/**
* Finishes a text selection.
*/
void finishSelect() {
me = ps;
checkSelect();
}
/**
* Selects the specified area.
* @param s start position
* @param e end position
*/
void select(final int s, final int e) {
ms = s;
me = e;
checkSelect();
}
/**
* Checks the validity of the selection.
*/
void checkSelect() {
if(ms == me) noSelect();
}
/**
* Returns the start of the text selection. The value is {@code -1} if no
* text is selected.
* @return start selection
*/
int start() {
return ms;
}
/**
* Tests if text is currently being selected, or has already been selected.
* @return result of check
*/
boolean selecting() {
return ms != -1;
}
/**
* Tests if text has been selected.
* @return result of check
*/
boolean selected() {
return ms != me;
}
/**
* Tests if the current text position is selected.
* @return result of check
*/
boolean selectStart() {
return selected() &&
(inSelect() || (ms < me ? ms >= ps && ms < pe : me >= ps && me < pe));
}
/**
* Tests if the current position is selected.
* @return result of check
*/
boolean inSelect() {
return ms < me ? ps >= ms && ps < me : ps >= me && ps < ms;
}
/**
* Returns the selected string.
* @return string
*/
String copy() {
final TokenBuilder tb = new TokenBuilder();
final int e = ms < me ? me : ms;
for(int s = ms < me ? ms : me; s < e; s += cl(text, s)) {
final int t = cp(text, s);
if(t < 0 || t >= ' ' || t == 0x0A || t == 0x09) tb.add(t);
}
return tb.toString();
}
/**
* Selects the word at the cursor position.
*/
void selectWord() {
pos(getCaret());
final boolean ch = ftChar(prev(true));
while(pos() > 0) {
final int c = prev(true);
if(c == '\n' || ch != ftChar(c)) break;
}
if(pos() != 0) next(true);
startSelect();
while(pos() < size()) {
final int c = curr();
if(c == '\n' || ch != ftChar(c)) break;
next(true);
}
finishSelect();
}
/**
* Selects the word at the cursor position.
*/
void selectLine() {
pos(getCaret());
bol(true);
startSelect();
eol(true);
finishSelect();
}
/**
* Tests if the current token is erroneous.
* @return result of check
*/
boolean erroneous() {
return es >= ps && es < pe;
}
/**
* Returns the error position.
* @return error position
*/
public int error() {
return es;
}
/**
* Sets the error position.
* @param s start position
*/
public void error(final int s) {
es = s;
}
/**
* Returns true if the cursor focuses a search string.
* @return result of check
*/
boolean searchStart() {
if(search == null) return false;
final IntList[] sps = spos;
if(sp == sps[0].size()) return false;
while(ps > sps[1].get(sp)) {
if(++sp == sps[0].size()) return false;
}
return pe > sps[0].get(sp);
}
/**
* Tests if the current position is within a search term.
* @return result of check
*/
boolean inSearch() {
if(sp >= spos[0].size() || ps < spos[0].get(sp)) return false;
final boolean in = ps < spos[1].get(sp);
if(!in) sp++;
return in;
}
/**
* Selects a search string.
* @param dir search direction
* @param select select hit
* @return new cursor position, or {@code -1}
*/
int jump(final SearchDir dir, final boolean select) {
if(spos[0].isEmpty()) {
if(select) noSelect();
return -1;
}
int s = spos[0].sortedIndexOf(!select || selected() ? pc : pc - 1);
switch(dir) {
case CURRENT: s = s < 0 ? -s - 1 : s; break;
case FORWARD: s = s < 0 ? -s - 1 : s + 1; break;
case BACKWARD: s = s < 0 ? -s - 2 : s - 1; break;
}
final int sl = spos[0].size();
if(s < 0) s = sl - 1;
else if(s == sl) s = 0;
final int pos = spos[0].get(s);
if(select) {
pc = pos;
ms = pos;
me = spos[1].get(s);
} else {
pc = pos;
}
return pos;
}
/**
* Checks if the text cursor moves over the current token.
* @return result of check
*/
boolean edited() {
return pc >= ps && pc < pe;
}
/**
* Sets the text cursor to the specified position.
* @param c cursor position
*/
void setCaret(final int c) {
pc = c;
ps = c;
}
/**
* Sets the text cursor to the current position.
*/
void setCaret() {
pc = ps;
}
/**
* Returns the position of the text cursor.
* @return cursor position
*/
int getCaret() {
return pc;
}
/**
* Returns the text size.
* @return text size
*/
int size() {
return text.length;
}
@Override
public String toString() {
return copy();
}
}
|
package org.dita.dost.module;
import net.sf.saxon.lib.ExtensionFunctionDefinition;
import org.apache.tools.ant.types.XMLCatalog;
import org.apache.tools.ant.util.FileNameMapper;
import org.apache.tools.ant.util.FileUtils;
import org.dita.dost.exception.DITAOTException;
import org.dita.dost.pipeline.AbstractPipelineInput;
import org.dita.dost.pipeline.AbstractPipelineOutput;
import org.dita.dost.util.Configuration;
import org.dita.dost.util.Job;
import org.dita.dost.util.XMLUtils;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import javax.xml.transform.*;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.File;
import java.io.IOException;
import java.util.*;
import static org.dita.dost.util.FileUtils.replaceExtension;
import static org.dita.dost.util.XMLUtils.withLogger;
/**
* XSLT processing module.
*
* <p>The module matches Ant's XSLT task with the following exceptions:</p>
* <ul>
* <li>If source and destination directories are same, transformation results are saved to a temporary file
* and the original source file is replaced after a successful transformation.</li>
* <li>If no {@code extension} attribute is set, the target file extension is the same as the source file extension.</li>
* </ul>
*
*/
public final class XsltModule extends AbstractPipelineModuleImpl {
private Templates templates;
private final Map<String, String> params = new HashMap<>();
private File style;
private File in;
private File out;
private File destDir;
private File baseDir;
private Collection<File> includes;
private String filenameparameter;
private String filedirparameter;
private boolean reloadstylesheet;
private XMLCatalog xmlcatalog;
private FileNameMapper mapper;
private String extension;
private Transformer t;
private XMLReader parser;
public AbstractPipelineOutput execute(AbstractPipelineInput input) throws DITAOTException {
if (fileInfoFilter != null) {
final Collection<Job.FileInfo> res = job.getFileInfo(fileInfoFilter);
includes = new ArrayList<>(res.size());
for (final Job.FileInfo f : res) {
includes.add(f.file);
}
baseDir = job.tempDir;
}
if ((includes == null || includes.isEmpty()) && (in == null)) {
return null;
}
if (destDir != null) {
logger.info("Transforming into " + destDir.getAbsolutePath());
}
final TransformerFactory tf = TransformerFactory.newInstance();
configureExtensions(tf);
tf.setURIResolver(xmlcatalog);
try {
templates = tf.newTemplates(new StreamSource(style));
} catch (TransformerConfigurationException e) {
throw new RuntimeException("Failed to compile stylesheet '" + style.getAbsolutePath() + "': " + e.getMessage(), e);
}
try {
parser = XMLUtils.getXMLReader();
} catch (final SAXException e) {
throw new RuntimeException("Failed to create XML reader: " + e.getMessage(), e);
}
parser.setEntityResolver(xmlcatalog);
if (in != null) {
transform(in, out);
} else {
for (final File include : includes) {
final File in = new File(baseDir, include.getPath());
File out = new File(destDir, include.getPath());
if (mapper != null) {
final String[] outs = mapper.mapFileName(include.getPath());
if (outs == null) {
continue;
}
if (outs.length > 1) {
throw new RuntimeException("XSLT module only support one to one output mapping");
}
out = new File(destDir, outs[0]);
} else if (extension != null) {
out = new File(replaceExtension(out.getAbsolutePath(), extension));
}
transform(in, out);
}
}
return null;
}
private void transform(final File in, final File out) throws DITAOTException {
if (reloadstylesheet || t == null) {
logger.info("Loading stylesheet " + style.getAbsolutePath());
try {
t = withLogger(templates.newTransformer(), logger);
if (Configuration.DEBUG) {
t.setURIResolver(new XMLUtils.DebugURIResolver(xmlcatalog));
}
} catch (final TransformerConfigurationException e) {
throw new DITAOTException("Failed to create Transformer: " + e.getMessage(), e);
}
}
final boolean same = in.getAbsolutePath().equals(out.getAbsolutePath());
final File tmp = same ? new File(out.getAbsolutePath() + ".tmp" + Long.toString(System.currentTimeMillis())) : out;
for (Map.Entry<String, String> e: params.entrySet()) {
logger.debug("Set parameter " + e.getKey() + " to '" + e.getValue() + "'");
t.setParameter(e.getKey(), e.getValue());
}
if (filenameparameter != null) {
logger.debug("Set parameter " + filenameparameter + " to '" + in.getName() + "'");
t.setParameter(filenameparameter, in.getName());
}
if (filedirparameter != null) {
final String v = in.getParent() != null ? in.getParent() : ".";
logger.debug("Set parameter " + filedirparameter + " to '" + v + "'");
t.setParameter(filedirparameter, v);
}
if (same) {
logger.info("Processing " + in.getAbsolutePath());
logger.debug("Processing " + in.getAbsolutePath() + " to " + tmp.getAbsolutePath());
} else {
logger.info("Processing " + in.getAbsolutePath() + " to " + tmp.getAbsolutePath());
}
final Source source = new SAXSource(parser, new InputSource(in.toURI().toString()));
try {
if (!tmp.getParentFile().exists() && !tmp.getParentFile().mkdirs()) {
throw new IOException("Failed to create directory " + tmp.getParent());
}
t.transform(source, new StreamResult(tmp));
if (same) {
logger.debug("Moving " + tmp.getAbsolutePath() + " to " + out.getAbsolutePath());
if (!out.delete()) {
throw new IOException("Failed to to delete input file " + out.getAbsolutePath());
}
if (!tmp.renameTo(out)) {
throw new IOException("Failed to to replace input file " + out.getAbsolutePath());
}
}
} catch (final RuntimeException e) {
throw e;
} catch (final Exception e) {
logger.error("Failed to transform document: " + e.getMessage(), e);
logger.debug("Remove " + tmp.getAbsolutePath());
FileUtils.delete(tmp);
}
}
public void setStyle(final File style) {
this.style = style;
}
public void setParam(final String key, final String value) {
params.put(key, value);
}
public void setIncludes(final Collection<File> includes) {
this.includes = includes;
}
public void setDestinationDir(final File destDir) {
this.destDir = destDir;
}
public void setSorceDir(final File baseDir) {
this.baseDir = baseDir;
}
public void setFilenameParam(final String filenameparameter) {
this.filenameparameter = filenameparameter;
}
public void setFiledirParam(final String filedirparameter) {
this.filedirparameter = filedirparameter;
}
public void setReloadstylesheet(final boolean reloadstylesheet) {
this.reloadstylesheet = reloadstylesheet;
}
public void setSource(final File in) {
this.in = in;
}
public void setResult(final File out) {
this.out = out;
}
public void setXMLCatalog(final XMLCatalog xmlcatalog) {
this.xmlcatalog = xmlcatalog;
}
public void setMapper(final FileNameMapper mapper) {
this.mapper = mapper;
}
public void setExtension(final String extension) {
this.extension = extension.startsWith(".") ? extension : ("." + extension);
}
private void configureExtensions (TransformerFactory tf) {
if (tf.getClass().isAssignableFrom(net.sf.saxon.TransformerFactoryImpl.class)) {
configureSaxonExtensions((net.sf.saxon.TransformerFactoryImpl) tf);
}
}
private void configureSaxonExtensions(net.sf.saxon.TransformerFactoryImpl tfi) {
final net.sf.saxon.Configuration conf = tfi.getConfiguration();
for (ExtensionFunctionDefinition def : ServiceLoader.load(ExtensionFunctionDefinition.class)) {
try {
conf.registerExtensionFunction(def.getClass().newInstance());
} catch (InstantiationException e) {
throw new RuntimeException("Failed to register " + def.getFunctionQName().getDisplayName()
+ ". Cannot create instance of " + def.getClass().getName() + ": " + e.getMessage(), e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
}
|
package org.junit.rules;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import org.junit.Rule;
/**
* The TemporaryFolder Rule allows creation of files and folders that should
* be deleted when the test method finishes (whether it passes or
* fails).
* By default no exception will be thrown in case the deletion fails.
*
* <p>Example of usage:
* <pre>
* public static class HasTempFolder {
* @Rule
* public TemporaryFolder folder= new TemporaryFolder();
*
* @Test
* public void testUsingTempFolder() throws IOException {
* File createdFile= folder.newFile("myfile.txt");
* File createdFolder= folder.newFolder("subfolder");
* // ...
* }
* }
* </pre>
*
* <p>TemporaryFolder rule supports assured deletion mode, which
* will fail the test in case deletion fails with {@link AssertionError}.
*
* <p>Creating TemporaryFolder with assured deletion:
* <pre>
* @Rule
* public TemporaryFolder folder= TemporaryFolder.builder().assureDeletion().build();
* </pre>
*
* @since 4.7
*/
public class TemporaryFolder extends ExternalResource {
private final File parentFolder;
private final boolean assureDeletion;
private File folder;
private static final int TEMP_DIR_ATTEMPTS = 10000;
private static final String TMP_PREFIX = "junit";
/**
* Create a temporary folder which uses system default temporary-file
* directory to create temporary resources.
*/
public TemporaryFolder() {
this((File) null);
}
/**
* Create a temporary folder which uses the specified directory to create
* temporary resources.
*
* @param parentFolder folder where temporary resources will be created.
* If {@code null} then system default temporary-file directory is used.
*/
public TemporaryFolder(File parentFolder) {
this.parentFolder = parentFolder;
this.assureDeletion = false;
}
/**
* Create a {@link TemporaryFolder} initialized with
* values from a builder.
*/
protected TemporaryFolder(Builder builder) {
this.parentFolder = builder.parentFolder;
this.assureDeletion = builder.assureDeletion;
}
/**
* Returns a new builder for building an instance of {@link TemporaryFolder}.
*
* @since 4.13
*/
public static Builder builder() {
return new Builder();
}
/**
* Builds an instance of {@link TemporaryFolder}.
*
* @since 4.13
*/
public static class Builder {
private File parentFolder;
private boolean assureDeletion;
protected Builder() {}
/**
* Specifies which folder to use for creating temporary resources.
* If {@code null} then system default temporary-file directory is
* used.
*
* @return this
*/
public Builder parentFolder(File parentFolder) {
this.parentFolder = parentFolder;
return this;
}
/**
* Setting this flag assures that no resources are left undeleted. Failure
* to fulfill the assurance results in failure of tests with an
* {@link AssertionError}.
*
* @return this
*/
public Builder assureDeletion() {
this.assureDeletion = true;
return this;
}
/**
* Builds a {@link TemporaryFolder} instance using the values in this builder.
*/
public TemporaryFolder build() {
return new TemporaryFolder(this);
}
}
@Override
protected void before() throws Throwable {
create();
}
@Override
protected void after() {
delete();
}
// testing purposes only
/**
* for testing purposes only. Do not use.
*/
public void create() throws IOException {
folder = createTemporaryFolderIn(parentFolder);
}
/**
* Returns a new fresh file with the given name under the temporary folder.
*/
public File newFile(String fileName) throws IOException {
File file = new File(getRoot(), fileName);
if (!file.createNewFile()) {
throw new IOException(
"a file with the name \'" + fileName + "\' already exists in the test folder");
}
return file;
}
/**
* Returns a new fresh file with a random name under the temporary folder.
*/
public File newFile() throws IOException {
return File.createTempFile(TMP_PREFIX, null, getRoot());
}
/**
* Returns a new fresh folder with the given path under the temporary
* folder.
*/
public File newFolder(String path) throws IOException {
return newFolder(new String[]{path});
}
/**
* Returns a new fresh folder with the given paths under the temporary
* folder. For example, if you pass in the strings {@code "parent"} and {@code "child"}
* then a directory named {@code "parent"} will be created under the temporary folder
* and a directory named {@code "child"} will be created under the newly-created
* {@code "parent"} directory.
*/
public File newFolder(String... paths) throws IOException {
if (paths.length == 0) {
throw new IllegalArgumentException("must pass at least one path");
}
File root = getRoot();
for (String path : paths) {
if (new File(path).isAbsolute()) {
throw new IOException("folder path \'" + path + "\' is not a relative path");
}
}
File relativePath = null;
File file = root;
boolean lastMkdirsCallSuccessful = true;
for (String path : paths) {
relativePath = new File(relativePath, path);
file = new File(root, relativePath.getPath());
lastMkdirsCallSuccessful = file.mkdirs();
if (!lastMkdirsCallSuccessful && !file.isDirectory()) {
throw new IOException(
"could not create a folder with the path \'" + relativePath.getPath() + "\'");
}
}
if (!lastMkdirsCallSuccessful) {
throw new IOException(
"a folder with the path \'" + relativePath.getPath() + "\' already exists");
}
return file;
}
/**
* Returns a new fresh folder with a random name under the temporary folder.
*/
public File newFolder() throws IOException {
return createTemporaryFolderIn(getRoot());
}
private File createTemporaryFolderIn(File parentFolder) throws IOException {
File createdFolder = null;
for (int i = 0; i < TEMP_DIR_ATTEMPTS; ++i) {
// Use createTempFile to get a suitable folder name.
String suffix = ".tmp";
File tmpFile = File.createTempFile(TMP_PREFIX, suffix, parentFolder);
String tmpName = tmpFile.toString();
// Discard .tmp suffix of tmpName.
String folderName = tmpName.substring(0, tmpName.length() - suffix.length());
createdFolder = new File(folderName);
if (createdFolder.mkdir()) {
tmpFile.delete();
return createdFolder;
}
tmpFile.delete();
}
throw new IOException("Unable to create temporary directory in: "
+ parentFolder.toString() + ". Tried " + TEMP_DIR_ATTEMPTS + " times. "
+ "Last attempted to create: " + createdFolder.toString());
}
/**
* @return the location of this temporary folder.
*/
public File getRoot() {
if (folder == null) {
throw new IllegalStateException(
"the temporary folder has not yet been created");
}
return folder;
}
/**
* Delete all files and folders under the temporary folder. Usually not
* called directly, since it is automatically applied by the {@link Rule}.
*
* @throws AssertionError if unable to clean up resources
* and deletion of resources is assured.
*/
public void delete() {
if (!tryDelete()) {
if (assureDeletion) {
fail("Unable to clean up temporary folder " + folder);
}
}
}
/**
* Tries to delete all files and folders under the temporary folder and
* returns whether deletion was successful or not.
*
* @return {@code true} if all resources are deleted successfully,
* {@code false} otherwise.
*/
private boolean tryDelete() {
if (folder == null) {
return true;
}
return recursiveDelete(folder);
}
private boolean recursiveDelete(File file) {
// Try deleting file before assuming file is a directory
// to prevent following symbolic links.
if (file.delete()) {
return true;
}
File[] files = file.listFiles();
if (files != null) {
for (File each : files) {
if (!recursiveDelete(each)) {
return false;
}
}
}
return file.delete();
}
}
|
package org.libj.xquery.parser;
import org.libj.xquery.lexer.TokenType;
import org.libj.xquery.lisp.Cons;
public class Unparser {
private int indent = 0;
private StringBuilder builder = new StringBuilder();
private void output(Object x) {
output((Cons) x);
}
private void output(Cons ast) {
if (ast == null) {
return;
}
TokenType t = (TokenType) ast.first();
switch (t) {
case PROG:
output((Cons) ast.third());
break;
case FLOWER:
outputFlower(ast);
break;
case IF:
builder.append("if (");
output(ast.second());
builder.append(") then ");
output(ast.third());
builder.append(" else ");
output(ast.nth(3));
break;
case CALL:
outputCall(ast);
break;
case VARIABLE:
builder.append(ast.second());
break;
case NUMBER:
builder.append(ast.second());
break;
case STRING:
builder.append('"');
builder.append(((String)ast.second()).replace("\\", "\\\\").replace("\"", "\\\""));
builder.append('"');
break;
case XPATH:
output(ast.second());
builder.append('/');
builder.append(ast.third());
break;
case ATTR_AT:
output(ast.second());
builder.append("/@");
builder.append(ast.third());
break;
case INDEX:
output(ast.second());
builder.append('[');
output(ast.third());
builder.append(']');
break;
case EQ:
outputBinary(ast, "=");
break;
case NE:
outputBinary(ast, "!=");
break;
case PLUS:
outputBinary(ast, "+");
break;
case LT:
outputBinary(ast, "<");
break;
case LE:
outputBinary(ast, "<=");
break;
case GT:
outputBinary(ast, ">");
break;
case GE:
outputBinary(ast, ">=");
break;
case LIST:
builder.append('(');
outputArguments(ast.next());
builder.append(')');
break;
case TO:
builder.append('(');
output(ast.second());
builder.append(" to ");
output(ast.third());
builder.append(')');
break;
case ELEMENT:
outputElement(ast);
break;
default:
throw new RuntimeException("Not Implemented: " + t);
}
}
private void outputArguments(Cons arguments) {
if (arguments != null) {
output(arguments.first());
for (Object x: arguments.rest()) {
builder.append(", ");
output(x);
}
}
}
private void outputFlower(Cons ast) {
Cons forlets = ((Cons)ast.second()).next();
for (Object forlet: forlets) {
outputForlet((Cons) forlet);
}
Cons groupby = (Cons) ast.nth(4);
if (groupby != null) {
builder.append("group by ");
outputArguments(groupby.next());
builder.append('\n');
}
Cons where = (Cons) ast.nth(3);
if (where != null) {
builder.append("where ");
output(where);
builder.append('\n');
}
builder.append("return ");
output(ast.third());
}
private void outputForlet(Cons ast) {
switch ((TokenType) ast.first()) {
case FOR:
builder.append("for ");
output(ast.second());
builder.append(" in ");
output(ast.third());
builder.append('\n');
break;
case LET:
builder.append("let ");
output(ast.second());
builder.append(" := ");
output(ast.third());
builder.append('\n');
break;
default:
throw new RuntimeException("Not Implemented!");
}
}
private void outputElement(Cons ast) {
String tag = (String) ast.nth(1);
Cons attrs = (Cons) ast.nth(2);
Cons contents = (Cons) ast.nth(3);
builder.append('<');
builder.append(tag);
if (attrs != null) {
for (Object x : attrs) {
Cons a = (Cons) x;
String name = (String) a.first();
Cons values = (Cons) a.second();
builder.append(' ');
builder.append(name);
builder.append('=');
builder.append('"');
for (Object v: values) {
if (v instanceof String) {
builder.append(v);
}
else {
builder.append('{');
output(v);
builder.append('}');
}
}
builder.append('"');
}
}
if (contents != null) {
for (Object v: contents) {
if (v instanceof String) {
builder.append(v);
}
else {
builder.append('{');
output(v);
builder.append('}');
}
}
builder.append("</");
builder.append(tag);
builder.append('>');
}
else {
builder.append("/>");
}
}
private void outputCall(Cons ast) {
ast = ast.next();
builder.append((String) ast.first());
builder.append('(');
outputArguments(ast.next());
builder.append(')');
}
private void outputBinary(Cons ast, String op) {
output(ast.second());
builder.append(" ");
builder.append(op);
builder.append(" ");
output(ast.third());
}
private void outputIndent(int n) {
for (int i = 0; i < n; i++) {
builder.append(" ");
}
}
public static String unparse(Cons ast) {
Unparser unparser = new Unparser();
unparser.output(ast);
return unparser.builder.toString();
}
public static void main(String[] args) {
String xquery = "$x/t/@a";
System.out.println(unparse(org.libj.xquery.Compile.compileToAST(xquery)));
}
}
|
package org.lightmare.utils;
import java.io.Closeable;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.lightmare.utils.reflect.MetaUtils;
/**
* Utility class to help with general object checks
*
* @author levan
*
*/
public class ObjectUtils {
public static final int NOT_EXISTING_INDEX = -1;
/**
* Checks if passed boolean value is not true
*
* @param statement
* @return <code>boolean</code>
*/
public static boolean notTrue(boolean statement) {
return !statement;
}
/**
* Checks if passed object is not null
*
* @param data
* @return <code>boolean</code>
*/
public static boolean notNull(Object data) {
return (data != null);
}
/**
* Checks if not a single object passed objects is not null
*
* @param datas
* @return <code>boolean</code>
*/
public static boolean notNullAll(Object... datas) {
boolean valid = notNull(datas);
if (valid) {
int length = datas.length;
Object data;
for (int i = 0; i < length && valid; i++) {
data = datas[i];
valid = notNull(data);
}
}
return valid;
}
/**
* Checks if parameters not equals
*
* @param x
* @param y
* @return <code>boolean</code>
*/
public static <X, Y> boolean notEquals(X x, Y y) {
boolean valid = !x.equals(y);
return valid;
}
public static boolean notNullNotEquals(Object data1, Object data2) {
return notNullAll(data1, data2) && notEquals(data1, data2);
}
/**
* Cats passed {@link Object} to generic parameter
*
* @param data
* @return <code>T</code>
*/
public static <T> T cast(Object data) {
@SuppressWarnings("unchecked")
T value = (T) data;
return value;
}
/**
* Cats passed {@link Object} to generic parameter
*
* @param data
* @param castClass
* @return <code>T</code>
*/
public static <T> T cast(Object data, Class<T> castClass) {
Class<T> wrapper = MetaUtils.getWrapper(castClass);
T value = wrapper.cast(data);
return value;
}
/**
* Simply locks passed {@link Lock} object
*
* @param lock
*/
public static void lock(Lock lock) {
lock.lock();
}
/**
* Locks passed {@link Lock} object for passed time in appropriate
* {@link TimeUnit} instance
*
* @param lock
* @return <code>boolean</code>
* @throws InterruptedException
*/
public static boolean tryLock(Lock lock, Long time, TimeUnit unit)
throws IOException {
boolean locked;
try {
locked = lock.tryLock(time, unit);
} catch (InterruptedException ex) {
throw new IOException(ex);
}
return locked;
}
/**
* Locks passed {@link Lock} object
*
* @param lock
* @return <code>boolean</code>
* @throws IOException
*/
public static boolean tryLock(Lock lock) {
return lock.tryLock();
}
/**
* Unlocks passed {@link Lock} instance
*
* @param lock
*/
public static void unlock(Lock lock) {
if (lock instanceof ReentrantLock) {
ReentrantLock reentrantLock = ObjectUtils.cast(lock,
ReentrantLock.class);
if (reentrantLock.isHeldByCurrentThread()) {
lock.unlock();
}
} else {
lock.unlock();
}
}
/**
* Checks if passed {@link Closeable} instance is not null and if not calls
* {@link Closeable#close()} method
*
* @param closeable
* @throws IOException
*/
public static void close(Closeable closeable) throws IOException {
if (ObjectUtils.notNull(closeable)) {
closeable.close();
}
}
/**
* Checks if passed array of {@link Closeable}'s is valid and closes all of
* them
*
* @param closeables
* @throws IOException
*/
public static void closeAll(Closeable... closeables) throws IOException {
if (CollectionUtils.valid(closeables)) {
for (Closeable closeable : closeables) {
close(closeable);
}
}
}
}
|
package org.made.neohabitat.mods;
import java.util.Hashtable;
import org.elkoserver.foundation.json.JSONMethod;
import org.elkoserver.foundation.json.OptBoolean;
import org.elkoserver.foundation.json.OptInteger;
import org.elkoserver.foundation.json.OptString;
import org.elkoserver.json.EncodeControl;
import org.elkoserver.json.JSONLiteral;
import org.elkoserver.server.context.Context;
import org.elkoserver.server.context.ContextMod;
import org.elkoserver.server.context.ContextShutdownWatcher;
import org.elkoserver.server.context.Item;
import org.elkoserver.server.context.User;
import org.elkoserver.server.context.UserWatcher;
import org.elkoserver.util.ArgRunnable;
import org.made.neohabitat.Constants;
import org.made.neohabitat.Container;
import org.made.neohabitat.HabitatMod;
import org.made.neohabitat.Toggle;
/**
* Habitat Region Mod (attached to a Elko Context)
*
* The Region has all the state and behaviors for the main object of Habitat. It
* is the "room" logic, controlling how things interact with each other - not on
* a Item to Item or User to User basis, but when interacting between multiple
* objects in the region.
*
* @author randy
*
*/
public class Region extends Container implements UserWatcher, ContextMod, ContextShutdownWatcher, Constants {
public static String MOTD = "Welcome to Habitat!";
/** Static flag on if new features should be activated. Anyone can toggle with //neohabitat */
public static boolean NEOHABITAT_FEATURES = true;
/** The number of tokens to give to an avatar each new day that the user loggs in */
public static final int STIPEND = 100;
/** The default depth for a region. */
public static final int DEFAULT_REGION_DEPTH = 32;
/** The default maximum number of avatars for a Region. */
public static final int DEFAULT_MAX_AVATARS = 6;
/** Statics are shared amongst all regions */
/** All the currently logged in user names for ESP lookup */
public static Hashtable<String, User> NameToUser = new Hashtable<String, User>();
/** All the currently instantiated regions for region transition testing */
public static Hashtable<String, Region> RefToRegion = new Hashtable<String, Region>();
public int HabitatClass() {
return CLASS_REGION;
}
public String HabitatModName() {
return "Region";
}
public int capacity() {
return 255;
}
public int pc_state_bytes() {
return 1;
};
public boolean known() {
return true;
}
public boolean opaque_container() {
return false;
}
public boolean filler() {
return false;
}
/** A collection of server-side region status flags */
public boolean nitty_bits[] = new boolean[32];
/** The lighting level in the room. 0 is Dark. */
public int lighting = 0;
/** The horizon line for the region to clip avatar motion */
public int depth = DEFAULT_REGION_DEPTH;
/** The maximum number of Avatars that can be in this Region */
public int max_avatars = DEFAULT_MAX_AVATARS;
/**
* This is an array holding all the Mods for all the Users and Items in this
* room.
*/
public HabitatMod noids[] = new HabitatMod[256];
public int nextNoid = 1;
public String neighbors[] = { "", "", "", "" };
/** Direction to nearest Town */
public String town_dir = "";
/** Direction to nearest Teleport Booth */
public String port_dir = "";
public boolean is_turf = false;
public String resident = "";
public String realm = "unknown";
public boolean locked = false;
/** C64 Heap Emulation */
public int[] class_ref_count = new int[256];
public int[][] resource_ref_count = new int[4][256]; // images, heads, behaviors, sounds
public int space_usage = 0;
/** A handle to the mandatory singleton ghost object for this region */
@JSONMethod({ "style", "x", "y", "orientation", "gr_state", "nitty_bits", "depth", "lighting",
"town_dir", "port_dir", "max_avatars", "neighbors", "is_turf", "resident", "realm", "locked" })
public Region(OptInteger style, OptInteger x, OptInteger y, OptInteger orientation, OptInteger gr_state,
OptInteger nitty_bits, OptInteger depth, OptInteger lighting,
OptString town_dir, OptString port_dir, OptInteger max_avatars,
String[] neighbors, OptBoolean is_turf, OptString resident, OptString realm,
OptBoolean locked) {
super(style, x, y, orientation, gr_state, new OptBoolean(false));
if (nitty_bits.value(-1) != -1) {
this.nitty_bits = unpackBits(nitty_bits.value());
}
this.depth = depth.value(DEFAULT_REGION_DEPTH);
this.lighting = lighting.value(0);
this.max_avatars = max_avatars.value(DEFAULT_MAX_AVATARS);
this.neighbors = neighbors;
this.town_dir = town_dir.value("");
this.port_dir = port_dir.value("");
this.is_turf = is_turf.value(false);
this.resident = resident.value("");
this.realm = realm.value("unknown");
this.locked = locked.value(false);
this.noid = THE_REGION;
}
public Region(int style, int x, int y, int orientation, int gr_state, boolean[] nitty_bits,
int depth, int lighting, String town_dir, String port_dir, int max_avatars,
String[] neighbors, boolean is_turf, String resident, String realm, boolean locked) {
super(style, x, y, orientation, gr_state, false);
this.nitty_bits = nitty_bits;
this.depth = depth;
this.lighting = lighting;
this.max_avatars = max_avatars;
this.neighbors = neighbors;
this.town_dir = town_dir;
this.port_dir = port_dir;
this.is_turf = is_turf;
this.resident = resident;
this.realm = realm;
this.locked = locked;
this.noid = THE_REGION;
}
@Override
public void objectIsComplete() {
((Context) object()).registerUserWatcher((UserWatcher) this);
noids[THE_REGION] = this;
note_object_creation(this);
Region.RefToRegion.put(obj_id(), this);
}
private Ghost regionGhost() {
return (Ghost) noids[GHOST_NOID];
}
public Ghost getGhost() {
Ghost ghost = regionGhost();
if (ghost == null) {
ghost = new Ghost(0, 4, 240, 0, 0, false);
ghost.noid = GHOST_NOID;
create_object("Ghost", ghost, this, true);
new Thread(announceGhostLater).start();
}
return ghost;
}
/**
* It could be that the ghost is getting created at startup time, which is too soon to send messages to the clients.
*/
protected Runnable announceGhostLater = new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
announce_object(current_region().noids[GHOST_NOID].object(), current_region());
} catch (InterruptedException neverHappens) {
Thread.currentThread().interrupt();
}
}
};
public void destroyGhost(User from) {
Ghost ghost = regionGhost();
if (ghost != null) {
if (from != null)
send_neighbor_msg(from, THE_REGION, "GOAWAY_$", "target", GHOST_NOID);
destroy_object(ghost);
}
}
@Override
public void noteContextShutdown() {
destroyGhost(null);
Region.RefToRegion.remove(obj_id());
}
public void noteUserArrival(User who) {
Avatar avatar = (Avatar) who.getMod(Avatar.class);
avatar.inc_record(HS$travel);
int today = (int) (System.currentTimeMillis() / ONE_DAY);
int time = (int) (System.currentTimeMillis() % ONE_DAY);
if (today > avatar.lastConnectedDay) {
avatar.bankBalance += STIPEND;
avatar.set_record(HS$wealth, avatar.bankBalance);
avatar.inc_record(HS$lifetime);
}
avatar.lastArrivedIn = context().baseRef();
avatar.lastConnectedDay = today;
avatar.lastConnectedTime = time;
if (avatar.amAGhost) {
getGhost().total_ghosts++; // Make sure the user has a ghost object..
}
if (avatar.firstConnection) {
object_say(who, MOTD);
if (NEOHABITAT_FEATURES) {
if (NameToUser.size() < 2) {
object_say(who, UPGRADE_PREFIX + "You are the only one here right now.");
} else {
object_say(who, UPGRADE_PREFIX + "There are " + (NameToUser.size() - 1) + " others here" +
(avatar.amAGhost ? "." : " Press F3 to see a list."));
}
if (avatar.amAGhost) {
object_say(who, UPGRADE_PREFIX + "You are a ghost. Press F1 to become an Avatar.");
}
tellEveryone(who.name() + " has arrived.");
}
}
avatar.check_mail();
Region.addUser(who);
}
public void noteUserDeparture(User who) {
Region.removeUser(who);
Avatar avatar = avatar(who);
Ghost ghost = regionGhost();
if (avatar.holding_restricted_object()) {
avatar.heldObject().putMeBack(who, false);
}
if (avatar.amAGhost) {
ghost.total_ghosts
if (ghost.total_ghosts == 0) {
destroyGhost(who);
}
} else {
lights_off(avatar);
}
avatar.lastConnectedDay = (int) (System.currentTimeMillis() / ONE_DAY);
avatar.lastConnectedTime = (int) (System.currentTimeMillis() % ONE_DAY);
avatar.gen_flags[MODIFIED] = true;
avatar.checkpoint_object(avatar);
}
private int avatarsPresent() {
return class_ref_count[CLASS_AVATAR];
}
public synchronized static void addUser(User from) {
NameToUser.put(from.name().toLowerCase(), from);
}
public synchronized static void removeUser(User from) {
Avatar avatar = (Avatar) from.getMod(Avatar.class);
NameToUser.remove(from.name().toLowerCase());
removeContentsFromRegion(avatar);
avatar.note_object_deletion(avatar);
removeFromObjList(avatar);
}
public static User getUserByName(String name) {
if (name != null) {
return (User) NameToUser.get(name.toLowerCase());
}
return null;
}
public static final int AVERAGE_C64_AVATAR_LOAD = 1000; // bytes. Non-scientific spitball guess of additional headroom needed for head image + 4 unique items.
public static boolean IsRoomForMyAvatarIn(String regionRef, User from) {
Region region = Region.RefToRegion.get(regionRef);
if (region == null)
return true; // if there is no instantiated region, there must be room!
return region.isRoomForMyAvatar(from);
}
public boolean isRoomForMyAvatar(User from) {
if (avatarsPresent() == max_avatars)
return false;
// TODO: Remove the silly headroom estimate below with something real someday?
if (space_usage + AVERAGE_C64_AVATAR_LOAD >= C64_HEAP_SIZE)
return false;
return mem_check_container(avatar(from)); // Check the pocket contents for other overflows.
}
@Override
public JSONLiteral encode(EncodeControl control) {
JSONLiteral result = new JSONLiteral(HabitatModName(), control); // Normally I would call encodeCommon() but don't want to bother with the extraneous fields.
result.addParameter("orientation", orientation);
if (packBits(nitty_bits) != 0) {
result.addParameter("nitty_bits", packBits(nitty_bits));
}
result.addParameter("depth", depth);
result.addParameter("lighting", lighting);
result.addParameter("neighbors", neighbors);
if (control.toRepository()) {
result.addParameter("max_avatars", max_avatars);
result.addParameter("town_dir", town_dir);
result.addParameter("port_dir", port_dir);
result.addParameter("is_turf", is_turf);
result.addParameter("resident", resident);
result.addParameter("realm", realm);
result.addParameter("locked", locked);
}
result.finish();
return result;
}
private static int incNoid(int noid) {
noid++;
switch (noid) {
case THE_REGION:
case GHOST_NOID:
case 256:
return 1;
}
return noid;
}
/**
* Add a HabitatMod to the object list for easy lookup by noid.
* This method uses a monotonically increasing index, remembering
* the previous noid assignment. Deleted objects will leave holes
* that we are in no hurry to fill in. Note the reserved NOID ids
* of THE_REGION (0) and GHOST_NOID (255).
*
* @param mod
*/
public static boolean addToNoids(HabitatMod mod) {
Region region = mod.current_region();
int noid = region.nextNoid;
HabitatMod[] noids = region.noids;
if (region.nextNoid == -1) {
return false; /* Too many things in this region!*/
}
noids[noid] = mod;
mod.noid = noid;
noid = incNoid(noid);
while (null != noids[noid]) {
noid = incNoid(noid);
if (noid == region.nextNoid) {
noid = -1;
break; // Searched everything, none free.
}
}
region.nextNoid = noid;
return true; // noid added, even if no
}
/**
* Remove the noid from the object list.
*
* @param mod
* The object to remove from the noid list.
*/
public static void removeFromObjList(HabitatMod mod) {
if (mod.noid < UNASSIGNED_NOID) {
mod.current_region().noids[mod.noid] = null;
mod.noid = UNASSIGNED_NOID;
}
}
/**
* When items go away because their container left or closed, we must reclaim scarce resources: noids and
*
* @param cont
*/
public static void removeContentsFromRegion(Container cont) {
for (int i = 0; i < cont.capacity(); i++) {
HabitatMod obj = cont.contents(i);
if (obj != null)
removeObjectFromRegion(obj);
}
}
public static void removeObjectFromRegion(HabitatMod obj) {
if (obj == null)
return;
Container cont = obj.container();
if (cont != null & cont.opaque_container())
obj.note_instance_deletion(obj);
else
obj.note_object_deletion(obj);
removeFromObjList(obj);
}
public static void tellEveryone(String text) {
for (String key: NameToUser.keySet()) {
User user = NameToUser.get(key);
Avatar avatar = (Avatar) user.getMod(Avatar.class);
avatar.object_say(user, UPGRADE_PREFIX + text);
}
}
public static void tellEveryone(int[] ascii) {
for (String key: NameToUser.keySet()) {
User user = NameToUser.get(key);
Avatar avatar = (Avatar) user.getMod(Avatar.class);
JSONLiteral msg = avatar.new_private_msg(THE_REGION, "OBJECTSPEAK_$");
int send[] = new int[ascii.length + 1];
send[0] = UPGRADE_PREFIX.charAt(0);
System.arraycopy(ascii, 0, send, 1, ascii.length);
msg.addParameter("ascii", send);
msg.addParameter("speaker", avatar.noid);
msg.finish();
user.send(msg);
}
}
/**
* The client is leaving the Habitat Application and wants to politely
* disconnect.
*
* @param from
* The client disconnecting
*/
@JSONMethod({ "reason" })
public void LEAVE(User from, OptInteger reason) {
if (reason.present()) {
trace_msg("Client error " + CLIENT_ERRORS[reason.value()] + " reported by " + from.ref());
}
try {
current_region().context().exit(from);
} catch (Exception ignored) {
trace_msg("Invalid attempt to leave by " + from.ref() + " failed: " + ignored.toString());
}
}
/**
* The client is slow and this might provide an advantage to others seeing a
* new avatar before it can react. The server is told by this message that
* it deal with messages before this as being before the user has appeared.
*
* @param from
* The client connection that needs to catch up...
*/
@JSONMethod
public void FINGER_IN_QUE(User from) {
this.send_private_msg(from, 0, from, "CAUGHT_UP_$", "err", TRUE);
}
/**
* Handle the client request to "appear" after the client is done loading
* the region.
*
* @param from
* The client connection that has "caught up" loading the
* contents vector it just received.
*/
@JSONMethod
public void I_AM_HERE(User from) {
Avatar who = avatar(from);
who.gr_state &= ~INVISIBLE;
who.showDebugInfo(from);
send_broadcast_msg(0, "APPEARING_$", "appearing", who.noid);
// If the avatar has any objects in their hands, perform any necessary side effects.
lights_on(who);
}
public boolean grabable(HabitatMod mod) {
if (nitty_bits[STEAL_FREE] |
mod.HabitatClass() == CLASS_PAPER |
mod.HabitatClass() == CLASS_BOOK |
mod.HabitatClass() == CLASS_TOKENS |
(mod.HabitatClass() == CLASS_MAGIC_LAMP && mod.gr_state == MAGIC_LAMP_GENIE)) {
return false;
}
return true;
}
public void lights_off(Avatar avatar) {
if (!empty_handed(avatar)) {
HabitatMod light = avatar.contents(HANDS);
if (light.HabitatClass() == CLASS_FLASHLIGHT) {
if (((Toggle) light).on == TRUE) {
lighting -= 1;
send_broadcast_msg(THE_REGION, "CHANGELIGHT_$", "adjustment", -1);
}
}
}
}
public void lights_on(Avatar avatar) {
if (!empty_handed(avatar)) {
HabitatMod held = avatar.contents(HANDS);
/* If holding a flashheld.on entry, turn on the held. */
if (held.HabitatClass() == CLASS_FLASHLIGHT) {
if (((Toggle) held).on == TRUE) {
lighting += 1;
send_broadcast_msg(THE_REGION, "CHANGELIGHT_$", "adjustment", +1);
}
}
/* If holding a compass, set the arrow pointer */
if (held.HabitatClass() == CLASS_COMPASS) {
held.gr_state = orientation;
held.gen_flags[MODIFIED] = true;
}
}
}
/**
* Handle request to change the Message of the Day.
* Presently, this is a non-persistent change.
*
* @param from
* @param MOTD
*/
@JSONMethod ({ "MOTD" })
public void SET_MOTD(User from, String MOTD) {
// TODO FRF Security is missing from this feature. Should this be a message on Admin/Session?
Region.MOTD = MOTD;
}
/**
* Handle request to send a word balloon message
* to every user currently online.
*
* @param from
* @param MOTD
*/
@JSONMethod ({ "text", "ascii" })
public void TELL_EVERYONE(User from, OptString text, int[] ascii) {
// TODO FRF Security is missing from this feature. Should this be a message on Admin/Session?
tellEveryone(" From: The Oracle To: All Avatars: ");
if (ascii != null) {
tellEveryone(ascii);
} else {
tellEveryone(text.value("... nevermind ..."));
}
}
/**
* Handle a prompted message, overloading the text-entry field. This
* requires some callback related storage in Avatar.
*
* @param from
* The user-connection that sent the prompt reply
* @param text
* The prompt reply (includes any prompt.)
*/
@JSONMethod({ "text" })
public void PROMPT_REPLY(User from, OptString text) {
String prompt = text.value("");
String body = null;
Avatar avatar = avatar(from);
if (prompt.contains(GOD_TOOL_PROMPT)) {
body = prompt.substring(GOD_TOOL_PROMPT.length());
if (0 == body.length()) {
avatar.savedMagical = null;
avatar.savedTarget = null;
return;
}
avatar.savedMagical.god_tool_revisited(from, body);
return;
}
}
public void describeRegion(User from, int noid) {
String name_str = object().name();
String help_str = "";
if (name_str.isEmpty())
help_str = "This region has no name";
else
help_str = "This region is " + name_str;
if (!town_dir.isEmpty())
help_str += ". The nearest town is " + town_dir;
if (!port_dir.isEmpty())
help_str += ". The nearest teleport booth is " + port_dir;
help_str += ".";
send_reply_msg(from, noid, "text", help_str);
}
}
|
package org.minperf.generator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.RecursiveAction;
import org.minperf.BitBuffer;
import org.minperf.Settings;
import org.minperf.bdz.BDZ;
import org.minperf.monotoneList.MonotoneList;
import org.minperf.universal.UniversalHash;
/**
* Generator of a hybrid MPHF. It is guaranteed to use linear space, because
* large buckets are encoded using an alternative algorithm.
*
* @param <T> the type
*/
public class Generator<T> {
public static final int MAX_FILL = 8;
public static final int MAX_BITS_PER_ENTRY = 8;
final ConcurrencyTool pool;
final UniversalHash<T> hash;
private final Settings settings;
private final boolean eliasFanoMonotoneLists;
private final int maxChunkSize;
public Generator(ConcurrencyTool pool,
UniversalHash<T> hash,
Settings settings,
boolean eliasFanoMonotoneLists,
int maxChunkSize) {
this.pool = pool;
this.settings = settings;
this.hash = hash;
this.eliasFanoMonotoneLists = eliasFanoMonotoneLists;
this.maxChunkSize = maxChunkSize;
}
@SuppressWarnings("unchecked")
public void generate(T[] data, long[] hashes, long startIndex, BitBuffer buff) {
int size = data.length;
if (size < 2) {
return;
}
if (size <= settings.getLeafSize()) {
long index = getIndex(data, hashes, startIndex);
int shift = settings.getGolombRiceShift(size);
long value = index - startIndex - 1;
buff.writeGolombRice(shift, value);
return;
}
long index = startIndex + 1;
while (true) {
if (Settings.needNewUniversalHashIndex(index)) {
long x = Settings.getUniversalHashIndex(index);
for (int i = 0; i < size; i++) {
hashes[i] = hash.universalHash(data[i], x);
}
}
if (trySplitEvenly(hashes, index)) {
break;
}
index++;
}
int writeK = settings.getGolombRiceShift(size);
long writeIndex = index - startIndex - 1;
buff.writeGolombRice(writeK, writeIndex);
int split = settings.getSplit(size);
int firstPart, otherPart;
if (split < 0) {
firstPart = -split;
otherPart = size - firstPart;
split = 2;
} else {
firstPart = size / split;
otherPart = firstPart;
}
T[][] data2;
long[][] hashes2;
if (firstPart != otherPart) {
data2 = (T[][]) new Object[][] { (T[]) new Object[firstPart],
(T[]) new Object[otherPart] };
hashes2 = new long[][] { new long[firstPart], new long[otherPart] };
} else {
data2 = (T[][]) new Object[split][firstPart];
hashes2 = new long[split][firstPart];
}
splitEvenly(data, hashes, index, data2, hashes2);
for (int i = 0; i < data2.length; i++) {
generate(data2[i], hashes2[i], index, buff);
}
}
private long getIndex(T[] data, long[] hashes, long startIndex) {
int size = data.length;
long index = startIndex + 1;
outer: while (true) {
if (Settings.needNewUniversalHashIndex(index)) {
long x = Settings.getUniversalHashIndex(index);
for (int i = 0; i < size; i++) {
hashes[i] = hash.universalHash(data[i], x);
}
Arrays.sort(hashes);
for (int i = 1; i < size; i++) {
if (hashes[i - 1] == hashes[i]) {
index++;
while (!Settings.needNewUniversalHashIndex(index)) {
index++;
}
continue outer;
}
}
}
if (tryUnique(hashes, index)) {
return index;
}
index++;
}
}
private boolean trySplitEvenly(long[] hashes, long index) {
int size = hashes.length;
int split = settings.getSplit(size);
int firstPart, otherPart;
if (split < 0) {
firstPart = -split;
otherPart = size - firstPart;
split = 2;
} else {
firstPart = size / split;
otherPart = firstPart;
}
if (firstPart != otherPart) {
int limit = firstPart;
for (int i = 0; i < size; i++) {
long h = hashes[i];
int x = Settings.supplementalHash(h, index);
x = Settings.reduce(x, size);
if (x < limit) {
if (--firstPart < 0) {
return false;
}
} else {
if (--otherPart < 0) {
return false;
}
}
}
return true;
}
int[] count = new int[split];
Arrays.fill(count, firstPart);
for (int i = 0; i < size; i++) {
long h = hashes[i];
int x = Settings.supplementalHash(h, index);
x = Settings.reduce(x, split);
if (--count[x] < 0) {
return false;
}
}
return true;
}
private void splitEvenly(T[] data, long[] hashes, long index, T[][] data2,
long[][] hashes2) {
int size = data.length;
int split = data2.length;
int firstPartSize = data2[0].length;
int otherPartSize = data2[1].length;
if (firstPartSize != otherPartSize) {
int i0 = 0, i1 = 0;
int limit = firstPartSize;
for (int i = 0; i < size; i++) {
T t = data[i];
long h = hashes[i];
int x = Settings.supplementalHash(h, index);
x = Settings.reduce(x, size);
if (x < limit) {
data2[0][i0] = t;
hashes2[0][i0] = h;
i0++;
} else {
data2[1][i1] = t;
hashes2[1][i1] = h;
i1++;
}
}
return;
}
int[] pos = new int[split];
for (int i = 0; i < size; i++) {
T t = data[i];
long h = hashes[i];
int x = Settings.supplementalHash(h, index);
int bucket = Settings.reduce(x, split);
int p = pos[bucket]++;
data2[bucket][p] = t;
hashes2[bucket][p] = h;
}
}
static <T> boolean tryUnique(long[] hashes, long index) {
int bits = 0;
int size = hashes.length;
for (int i = 0; i < size; i++) {
long x = hashes[i];
int h = Settings.supplementalHash(x, index);
h = Settings.reduce(h, size);
if ((bits & (1 << h)) != 0) {
return false;
}
bits |= 1 << h;
}
return true;
}
public BitBuffer generate(Collection<T> collection) {
long size = collection.size();
int bucketCount = Settings.getBucketCount(size, settings.getAverageBucketSize());
ArrayList<Bucket> buckets = new ArrayList<Bucket>(bucketCount);
int averageBucketSize = settings.getAverageBucketSize();
if (size <= maxChunkSize || bucketCount == 1) {
for (int i = 0; i < bucketCount; i++) {
buckets.add(new Bucket(averageBucketSize));
}
for (T t : collection) {
int b;
if (bucketCount == 1) {
b = 0;
} else {
long h = hash.universalHash(t, 0);
b = Settings.reduce((int) h, bucketCount);
if (b >= bucketCount || b < 0) {
throw new AssertionError();
}
}
buckets.get(b).add(t);
}
processBuckets(size, bucketCount, buckets);
} else {
// split into chunks
int bucketsPerChunk = Math.max(1, maxChunkSize / averageBucketSize);
int remaining = bucketCount;
for (int bucketOffset = 0; bucketOffset < bucketCount; bucketOffset += bucketsPerChunk) {
int chunkSize = Math.min(bucketsPerChunk, remaining);
remaining -= chunkSize;
ArrayList<Bucket> buckets2 = new ArrayList<Bucket>(chunkSize);
for (int i = 0; i < chunkSize; i++) {
buckets2.add(new Bucket(averageBucketSize));
}
for (T t : collection) {
int b;
long h = hash.universalHash(t, 0);
b = Settings.reduce((int) h, bucketCount);
if (b >= bucketCount || b < 0) {
throw new AssertionError();
}
if (b >= bucketOffset && b < bucketOffset + bucketsPerChunk) {
buckets2.get(b - bucketOffset).add(t);
}
}
processBuckets(size, bucketCount, buckets2);
for (Bucket b2 : buckets2) {
buckets.add(b2);
}
buckets2.clear();
}
}
ArrayList<T> alternativeList = new ArrayList<T>();
for (int i = 0; i < buckets.size(); i++) {
Bucket b = buckets.get(i);
// move all buckets first, so overlap is not affected
b.moveToAlternative(alternativeList);
}
int[] startList = new int[buckets.size() + 1];
int[] offsetList = new int[buckets.size() + 1];
int start = 0, offset = 0;
for (int i = 0; i < buckets.size(); i++) {
Bucket b = buckets.get(i);
if (start - offset < 0) {
throw new AssertionError();
}
int pos = b.buff.position();
// possible overlap
if (i < buckets.size() - 1) {
Bucket next = buckets.get(i + 1);
int maxOverlap = Math.min(16, next.buff.position());
// at least one bit per entry
int minBitCount = getMinBitCount(b.entryCount);
maxOverlap = Math.min(maxOverlap, b.buff.position() - minBitCount);
int overlap = 0;
for (; overlap < maxOverlap; overlap++) {
if (next.buff.readNumber(0, overlap + 1) !=
b.buff.readNumber(pos - overlap - 1, overlap + 1)) {
break;
}
}
pos -= overlap;
b.buff.seek(pos);
}
start += pos;
offset += b.entryCount;
startList[i + 1] = start;
offsetList[i + 1] = offset;
}
shrinkList(startList, offsetList);
int minOffsetDiff = shrinkList(offsetList);
int minStartDiff = shrinkList(startList);
if (minStartDiff < 0) {
throw new AssertionError();
}
BitBuffer alt = null;
if (!alternativeList.isEmpty()) {
alt = BDZ.generate(hash, alternativeList);
}
int bitCount = BitBuffer.getEliasDeltaSize(size + 1);
bitCount += 1;
bitCount += BitBuffer.getEliasDeltaSize(minOffsetDiff + 1);
bitCount += BitBuffer.getEliasDeltaSize(minStartDiff + 1);
bitCount += MonotoneList.getSize(offsetList, eliasFanoMonotoneLists);
bitCount += MonotoneList.getSize(startList, eliasFanoMonotoneLists);
bitCount += start;
if (alt != null) {
bitCount += alt.position();
}
BitBuffer all = new BitBuffer(bitCount);
all.writeEliasDelta(size + 1);
all.writeBit(alternativeList.isEmpty() ? 0 : 1);
all.writeEliasDelta(minOffsetDiff + 1);
all.writeEliasDelta(minStartDiff + 1);
MonotoneList.generate(offsetList, all, eliasFanoMonotoneLists);
MonotoneList.generate(startList, all, eliasFanoMonotoneLists);
for (int i = 0; i < buckets.size(); i++) {
Bucket b = buckets.get(i);
all.write(b.buff);
}
if (alt != null) {
all.write(alt);
}
if (bitCount != all.position()) {
throw new AssertionError();
}
return all;
}
private void processBuckets(long size, int bucketCount, final ArrayList<Bucket> buckets) {
int averageBucketSize = (int) (size / bucketCount);
final int maxBucketSize = averageBucketSize * MAX_FILL;
final int maxBits = maxBucketSize * MAX_BITS_PER_ENTRY;
pool.invoke(new RecursiveAction() {
private static final long serialVersionUID = 1L;
@Override
protected void compute() {
RecursiveAction[] list = new RecursiveAction[buckets.size()];
for (int i = 0; i < buckets.size(); i++) {
final Bucket b = buckets.get(i);
list[i] = new RecursiveAction() {
private static final long serialVersionUID = 1L;
@Override
protected void compute() {
b.generateBucket(hash, maxBucketSize, maxBits);
}
};
}
pool.invokeAll(list);
}
});
}
public static void shrinkList(int[] targetList, int[] sourceList) {
int sum = 0;
for (int i = 1; i < sourceList.length; i++) {
int d = sourceList[i] - sourceList[i - 1];
sum += d;
targetList[i] -= getMinBitCount(sum);
if (targetList[i] < targetList[i - 1]) {
throw new IllegalArgumentException("");
}
}
}
public static int shrinkList(int[] list) {
int min = Integer.MAX_VALUE;
for (int i = 0; i < list.length - 1; i++) {
int d = list[i + 1] - list[i];
min = Math.min(min, d);
}
for (int i = 1; i < list.length; i++) {
list[i] -= i * min;
}
return min;
}
public static int getMinBitCount(int size) {
// at least 1.375 bits per key (if it is less, fill with zeroes)
return (size * 11 + 7) >> 3;
}
/**
* A bucket.
*/
class Bucket {
ArrayList<T> list;
BitBuffer buff;
int entryCount;
boolean alternative;
Bucket(int averageBucketSize) {
list = new ArrayList<T>(averageBucketSize * 11 / 10);
}
@Override
public String toString() {
return "" + entryCount;
}
public void moveToAlternative(ArrayList<T> alternativeList) {
if (alternative) {
alternativeList.addAll(list);
list = null;
entryCount = 0;
buff = new BitBuffer(0);
}
}
void add(T obj) {
list.add(obj);
}
void generateBucket(UniversalHash<T> hash, int maxBucketSize, int maxBits) {
int size = list.size();
entryCount = size;
int minSize = getMinBitCount(size);
if (size <= 1) {
// zero or one entry
buff = new BitBuffer(minSize);
while (buff.position() < minSize) {
buff.writeBit(1);
}
return;
}
if (size > maxBucketSize) {
alternative = true;
buff = new BitBuffer(0);
return;
}
@SuppressWarnings("unchecked")
T[] data = list.toArray((T[]) new Object[0]);
list = null;
long[] hashes = new long[size];
long startIndex = 0;
for (int i = 0; i < size; i++) {
hashes[i] = hash.universalHash(data[i],
Settings.getUniversalHashIndex(startIndex));
}
// this is very conservative; less memory could be allocated
int bufferSize = 8 * size;
if (settings.getLeafSize() < 6) {
bufferSize *= 4;
}
buff = new BitBuffer(bufferSize);
generate(data, hashes, startIndex, buff);
if (buff.position() < minSize) {
while (buff.position() < minSize) {
buff.writeBit(1);
}
}
if (buff.position() > maxBits) {
alternative = true;
}
}
}
}
|
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
public class RadioMenuItemGroup
{
ArrayList<RadioMenuItem> radios;
// Default methods from java.awt.CheckboxGroup
public RadioMenuItemGroup()
{
radios = new ArrayList<>();
}
// Gets the current choice from this radio menu item group. The current choice
// is the radio menu item in this group that is currently in the "on" state, or
// null if all radio menu itemes in the group are off.
public RadioMenuItem getSelectedRadioMenuItem()
{
for (RadioMenuItem radio : radios)
if ( radio.getState() )
return radio;
return null;
}
// Sets the currently selected radio menu item in this group to be the specified
// radio menu item. This method sets the state of that radio menu item to "on" and sets
// all other radio menu itemes in the group to be off.
// If the radio menu item argument is null, all radio menu itemes in this radio menu item
// group are deselected. If the radio menu item argument belongs to a different
// radio menu item group, this method does nothing.
public void setSelectedRadioMenuItem(RadioMenuItem radio)
{
// If the user gave us a random RadioMenuItem not in this group, add it
if ( radio.getRadioMenuItemGroup() != this )
radio.setRadioMenuItemGroup(this);
// Set all of the radios to off
for (RadioMenuItem _radio : radios)
_radio.setState(false);
// Turn our radio on
radio.setState(true);
}
// Returns a string representation of this radio menu item group, including the
// value of its current selection.
public String toString()
{
// I don't know exactly how CheckboxGroup's toString works
String s = "[";
for(RadioMenuItem radio : radios)
s += radio.getLabel() + ": " + radio.getState() + ", ";
return s.substring(0, s.length()-2)+"]";
}
// Custom methods
public void addRadioMenuItem(RadioMenuItem radio)
{
// If the user gave us a random RadioMenuItem not in this group, add it
if ( radio.getRadioMenuItemGroup() != this )
{
radio.setRadioMenuItemGroup(this);
}
else
{
radios.add(radio);
radios.get(radios.size()-1).addItemListener( new ItemListener()
{
@Override
public void itemStateChanged(ItemEvent e)
{
if ( e.getStateChange() == ItemEvent.SELECTED )
radios.get(radios.size()-1).getRadioMenuItemGroup().setSelectedRadioMenuItem(radios.get(radios.size()-1));
}
});
if ( radio.getState() )
{
setSelectedRadioMenuItem( radio );
}
}
}
}
|
package org.spongepowered.api.data;
import io.leangen.geantyref.TypeToken;
import net.kyori.adventure.bossbar.BossBar;
import net.kyori.adventure.text.Component;
import org.spongepowered.api.ResourceKey;
import org.spongepowered.api.block.BlockState;
import org.spongepowered.api.block.BlockType;
import org.spongepowered.api.block.BlockTypes;
import org.spongepowered.api.block.entity.Banner;
import org.spongepowered.api.block.entity.BlockEntity;
import org.spongepowered.api.block.entity.CommandBlock;
import org.spongepowered.api.block.entity.EndGateway;
import org.spongepowered.api.block.entity.Jukebox;
import org.spongepowered.api.block.entity.Lectern;
import org.spongepowered.api.block.entity.MobSpawner;
import org.spongepowered.api.block.entity.Piston;
import org.spongepowered.api.block.entity.Sign;
import org.spongepowered.api.block.entity.StructureBlock;
import org.spongepowered.api.block.entity.carrier.Beacon;
import org.spongepowered.api.block.entity.carrier.BrewingStand;
import org.spongepowered.api.block.entity.carrier.CarrierBlockEntity;
import org.spongepowered.api.block.entity.carrier.Hopper;
import org.spongepowered.api.block.entity.carrier.furnace.FurnaceBlockEntity;
import org.spongepowered.api.data.meta.BannerPatternLayer;
import org.spongepowered.api.data.type.ArmorMaterial;
import org.spongepowered.api.data.type.ArtType;
import org.spongepowered.api.data.type.AttachmentSurface;
import org.spongepowered.api.data.type.BoatType;
import org.spongepowered.api.data.type.BodyPart;
import org.spongepowered.api.data.type.BodyParts;
import org.spongepowered.api.data.type.CatType;
import org.spongepowered.api.data.type.ChestAttachmentType;
import org.spongepowered.api.data.type.ComparatorMode;
import org.spongepowered.api.data.type.DoorHinge;
import org.spongepowered.api.data.type.DyeColor;
import org.spongepowered.api.data.type.FoxType;
import org.spongepowered.api.data.type.HandPreference;
import org.spongepowered.api.data.type.HorseColor;
import org.spongepowered.api.data.type.HorseStyle;
import org.spongepowered.api.data.type.InstrumentType;
import org.spongepowered.api.data.type.ItemTier;
import org.spongepowered.api.data.type.LlamaType;
import org.spongepowered.api.data.type.MatterType;
import org.spongepowered.api.data.type.MooshroomType;
import org.spongepowered.api.data.type.NotePitch;
import org.spongepowered.api.data.type.PandaGene;
import org.spongepowered.api.data.type.PandaGenes;
import org.spongepowered.api.data.type.ParrotType;
import org.spongepowered.api.data.type.PhantomPhase;
import org.spongepowered.api.data.type.PickupRule;
import org.spongepowered.api.data.type.PistonType;
import org.spongepowered.api.data.type.PortionType;
import org.spongepowered.api.data.type.ProfessionType;
import org.spongepowered.api.data.type.RabbitType;
import org.spongepowered.api.data.type.RailDirection;
import org.spongepowered.api.data.type.SkinPart;
import org.spongepowered.api.data.type.SlabPortion;
import org.spongepowered.api.data.type.SpellType;
import org.spongepowered.api.data.type.SpellTypes;
import org.spongepowered.api.data.type.StairShape;
import org.spongepowered.api.data.type.StructureMode;
import org.spongepowered.api.data.type.TropicalFishShape;
import org.spongepowered.api.data.type.VillagerType;
import org.spongepowered.api.data.type.WireAttachmentType;
import org.spongepowered.api.data.value.ListValue;
import org.spongepowered.api.data.value.MapValue;
import org.spongepowered.api.data.value.SetValue;
import org.spongepowered.api.data.value.Value;
import org.spongepowered.api.data.value.WeightedCollectionValue;
import org.spongepowered.api.effect.VanishState;
import org.spongepowered.api.effect.particle.ParticleEffect;
import org.spongepowered.api.effect.particle.ParticleOption;
import org.spongepowered.api.effect.particle.ParticleType;
import org.spongepowered.api.effect.potion.PotionEffect;
import org.spongepowered.api.effect.potion.PotionEffectType;
import org.spongepowered.api.effect.potion.PotionEffectTypes;
import org.spongepowered.api.effect.sound.music.MusicDisc;
import org.spongepowered.api.entity.AreaEffectCloud;
import org.spongepowered.api.entity.Entity;
import org.spongepowered.api.entity.EntityArchetype;
import org.spongepowered.api.entity.EntityType;
import org.spongepowered.api.entity.ExperienceOrb;
import org.spongepowered.api.entity.FallingBlock;
import org.spongepowered.api.entity.Item;
import org.spongepowered.api.entity.ai.goal.GoalExecutorTypes;
import org.spongepowered.api.entity.explosive.EndCrystal;
import org.spongepowered.api.entity.explosive.Explosive;
import org.spongepowered.api.entity.explosive.fused.FusedExplosive;
import org.spongepowered.api.entity.explosive.fused.PrimedTNT;
import org.spongepowered.api.entity.hanging.Hanging;
import org.spongepowered.api.entity.hanging.ItemFrame;
import org.spongepowered.api.entity.hanging.LeashKnot;
import org.spongepowered.api.entity.hanging.Painting;
import org.spongepowered.api.entity.living.Ageable;
import org.spongepowered.api.entity.living.Agent;
import org.spongepowered.api.entity.living.ArmorStand;
import org.spongepowered.api.entity.living.Bat;
import org.spongepowered.api.entity.living.Humanoid;
import org.spongepowered.api.entity.living.Living;
import org.spongepowered.api.entity.living.animal.Animal;
import org.spongepowered.api.entity.living.animal.Cat;
import org.spongepowered.api.entity.living.animal.Chicken;
import org.spongepowered.api.entity.living.animal.Fox;
import org.spongepowered.api.entity.living.animal.Ocelot;
import org.spongepowered.api.entity.living.animal.Panda;
import org.spongepowered.api.entity.living.animal.Parrot;
import org.spongepowered.api.entity.living.animal.Pig;
import org.spongepowered.api.entity.living.animal.PolarBear;
import org.spongepowered.api.entity.living.animal.Rabbit;
import org.spongepowered.api.entity.living.animal.Sheep;
import org.spongepowered.api.entity.living.animal.TameableAnimal;
import org.spongepowered.api.entity.living.animal.Turtle;
import org.spongepowered.api.entity.living.animal.Wolf;
import org.spongepowered.api.entity.living.animal.cow.Mooshroom;
import org.spongepowered.api.entity.living.animal.horse.Horse;
import org.spongepowered.api.entity.living.animal.horse.HorseLike;
import org.spongepowered.api.entity.living.animal.horse.PackHorse;
import org.spongepowered.api.entity.living.animal.horse.llama.Llama;
import org.spongepowered.api.entity.living.animal.horse.llama.TraderLlama;
import org.spongepowered.api.entity.living.aquatic.Dolphin;
import org.spongepowered.api.entity.living.aquatic.fish.school.TropicalFish;
import org.spongepowered.api.entity.living.golem.IronGolem;
import org.spongepowered.api.entity.living.golem.Shulker;
import org.spongepowered.api.entity.living.monster.Blaze;
import org.spongepowered.api.entity.living.monster.Creeper;
import org.spongepowered.api.entity.living.monster.Enderman;
import org.spongepowered.api.entity.living.monster.Endermite;
import org.spongepowered.api.entity.living.monster.Patroller;
import org.spongepowered.api.entity.living.monster.Phantom;
import org.spongepowered.api.entity.living.monster.Vex;
import org.spongepowered.api.entity.living.monster.boss.Boss;
import org.spongepowered.api.entity.living.monster.boss.Wither;
import org.spongepowered.api.entity.living.monster.boss.dragon.EnderDragon;
import org.spongepowered.api.entity.living.monster.guardian.Guardian;
import org.spongepowered.api.entity.living.monster.raider.Raider;
import org.spongepowered.api.entity.living.monster.raider.Ravager;
import org.spongepowered.api.entity.living.monster.raider.illager.Pillager;
import org.spongepowered.api.entity.living.monster.raider.illager.Vindicator;
import org.spongepowered.api.entity.living.monster.raider.illager.spellcaster.Evoker;
import org.spongepowered.api.entity.living.monster.raider.illager.spellcaster.Spellcaster;
import org.spongepowered.api.entity.living.monster.slime.Slime;
import org.spongepowered.api.entity.living.monster.spider.Spider;
import org.spongepowered.api.entity.living.monster.zombie.ZombieVillager;
import org.spongepowered.api.entity.living.monster.zombie.ZombifiedPiglin;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.entity.living.player.User;
import org.spongepowered.api.entity.living.player.chat.ChatVisibility;
import org.spongepowered.api.entity.living.player.gamemode.GameMode;
import org.spongepowered.api.entity.living.player.server.ServerPlayer;
import org.spongepowered.api.entity.living.trader.Trader;
import org.spongepowered.api.entity.living.trader.Villager;
import org.spongepowered.api.entity.projectile.DamagingProjectile;
import org.spongepowered.api.entity.projectile.EyeOfEnder;
import org.spongepowered.api.entity.projectile.FishingBobber;
import org.spongepowered.api.entity.projectile.Potion;
import org.spongepowered.api.entity.projectile.Projectile;
import org.spongepowered.api.entity.projectile.ShulkerBullet;
import org.spongepowered.api.entity.projectile.arrow.Arrow;
import org.spongepowered.api.entity.projectile.arrow.ArrowEntity;
import org.spongepowered.api.entity.projectile.explosive.FireworkRocket;
import org.spongepowered.api.entity.projectile.explosive.WitherSkull;
import org.spongepowered.api.entity.projectile.explosive.fireball.FireballEntity;
import org.spongepowered.api.entity.vehicle.Boat;
import org.spongepowered.api.entity.vehicle.minecart.BlockOccupiedMinecart;
import org.spongepowered.api.entity.vehicle.minecart.CommandBlockMinecart;
import org.spongepowered.api.entity.vehicle.minecart.FurnaceMinecart;
import org.spongepowered.api.entity.vehicle.minecart.Minecart;
import org.spongepowered.api.entity.vehicle.minecart.MinecartLike;
import org.spongepowered.api.entity.weather.LightningBolt;
import org.spongepowered.api.entity.weather.WeatherEffect;
import org.spongepowered.api.event.cause.entity.damage.source.DamageSources;
import org.spongepowered.api.fluid.FluidStackSnapshot;
import org.spongepowered.api.item.FireworkEffect;
import org.spongepowered.api.item.FireworkShape;
import org.spongepowered.api.item.ItemRarity;
import org.spongepowered.api.item.ItemType;
import org.spongepowered.api.item.ItemTypes;
import org.spongepowered.api.item.enchantment.Enchantment;
import org.spongepowered.api.item.enchantment.EnchantmentTypes;
import org.spongepowered.api.item.inventory.Inventory;
import org.spongepowered.api.item.inventory.ItemStack;
import org.spongepowered.api.item.inventory.ItemStackSnapshot;
import org.spongepowered.api.item.inventory.Slot;
import org.spongepowered.api.item.inventory.equipment.EquipmentType;
import org.spongepowered.api.item.inventory.slot.EquipmentSlot;
import org.spongepowered.api.item.inventory.type.GridInventory;
import org.spongepowered.api.item.merchant.TradeOffer;
import org.spongepowered.api.item.potion.PotionType;
import org.spongepowered.api.map.MapCanvas;
import org.spongepowered.api.map.MapInfo;
import org.spongepowered.api.map.decoration.MapDecoration;
import org.spongepowered.api.profile.GameProfile;
import org.spongepowered.api.profile.property.ProfileProperty;
import org.spongepowered.api.projectile.source.ProjectileSource;
import org.spongepowered.api.raid.RaidWave;
import org.spongepowered.api.statistic.Statistic;
import org.spongepowered.api.util.Axis;
import org.spongepowered.api.util.Color;
import org.spongepowered.api.util.Direction;
import org.spongepowered.api.util.RespawnLocation;
import org.spongepowered.api.util.Ticks;
import org.spongepowered.api.util.orientation.Orientation;
import org.spongepowered.api.util.weighted.WeightedSerializableObject;
import org.spongepowered.api.world.explosion.Explosion;
import org.spongepowered.api.world.server.ServerLocation;
import org.spongepowered.api.world.server.ServerWorld;
import org.spongepowered.api.world.weather.WeatherType;
import org.spongepowered.api.world.weather.WeatherTypes;
import org.spongepowered.math.vector.Vector2i;
import org.spongepowered.math.vector.Vector3d;
import org.spongepowered.math.vector.Vector3i;
import org.spongepowered.plugin.PluginContainer;
import java.time.Instant;
import java.util.List;
import java.util.Locale;
import java.util.UUID;
/**
* An enumeration of known {@link Key}s used throughout the API.
*/
@SuppressWarnings({"unused", "WeakerAccess"})
public final class Keys {
// @formatter:off
// SORTFIELDS:ON
/**
* The {@link PotionEffectTypes#ABSORPTION} amount of a {@link Living} entity.
*/
public static final Key<Value<Double>> ABSORPTION = Keys.key(ResourceKey.sponge("absorption"), Double.class);
/**
* The acceleration of a {@link DamagingProjectile}.
*/
public static final Key<Value<Vector3d>> ACCELERATION = Keys.key(ResourceKey.sponge("acceleration"), Vector3d.class);
/**
* The item a {@link Living} entity is currently using.
* For example a player eating a food or blocking with a shield.
*
* <p>If there is no item, the snapshot will be empty. You can check this
* with {@link ItemStackSnapshot#isEmpty()}.</p>
*/
public static final Key<Value<ItemStackSnapshot>> ACTIVE_ITEM = Keys.key(ResourceKey.sponge("active_item"), ItemStackSnapshot.class);
/**
* Whether a {@link Player}s affects spawning.
*
* <p>A {@link Player} who does not affect spawning will be treated as a
* spectator in regards to spawning. A {@link MobSpawner} will not be
* activated by his presence and mobs around him may naturally despawn
* if there is no other Player around who affects spawning.</p>
*/
public static final Key<Value<Boolean>> AFFECTS_SPAWNING = Keys.key(ResourceKey.sponge("affects_spawning"), Boolean.class);
/**
* The age (in ticks) of an entity.
* e.g. The age of an {@link AreaEffectCloud}.
* <p>Note that in vanilla this value is not persisted for most entities.</p>
*/
public static final Key<Value<Integer>> AGE = Keys.key(ResourceKey.sponge("age"), Integer.class);
/**
* The modifier to {@link Keys#VELOCITY} of a {@link Minecart} while airborne.
*/
public static final Key<Value<Vector3d>> AIRBORNE_VELOCITY_MODIFIER = Keys.key(ResourceKey.sponge("airborne_velocity_modifier"), Vector3d.class);
/**
* The anger level of a {@link ZombifiedPiglin}.
*
* <p>Unlike {@link Keys#IS_ANGRY}, the aggressiveness represented by this key may
* fade over time and the entity will become peaceful again once its anger
* reaches its minimum.</p>
*/
public static final Key<Value<Integer>> ANGER_LEVEL = Keys.key(ResourceKey.sponge("anger_level"), Integer.class);
/**
* The set of {@link PotionEffect}s applied on use of an {@link ItemStack}.
* Readonly
*/
public static final Key<WeightedCollectionValue<PotionEffect>> APPLICABLE_POTION_EFFECTS = Keys.weightedKey(ResourceKey.sponge("applicable_potion_effects"), PotionEffect.class);
/**
* The enchantments applied to an {@link ItemStack}.
*
* <p>This data is usually applicable to all types of armor, weapons and
* tools. Enchantments that are only stored on an item stack in order to
* be transferred to another item (like on
* {@link ItemTypes#ENCHANTED_BOOK}s) use the {@link #STORED_ENCHANTMENTS}
* key instead.)</p>
*/
public static final Key<ListValue<Enchantment>> APPLIED_ENCHANTMENTS = Keys.listKey(ResourceKey.sponge("applied_enchantments"), Enchantment.class);
/**
* The {@link ArmorMaterial} of an armor {@link ItemStack}.
* Readonly
*/
public static final Key<Value<ArmorMaterial>> ARMOR_MATERIAL = Keys.key(ResourceKey.sponge("armor_material"), ArmorMaterial.class);
/**
* The type of {@link ArtType} shown by {@link Painting}s.
*/
public static final Key<Value<ArtType>> ART_TYPE = Keys.key(ResourceKey.sponge("art_type"), ArtType.class);
/**
* The attachment {@link AttachmentSurface} of a button or lever {@link BlockState}
*/
public static final Key<Value<AttachmentSurface>> ATTACHMENT_SURFACE = Keys.key(ResourceKey.sponge("attachment_surface"), AttachmentSurface.class);
/**
* The damage dealt by an {@link ArrowEntity} on impact.
*/
public static final Key<Value<Double>> ATTACK_DAMAGE = Keys.key(ResourceKey.sponge("attack_damage"), Double.class);
/**
* The time of a {@link Ravager} is considered attacking.
*/
public static final Key<Value<Ticks>> ATTACK_TIME = Keys.key(ResourceKey.sponge("attack_time"), Ticks.class);
/**
* Remaining ticks of the auto spin attack a {@link Living} is doing.
* @see #IS_AUTO_SPIN_ATTACK
*/
public static final Key<Value<Ticks>> AUTO_SPIN_ATTACK_TICKS = Keys.key(ResourceKey.sponge("auto_spin_attack_ticks"), Ticks.class);
/**
* The author of a {@link ItemTypes#WRITTEN_BOOK} {@link ItemStack}.
*/
public static final Key<Value<Component>> AUTHOR = Keys.key(ResourceKey.sponge("author"), Component.class);
/**
* The {@link Axis} direction of a {@link BlockState}.
*/
public static final Key<Value<Axis>> AXIS = Keys.key(ResourceKey.sponge("axis"), Axis.class);
/**
* The ticks until a {@link Ageable} turns into an adult.
*/
public static final Key<Value<Ticks>> BABY_TICKS = Keys.key(ResourceKey.sponge("baby_ticks"), Ticks.class);
/**
* The {@link BannerPatternLayer}s of a {@link Banner}.
*/
public static final Key<ListValue<BannerPatternLayer>> BANNER_PATTERN_LAYERS = Keys.listKey(ResourceKey.sponge("banner_pattern_layers"), BannerPatternLayer.class);
/**
* The width of the physical form of an {@link Entity}.
*
* <p>Together with {@link #HEIGHT} and {@link #SCALE} this defines
* the size of an {@link Entity}.</p>
* Readonly
*/
public static final Key<Value<Double>> BASE_SIZE = Keys.key(ResourceKey.sponge("base_size"), Double.class);
/**
* The base vehicle a passenger is riding at the moment.
* This may be different from {@link Keys#VEHICLE} as the
* vehicle an {@link Entity} is riding may itself be the passenger of
* another vehicle.
* Readonly
*/
public static final Key<Value<Entity>> BASE_VEHICLE = Keys.key(ResourceKey.sponge("base_vehicle"), Entity.class);
/**
* The target entity of a {@link Guardian} beam.
*/
public static final Key<Value<Living>> BEAM_TARGET_ENTITY = Keys.key(ResourceKey.sponge("beam_target_entity"), Living.class);
/**
* The default temperature of a biome at a specific {@link ServerLocation}.
* For the exact block temperature see {@link #BLOCK_TEMPERATURE}.
* Readonly
*/
public static final Key<Value<Double>> BIOME_TEMPERATURE = Keys.key(ResourceKey.sponge("biome_temperature"), Double.class);
/**
* The blast resistance of a {@link BlockState}.
* Readonly
*/
public static final Key<Value<Double>> BLAST_RESISTANCE = Keys.key(ResourceKey.sponge("blast_resistance"), Double.class);
/**
* The amount of light that is emitted by the surrounding blocks at a block {@link ServerLocation}.
* The value scales normally from 0 to 1.
* <p>In vanilla minecraft is this value in steps of 1/15 from 0 to 1.</p>
* <p>For the skylight see {@link #SKY_LIGHT}.</p>
* Readonly
*/
public static final Key<Value<Integer>> BLOCK_LIGHT = Keys.key(ResourceKey.sponge("block_light"), Integer.class);
/**
* The {@link BlockState} of a {@link BlockOccupiedMinecart} or {@link FallingBlock}.
*/
public static final Key<Value<BlockState>> BLOCK_STATE = Keys.key(ResourceKey.sponge("block_state"), BlockState.class);
/**
* The temperature at a specific {@link ServerLocation}.
* For the default biome temperature see {@link #BIOME_TEMPERATURE}.
* Readonly
*/
public static final Key<Value<Double>> BLOCK_TEMPERATURE = Keys.key(ResourceKey.sponge("block_temperature"), Double.class);
/**
* The type of the boat.
*/
public static final Key<Value<BoatType>> BOAT_TYPE = Keys.key(ResourceKey.sponge("boat_type"), BoatType.class);
/**
* The rotation of specific body parts of a {@link ArmorStand} or {@link Living}.
*
* <p>This value provides a mapping, effectively combining the data
* referenced by {@link #HEAD_ROTATION}, {@link #CHEST_ROTATION},
* {@link #RIGHT_ARM_ROTATION}, {@link #LEFT_ARM_ROTATION},
* {@link #RIGHT_LEG_ROTATION}, and {@link #LEFT_LEG_ROTATION}.</p>
*/
public static final Key<MapValue<BodyPart, Vector3d>> BODY_ROTATIONS = Keys.mapKey(ResourceKey.sponge("body_rotations"), BodyPart.class, Vector3d.class);
/**
* The {@link BossBar} displayed to the client by a {@link Boss}.
* TODO Readonly but mutable?
*/
public static final Key<Value<BossBar>> BOSS_BAR = Keys.key(ResourceKey.sponge("boss_bar"), BossBar.class);
/**
* The {@link BlockType}s able to be broken by an {@link ItemStack}.
*/
public static final Key<SetValue<BlockType>> BREAKABLE_BLOCK_TYPES = Keys.setKey(ResourceKey.sponge("breakable_block_types"), BlockType.class);
/**
* The current breeder of an {@link Animal}, usually a {@link Player}s UUID.
*/
public static final Key<Value<UUID>> BREEDER = Keys.key(ResourceKey.sponge("breeder"), UUID.class);
/**
* The ticks until an {@link Animal} can breed again. Also see {@link #CAN_BREED}.
*/
public static final Key<Value<Ticks>> BREEDING_COOLDOWN = Keys.key(ResourceKey.sponge("breeding_cooldown"), Ticks.class);
/**
* The burntime of an {@link ItemStack} fuel in a furnace.
* See {@link #FUEL} for the time
* Readonly
*/
public static final Key<Value<Integer>> BURN_TIME = Keys.key(ResourceKey.sponge("burn_time"), Integer.class);
/**
* Whether an {@link Animal} can breed.
* In Vanilla, animals can breed if their {@link Keys#BREEDING_COOLDOWN} is equal to 0.
*/
public static final Key<Value<Boolean>> CAN_BREED = Keys.key(ResourceKey.sponge("can_breed"), Boolean.class);
/**
* Whether a {@link FallingBlock} can drop as an item.
*/
public static final Key<Value<Boolean>> CAN_DROP_AS_ITEM = Keys.key(ResourceKey.sponge("can_drop_as_item"), Boolean.class);
/**
* Whether a {@link Humanoid} can fly.
*
* <p>For a {@link Player} this means they are able to toggle flight mode
* by double-tapping the jump button.</p>
*/
public static final Key<Value<Boolean>> CAN_FLY = Keys.key(ResourceKey.sponge("can_fly"), Boolean.class);
/**
* Whether a {@link Living} entity may change blocks.
* This mostly applies to {@link Enderman} or
* {@link Creeper}s, but also to some projectiles like {@link FireballEntity}s or {@link WitherSkull}.
*/
public static final Key<Value<Boolean>> CAN_GRIEF = Keys.key(ResourceKey.sponge("can_grief"), Boolean.class);
/**
* The set of harvestable {@link BlockType}s with an {@link ItemStack}. {@link #EFFICIENCY}
* Readonly
*/
public static final Key<SetValue<BlockType>> CAN_HARVEST = Keys.setKey(ResourceKey.sponge("can_harvest"), BlockType.class);
/**
* Whether a {@link FallingBlock} will damage an {@link Entity} it lands on.
*/
public static final Key<Value<Boolean>> CAN_HURT_ENTITIES = Keys.key(ResourceKey.sponge("can_hurt_entities"), Boolean.class);
/**
* Whether a {@link Raider} can join a raid.
*/
public static final Key<Value<Boolean>> CAN_JOIN_RAID = Keys.key(ResourceKey.sponge("can_join_raid"), Boolean.class);
/**
* Whether a {@link Boat} can move on land.
*/
public static final Key<Value<Boolean>> CAN_MOVE_ON_LAND = Keys.key(ResourceKey.sponge("can_move_on_land"), Boolean.class);
/**
* Whether a {@link FallingBlock} will place itself upon landing.
*/
public static final Key<Value<Boolean>> CAN_PLACE_AS_BLOCK = Keys.key(ResourceKey.sponge("can_place_as_block"), Boolean.class);
/**
* The current casting time of a {@link Spellcaster}.
*/
public static final Key<Value<Integer>> CASTING_TIME = Keys.key(ResourceKey.sponge("casting_time"), Integer.class);
/**
* The type of a {@link Cat}.
*/
public static final Key<Value<CatType>> CAT_TYPE = Keys.key(ResourceKey.sponge("cat_type"), CatType.class);
/**
* Whether a {@link ServerPlayer} can will see colours sent in messages.
*/
public static final Key<Value<Boolean>> CHAT_COLORS_ENABLED = Keys.key(ResourceKey.sponge("chat_colors_enabled"), Boolean.class);
/**
* The types of chat a {@link ServerPlayer} can see.
*/
public static final Key<Value<ChatVisibility>> CHAT_VISIBILITY = Keys.key(ResourceKey.sponge("chat_visibility"), ChatVisibility.class);
/**
* The attachment of a {@link BlockTypes#CHEST} or {@link BlockTypes#TRAPPED_CHEST} {@link BlockState}.
*/
public static final Key<Value<ChestAttachmentType>> CHEST_ATTACHMENT_TYPE = Keys.key(ResourceKey.sponge("chest_attachment_type"), ChestAttachmentType.class);
/**
* The rotation of the {@link BodyParts#CHEST}.
*/
public static final Key<Value<Vector3d>> CHEST_ROTATION = Keys.key(ResourceKey.sponge("chest_rotation"), Vector3d.class);
/**
* The {@link Color} of an {@link ItemStack}
* <p>
* e.g. {@link ItemTypes#LEATHER_CHESTPLATE} or {@link ItemTypes#POTION} custom color
* </p>
* or an {@link AreaEffectCloud}.
*/
public static final Key<Value<Color>> COLOR = Keys.key(ResourceKey.sponge("color"), Color.class);
/**
* A command stored in a {@link CommandBlock} or {@link CommandBlockMinecart}.
*/
public static final Key<Value<String>> COMMAND = Keys.key(ResourceKey.sponge("command"), String.class);
/**
* The {@link ComparatorMode} of a {@link BlockTypes#COMPARATOR} {@link BlockState}.
*/
public static final Key<Value<ComparatorMode>> COMPARATOR_MODE = Keys.key(ResourceKey.sponge("comparator_mode"), ComparatorMode.class);
/**
* The connected directions of a {@link BlockState}.
* <p>
* e.g. {@link BlockTypes#GLASS_PANE}, {@link BlockTypes#IRON_BARS}, {@link BlockTypes#CHEST},
* </p>
*/
public static final Key<SetValue<Direction>> CONNECTED_DIRECTIONS = Keys.setKey(ResourceKey.sponge("connected_directions"), Direction.class);
/**
* The container {@link ItemType} of an {@link ItemStack}.
* e.g. {@link ItemTypes#BUCKET} for a {@link ItemTypes#WATER_BUCKET} stack.
* Readonly
*/
public static final Key<Value<ItemType>> CONTAINER_ITEM = Keys.key(ResourceKey.sponge("container_item"), ItemType.class);
/**
* The amount of ticks a {@link Hopper} has to wait before transferring the next item. (in Vanilla this is 8 ticks)
* or
* The amount of ticks a {@link EndGateway} has to wait for the next teleportation.
*/
public static final Key<Value<Ticks>> COOLDOWN = Keys.key(ResourceKey.sponge("cooldown"), Ticks.class);
/**
* The creator, usually of an {@link Entity}. It is up to the implementation to define.
*/
public static final Key<Value<UUID>> CREATOR = Keys.key(ResourceKey.sponge("creator"), UUID.class);
/**
* The current {@link SpellType} a {@link Spellcaster} is casting.
*/
public static final Key<Value<SpellType>> CURRENT_SPELL = Keys.key(ResourceKey.sponge("current_spell"), SpellType.class);
/**
* The damage dealt towards entities of a specific {@link EntityType} by a {@link ArrowEntity}.
*
* <p>Note that in events, the damage defined for the provided
* {@link EntityType} will take priority over the "default" damage as
* defined from {@link ArrowEntity#attackDamage()}.</p>
*
* <p>Types not present in this mapping will be
* dealt damage to according to {@link #ATTACK_DAMAGE}.</p>
*/
public static final Key<MapValue<EntityType<?>, Double>> CUSTOM_ATTACK_DAMAGE = Keys.mapKey(ResourceKey.sponge("custom_attack_damage"), new TypeToken<EntityType<?>>() {}, TypeToken.get(Double.class));
/**
* The resource pack model index of an {@link ItemStack}.
*
* <p>Resource packs can use the same index in their files to replace the
* item model of an ItemStack.</p>
*/
public static final Key<Value<Integer>> CUSTOM_MODEL_DATA = Keys.key(ResourceKey.sponge("custom_model_data"), Integer.class);
/**
* The custom name of an {@link Entity}, {@link ItemStack} or {@link BlockEntity}.
* <p>If no custom name is set the dataholder may still have a {@link Keys#DISPLAY_NAME}</p>
*/
public static final Key<Value<Component>> CUSTOM_NAME = Keys.key(ResourceKey.sponge("custom_name"), Component.class);
/**
* The damage absorbed by an armor {@link ItemStack}.
* Readonly
*/
public static final Key<Value<Double>> DAMAGE_ABSORPTION = Keys.key(ResourceKey.sponge("damage_absorption"), Double.class);
/**
* How much damage a {@link FallingBlock} deals to {@link Living} entities
* it hits per block fallen.
*
* <p>This damage is capped by {@link #MAX_FALL_DAMAGE}.</p>
*/
public static final Key<Value<Double>> DAMAGE_PER_BLOCK = Keys.key(ResourceKey.sponge("damage_per_block"), Double.class);
/**
* The distance at which a {@link BlockState} will decay.
* This usually applies to leaves, for example {@link BlockTypes#OAK_LEAVES}.
*/
public static final Key<Value<Integer>> DECAY_DISTANCE = Keys.key(ResourceKey.sponge("decay_distance"), Integer.class);
/**
* The modifier to {@link Keys#VELOCITY} of a {@link Minecart} while derailed.
*/
public static final Key<Value<Vector3d>> DERAILED_VELOCITY_MODIFIER = Keys.key(ResourceKey.sponge("derailed_velocity_modifier"), Vector3d.class);
/**
* The despawn delay (in ticks) of a {@link Item}, {@link Endermite}, {@link WeatherType} {@link TraderLlama} or {@link EyeOfEnder}.
*/
public static final Key<Value<Ticks>> DESPAWN_DELAY = Keys.key(ResourceKey.sponge("despawn_delay"), Ticks.class);
/**
* The destroy speed of a {@link BlockState}s {@link BlockType}.
*
* <p>This value is read-only.</p>
*/
public static final Key<Value<Double>> DESTROY_SPEED = Keys.key(ResourceKey.sponge("destroy_speed"), Double.class);
/**
* The detonator of a {@link PrimedTNT}.
*/
public static final Key<Value<Living>> DETONATOR = Keys.key(ResourceKey.sponge("detonator"), Living.class);
/**
* The {@link Direction} a {@link BlockState}, {@link Hanging}, or {@link Shulker} is facing or the
* heading of a {@link ShulkerBullet}.
*/
public static final Key<Value<Direction>> DIRECTION = Keys.key(ResourceKey.sponge("direction"), Direction.class);
/**
* The display name of an {@link Entity}, {@link ItemStack} or {@link BlockEntity}.
*
* <p>To change a display name set a {@link Keys#CUSTOM_NAME} instead.</p>
* <p>On an {@link Entity}, this represents a combination of {@link Keys#CUSTOM_NAME} (if set), scoreboard info, and any click data.</p>
* <p>On an {@link ItemStack}, this represents the {@link Keys#CUSTOM_NAME} or if not set the {@link ItemType}s translation.
* <p>On a {@link BlockEntity}, this usually represents the name displayed in its {@link org.spongepowered.api.item.inventory.Container}
*/
public static final Key<Value<Component>> DISPLAY_NAME = Keys.key(ResourceKey.sponge("display_name"), Component.class);
/**
* The dominant {@link HandPreference} of an {@link Agent} entity.
*
* <p><em>NOTE:</em> For {@link Player}s is this key read-only, the
* {@link HandPreference} of a player can not be changed server-side.</p>
*/
public static final Key<Value<HandPreference>> DOMINANT_HAND = Keys.key(ResourceKey.sponge("dominant_hand"), HandPreference.class);
/**
* The {@link DoorHinge} of a door {@link BlockState}.
*/
public static final Key<Value<DoorHinge>> DOOR_HINGE = Keys.key(ResourceKey.sponge("door_hinge"), DoorHinge.class);
/**
* Whether exact teleport location should be used with a {@link EndGateway}.
*/
public static final Key<Value<Boolean>> DO_EXACT_TELEPORT = Keys.key(ResourceKey.sponge("do_exact_teleport"), Boolean.class);
/**
* The remaining duration (in ticks) of an {@link AreaEffectCloud}.
*/
public static final Key<Value<Ticks>> DURATION = Keys.key(ResourceKey.sponge("duration"), Ticks.class);
/**
* The amount of ticks the duration of an {@link AreaEffectCloud}
* is increased or reduced when it applies its effect.
*/
public static final Key<Value<Ticks>> DURATION_ON_USE = Keys.key(ResourceKey.sponge("duration_on_use"), Ticks.class);
/**
* The color of a dyeable {@link BlockState}, {@link ItemStack} or entity like {@link Cat}s.
* or
* The base {@link DyeColor} of a {@link Banner} or {@link TropicalFish}.
*/
public static final Key<Value<DyeColor>> DYE_COLOR = Keys.key(ResourceKey.sponge("dye_color"), DyeColor.class);
/**
* The time a {@link Panda} has been eating (in ticks)
*/
public static final Key<Value<Ticks>> EATING_TIME = Keys.key(ResourceKey.sponge("eating_time"), Ticks.class);
/**
* The efficiency of an {@link ItemStack} tool. Affects mining speed of supported materials. {@link #CAN_HARVEST}
* Readonly
*/
public static final Key<Value<Double>> EFFICIENCY = Keys.key(ResourceKey.sponge("efficiency"), Double.class);
/**
* The time (in ticks) until a {@link Chicken} lays an {@link ItemTypes#EGG}.
*
* <p>
* Vanilla will calculate the egg timer by taking a random value between
* 0 (inclusive) and 6000 (exclusive) and then add that by another 6000.
* This unit ends up being in ticks. Once the chicken lays the egg, this
* calculation is ran again.
* </p>
*/
public static final Key<Value<Ticks>> EGG_TIME = Keys.key(ResourceKey.sponge("egg_time"), Ticks.class);
/**
* The age (in ticks) of an {@link EndGateway}
*/
public static final Key<Value<Ticks>> END_GATEWAY_AGE = Keys.key(ResourceKey.sponge("end_gateway_age"), Ticks.class);
/**
* The {@link EntityType entity type} of a spawn egg, which may be one of
* several based on {@link ItemTypes#ZOMBIE_SPAWN_EGG}, etc. It is not
* guaranteed that the type of entity is the same as the one that will be
* spawned when used. It is likely unable to change the type of entity on
* an {@link ItemStack}, but it is possible to change the
* {@link EntityArchetype archetype} by using {@link #ENTITY_TO_SPAWN}.
*
* @see #ENTITY_TO_SPAWN
*/
@SuppressWarnings("unchecked")
public static final Key<Value<? extends EntityType<?>>> ENTITY_TYPE = Keys.key(ResourceKey.sponge("entity_type"), (Class) EntityType.class);
/**
* The {@link EntityArchetype} to spawn from any spawn egg, such as a
* {@link ItemTypes#ZOMBIE_SPAWN_EGG} or {@link ItemTypes#CREEPER_SPAWN_EGG}.
* <p>The {@link #ENTITY_TYPE} is not guaranteed to be the same as the
* {@link EntityArchetype#type()} returned, but the spawned entity will be
* based on the {@link EntityArchetype} returned here.
*/
public static final Key<Value<EntityArchetype>> ENTITY_TO_SPAWN = Keys.key(ResourceKey.sponge("entity_to_spawn"), EntityArchetype.class);
/**
* The {@link EquipmentType} that the target inventory supports. This usually applies to {@link EquipmentSlot}s.
* or
* The {@link EquipmentType} of an {@link ItemStack}
* Readonly
*/
public static final Key<Value<EquipmentType>> EQUIPMENT_TYPE = Keys.key(ResourceKey.sponge("equipment_type"), EquipmentType.class);
public static final Key<Value<Double>> EXHAUSTION = Keys.key(ResourceKey.sponge("exhaustion"), Double.class);
/**
* The amount of experience a {@link Player} has or an {@link ExperienceOrb} contains.
*/
public static final Key<Value<Integer>> EXPERIENCE = Keys.key(ResourceKey.sponge("experience"), Integer.class);
/**
* The total experience a {@link Player} requires to advance from his current level to the next one.
* Readonly
*/
public static final Key<Value<Integer>> EXPERIENCE_FROM_START_OF_LEVEL = Keys.key(ResourceKey.sponge("experience_from_start_of_level"), Integer.class);
/**
* The current level a {@link Player} has.
*/
public static final Key<Value<Integer>> EXPERIENCE_LEVEL = Keys.key(ResourceKey.sponge("experience_level"), Integer.class);
/**
* The amount of experience a {@link Player} has collected towards the next level.
*/
public static final Key<Value<Integer>> EXPERIENCE_SINCE_LEVEL = Keys.key(ResourceKey.sponge("experience_since_level"), Integer.class);
public static final Key<Value<Integer>> EXPLOSION_RADIUS = Keys.key(ResourceKey.sponge("explosion_radius"), Integer.class);
/**
* The eye height of an {@link Entity}.
* Readonly
*/
public static final Key<Value<Double>> EYE_HEIGHT = Keys.key(ResourceKey.sponge("eye_height"), Double.class);
/**
* The eye position of an {@link Entity}.
* Readonly
*/
public static final Key<Value<Vector3d>> EYE_POSITION = Keys.key(ResourceKey.sponge("eye_position"), Vector3d.class);
/**
* The distance an {@link Entity} has fallen.
*/
public static final Key<Value<Double>> FALL_DISTANCE = Keys.key(ResourceKey.sponge("fall_distance"), Double.class);
/**
* The amount of ticks a {@link FallingBlock} has been falling for.
*/
public static final Key<Value<Ticks>> FALL_TIME = Keys.key(ResourceKey.sponge("fall_time"), Ticks.class);
/**
* The {@link FireworkEffect}s of a
* {@link ItemTypes#FIREWORK_STAR}, {@link ItemTypes#FIREWORK_ROCKET} {@link ItemStack} or a
* {@link FireworkRocket}.
*/
public static final Key<ListValue<FireworkEffect>> FIREWORK_EFFECTS = Keys.listKey(ResourceKey.sponge("firework_effects"), FireworkEffect.class);
/**
* The flight duration of a {@link FireworkRocket}
*
* <p>The duration is tiered and will stay partially random. A rocket will
* fly for roughly {@code modifier * 10 + (random number from 0 to 13)}
* ticks in Vanilla Minecraft.</p>
*/
public static final Key<Value<Ticks>> FIREWORK_FLIGHT_MODIFIER = Keys.key(ResourceKey.sponge("firework_flight_modifier"), Ticks.class);
public static final Key<Value<FireworkShape>> FIREWORK_SHAPE = Keys.key(ResourceKey.sponge("firework_shape"), FireworkShape.class);
/**
* The delay in ticks until the {@link Entity} will be damaged by the fire.
*/
public static final Key<Value<Ticks>> FIRE_DAMAGE_DELAY = Keys.key(ResourceKey.sponge("fire_damage_delay"), Ticks.class);
/**
* The amount of ticks an {@link Entity} is still burning.
*/
public static final Key<Value<Ticks>> FIRE_TICKS = Keys.key(ResourceKey.sponge("fire_ticks"), Ticks.class);
/**
* The time a {@link User} first joined on the Server.
*/
public static final Key<Value<Instant>> FIRST_DATE_JOINED = Keys.key(ResourceKey.sponge("first_date_joined"), Instant.class);
/**
* A {@link Fox fox's} first trusted {@link UUID}, usually a {@link Player}.
*/
public static final Key<Value<UUID>> FIRST_TRUSTED = Keys.key(ResourceKey.sponge("first_trusted"), UUID.class);
/**
* The {@link FluidStackSnapshot} contained within an item container.
* Item containers may include buckets and other mod added items.
* See {@link #CONTAINER_ITEM}
*/
public static final Key<Value<FluidStackSnapshot>> FLUID_ITEM_STACK = Keys.key(ResourceKey.sponge("fluid_item_stack"), FluidStackSnapshot.class);
/**
* The fluid level of a liquid {@link BlockState}.
*/
public static final Key<Value<Integer>> FLUID_LEVEL = Keys.key(ResourceKey.sponge("fluid_level"), Integer.class);
/**
* The directional tank information.
* TODO dataholder? cauldron blockstate? modded?
*/
public static final Key<MapValue<Direction, List<FluidStackSnapshot>>> FLUID_TANK_CONTENTS = Keys.mapKey(ResourceKey.sponge("fluid_tank_contents"), TypeToken.get(Direction.class), new TypeToken<List<FluidStackSnapshot>>() {});
/**
* The speed at which an {@link Player} flies.
*/
public static final Key<Value<Double>> FLYING_SPEED = Keys.key(ResourceKey.sponge("flying_speed"), Double.class);
/**
* The food level of a {@link Humanoid}.
*
* <p>For a {@link Humanoid}, food level has health effects, depending on game difficulty and
* hunger levels. If the food level is high enough, the humanoid may heal. If the food level is at 0,
* the humanoid may starve.</p>
*/
public static final Key<Value<Integer>> FOOD_LEVEL = Keys.key(ResourceKey.sponge("food_level"), Integer.class);
/**
* The type of a {@link Fox}.
*/
public static final Key<Value<FoxType>> FOX_TYPE = Keys.key(ResourceKey.sponge("fox_type"), FoxType.class);
/**
* Represents the {@link Key} for the amount of fuel left in a {@link BrewingStand} or {@link FurnaceBlockEntity} or {@link FurnaceMinecart}
*
* <p>One {@link ItemTypes#BLAZE_POWDER} adds 20 fuel to the brewing stand.</p>
* <p>The fuel value corresponds with the number of batches of potions that can be brewed.</p>
*
* <p>See {@link #BURN_TIME} for the burn time added by a fuel {@link ItemStack} to a furnace</p>
*/
public static final Key<Value<Integer>> FUEL = Keys.key(ResourceKey.sponge("fuel"), Integer.class);
/**
* The time (in ticks) a {@link FusedExplosive}'s fuse will burn before the explosion.
*/
public static final Key<Value<Ticks>> FUSE_DURATION = Keys.key(ResourceKey.sponge("fuse_duration"), Ticks.class);
/**
* The {@link GameMode} a {@link Humanoid} has.
*/
public static final Key<Value<GameMode>> GAME_MODE = Keys.key(ResourceKey.sponge("game_mode"), GameMode.class);
/**
* The player represented by a {@link BlockTypes#PLAYER_HEAD} (and {@link BlockTypes#PLAYER_WALL_HEAD})
* {@link BlockState} or a {@link ItemTypes#PLAYER_HEAD} {@link ItemStack}.
*
* <p>The offered game profile will be set exactly, unlike in vanilla where the game profile will
* be resolved automatically for properties (including textures). You can obtain a game profile with
* properties using {@link org.spongepowered.api.profile.GameProfileManager#profile}.</p>
*/
public static final Key<Value<GameProfile>> GAME_PROFILE = Keys.key(ResourceKey.sponge("game_profile"), GameProfile.class);
/**
* The generation of a {@link ItemTypes#WRITTEN_BOOK} {@link ItemStack}.
* Depending on the book's generation it may be impossible to copy it.
*/
public static final Key<Value<Integer>> GENERATION = Keys.key(ResourceKey.sponge("generation"), Integer.class);
/**
* The "growth stage" state of a {@link BlockState}.
* e.g. {@link BlockTypes#CACTUS} or {@link BlockTypes#WHEAT} etc.
*/
public static final Key<Value<Integer>> GROWTH_STAGE = Keys.key(ResourceKey.sponge("growth_stage"), Integer.class);
/**
* Whether an {@link ArmorStand}'s arms are visible.
*/
public static final Key<Value<Boolean>> HAS_ARMS = Keys.key(ResourceKey.sponge("has_arms"), Boolean.class);
/**
* Whether an {@link ArmorStand} has a visible base plate.
*/
public static final Key<Value<Boolean>> HAS_BASE_PLATE = Keys.key(ResourceKey.sponge("has_base_plate"), Boolean.class);
/**
* Whether a {@link PackHorse} has a chest.
*/
public static final Key<Value<Boolean>> HAS_CHEST = Keys.key(ResourceKey.sponge("has_chest"), Boolean.class);
/**
*Whether a {@link Turtle} currently has an egg.
*/
public static final Key<Value<Boolean>> HAS_EGG = Keys.key(ResourceKey.sponge("has_egg"), Boolean.class);
/**
* Whether a {@link Dolphin} has a fish.
* <p>
* Dolphins will navigate to a treasure (if a structure that provides one is nearby)
* if they have been given a fish.
* </p>
*/
public static final Key<Value<Boolean>> HAS_FISH = Keys.key(ResourceKey.sponge("has_fish"), Boolean.class);
/**
* Whether an {@link ArmorStand} is a "marker" stand.
*
* <p>If {@code true}, the armor stand's bounding box is near
* impossible to see, and the armor stand can no longer be
* interacted with.</p>
*/
public static final Key<Value<Boolean>> HAS_MARKER = Keys.key(ResourceKey.sponge("has_marker"), Boolean.class);
/**
* Whether a giant mushroom {@link BlockState} has pores on the {@link Direction#DOWN} direction. See {@link #PORES}.
*/
public static final Key<Value<Boolean>> HAS_PORES_DOWN = Keys.key(ResourceKey.sponge("has_pores_down"), Boolean.class);
/**
* Whether a giant mushroom {@link BlockState} has pores on the {@link Direction#EAST} direction. See {@link #PORES}.
*/
public static final Key<Value<Boolean>> HAS_PORES_EAST = Keys.key(ResourceKey.sponge("has_pores_east"), Boolean.class);
/**
* Whether a giant mushroom {@link BlockState} has pores on the {@link Direction#NORTH} direction. See {@link #PORES}.
*/
public static final Key<Value<Boolean>> HAS_PORES_NORTH = Keys.key(ResourceKey.sponge("has_pores_north"), Boolean.class);
/**
* Whether a giant mushroom {@link BlockState} has pores on the {@link Direction#SOUTH} direction. See {@link #PORES}.
*/
public static final Key<Value<Boolean>> HAS_PORES_SOUTH = Keys.key(ResourceKey.sponge("has_pores_south"), Boolean.class);
/**
* Whether a giant mushroom {@link BlockState} has pores on the {@link Direction#UP} direction. See {@link #PORES}.
*/
public static final Key<Value<Boolean>> HAS_PORES_UP = Keys.key(ResourceKey.sponge("has_pores_up"), Boolean.class);
/**
* Whether a giant mushroom {@link BlockState} has pores on the {@link Direction#WEST} direction. See {@link #PORES}.
*/
public static final Key<Value<Boolean>> HAS_PORES_WEST = Keys.key(ResourceKey.sponge("has_pores_west"), Boolean.class);
/**
* Whether a server player has viewed the credits.
*
* <p>The credits are displayed the first time a player returns to the overworld safely using an end portal.</p>
*/
public static final Key<Value<Boolean>> HAS_VIEWED_CREDITS = Keys.key(ResourceKey.sponge("has_viewed_credits"), Boolean.class);
/**
* The rotation of a {@link Living}'s or {@link ArmorStand}'s head.
*
* <p>The format of the rotation is represented by:</p>
*
* <ul>
* <li>{@code x -> pitch}</li>
* <li> {@code y -> yaw}</li>
* <li>{@code z -> roll}</li>
* </ul>
*
* <p>Note that the pitch will be the same x value returned by
* {@link Entity#rotation()} and Minecraft does not currently support
* head roll so the z value will always be zero.</p>
*/
public static final Key<Value<Vector3d>> HEAD_ROTATION = Keys.key(ResourceKey.sponge("head_rotation"), Vector3d.class);
/**
* The {@link EndCrystal} currently healing an {@link EnderDragon}.
*/
public static final Key<Value<EndCrystal>> HEALING_CRYSTAL = Keys.key(ResourceKey.sponge("healing_crystal"), EndCrystal.class);
/**
* A {@link Living}'s or {@link EndCrystal}'s current health.
*
* <p>The range of the health depends on the object on which this
* method is defined. For {@link Player Players} in Minecraft, the nominal range is
* between 0 and 20, inclusive, but the range can be adjusted.</p>
*
* <p>Convention dictates that health does not fall below 0 but this
* convention may be broken.</p>
*/
public static final Key<Value<Double>> HEALTH = Keys.key(ResourceKey.sponge("health"), Double.class);
/**
* The value a {@link ServerPlayer}s max-health (excluding absorption) in the GUI will scale to.
* <p>Two health is equal to one heart displayed.</p>
* <p>With scaling is disabled health automatically scales to {@link #MAX_HEALTH}</p>
*/
public static final Key<Value<Double>> HEALTH_SCALE = Keys.key(ResourceKey.sponge("health_scale"), Double.class);
/**
* The height of the physical form of an {@link Entity}.
*
* <p>Together with {@link #BASE_SIZE} and {@link #SCALE} this defines the size of an
* {@link Entity}.</p>
* Readonly
*/
public static final Key<Value<Double>> HEIGHT = Keys.key(ResourceKey.sponge("height"), Double.class);
/**
* The {@link ItemType} a {@link BlockState} represents.
* Readonly
*/
public static final Key<Value<ItemType>> HELD_ITEM = Keys.key(ResourceKey.sponge("held_item"), ItemType.class);
/**
* The hidden {@link PandaGene gene} of a {@link Panda}.
*/
public static final Key<Value<PandaGene>> HIDDEN_GENE = Keys.key(ResourceKey.sponge("hidden_gene"), PandaGene.class);
/**
* Whether the attributes of an {@link ItemStack} are hidden.
*/
public static final Key<Value<Boolean>> HIDE_ATTRIBUTES = Keys.key(ResourceKey.sponge("hide_attributes"), Boolean.class);
/**
* Whether the {@link #BREAKABLE_BLOCK_TYPES} of an {@link ItemStack} are hidden.
*/
public static final Key<Value<Boolean>> HIDE_CAN_DESTROY = Keys.key(ResourceKey.sponge("hide_can_destroy"), Boolean.class);
/**
* Whether the {@link #PLACEABLE_BLOCK_TYPES} of an {@link ItemStack} are hidden.
*/
public static final Key<Value<Boolean>> HIDE_CAN_PLACE = Keys.key(ResourceKey.sponge("hide_can_place"), Boolean.class);
/**
* Whether the {@link #APPLIED_ENCHANTMENTS} of an {@link ItemStack} are hidden.
*/
public static final Key<Value<Boolean>> HIDE_ENCHANTMENTS = Keys.key(ResourceKey.sponge("hide_enchantments"), Boolean.class);
/**
* Whether miscellaneous values of an {@link ItemStack} are hidden.
* e.g. potion effects or shield pattern info
*/
public static final Key<Value<Boolean>> HIDE_MISCELLANEOUS = Keys.key(ResourceKey.sponge("hide_miscellaneous"), Boolean.class);
/**
* Whether {@link #IS_UNBREAKABLE} state of an {@link ItemStack} is hidden.
*/
public static final Key<Value<Boolean>> HIDE_UNBREAKABLE = Keys.key(ResourceKey.sponge("hide_unbreakable"), Boolean.class);
/**
* The {@link Vector3i position} where a {@link Turtle} lays {@link BlockTypes#TURTLE_EGG eggs}.
*/
public static final Key<Value<Vector3i>> HOME_POSITION = Keys.key(ResourceKey.sponge("home_position"), Vector3i.class);
/**
* The {@link HorseColor} of a {@link Horse}.
*/
public static final Key<Value<HorseColor>> HORSE_COLOR = Keys.key(ResourceKey.sponge("horse_color"), HorseColor.class);
/**
* The {@link HorseStyle} of a {@link Horse}.
*/
public static final Key<Value<HorseStyle>> HORSE_STYLE = Keys.key(ResourceKey.sponge("horse_style"), HorseStyle.class);
/**
* The inaccuracy of an {@link ItemStack} that launches {@link Projectile}s.
*
* <p>An inaccuracy of 0 means perfect accuracy. Inaccuracy of 1 is the default for most vanilla items.</p>
*/
public static final Key<Value<Double>> INACCURACY = Keys.key(ResourceKey.sponge("inaccuracy"), Double.class);
/**
* Whether an {@link Item} will not despawn for an infinite time.
*/
public static final Key<Value<Boolean>> INFINITE_DESPAWN_DELAY = Keys.key(ResourceKey.sponge("infinite_despawn_delay"), Boolean.class);
/**
* Whether an {@link Item} has an infinite pickup delay.
*/
public static final Key<Value<Boolean>> INFINITE_PICKUP_DELAY = Keys.key(ResourceKey.sponge("infinite_pickup_delay"), Boolean.class);
/**
* The {@link InstrumentType} of a {@link BlockTypes#NOTE_BLOCK} {@link BlockState}.
*/
public static final Key<Value<InstrumentType>> INSTRUMENT_TYPE = Keys.key(ResourceKey.sponge("instrument_type"), InstrumentType.class);
/**
* Whether a {@link BlockTypes#DAYLIGHT_DETECTOR} {@link BlockState} is inverted.
*/
public static final Key<Value<Boolean>> INVERTED = Keys.key(ResourceKey.sponge("inverted"), Boolean.class);
/**
* The amount of ticks an {@link Entity} will remain invulnerable for.
*/
public static final Key<Value<Ticks>> INVULNERABILITY_TICKS = Keys.key(ResourceKey.sponge("invulnerability_ticks"), Ticks.class);
/**
* Whether an {@link Entity} is invulnerable.
*
* <p>This does not protect from the void, players in creative mode,
* and manual killing like the /kill command.</p>
*/
public static final Key<Value<Boolean>> INVULNERABLE = Keys.key(ResourceKey.sponge("invulnerable"), Boolean.class);
/**
* Whether a fence gate {@link BlockState} is in a wall.
*/
public static final Key<Value<Boolean>> IN_WALL = Keys.key(ResourceKey.sponge("in_wall"), Boolean.class);
/**
* Whether an {@link Ageable} is considered an adult.
*/
public static final Key<Value<Boolean>> IS_ADULT = Keys.key(ResourceKey.sponge("is_adult"), Boolean.class);
/**
* Whether a {@link Blaze} is currently burning.
*
* <p>Unlike {@link Keys#FIRE_TICKS}, the burning effect will not damage
* the burning entity.</p>
*/
public static final Key<Value<Boolean>> IS_AFLAME = Keys.key(ResourceKey.sponge("is_aflame"), Boolean.class);
/**
* Whether an {@link Agent}s AI is enabled.
*/
public static final Key<Value<Boolean>> IS_AI_ENABLED = Keys.key(ResourceKey.sponge("is_ai_enabled"), Boolean.class);
/**
* Whether an entity is currently aggressive.
* e.g. {@link Wolf wolves} or {@link ZombifiedPiglin}
*/
public static final Key<Value<Boolean>> IS_ANGRY = Keys.key(ResourceKey.sponge("is_angry"), Boolean.class);
/**
* Whether a {@link BlockState} is "attached" to another block.
*/
public static final Key<Value<Boolean>> IS_ATTACHED = Keys.key(ResourceKey.sponge("is_attached"), Boolean.class);
/**
* Whether a {@link Living} is doing an auto spin attack (doable with the {@link EnchantmentTypes#RIPTIDE} enchantment.)
* @see #AUTO_SPIN_ATTACK_TICKS
*/
public static final Key<Value<Boolean>> IS_AUTO_SPIN_ATTACK = Keys.key(ResourceKey.sponge("is_auto_spin_attack"), Boolean.class);
/**
* Whether an entity is begging for food.
* e.g. {@link Cat cats} or tamed {@link Wolf wolves}
*/
public static final Key<Value<Boolean>> IS_BEGGING_FOR_FOOD = Keys.key(ResourceKey.sponge("is_begging_for_food"), Boolean.class);
/**
* Whether {@link Raider}s are currently celebrating.
*/
public static final Key<Value<Boolean>> IS_CELEBRATING = Keys.key(ResourceKey.sponge("is_celebrating"), Boolean.class);
/**
* Whether a {@link Creeper} is charged.
*/
public static final Key<Value<Boolean>> IS_CHARGED = Keys.key(ResourceKey.sponge("is_charged"), Boolean.class);
/**
* Whether a {@link Pillager} is charging it's crossbow.
*/
public static final Key<Value<Boolean>> IS_CHARGING_CROSSBOW = Keys.key(ResourceKey.sponge("is_charging_crossbow"), Boolean.class);
/**
* Whether a {@link Spider} is currently climbing.
*/
public static final Key<Value<Boolean>> IS_CLIMBING = Keys.key(ResourceKey.sponge("is_climbing"), Boolean.class);
/**
* Whether a {@link BlockState} is connected to the {@link Direction#EAST}.
* Also see {@link #CONNECTED_DIRECTIONS}.
*/
public static final Key<Value<Boolean>> IS_CONNECTED_EAST = Keys.key(ResourceKey.sponge("is_connected_east"), Boolean.class);
/**
* Whether a {@link BlockState} is connected to the {@link Direction#NORTH}.
* Also see {@link #CONNECTED_DIRECTIONS}.
*/
public static final Key<Value<Boolean>> IS_CONNECTED_NORTH = Keys.key(ResourceKey.sponge("is_connected_north"), Boolean.class);
/**
* Whether a {@link BlockState} is connected to the {@link Direction#SOUTH}.
* Also see {@link #CONNECTED_DIRECTIONS}.
*/
public static final Key<Value<Boolean>> IS_CONNECTED_SOUTH = Keys.key(ResourceKey.sponge("is_connected_south"), Boolean.class);
/**
* Whether a {@link BlockState} is connected to the {@link Direction#UP}.
* Also see {@link #CONNECTED_DIRECTIONS}.
*/
public static final Key<Value<Boolean>> IS_CONNECTED_UP = Keys.key(ResourceKey.sponge("is_connected_up"), Boolean.class);
/**
* Whether a {@link BlockState} is connected to the {@link Direction#WEST}.
* Also see {@link #CONNECTED_DIRECTIONS}.
*/
public static final Key<Value<Boolean>> IS_CONNECTED_WEST = Keys.key(ResourceKey.sponge("is_connected_west"), Boolean.class);
/**
* Whether an {@link Arrow} will cause a critical hit.
*/
public static final Key<Value<Boolean>> IS_CRITICAL_HIT = Keys.key(ResourceKey.sponge("is_critical_hit"), Boolean.class);
/**
* Whether a {@link Fox} is currently crouching.
*/
public static final Key<Value<Boolean>> IS_CROUCHING = Keys.key(ResourceKey.sponge("is_crouching"), Boolean.class);
/**
* Whether a custom name is visible on an {@link Entity}.
*/
public static final Key<Value<Boolean>> IS_CUSTOM_NAME_VISIBLE = Keys.key(ResourceKey.sponge("is_custom_name_visible"), Boolean.class);
/**
* Whether a {@link Fox} is currently defending.
*/
public static final Key<Value<Boolean>> IS_DEFENDING = Keys.key(ResourceKey.sponge("is_defending"), Boolean.class);
/**
* Whether a {@link BlockState} is disarmed.
* e.g. {@link BlockTypes#TRIPWIRE}s and {@link BlockTypes#TRIPWIRE_HOOK}s.
*/
public static final Key<Value<Boolean>> IS_DISARMED = Keys.key(ResourceKey.sponge("is_disarmed"), Boolean.class);
/**
* Whether an entity is eating.
* e.g. {@link Panda}
*/
public static final Key<Value<Boolean>> IS_EATING = Keys.key(ResourceKey.sponge("is_eating"), Boolean.class);
/**
* Whether a {@link WeatherEffect} like {@link LightningBolt} is harmful to other {@link Entity entities}.
* Readonly
*/
public static final Key<Value<Boolean>> IS_EFFECT_ONLY = Keys.key(ResourceKey.sponge("is_effect_only"), Boolean.class);
/**
* Whether a {@link Player} is flying with an {@link ItemTypes#ELYTRA}.
*/
public static final Key<Value<Boolean>> IS_ELYTRA_FLYING = Keys.key(ResourceKey.sponge("is_elytra_flying"), Boolean.class);
/**
* Whether a piston {@link BlockState} is currently extended.
* TODO {@link Piston}?
*/
public static final Key<Value<Boolean>> IS_EXTENDED = Keys.key(ResourceKey.sponge("is_extended"), Boolean.class);
/**
* Whether a {@link Fox} is currently faceplanted.
*/
public static final Key<Value<Boolean>> IS_FACEPLANTED = Keys.key(ResourceKey.sponge("is_faceplanted"), Boolean.class);
/**
* Whether a {@link BlockState} is filled.
* <p>e.g. {@link BlockTypes#END_PORTAL_FRAME}s.</p>
*/
public static final Key<Value<Boolean>> IS_FILLED = Keys.key(ResourceKey.sponge("is_filled"), Boolean.class);
/**
* Whether a {@link BlockState} is flammable.
* Readonly
*/
public static final Key<Value<Boolean>> IS_FLAMMABLE = Keys.key(ResourceKey.sponge("is_flammable"), Boolean.class);
/**
* Whether an {@link Entity} is flying. TODO only player?
*
* <p>This key only tells whether an entity is flying at the moment. On a
* {@link Player} it does not necessarily mean that the player may toggle
* freely between flying and walking. To check whether a player may switch
* his flying state, check {@link #CAN_FLY}.</p>
*/
public static final Key<Value<Boolean>> IS_FLYING = Keys.key(ResourceKey.sponge("is_flying"), Boolean.class);
/**
* Whether an entity is frightened.
*
* <p>In vanilla, {@link Panda}s that have a {@link Panda#knownGene()}
* of {@link PandaGenes#WORRIED} and are in a {@link ServerWorld world} whose {@link WeatherType} is currently a
* {@link WeatherTypes#THUNDER} are considered "frightened".</p>
*/
public static final Key<Value<Boolean>> IS_FRIGHTENED = Keys.key(ResourceKey.sponge("is_frightened"), Boolean.class);
/**
* Whether the block at the {@link ServerLocation} is a full block.
*/
public static final Key<Value<Boolean>> IS_FULL_BLOCK = Keys.key(ResourceKey.sponge("is_full_block"), Boolean.class);
/**
* Whether an {@link Entity} has a glowing outline.
*/
public static final Key<Value<Boolean>> IS_GLOWING = Keys.key(ResourceKey.sponge("is_glowing"), Boolean.class);
/**
* Whether {@link Turtle} is proceeding to it's {@link Vector3i home position}.
*/
public static final Key<Value<Boolean>> IS_GOING_HOME = Keys.key(ResourceKey.sponge("is_going_home"), Boolean.class);
/**
* Whether something is affected by gravity.
* e.g. {@link Entity}s and {@link BlockState}s
* Readonly(BlockState.class)
*/
public static final Key<Value<Boolean>> IS_GRAVITY_AFFECTED = Keys.key(ResourceKey.sponge("is_gravity_affected"), Boolean.class);
/**
* Whether a {@link Cat} is hissing.
*/
public static final Key<Value<Boolean>> IS_HISSING = Keys.key(ResourceKey.sponge("is_hissing"), Boolean.class);
/**
* Whether a {@link Ravager} is immobilized.
* Readonly
*/
public static final Key<Value<Boolean>> IS_IMMOBILIZED = Keys.key(ResourceKey.sponge("is_immobilized"), Boolean.class);
/**
* Whether a {@link ServerLocation} is indirectly powered.
* Readonly
*/
public static final Key<Value<Boolean>> IS_INDIRECTLY_POWERED = Keys.key(ResourceKey.sponge("is_indirectly_powered"), Boolean.class);
/**
* Whether a {@link Fox} is currently interested in something.
*/
public static final Key<Value<Boolean>> IS_INTERESTED = Keys.key(ResourceKey.sponge("is_interested"), Boolean.class);
/**
* Whether an {@link Entity} is currently invisible.
* This will only simply render the entity as vanished,
* but not prevent any entity updates being sent to clients.
* To fully "vanish" an {@link Entity}, use {@link #VANISH_STATE}.
*/
public static final Key<Value<Boolean>> IS_INVISIBLE = Keys.key(ResourceKey.sponge("is_invisible"), Boolean.class);
/**
* Whether a {@link Boat} is currently in {@link BlockTypes#WATER}.
* Readonly
*/
public static final Key<Value<Boolean>> IS_IN_WATER = Keys.key(ResourceKey.sponge("is_in_water"), Boolean.class);
public static final Key<Value<Boolean>> IS_JOHNNY = Keys.key(ResourceKey.sponge("is_johnny"), Boolean.class);
/**
* Whether a {@link Turtle} is currently digging to lay an egg.
*/
public static final Key<Value<Boolean>> IS_LAYING_EGG = Keys.key(ResourceKey.sponge("is_laying_egg"), Boolean.class);
/**
* Whether a {@link Patroller} is the leader.
*/
public static final Key<Value<Boolean>> IS_LEADER = Keys.key(ResourceKey.sponge("is_leader"), Boolean.class);
/**
* Whether a {@link BlockState} is lit.
* e.g. {@link BlockTypes#FURNACE}, {@link BlockTypes#CAMPFIRE}
* or {@link BlockTypes#REDSTONE_TORCH}.
*/
public static final Key<Value<Boolean>> IS_LIT = Keys.key(ResourceKey.sponge("is_lit"), Boolean.class);
/**
* Whether a {@link Cat} is lying down.
*
* <p>In vanilla, a cat lies down near its owner when the owner goes to
* sleep.</p>
*/
public static final Key<Value<Boolean>> IS_LYING_DOWN = Keys.key(ResourceKey.sponge("is_lying_down"), Boolean.class);
/**
* Whether a {@link Panda} is lying on it's back.
*/
public static final Key<Value<Boolean>> IS_LYING_ON_BACK = Keys.key(ResourceKey.sponge("is_lying_on_back"), Boolean.class);
/**
* Whether a bed {@link BlockState} is occupied.
* e.g. {@link BlockTypes#WHITE_BED}.
*/
public static final Key<Value<Boolean>> IS_OCCUPIED = Keys.key(ResourceKey.sponge("is_occupied"), Boolean.class);
/**
* Whether a {@link Minecart} is on it's rail
* Readonly
*/
public static final Key<Value<Boolean>> IS_ON_RAIL = Keys.key(ResourceKey.sponge("is_on_rail"), Boolean.class);
/**
* Whether a door/fencegate/trapdoor {@link BlockState} is open.
*/
public static final Key<Value<Boolean>> IS_OPEN = Keys.key(ResourceKey.sponge("is_open"), Boolean.class);
/**
* Whether a {@link BlockState} is passable (can be walked through).
* Readonly
*/
public static final Key<Value<Boolean>> IS_PASSABLE = Keys.key(ResourceKey.sponge("is_passable"), Boolean.class);
/**
* Whether a {@link Patroller} is currently patrolling.
*/
public static final Key<Value<Boolean>> IS_PATROLLING = Keys.key(ResourceKey.sponge("is_patrolling"), Boolean.class);
/**
* Whether an {@link Entity} or leaves {@link BlockState} will
* be prevented from despawning/decaying.
*
* <p>In Vanilla, entities may despawn if the player moves too far from
* them. A persisting entity will not be removed due to no players being
* near it.</p>
*/
public static final Key<Value<Boolean>> IS_PERSISTENT = Keys.key(ResourceKey.sponge("is_persistent"), Boolean.class);
/**
* Whether players are prevented from placing
* items from an equipment slot on an {@link ArmorStand}
*/
public static final Key<MapValue<EquipmentType, Boolean>> IS_PLACING_DISABLED = Keys.mapKey(ResourceKey.sponge("is_placing_disabled"), EquipmentType.class, Boolean.class);
public static final Key<Value<Boolean>> IS_PLAYER_CREATED = Keys.key(ResourceKey.sponge("is_player_created"), Boolean.class);
/**
* Whether a {@link Fox} is currently pouncing.
*/
public static final Key<Value<Boolean>> IS_POUNCING = Keys.key(ResourceKey.sponge("is_pouncing"), Boolean.class);
/**
* Whether a {@link BlockState} is powered.
*
* <p>Applies to blocks that may be powered in order to emit a
* Redstone signal of consistently maximum strength, such as
* {@link BlockTypes#LEVER}, {@link BlockTypes#OAK_BUTTON},
* {@link BlockTypes#OAK_PRESSURE_PLATE}, and their stone
* counterparts.</p>
*/
public static final Key<Value<Boolean>> IS_POWERED = Keys.key(ResourceKey.sponge("is_powered"), Boolean.class);
/**
* Whether a {@link FusedExplosive} is currently primed.
* Readonly
*/
public static final Key<Value<Boolean>> IS_PRIMED = Keys.key(ResourceKey.sponge("is_primed"), Boolean.class);
/**
* Whether a {@link Cat} is purring.
*/
public static final Key<Value<Boolean>> IS_PURRING = Keys.key(ResourceKey.sponge("is_purring"), Boolean.class);
/**
* Whether a {@link Cat} is relaxed.
*
* <p>In vanilla, a cat relaxes before lying down.</p>
*/
public static final Key<Value<Boolean>> IS_RELAXED = Keys.key(ResourceKey.sponge("is_relaxed"), Boolean.class);
/**
* Whether a {@link BlockState} can be replaced by a player without breaking it first.
* e.g. {@link BlockTypes#WATER}
* Readonly
*/
public static final Key<Value<Boolean>> IS_REPLACEABLE = Keys.key(ResourceKey.sponge("is_replaceable"), Boolean.class);
/**
* Whether a {@link Ravager} is roaring.
* Readonly
*/
public static final Key<Value<Boolean>> IS_ROARING = Keys.key(ResourceKey.sponge("is_roaring"), Boolean.class);
/**
* Whether a {@link Panda} is rolling around.
*/
public static final Key<Value<Boolean>> IS_ROLLING_AROUND = Keys.key(ResourceKey.sponge("is_rolling_around"), Boolean.class);
/**
* Whether an entity is saddled.
* e.g. {@link Horse}s and {@link Pig}s
*/
public static final Key<Value<Boolean>> IS_SADDLED = Keys.key(ResourceKey.sponge("is_saddled"), Boolean.class);
/**
* Whether an {@link Enderman} is screaming.
*/
public static final Key<Value<Boolean>> IS_SCREAMING = Keys.key(ResourceKey.sponge("is_screaming"), Boolean.class);
/**
* Whether a {@link Sheep} is sheared.
*/
public static final Key<Value<Boolean>> IS_SHEARED = Keys.key(ResourceKey.sponge("is_sheared"), Boolean.class);
/**
* Whether an {@link Entity} is silent.
*
* <p>A silent entity will not emit sounds or make noises.</p>
*/
public static final Key<Value<Boolean>> IS_SILENT = Keys.key(ResourceKey.sponge("is_silent"), Boolean.class);
/**
* Whether a {@link Wolf}, {@link Cat}, {@link Panda}, or {@link Fox} is sitting.
*/
public static final Key<Value<Boolean>> IS_SITTING = Keys.key(ResourceKey.sponge("is_sitting"), Boolean.class);
/**
* Whether a {@link Bat}, {@link Fox} or {@link Player} is sleeping.
*
* <p>If a player is considered sleeping as per this data value, the player does
* not need to be in bed in order for the other players to be able to
* advance through the night by going to bed.</p>
* Readonly(Player.class)
*/
public static final Key<Value<Boolean>> IS_SLEEPING = Keys.key(ResourceKey.sponge("is_sleeping"), Boolean.class);
/**
* Whether a {@link Player Player's} sleeping status is ignored when checking whether to
* skip the night due to players sleeping. The time in a world will be
* advanced to day if all players in it either are sleeping or are set to ignore.
*/
public static final Key<Value<Boolean>> IS_SLEEPING_IGNORED = Keys.key(ResourceKey.sponge("is_sleeping_ignored"), Boolean.class);
/**
* Whether an {@link ArmorStand} is small.
*/
public static final Key<Value<Boolean>> IS_SMALL = Keys.key(ResourceKey.sponge("is_small"), Boolean.class);
/**
* Whether an {@link Entity} is sneaking.
*
* <p>Sneaking entities generally move slower and do not make walking
* sounds.</p>
*/
public static final Key<Value<Boolean>> IS_SNEAKING = Keys.key(ResourceKey.sponge("is_sneaking"), Boolean.class);
/**
* Whether a {@link Panda} is sneezing.
*/
public static final Key<Value<Boolean>> IS_SNEEZING = Keys.key(ResourceKey.sponge("is_sneezing"), Boolean.class);
/**
* Whether a {@link BlockTypes#DIRT} {@link BlockState} is snowy.
*/
public static final Key<Value<Boolean>> IS_SNOWY = Keys.key(ResourceKey.sponge("is_snowy"), Boolean.class);
/**
* Whether a {@link BlockState} is solid.
* Readonly
*/
public static final Key<Value<Boolean>> IS_SOLID = Keys.key(ResourceKey.sponge("is_solid"), Boolean.class);
/**
* Whether an {@link Entity} is sprinting.
*/
public static final Key<Value<Boolean>> IS_SPRINTING = Keys.key(ResourceKey.sponge("is_sprinting"), Boolean.class);
/**
* Whether a {@link PolarBear} is currently standing.
*/
public static final Key<Value<Boolean>> IS_STANDING = Keys.key(ResourceKey.sponge("is_standing"), Boolean.class);
/**
* Whether a {@link Ravager} is stunned.
* Readonly
*/
public static final Key<Value<Boolean>> IS_STUNNED = Keys.key(ResourceKey.sponge("is_stunned"), Boolean.class);
/**
* Whether a {@link BlockState} is a surrogate block for a block that was provided in an environment
* (almost always modded), that the block type provider no longer exists.
* If true this may indicate that the surrogate block functions differently than the original block.
* Readonly
*/
public static final Key<Value<Boolean>> IS_SURROGATE_BLOCK = Keys.key(ResourceKey.sponge("is_surrogate_block"), Boolean.class);
/**
* Whether players are prevented from taking
* items from an equipment slot on an {@link ArmorStand}
*/
public static final Key<MapValue<EquipmentType, Boolean>> IS_TAKING_DISABLED = Keys.mapKey(ResourceKey.sponge("is_taking_disabled"), EquipmentType.class, Boolean.class);
/**
* Whether a {@link TameableAnimal} is currently tamed
*/
public static final Key<Value<Boolean>> IS_TAMED = Keys.key(ResourceKey.sponge("is_tamed"), Boolean.class);
/**
* Whether a {@link Trader} is currently trading with a {@link Player}.
* Readonly
*/
public static final Key<Value<Boolean>> IS_TRADING = Keys.key(ResourceKey.sponge("is_trading"), Boolean.class);
/**
* Whether a {@link Turtle} is currently traveling.
*/
public static final Key<Value<Boolean>> IS_TRAVELING = Keys.key(ResourceKey.sponge("is_traveling"), Boolean.class);
/**
* Whether an {@link Ocelot} is currently trusting of {@link Player}s.
*/
public static final Key<Value<Boolean>> IS_TRUSTING = Keys.key(ResourceKey.sponge("is_trusting"), Boolean.class);
/**
* Whether an {@link ItemStack} or {@link BlockState} is unbreakable.
*
* <p>Setting this to {@code true} will prevent the item stack's
* {@link #ITEM_DURABILITY} from changing.</p>
* Readonly(BlockState.class)
*/
public static final Key<Value<Boolean>> IS_UNBREAKABLE = Keys.key(ResourceKey.sponge("is_unbreakable"), Boolean.class);
/**
* Whether a {@link Panda} is unhappy.
*/
public static final Key<Value<Boolean>> IS_UNHAPPY = Keys.key(ResourceKey.sponge("is_unhappy"), Boolean.class);
/**
* Whehter a {@link BlockState} is waterlogged.
*/
public static final Key<Value<Boolean>> IS_WATERLOGGED = Keys.key(ResourceKey.sponge("is_waterlogged"), Boolean.class);
/**
* Whether an {@link Entity} like {@link Wolf} is wet.
* Readonly(Entity.class) except Wolf
*/
public static final Key<Value<Boolean>> IS_WET = Keys.key(ResourceKey.sponge("is_wet"), Boolean.class);
/**
* The durability of an {@link ItemStack}. {@link #MAX_DURABILITY}
*/
public static final Key<Value<Integer>> ITEM_DURABILITY = Keys.key(ResourceKey.sponge("item_durability"), Integer.class);
/**
* The rarity of an item.
*/
public static final Key<Value<ItemRarity>> ITEM_RARITY = Keys.key(ResourceKey.sponge("item_rarity"), ItemRarity.class);
/**
* The {@link ItemStackSnapshot item} in an
* {@link Item}, {@link ItemFrame}, {@link Jukebox}, {@link Lectern} or
* {@link Potion}.
*/
public static final Key<Value<ItemStackSnapshot>> ITEM_STACK_SNAPSHOT = Keys.key(ResourceKey.sponge("item_stack_snapshot"), ItemStackSnapshot.class);
/**
* The knockback strength applied by an {@link ArrowEntity}.
*
* <p>For the knockback provided by hits with a weapon according to the
* enchantment of the same name, see {@link #APPLIED_ENCHANTMENTS}.</p>
*/
public static final Key<Value<Double>> KNOCKBACK_STRENGTH = Keys.key(ResourceKey.sponge("knockback_strength"), Double.class);
/**
* The known {@link PandaGene gene} of a {@link Panda}.
*/
public static final Key<Value<PandaGene>> KNOWN_GENE = Keys.key(ResourceKey.sponge("known_gene"), PandaGene.class);
/**
* The last attacking {@link Entity} of a {@link Living}.
*/
public static final Key<Value<Entity>> LAST_ATTACKER = Keys.key(ResourceKey.sponge("last_attacker"), Entity.class);
/**
* The output yielded by the last command of a {@link CommandBlock} or {@link CommandBlockMinecart}.
*/
public static final Key<Value<Component>> LAST_COMMAND_OUTPUT = Keys.key(ResourceKey.sponge("last_command_output"), Component.class);
/**
* The last damage a {@link Living} received.
*/
public static final Key<Value<Double>> LAST_DAMAGE_RECEIVED = Keys.key(ResourceKey.sponge("last_damage_received"), Double.class);
/**
* The last time a {@link User} joined on the server.
*/
public static final Key<Value<Instant>> LAST_DATE_JOINED = Keys.key(ResourceKey.sponge("last_date_joined"), Instant.class);
/**
* The last time a {@link User} has been playing on the server.
*/
public static final Key<Value<Instant>> LAST_DATE_PLAYED = Keys.key(ResourceKey.sponge("last_date_played"), Instant.class);
/**
* The amount of layers a {@link BlockState} has.
* e.g. {@link BlockTypes#SNOW}, {@link BlockTypes#CAKE}
*/
public static final Key<Value<Integer>> LAYER = Keys.key(ResourceKey.sponge("layer"), Integer.class);
/**
* The holder of a leashed {@link Agent}
* e.g. a {@link Player} or {@link LeashKnot}.
* <p>Usually, a {@link LeashKnot} will always exist so long as there is
* a leashed {@link Entity} attached. If the leash is broken, the leash
* hitch is removed.</p>
*/
public static final Key<Value<Entity>> LEASH_HOLDER = Keys.key(ResourceKey.sponge("leash_holder"), Entity.class);
/**
* The rotation of an {@link ArmorStand}'s left arm.
*/
public static final Key<Value<Vector3d>> LEFT_ARM_ROTATION = Keys.key(ResourceKey.sponge("left_arm_rotation"), Vector3d.class);
/**
* The rotation of an {@link ArmorStand}'s left leg.
*/
public static final Key<Value<Vector3d>> LEFT_LEG_ROTATION = Keys.key(ResourceKey.sponge("left_leg_rotation"), Vector3d.class);
/**
* The amount of ticks till a {@link Vex} starts
* taking damage due to living too long.
*
* <p>When this value hits 0 or lower, the Vex will receive damage and
* then the value will set back to 20 until the Vex dies.</p>
*
* <p>If the Vex was summoned by a player, this value will be pegged at 0
* and the Vex will not take any damage.</p>
*/
public static final Key<Value<Ticks>> LIFE_TICKS = Keys.key(ResourceKey.sponge("life_ticks"), Ticks.class);
/**
* The amount of light that emitted by a {@link BlockState}.
* Readonly
*/
public static final Key<Value<Integer>> LIGHT_EMISSION = Keys.key(ResourceKey.sponge("light_emission"), Integer.class);
/**
* A {@link Llama}'s {@link LlamaType}.
*/
public static final Key<Value<LlamaType>> LLAMA_TYPE = Keys.key(ResourceKey.sponge("llama_type"), LlamaType.class);
/**
* A {@link ServerPlayer}'s client language.
*/
public static final Key<Value<Locale>> LOCALE = Keys.key(ResourceKey.sponge("locale"), Locale.class);
/**
* The token used to lock a {@link CarrierBlockEntity}. Or the token on an {@link ItemStack} to unlock it.
*/
public static final Key<Value<String>> LOCK_TOKEN = Keys.key(ResourceKey.sponge("lock_token"), String.class);
/**
* A lodestone location, used with {@link ItemTypes#COMPASS}.
*/
public static final Key<Value<ServerLocation>> LODESTONE = Keys.key(ResourceKey.sponge("lodestone"), ServerLocation.class);
/**
* The displayed description ("lore") text of an {@link ItemStack}.
*
* <p>The lore text is usually displayed when the player hovers his cursor
* over the stack. For the contents of a book see {@link #PAGES}
* instead.</p>
*/
public static final Key<ListValue<Component>> LORE = Keys.listKey(ResourceKey.sponge("lore"), Component.class);
/**
* Represents the {@link Key} for the {@link MapCanvas} of a map
* for a {@link MapInfo}.
* This contains the colors displayed on a map.
*
*/
public static final Key<Value<MapCanvas>> MAP_CANVAS = Keys.key(ResourceKey.sponge("map_canvas"), MapCanvas.class);
/**
* Represents the {@link Key} for the Set of {@link MapDecoration}s
* for a {@link MapInfo}.
*
*/
public static final Key<SetValue<MapDecoration>> MAP_DECORATIONS = Keys.setKey(ResourceKey.sponge("map_decorations"), MapDecoration.class);
/**
* Represents the {@link Key} for the {@link MapInfo}
* of an {@link ItemStack} of type {@link ItemTypes#FILLED_MAP}.
*
* <b>Can be null if the ItemStack was made by a plugin and hasn't been offered a MapInfo yet.</b>
*/
public static final Key<Value<MapInfo>> MAP_INFO = Keys.key(ResourceKey.sponge("map_info"), MapInfo.class);
/**
* Represents the {@link Key} for the centre x and z of where a
* {@link MapInfo} represents.
* This will be automatically centralised correctly.
*/
public static final Key<Value<Vector2i>> MAP_LOCATION = Keys.key(ResourceKey.sponge("map_location"), Vector2i.class);
public static final Key<Value<Boolean>> MAP_LOCKED = Keys.key(ResourceKey.sponge("map_locked"), Boolean.class);
public static final Key<Value<Integer>> MAP_SCALE = Keys.key(ResourceKey.sponge("map_scale"), Integer.class);
/**
* Represents the {@link Key} for whether a {@link MapInfo}
* tracks player positions.
*/
public static final Key<Value<Boolean>> MAP_TRACKS_PLAYERS = Keys.key(ResourceKey.sponge("map_tracks_players"), Boolean.class);
/**
* Represents the {@link Key} for whether a {@link MapInfo} can track
* a player from anywhere in the world.
*/
public static final Key<Value<Boolean>> MAP_UNLIMITED_TRACKING = Keys.key(ResourceKey.sponge("map_unlimited_tracking"), Boolean.class);
/**
* Represents the {@link Key} for the {@link ResourceKey} of a {@link ServerWorld}.
* {@link MapInfo}
*/
public static final Key<Value<ResourceKey>> MAP_WORLD = Keys.key(ResourceKey.sponge("map_world"), ResourceKey.class);
/**
* The matter state of a {@link BlockState}
* Readonly
*/
public static final Key<Value<MatterType>> MATTER_TYPE = Keys.key(ResourceKey.sponge("matter_type"), MatterType.class);
/**
* The maximum air supply a {@link Living} may have.
*
* <p>For the current amount of air, check {@link #REMAINING_AIR}.</p>
*/
public static final Key<Value<Integer>> MAX_AIR = Keys.key(ResourceKey.sponge("max_air"), Integer.class);
/**
* The maximum amount of ticks a {@link FurnaceBlockEntity}
* can burn with the currently used fuel item.
*/
public static final Key<Value<Ticks>> MAX_BURN_TIME = Keys.key(ResourceKey.sponge("max_burn_time"), Ticks.class);
/**
* The total time the current {@link ItemStack} in a
* {@link FurnaceBlockEntity} has to be cooked.
*/
public static final Key<Value<Ticks>> MAX_COOK_TIME = Keys.key(ResourceKey.sponge("max_cook_time"), Ticks.class);
/**
* The maximum durability of an {@link ItemStack}. {@link #ITEM_DURABILITY}
* Readonly
*/
public static final Key<Value<Integer>> MAX_DURABILITY = Keys.key(ResourceKey.sponge("max_durability"), Integer.class);
/**
* The maximum exhuastion of a {@link Humanoid}. Readonly.
*
* @see Keys#EXHAUSTION
*/
public static final Key<Value<Double>> MAX_EXHAUSTION = Keys.key(ResourceKey.sponge("max_exhaustion"), Double.class);
/**
* The maximum damage a {@link FallingBlock} can deal.
*/
public static final Key<Value<Double>> MAX_FALL_DAMAGE = Keys.key(ResourceKey.sponge("max_fall_damage"), Double.class);
/**
* The maximum food level of a {@link Humanoid}. Readonly.
*
* @see Keys#FOOD_LEVEL
*/
public static final Key<Value<Integer>> MAX_FOOD_LEVEL = Keys.key(ResourceKey.sponge("max_food_level"), Integer.class);
/**
* The maximum health of a {@link Living}.
*
* <p>The maximum health set here may affect the attribute increasing
* health points. The base health should be minded that it may be lower
* than the total maximum health of the entity.</p>
*/
public static final Key<Value<Double>> MAX_HEALTH = Keys.key(ResourceKey.sponge("max_health"), Double.class);
/**
* The maximum number of entities around a {@link MobSpawner}.
* A spawner will not spawn entities if there are more
* entities around than this value permits.
*/
public static final Key<Value<Integer>> MAX_NEARBY_ENTITIES = Keys.key(ResourceKey.sponge("max_nearby_entities"), Integer.class);
/**
* The maximum saturation of a {@link Humanoid}. Readonly.
*
* @see Keys#SATURATION
*/
public static final Key<Value<Double>> MAX_SATURATION = Keys.key(ResourceKey.sponge("max_saturation"), Double.class);
/**
* The maximum amount of ticks between two
* batches of entities spawned by a {@link MobSpawner}.
*/
public static final Key<Value<Ticks>> MAX_SPAWN_DELAY = Keys.key(ResourceKey.sponge("max_spawn_delay"), Ticks.class);
/**
* The max speed of a {@link Boat}. In vanilla, this is 0.4
*/
public static final Key<Value<Double>> MAX_SPEED = Keys.key(ResourceKey.sponge("max_speed"), Double.class);
/**
* The maximum stack size of slots in an inventory. For most vanilla inventories this is 64.
* Readonly
*/
public static final Key<Value<Integer>> MAX_STACK_SIZE = Keys.key(ResourceKey.sponge("max_stack_size"), Integer.class);
/**
* The represented block's offset of a {@link MinecartLike}.
*/
public static final Key<Value<Integer>> MINECART_BLOCK_OFFSET = Keys.key(ResourceKey.sponge("minecart_block_offset"), Integer.class);
/**
* The minimum amount of ticks between two
* batches of entities spawned by a {@link MobSpawner}.
*/
public static final Key<Value<Ticks>> MIN_SPAWN_DELAY = Keys.key(ResourceKey.sponge("min_spawn_delay"), Ticks.class);
/**
* The moisture value of a {@link BlockTypes#FARMLAND} {@link BlockState}.
*/
public static final Key<Value<Integer>> MOISTURE = Keys.key(ResourceKey.sponge("moisture"), Integer.class);
/**
* The type of a {@link Mooshroom}.
*/
public static final Key<Value<MooshroomType>> MOOSHROOM_TYPE = Keys.key(ResourceKey.sponge("mooshroom_type"), MooshroomType.class);
/**
* The type of {@link MusicDisc} an {@link ItemStack} holds.
*/
public static final Key<Value<MusicDisc>> MUSIC_DISC = Keys.key(ResourceKey.sponge("music_disc"), MusicDisc.class);
/**
* The next entity that will be spawned by a {@link MobSpawner}.
*
* <p>Normally the entities to be spawned are determined by a random value
* applied to the {@link #SPAWNABLE_ENTITIES} weighted collection. If this
* value exists, it will override the random spawn with a definite one.</p>
*/
public static final Key<Value<WeightedSerializableObject<EntityArchetype>>> NEXT_ENTITY_TO_SPAWN = Keys.key(ResourceKey.sponge("next_entity_to_spawn"), new TypeToken<WeightedSerializableObject<EntityArchetype>>() {});
/**
* The pitch of a {@link BlockTypes#NOTE_BLOCK} {@link BlockState}.
*/
public static final Key<Value<NotePitch>> NOTE_PITCH = Keys.key(ResourceKey.sponge("note_pitch"), NotePitch.class);
/**
* The notifier, usually of an {@link Entity}. It is up to the implementation to define.
*/
public static final Key<Value<UUID>> NOTIFIER = Keys.key(ResourceKey.sponge("notifier"), UUID.class);
/**
* The deceleration a {@link Boat} while it has {@link Keys#PASSENGERS}.
*/
public static final Key<Value<Double>> OCCUPIED_DECELERATION = Keys.key(ResourceKey.sponge("occupied_deceleration"), Double.class);
/**
* Whether an {@link Entity} is currently considered to be on the ground.
* Readonly
*/
public static final Key<Value<Boolean>> ON_GROUND = Keys.key(ResourceKey.sponge("on_ground"), Boolean.class);
/**
* The {@link Orientation} of an {@link ItemFrame}.
*/
public static final Key<Value<Orientation>> ORIENTATION = Keys.key(ResourceKey.sponge("orientation"), Orientation.class);
/**
* The content of a {@link ItemTypes#WRITTEN_BOOK} {@link ItemStack}.
*
* <p>Use {@link Keys#PLAIN_PAGES} if you wish to inspect the contents
* of a {@link ItemTypes#WRITABLE_BOOK}.</p>
*/
public static final Key<ListValue<Component>> PAGES = Keys.listKey(ResourceKey.sponge("pages"), Component.class);
/**
* The {@link ParrotType type} of a {@link Parrot}.
*/
public static final Key<Value<ParrotType>> PARROT_TYPE = Keys.key(ResourceKey.sponge("parrot_type"), ParrotType.class);
/**
* The particle type of an {@link AreaEffectCloud}.
*
* <p>Only a few {@link ParticleOption}s will be usable for this
* effect for specific {@link ParticleType}s and not every
* {@link ParticleType} will be applicable.</p>
*/
public static final Key<Value<ParticleEffect>> PARTICLE_EFFECT = Keys.key(ResourceKey.sponge("particle_effect"), ParticleEffect.class);
/**
* The amount of ticks a {@link FurnaceBlockEntity} has
* been cooking the current item for.
*
* <p>Once this value reaches the {@link #MAX_COOK_TIME}, the
* item will be finished cooking.</p>
*/
public static final Key<Value<Ticks>> PASSED_COOK_TIME = Keys.key(ResourceKey.sponge("passed_cook_time"), Ticks.class);
/**
* The entities that act as passengers for an {@link Entity}.
*
* <p>For example, a {@link Player} riding on a {@link Horse} or a
* {@link Pig} would be considered its passenger.</p>
*/
public static final Key<ListValue<Entity>> PASSENGERS = Keys.listKey(ResourceKey.sponge("passengers"), Entity.class);
/**
* A {@link TropicalFish}'s pattern color.
*/
public static final Key<Value<DyeColor>> PATTERN_COLOR = Keys.key(ResourceKey.sponge("pattern_color"), DyeColor.class);
/**
* The {@link PhantomPhase phase} of a {@link Phantom}.
*/
public static final Key<Value<PhantomPhase>> PHANTOM_PHASE = Keys.key(ResourceKey.sponge("phantom_phase"), PhantomPhase.class);
/**
* The pickup delay (in ticks) of an {@link Item}.
*/
public static final Key<Value<Ticks>> PICKUP_DELAY = Keys.key(ResourceKey.sponge("pickup_delay"), Ticks.class);
/**
* The {@link PickupRule} of an {@link ArrowEntity}.
*/
public static final Key<Value<PickupRule>> PICKUP_RULE = Keys.key(ResourceKey.sponge("pickup_rule"), PickupRule.class);
/**
* The piston type of a piston {@link BlockState} TODO dataholder {@link Piston}.
*/
public static final Key<Value<PistonType>> PISTON_TYPE = Keys.key(ResourceKey.sponge("piston_type"), PistonType.class);
/**
* The block types an {@link ItemStack} may be placed on.
*/
public static final Key<SetValue<BlockType>> PLACEABLE_BLOCK_TYPES = Keys.setKey(ResourceKey.sponge("placeable_block_types"), BlockType.class);
/**
* The content of a {@link ItemTypes#WRITABLE_BOOK} {@link ItemStack}.
*
* <p>Use {@link Keys#PAGES} if you wish to get the contents of a
* {@link ItemTypes#WRITTEN_BOOK}</p>
*/
public static final Key<ListValue<String>> PLAIN_PAGES = Keys.listKey(ResourceKey.sponge("plain_pages"), String.class);
/**
* The plugin that created an {@link Inventory}
*/
public static final Key<Value<PluginContainer>> PLUGIN_CONTAINER = Keys.key(ResourceKey.sponge("plugin_container"), PluginContainer.class);
/**
* The pore sides of a {@link BlockTypes#BROWN_MUSHROOM_BLOCK} or
* {@link BlockTypes#RED_MUSHROOM_BLOCK} {@link BlockState}.
* See {@link #HAS_PORES_UP}, {@link #HAS_PORES_DOWN}, {@link #HAS_PORES_NORTH}, {@link #HAS_PORES_EAST}, {@link #HAS_PORES_SOUTH}, {@link #HAS_PORES_WEST}.
*/
public static final Key<SetValue<Direction>> PORES = Keys.setKey(ResourceKey.sponge("pores"), Direction.class);
/**
* The {@link PortionType} of a {@link BlockState}.
* e.g. {@link BlockTypes#OAK_DOOR}, {@link BlockTypes#ROSE_BUSH} or {@link BlockTypes#WHITE_BED}
* For slabs use {@link #SLAB_PORTION} instead
*/
public static final Key<Value<PortionType>> PORTION_TYPE = Keys.key(ResourceKey.sponge("portion_type"), PortionType.class);
/**
* The potential max speed of a {@link Minecart}.
*/
public static final Key<Value<Double>> POTENTIAL_MAX_SPEED = Keys.key(ResourceKey.sponge("potential_max_speed"), Double.class);
/**
* The potion effects that are present on an {@link Entity}
* <p>or applied by an {@link AreaEffectCloud} or {@link ArrowEntity}</p>
* <p>or stored on an {@link ItemStack}.</p>
*/
public static final Key<ListValue<PotionEffect>> POTION_EFFECTS = Keys.listKey(ResourceKey.sponge("potion_effects"), PotionEffect.class);
/**
* The potion type of an {@link ItemStack}.
*/
public static final Key<Value<PotionType>> POTION_TYPE = Keys.key(ResourceKey.sponge("potion_type"), PotionType.class);
/**
* The signal power of a {@link BlockState}.
*
* <p>Applies to blocks that may emit a Redstone signal of variable
* strength, such as {@link BlockTypes#REDSTONE_WIRE},
* {@link BlockTypes#DAYLIGHT_DETECTOR},
* {@link BlockTypes#LIGHT_WEIGHTED_PRESSURE_PLATE} etc.</p>
*/
public static final Key<Value<Integer>> POWER = Keys.key(ResourceKey.sponge("power"), Integer.class);
/**
* A {@link Beacon}'s primary effect.
*/
public static final Key<Value<PotionEffectType>> PRIMARY_POTION_EFFECT_TYPE = Keys.key(ResourceKey.sponge("primary_potion_effect_type"), PotionEffectType.class);
/**
* The {@link Villager} or {@link ZombieVillager}'s {@link ProfessionType}.
*/
public static final Key<Value<ProfessionType>> PROFESSION_TYPE = Keys.key(ResourceKey.sponge("profession_type"), ProfessionType.class);
/**
* The {@link Villager} or {@link ZombieVillager}'s {@link ProfessionType} level.
*/
public static final Key<Value<Integer>> PROFESSION_LEVEL = Keys.key(ResourceKey.sponge("profession_level"), Integer.class);
/**
* The type of a {@link Rabbit}.
*/
public static final Key<Value<RabbitType>> RABBIT_TYPE = Keys.key(ResourceKey.sponge("rabbit_type"), RabbitType.class);
/**
* The radius of an {@link AreaEffectCloud}.
*/
public static final Key<Value<Double>> RADIUS = Keys.key(ResourceKey.sponge("radius"), Double.class);
/**
* The amount the radius of an
* {@link AreaEffectCloud} grows or shrinks each time it applies its
* effect.
*/
public static final Key<Value<Double>> RADIUS_ON_USE = Keys.key(ResourceKey.sponge("radius_on_use"), Double.class);
/**
* The amount the radius of an
* {@link AreaEffectCloud} grows or shrinks per tick.
*/
public static final Key<Value<Double>> RADIUS_PER_TICK = Keys.key(ResourceKey.sponge("radius_per_tick"), Double.class);
/**
* The wave number of a raid a {@link Raider} is in.
* Readonly but mutable
*/
public static final Key<Value<RaidWave>> RAID_WAVE = Keys.key(ResourceKey.sponge("raid_wave"), RaidWave.class);
/**
* The {@link RailDirection} of a {@link BlockState}.
*/
public static final Key<Value<RailDirection>> RAIL_DIRECTION = Keys.key(ResourceKey.sponge("rail_direction"), RailDirection.class);
/**
* The delay (in ticks) after which an
* {@link AreaEffectCloud} will reapply its effect on a previously
* affected {@link Entity}.
*/
public static final Key<Value<Ticks>> REAPPLICATION_DELAY = Keys.key(ResourceKey.sponge("reapplication_delay"), Ticks.class);
/**
* The redstone delay on a {@link BlockTypes#REPEATER} {@link BlockState}.
*/
public static final Key<Value<Integer>> REDSTONE_DELAY = Keys.key(ResourceKey.sponge("redstone_delay"), Integer.class);
/**
* The amount of air a {@link Living} has left.
*/
public static final Key<Value<Integer>> REMAINING_AIR = Keys.key(ResourceKey.sponge("remaining_air"), Integer.class);
/**
* The remaining amount of ticks the current brewing
* process of a {@link BrewingStand} will take.
*
* <p>If nothing is being brewed, the remaining brew time will be 0.</p>
*/
public static final Key<Value<Ticks>> REMAINING_BREW_TIME = Keys.key(ResourceKey.sponge("remaining_brew_time"), Ticks.class);
/**
* Represents the {@link Key} for the remaining number of ticks to pass
* before another attempt to spawn entities is made by a {@link MobSpawner}.
*/
public static final Key<Value<Ticks>> REMAINING_SPAWN_DELAY = Keys.key(ResourceKey.sponge("remaining_spawn_delay"), Ticks.class);
/**
* The amount of food a food {@link ItemStack} restores when eaten.
* Readonly
*/
public static final Key<Value<Integer>> REPLENISHED_FOOD = Keys.key(ResourceKey.sponge("replenished_food"), Integer.class);
/**
* The amount of saturation a food {@link ItemStack} provides when eaten.
* Readonly
*/
public static final Key<Value<Double>> REPLENISHED_SATURATION = Keys.key(ResourceKey.sponge("replenished_saturation"), Double.class);
/**
* The {@link InstrumentType} of a {@link BlockState} when placed under a {@link BlockTypes#NOTE_BLOCK}.
* Readonly
*/
public static final Key<Value<InstrumentType>> REPRESENTED_INSTRUMENT = Keys.key(ResourceKey.sponge("represented_instrument"), InstrumentType.class);
/**
* How close a {@link Player} has to be around the {@link MobSpawner}
* in order for it to attempt to spawn entities.
*/
public static final Key<Value<Double>> REQUIRED_PLAYER_RANGE = Keys.key(ResourceKey.sponge("required_player_range"), Double.class);
/**
* The spawn locations a {@link Player}
* may have for various worlds based on {@link UUID} of the world.
*/
public static final Key<MapValue<ResourceKey, RespawnLocation>> RESPAWN_LOCATIONS = Keys.mapKey(ResourceKey.sponge("respawn_locations"), ResourceKey.class, RespawnLocation.class);
/**
* The rotation of an {@link ArmorStand}'s right arm.
*/
public static final Key<Value<Vector3d>> RIGHT_ARM_ROTATION = Keys.key(ResourceKey.sponge("right_arm_rotation"), Vector3d.class);
/**
* The rotation of an {@link ArmorStand}'s right leg.
*/
public static final Key<Value<Vector3d>> RIGHT_LEG_ROTATION = Keys.key(ResourceKey.sponge("right_leg_rotation"), Vector3d.class);
/**
* The time a {@link Ravager} is roaring.
*/
public static final Key<Value<Ticks>> ROARING_TIME = Keys.key(ResourceKey.sponge("roaring_time"), Ticks.class);
public static final Key<Value<Double>> SATURATION = Keys.key(ResourceKey.sponge("saturation"), Double.class);
/**
* The "scale" for the size of an {@link Entity}.
*
* <p>Together with {@link #BASE_SIZE} and {@link #HEIGHT} this defines the size of an {@link Entity}.</p>
*/
public static final Key<Value<Double>> SCALE = Keys.key(ResourceKey.sponge("scale"), Double.class);
public static final Key<SetValue<String>> SCOREBOARD_TAGS = Keys.setKey(ResourceKey.sponge("scoreboard_tags"), String.class);
/**
* A {@link Beacon}'s secondary effect.
*/
public static final Key<Value<PotionEffectType>> SECONDARY_POTION_EFFECT_TYPE = Keys.key(ResourceKey.sponge("secondary_potion_effect_type"), PotionEffectType.class);
/**
* A {@link Fox fox's} second trusted {@link UUID}, usually a {@link Player}.
*/
public static final Key<Value<UUID>> SECOND_TRUSTED = Keys.key(ResourceKey.sponge("second_trusted"), UUID.class);
/**
* The shooter of a {@link Projectile}.
*/
public static final Key<Value<ProjectileSource>> SHOOTER = Keys.key(ResourceKey.sponge("shooter"), ProjectileSource.class);
/**
* Whether a {@link EndCrystal} should show it's bottom bedrock platform.
*/
public static final Key<Value<Boolean>> SHOW_BOTTOM = Keys.key(ResourceKey.sponge("show_bottom"), Boolean.class);
/**
* The lines displayed on a {@link Sign}.
*/
public static final Key<ListValue<Component>> SIGN_LINES = Keys.listKey(ResourceKey.sponge("sign_lines"), Component.class);
/**
* The size of a {@link Slime}.
* or
* The size of a {@link Phantom}. In vanilla, this ranges between 0 and 64.
*/
public static final Key<Value<Integer>> SIZE = Keys.key(ResourceKey.sponge("size"), Integer.class);
/**
* The parts of a {@link ServerPlayer} skin that should be displayed.
*
* <p>This is a read-only value, set by the client.</p>
*/
public static final Key<SetValue<SkinPart>> SKIN_PARTS = Keys.setKey(ResourceKey.sponge("skin_parts"), SkinPart.class);
/**
* The skin of a {@link Humanoid}.
*
* <p>Skins can only be manipulated by supplying the UUID of a player
* having that skin. The binary skin data is signed by Mojang so fully
* customized skins are not possible.</p>
* Readonly (Player)
*/
public static final Key<Value<ProfileProperty>> SKIN_PROFILE_PROPERTY = Keys.key(ResourceKey.sponge("skin_profile_property"), ProfileProperty.class);
/**
* The "moisture" state of a {@link Dolphin}.
*
* <p>
* Vanilla sets the dolphin's skin moisture to 2400 so long as the entity
* is in water, being rained on, or in a bubble column. If not, the dolphin
* will loose 1 moisture per tick. Once this value is 0 or below, the dolphin
* will be damaged via {@link DamageSources#DRYOUT} with a value of 1 per tick
* until death.
* </p>
*/
public static final Key<Value<Integer>> SKIN_MOISTURE = Keys.key(ResourceKey.sponge("skin_moisture"), Integer.class);
/**
* The skylight value at a {@link ServerLocation}.
* For the blocklight see {@link #BLOCK_LIGHT}.
* Readonly
*/
public static final Key<Value<Integer>> SKY_LIGHT = Keys.key(ResourceKey.sponge("sky_light"), Integer.class);
/**
* The {@link SlabPortion} of a {@link BlockState}.
*/
public static final Key<Value<SlabPortion>> SLAB_PORTION = Keys.key(ResourceKey.sponge("slab_portion"), SlabPortion.class);
/**
* The sleep timer of a {@link Player}.
*/
public static final Key<Value<Integer>> SLEEP_TIMER = Keys.key(ResourceKey.sponge("sleep_timer"), Integer.class);
/**
* The index of a {@link Slot} in an {@link Inventory}
* Readonly
*/
public static final Key<Value<Integer>> SLOT_INDEX = Keys.key(ResourceKey.sponge("slot_index"), Integer.class);
/**
* The position of a {@link Slot} within a {@link GridInventory}.
* Readonly
*/
public static final Key<Value<Vector2i>> SLOT_POSITION = Keys.key(ResourceKey.sponge("slot_position"), Vector2i.class);
/**
* The side of a particular {@link Slot}, for use in querying "sided inventories".
* Readonly
*/
public static final Key<Value<Direction>> SLOT_SIDE = Keys.key(ResourceKey.sponge("slot_side"), Direction.class);
/**
* Whether a {@link Minecart} slows down when it has no {@link Keys#PASSENGERS}.
*/
public static final Key<Value<Boolean>> SLOWS_UNOCCUPIED = Keys.key(ResourceKey.sponge("slows_unoccupied"), Boolean.class);
/**
* The time a {@link Panda} has been sneezing (in ticks)
*/
public static final Key<Value<Ticks>> SNEEZING_TIME = Keys.key(ResourceKey.sponge("sneezing_time"), Ticks.class);
/**
* The list of {@link EntityArchetype}s able to be spawned by a {@link MobSpawner}.
*/
public static final Key<WeightedCollectionValue<EntityArchetype>> SPAWNABLE_ENTITIES = Keys.weightedKey(ResourceKey.sponge("spawnable_entities"), EntityArchetype.class);
/**
* How many entities a {@link MobSpawner} has spawned so far.
*/
public static final Key<Value<Integer>> SPAWN_COUNT = Keys.key(ResourceKey.sponge("spawn_count"), Integer.class);
/**
* How far away from the {@link MobSpawner} the entities spawned by it may appear.
*/
public static final Key<Value<Double>> SPAWN_RANGE = Keys.key(ResourceKey.sponge("spawn_range"), Double.class);
/**
* The {@link Entity target} of the spectator camera of a {@link Player}.
*/
public static final Key<Value<Entity>> SPECTATOR_TARGET = Keys.key(ResourceKey.sponge("spectator_target"), Entity.class);
/**
* The {@link StairShape} of a {@link BlockState}.
*/
public static final Key<Value<StairShape>> STAIR_SHAPE = Keys.key(ResourceKey.sponge("stair_shape"), StairShape.class);
/**
* The {@link Statistic}s of a {@link Player}.
*/
public static final Key<MapValue<Statistic, Long>> STATISTICS = Keys.mapKey(ResourceKey.sponge("statistics"), Statistic.class, Long.class);
/**
* The enchantments stored on an {@link ItemStack}.
*
* <p>Stored enchantments are meant to be transferred. Usually this key
* applies to {@link ItemTypes#ENCHANTED_BOOK} {@link ItemStack}s. Enchantments
* affecting the item stack are retrieved via {@link #APPLIED_ENCHANTMENTS}
* instead.</p>
*/
public static final Key<ListValue<Enchantment>> STORED_ENCHANTMENTS = Keys.listKey(ResourceKey.sponge("stored_enchantments"), Enchantment.class);
/**
* A {@link Llama}s carrying strength. The higher the strength,
* the more items it can carry (effectively the size of inventory).
*/
public static final Key<Value<Integer>> STRENGTH = Keys.key(ResourceKey.sponge("strength"), Integer.class);
/**
* The author of a structure from a {@link StructureBlock}.
*/
public static final Key<Value<String>> STRUCTURE_AUTHOR = Keys.key(ResourceKey.sponge("structure_author"), String.class);
/**
* Whether a {@link StructureBlock} should
* ignore entities when saving a structure.
*/
public static final Key<Value<Boolean>> STRUCTURE_IGNORE_ENTITIES = Keys.key(ResourceKey.sponge("structure_ignore_entities"), Boolean.class);
/**
* The integrity of a {@link StructureBlock}.
*/
public static final Key<Value<Double>> STRUCTURE_INTEGRITY = Keys.key(ResourceKey.sponge("structure_integrity"), Double.class);
/**
* The mode of a {@link StructureBlock}.
*/
public static final Key<Value<StructureMode>> STRUCTURE_MODE = Keys.key(ResourceKey.sponge("structure_mode"), StructureMode.class);
/**
* The position of a {@link StructureBlock}.
*/
public static final Key<Value<Vector3i>> STRUCTURE_POSITION = Keys.key(ResourceKey.sponge("structure_position"), Vector3i.class);
/**
* Whether a {@link StructureBlock} is powered.
*/
public static final Key<Value<Boolean>> STRUCTURE_POWERED = Keys.key(ResourceKey.sponge("structure_powered"), Boolean.class);
/**
* The seed of a {@link StructureBlock}
*/
public static final Key<Value<Long>> STRUCTURE_SEED = Keys.key(ResourceKey.sponge("structure_seed"), Long.class);
/**
* Whether a
* {@link StructureBlock} should make all {@link BlockTypes#AIR},
* {@link BlockTypes#CAVE_AIR}, {@link BlockTypes#STRUCTURE_VOID} visible.
*/
public static final Key<Value<Boolean>> STRUCTURE_SHOW_AIR = Keys.key(ResourceKey.sponge("structure_show_air"), Boolean.class);
/**
* Whether a {@link StructureBlock} shows the bounding box.
*/
public static final Key<Value<Boolean>> STRUCTURE_SHOW_BOUNDING_BOX = Keys.key(ResourceKey.sponge("structure_show_bounding_box"), Boolean.class);
/**
* The size of a {@link StructureBlock}s structure.
*/
public static final Key<Value<Vector3i>> STRUCTURE_SIZE = Keys.key(ResourceKey.sponge("structure_size"), Vector3i.class);
/**
* The amount of "stuck arrows" in a {@link Living}.
*/
public static final Key<Value<Integer>> STUCK_ARROWS = Keys.key(ResourceKey.sponge("stuck_arrows"), Integer.class);
/**
* The time (in ticks) a {@link Ravager} is stunned.
*/
public static final Key<Value<Ticks>> STUNNED_TIME = Keys.key(ResourceKey.sponge("stunned_time"), Ticks.class);
/**
* The amount of successful executions of a command
* stored in a {@link CommandBlock} or {@link CommandBlockMinecart}.
*/
public static final Key<Value<Integer>> SUCCESS_COUNT = Keys.key(ResourceKey.sponge("success_count"), Integer.class);
/**
* Whether a {@link BlockState} is suspended.
*/
public static final Key<Value<Boolean>> SUSPENDED = Keys.key(ResourceKey.sponge("suspended"), Boolean.class);
/**
* The swiftness of an {@link Entity} e.g. {@link Minecart}s.
* <p>This is equivalent to the magnitude of the {@link #VELOCITY} vector</p>
*/
public static final Key<Value<Double>> SWIFTNESS = Keys.key(ResourceKey.sponge("swiftness"), Double.class);
/**
* The tamer of a {@link TameableAnimal} or {@link HorseLike}.
*/
public static final Key<Value<UUID>> TAMER = Keys.key(ResourceKey.sponge("tamer"), UUID.class);
/**
* The targeted entity either by an {@link Agent} and it's
* {@link GoalExecutorTypes#TARGET} selector or by a {@link FishingBobber} or {@link ShulkerBullet}.
*/
public static final Key<Value<Entity>> TARGET_ENTITY = Keys.key(ResourceKey.sponge("target_entity"), Entity.class);
/**
* A target location.
* e.g. An {@link EyeOfEnder} target or a {@link Player}'s compass.
*/
public static final Key<Value<Vector3d>> TARGET_LOCATION = Keys.key(ResourceKey.sponge("target_location"), Vector3d.class);
/**
* A target block position.
* e.g. A {@link Patroller}'s patrol target,
* the travel position of a {@link Turtle},
* the exit portal position of a {@link EndGateway} or
* an {@link EndCrystal}'s beam target.
*/
public static final Key<Value<Vector3i>> TARGET_POSITION = Keys.key(ResourceKey.sponge("target_position"), Vector3i.class);
/**
* The remaining fuse time in ticks of a {@link FusedExplosive}.
* This value may be set to an arbitrary value
* if the explosive is not primed.
*/
public static final Key<Value<Ticks>> TICKS_REMAINING = Keys.key(ResourceKey.sponge("ticks_remaining"), Ticks.class);
/**
* The {@link ItemTier} of an {@link ItemStack} tool.
* Readonly
*/
public static final Key<Value<ItemTier>> TOOL_TYPE = Keys.key(ResourceKey.sponge("tool_type"), ItemTier.class);
/**
* Whether a {@link CommandBlock} does track its output.
*
* <p>If this is set, the output of the most recent execution can be
* retrieved using {@link #LAST_COMMAND_OUTPUT}.</p>
*/
public static final Key<Value<Boolean>> TRACKS_OUTPUT = Keys.key(ResourceKey.sponge("tracks_output"), Boolean.class);
/**
* The {@link TradeOffer}s offered by a {@link Trader}.
*/
public static final Key<ListValue<TradeOffer>> TRADE_OFFERS = Keys.listKey(ResourceKey.sponge("trade_offers"), TradeOffer.class);
/**
* Whether an {@link Entity} is transient.
* This prevents the entity from being saved to disk.
* The rules for this are as follows...
* If the entity type says that it isn't transient then this key is readonly.
* If the entity type says that it is transient, then this key dictates the current state.
*/
public static final Key<Value<Boolean>> TRANSIENT = Keys.key(ResourceKey.sponge("transient"), Boolean.class);
/**
* A {@link TropicalFish}'s shape.
*/
public static final Key<Value<TropicalFishShape>> TROPICAL_FISH_SHAPE = Keys.key(ResourceKey.sponge("tropical_fish_shape"), TropicalFishShape.class);
/**
* The time a {@link Panda} has been unhappy (in ticks)
*/
public static final Key<Value<Ticks>> UNHAPPY_TIME = Keys.key(ResourceKey.sponge("unhappy_time"), Ticks.class);
/**
* The {@link UUID} of a custom inventory.
*/
public static final Key<Value<UUID>> UNIQUE_ID = Keys.key(ResourceKey.sponge("unique_id"), UUID.class);
/**
* The deceleration a {@link Boat} while it does not have {@link Keys#PASSENGERS}.
*/
public static final Key<Value<Double>> UNOCCUPIED_DECELERATION = Keys.key(ResourceKey.sponge("unoccupied_deceleration"), Double.class);
/**
* Whether a {@link BlockTypes#TNT} {@link BlockState} is unstable.
*/
public static final Key<Value<Boolean>> UNSTABLE = Keys.key(ResourceKey.sponge("unstable"), Boolean.class);
/**
* Whether changes to {@link Keys#SKIN_PROFILE_PROPERTY} should
* be reflected in an entitie's {@link GameProfile}.
*/
public static final Key<Value<Boolean>> UPDATE_GAME_PROFILE = Keys.key(ResourceKey.sponge("update_game_profile"), Boolean.class);
/**
* The {@link VanishState} of an {@link Entity}.
*
* <p>The presence of a vanished entity will not be made known to a client;
* no packets pertaining to this entity are sent. Client-side, this entity
* will cease to exist. Server-side it may still be targeted by hostile
* entities or collide with other entities.</p>
*
* <p>Vanishing an {@link Entity} ridden by other entities (see
* {@link #PASSENGERS} will cause problems.</p>
*/
public static final Key<Value<VanishState>> VANISH_STATE = Keys.key(ResourceKey.sponge("vanish"), VanishState.class);
/**
* Whether an {@link Entity} is vanished.
*
* <p>The presence of a vanished entity will not be made known to a client;
* no packets pertaining to this entity are sent. Client-side, this entity
* will cease to exist. Server-side it may still be targeted by hostile
* entities or collide with other entities.</p>
*
* <p>Vanishing an {@link Entity} ridden by other entities (see
* {@link #PASSENGERS} will cause problems.</p>
* @deprecated use {@link #VANISH_STATE}
*/
@Deprecated
public static final Key<Value<Boolean>> VANISH = Keys.key(ResourceKey.sponge("vanish"), Boolean.class);
/**
* Whether an {@link Entity} ignores collision with other entities.
*
* <p>This state will be ignored if the {@link Entity} is not also
* vanished as per {@link #VANISH}.</p>
* @deprecated use {@link #VANISH_STATE}
*/
@Deprecated
public static final Key<Value<Boolean>> VANISH_IGNORES_COLLISION = Keys.key(ResourceKey.sponge("vanish_ignores_collision"), Boolean.class);
/**
* Whether an {@link Entity} can be targeted for attack by another entity.
* This prevents neither {@link Player}s from attacking the entity nor
* will it be protected from untargeted damage like fire or explosions.
*
* <p>This state will be ignored if the {@link Entity} is not also
* vanished as per {@link #VANISH}.}.</p>
* @deprecated use {@link #VANISH_STATE}
*/
@Deprecated
public static final Key<Value<Boolean>> VANISH_PREVENTS_TARGETING = Keys.key(ResourceKey.sponge("vanish_prevents_targeting"), Boolean.class);
/**
* The vehicle an {@link Entity} is riding.
*
* <p>Vehicles may be nested as a vehicle might itself ride another entity.
* To get the vehicle on bottom, use {@link Keys#BASE_VEHICLE}.</p>
*/
public static final Key<Value<Entity>> VEHICLE = Keys.key(ResourceKey.sponge("vehicle"), Entity.class);
/**
* The velocity of an {@link Entity}.
*/
public static final Key<Value<Vector3d>> VELOCITY = Keys.key(ResourceKey.sponge("velocity"), Vector3d.class);
/**
* The client view distance of a {@link ServerPlayer}. Read-only.
*
* <p>This value represents the radius (around the player) in
* unit chunks.</p>
*/
public static final Key<Value<Integer>> VIEW_DISTANCE = Keys.key(ResourceKey.sponge("view_distance"), Integer.class);
/**
* The type of a {@link Villager} or {@link ZombieVillager}.
*/
public static final Key<Value<VillagerType>> VILLAGER_TYPE = Keys.key(ResourceKey.sponge("villager_type"), VillagerType.class);
/**
* The duration in ticks after which an
* {@link AreaEffectCloud} will begin to apply its effect to entities.
*/
public static final Key<Value<Ticks>> WAIT_TIME = Keys.key(ResourceKey.sponge("wait_time"), Ticks.class);
/**
* The base speed at which a {@link Player} or {@link Living} walks.
*/
public static final Key<Value<Double>> WALKING_SPEED = Keys.key(ResourceKey.sponge("walking_speed"), Double.class);
/**
* Whether a thrown {@link EyeOfEnder} will shatter.
*/
public static final Key<Value<Boolean>> WILL_SHATTER = Keys.key(ResourceKey.sponge("will_shatter"), Boolean.class);
/**
* The {@link WireAttachmentType}s of a {@link BlockTypes#REDSTONE_WIRE} {@link BlockState} for its neighboring blocks.
*/
public static final Key<MapValue<Direction, WireAttachmentType>> WIRE_ATTACHMENTS = Keys.mapKey(ResourceKey.sponge("wire_attachments"), Direction.class, WireAttachmentType.class);
/**
* The {@link WireAttachmentType} of a {@link BlockTypes#REDSTONE_WIRE} {@link BlockState}
* for its neighboring block to the {@link Direction#EAST}.
*/
public static final Key<Value<WireAttachmentType>> WIRE_ATTACHMENT_EAST = Keys.key(ResourceKey.sponge("wire_attachment_east"), WireAttachmentType.class);
/**
* The {@link WireAttachmentType} of a {@link BlockTypes#REDSTONE_WIRE} {@link BlockState}
* for its neighboring block to the {@link Direction#NORTH}.
*/
public static final Key<Value<WireAttachmentType>> WIRE_ATTACHMENT_NORTH = Keys.key(ResourceKey.sponge("wire_attachment_north"), WireAttachmentType.class);
/**
* The {@link WireAttachmentType} of a {@link BlockTypes#REDSTONE_WIRE} {@link BlockState}
* for its neighboring block to the {@link Direction#SOUTH}.
*/
public static final Key<Value<WireAttachmentType>> WIRE_ATTACHMENT_SOUTH = Keys.key(ResourceKey.sponge("wire_attachment_south"), WireAttachmentType.class);
/**
* The {@link WireAttachmentType} of a {@link BlockTypes#REDSTONE_WIRE} {@link BlockState}
* for its neighboring block to the {@link Direction#WEST}.
*/
public static final Key<Value<WireAttachmentType>> WIRE_ATTACHMENT_WEST = Keys.key(ResourceKey.sponge("wire_attachment_west"), WireAttachmentType.class);
/**
* The entities targeted by the three {@link Wither} heads. In vanilla the wither only targets {@link Living}. {@code null} for no target entity.
*/
public static final Key<ListValue<Entity>> WITHER_TARGETS = Keys.listKey(ResourceKey.sponge("wither_targets"), Entity.class);
/**
* The {@link Sheep} who is being targeted by the {@link SpellTypes#WOLOLO}
* spell being casted by an {@link Evoker}
*/
public static final Key<Value<Sheep>> WOLOLO_TARGET = Keys.key(ResourceKey.sponge("wololo_target"), Sheep.class);
// SORTFIELDS:OFF
// @formatter:on
private static <T> Key<Value<T>> key(final ResourceKey resourceKey, final TypeToken<T> token) {
return Key.builder().key(resourceKey).elementType(token).build();
}
private static <T> Key<Value<T>> key(final ResourceKey resourceKey, final Class<T> type) {
return Key.builder().key(resourceKey).elementType(type).build();
}
private static <T> Key<ListValue<T>> listKey(final ResourceKey resourceKey, final Class<T> elementType) {
return Key.builder().key(resourceKey).listElementType(elementType).build();
}
private static <T> Key<ListValue<T>> listKey(final ResourceKey resourceKey, final TypeToken<T> elementType) {
return Key.builder().key(resourceKey).listElementType(elementType).build();
}
private static <T> Key<SetValue<T>> setKey(final ResourceKey resourceKey, final Class<T> elementType) {
return Key.builder().key(resourceKey).setElementType(elementType).build();
}
private static <T> Key<SetValue<T>> setKey(final ResourceKey resourceKey, final TypeToken<T> elementType) {
return Key.builder().key(resourceKey).setElementType(elementType).build();
}
private static <K, V> Key<MapValue<K, V>> mapKey(final ResourceKey resourceKey, final Class<K> keyType, final Class<V> valueType) {
return Key.builder().key(resourceKey).mapElementType(keyType, valueType).build();
}
private static <K, V> Key<MapValue<K, V>> mapKey(final ResourceKey resourceKey, final TypeToken<K> keyType, final TypeToken<V> valueType) {
return Key.builder().key(resourceKey).mapElementType(keyType, valueType).build();
}
private static <T> Key<WeightedCollectionValue<T>> weightedKey(final ResourceKey resourceKey, final Class<T> elementType) {
return Key.builder().key(resourceKey).weightedCollectionElementType(elementType).build();
}
private static <T> Key<WeightedCollectionValue<T>> weightedKey(final ResourceKey resourceKey, final TypeToken<T> elementType) {
return Key.builder().key(resourceKey).weightedCollectionElementType(elementType).build();
}
private Keys() {
}
}
|
package org.wahlzeit.model;
import com.google.appengine.api.images.Image;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Work;
import org.wahlzeit.model.persistance.ImageStorage;
import org.wahlzeit.services.LogBuilder;
import org.wahlzeit.services.ObjectManager;
import org.wahlzeit.services.Persistent;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
/**
* A photo manager provides access to and manages photos.
*
* @author dirkriehle
*/
public class PhotoManager extends ObjectManager {
protected static final PhotoManager instance = new PhotoManager();
private static final Logger log = Logger.getLogger(PhotoManager.class.getName());
/**
* In-memory cache for photos
*/
protected Map<PhotoId, Photo> photoCache = new HashMap<PhotoId, Photo>();
protected PhotoTagCollector photoTagCollector = null;
public PhotoManager() {
photoTagCollector = PhotoFactory.getInstance().createPhotoTagCollector();
}
public static final PhotoManager getInstance() {
return instance;
}
public final boolean hasPhoto(String id) {
return hasPhoto(PhotoId.getIdFromString(id));
}
public final boolean hasPhoto(PhotoId id) {
return getPhoto(id) != null;
}
public final Photo getPhoto(PhotoId id) {
return instance.getPhotoFromId(id);
}
public Photo getPhotoFromId(PhotoId id) {
if (id == null) {
return null;
}
Photo result = doGetPhotoFromId(id);
if (result == null) {
result = PhotoFactory.getInstance().loadPhoto(id);
if (result != null) {
doAddPhoto(result);
}
}
return result;
}
/**
* @methodtype get
* @methodproperties primitive
*/
protected Photo doGetPhotoFromId(PhotoId id) {
return photoCache.get(id);
}
/**
* @methodtype command
* @methodproperties primitive
*/
protected void doAddPhoto(Photo myPhoto) {
photoCache.put(myPhoto.getId(), myPhoto);
}
/**
* @methodtype get
*/
public final Photo getPhoto(String id) {
return getPhoto(PhotoId.getIdFromString(id));
}
/**
* @methodtype init Loads all Photos from the Datastore and holds them in the cache
*/
public void init() {
loadPhotos();
}
/**
* @methodtype command
*
* Load all persisted photos. Executed when Wahlzeit is restarted.
*/
public void loadPhotos() {
Collection<Photo> existingPhotos = ObjectifyService.run(new Work<Collection<Photo>>() {
@Override
public Collection<Photo> run() {
Collection<Photo> existingPhotos = new ArrayList<Photo>();
readObjects(existingPhotos, Photo.class);
return existingPhotos;
}
});
for (Photo photo : existingPhotos) {
if (!doHasPhoto(photo.getId())) {
log.config(LogBuilder.createSystemMessage().
addParameter("Load Photo with ID", photo.getIdAsString()).toString());
loadScaledImages(photo);
doAddPhoto(photo);
} else {
log.config(LogBuilder.createSystemMessage().
addParameter("Already loaded Photo", photo.getIdAsString()).toString());
}
}
log.info(LogBuilder.createSystemMessage().addMessage("All photos loaded.").toString());
}
/**
* @methodtype boolean-query
* @methodproperty primitive
*/
protected boolean doHasPhoto(PhotoId id) {
return photoCache.containsKey(id);
}
/**
* @methodtype command
* <p/>
* Loads all scaled Images of this Photo from Google Cloud Storage
*/
protected void loadScaledImages(Photo photo) {
String photoIdAsString = photo.getId().asString();
ImageStorage imageStorage = ImageStorage.getInstance();
for (PhotoSize photoSize : PhotoSize.values()) {
log.config(LogBuilder.createSystemMessage().
addAction("loading image").
addParameter("image size", photoSize.asString()).
addParameter("photo ID", photoIdAsString).toString());
if (imageStorage.doesImageExist(photoIdAsString, photoSize.asInt())) {
try {
Serializable rawImage = imageStorage.readImage(photoIdAsString, photoSize.asInt());
if (rawImage != null && rawImage instanceof Image) {
photo.setImage(photoSize, (Image) rawImage);
}
} catch (IOException e) {
log.warning(LogBuilder.createSystemMessage().
addParameter("size", photoSize.asString()).
addParameter("photo ID", photoIdAsString).
addException("Could not load image although it exists", e).toString());
}
} else {
log.config(LogBuilder.createSystemMessage().
addParameter("Size does not exist", photoSize.asString()).toString());
}
}
}
public void savePhoto(Photo photo) {
updateObject(photo);
}
@Override
protected void updateDependents(Persistent obj) {
if (obj instanceof Photo) {
Photo photo = (Photo) obj;
saveScaledImages(photo);
updateTags(photo);
UserManager userManager = UserManager.getInstance();
Client owner = userManager.getClientById(photo.getOwnerId());
userManager.saveClient(owner);
}
}
/**
* @methodtype helper
*/
public List<Tag> addTagsThatMatchCondition(List<Tag> tags, String condition) {
readObjects(tags, Tag.class, Tag.TEXT, condition);
return tags;
}
/**
* @methodtype command
* <p/>
* Writes all Images of the different sizes to Google Cloud Storage.
*/
protected void saveScaledImages(Photo photo) {
String photoIdAsString = photo.getId().asString();
ImageStorage imageStorage = ImageStorage.getInstance();
for (PhotoSize photoSize : PhotoSize.values()) {
Image image = photo.getImage(photoSize);
if (image != null) {
try {
if (!imageStorage.doesImageExist(photoIdAsString, photoSize.asInt())) {
imageStorage.writeImage(image, photoIdAsString, photoSize.asInt());
}
} catch (IllegalArgumentException e) {
log.warning(LogBuilder.createSystemMessage().
addException("Invalid parameter to store Image", e).toString());
} catch (IOException e) {
log.warning(LogBuilder.createSystemMessage().
addException("Problem storing image", e).toString());
}
} else {
log.config(LogBuilder.createSystemMessage().
addParameter("No image for size", photoSize.asString()).toString());
}
}
}
/**
* Removes all tags of the Photo (obj) in the datastore that have been removed by the user and adds all new tags of
* the photo to the datastore.
*/
protected void updateTags(Photo photo) {
// delete all existing tags, for the case that some have been removed
deleteObjects(Tag.class, Tag.PHOTO_ID, photo.getId().asString());
// add all current tags to the datastore
Set<String> tags = new HashSet<String>();
photoTagCollector.collect(tags, photo);
for (Iterator<String> i = tags.iterator(); i.hasNext(); ) {
Tag tag = new Tag(i.next(), photo.getId().asString());
log.config(LogBuilder.createSystemMessage().addParameter("Writing Tag", tag.asString()).toString());
writeObject(tag);
}
}
public void savePhotos() {
updateObjects(photoCache.values());
}
/**
* @methodtype get
*/
public Map<PhotoId, Photo> getPhotoCache() {
return photoCache;
}
public Set<Photo> findPhotosByOwner(String ownerName) {
Set<Photo> result = new HashSet<Photo>();
readObjects(result, Photo.class, Photo.OWNER_ID, ownerName);
for (Iterator<Photo> i = result.iterator(); i.hasNext(); ) {
doAddPhoto(i.next());
}
return result;
}
public Photo getVisiblePhoto(PhotoFilter filter) {
filter.generateDisplayablePhotoIds();
return getPhotoFromId(filter.getRandomDisplayablePhotoId());
}
public Photo createPhoto(String filename, Image uploadedImage) throws Exception {
PhotoId id = PhotoId.getNextId();
Photo result = PhotoUtil.createPhoto(filename, id, uploadedImage);
addPhoto(result);
return result;
}
/**
* @methodtype command
*/
public void addPhoto(Photo photo) {
PhotoId id = photo.getId();
assertIsNewPhoto(id);
doAddPhoto(photo);
GlobalsManager.getInstance().saveGlobals();
}
/**
* @methodtype assertion
*/
protected void assertIsNewPhoto(PhotoId id) {
if (hasPhoto(id)) {
throw new IllegalStateException("Photo already exists!");
}
}
}
|
package permafrost.tundra.data;
import com.wm.data.*;
import com.wm.util.coder.IDataCodable;
import com.wm.util.coder.ValuesCodable;
import permafrost.tundra.lang.ObjectHelper;
import java.util.*;
/**
* Wraps an IData document in an implementation of the Iterable, Comparable,
* and Map interfaces.
*/
public class IDataMap extends WrappedIData implements Iterable<Map.Entry<String, Object>>, Comparable<IData>, Map<String, Object> {
/**
* The default comparator used when no other comparator or comparison criteria is specified.
*/
public static final IDataComparator DEFAULT_COMPARATOR = BasicIDataComparator.getInstance();
protected IDataComparator comparator = DEFAULT_COMPARATOR;
/**
* Construct a new IDataMap object.
*/
public IDataMap() {
super();
}
/**
* Construct a new IDataMap object.
* @param document The IData document to be wrapped.
*/
public IDataMap(IData document) {
super(document);
}
/**
* Construct a new IDataMap object.
* @param document The IData document to be wrapped.
* @param comparator The IDataComparator to be used to compare IData objects.
*
*/
public IDataMap(IData document, IDataComparator comparator) {
this(document);
setComparator(comparator);
}
/**
* Constructs a new IDataMap wrapping the given IDataCodable object.
* @param codable The IDataCodable object to be wrapped.
*/
public IDataMap(IDataCodable codable) {
super(codable);
}
/**
* Constructs a new IDataMap wrapping the given IDataCodable object.
* @param codable The IDataCodable object to be wrapped.
* @param comparator The IDataComparator to be used to compare IData objects.
*
*/
public IDataMap(IDataCodable codable, IDataComparator comparator) {
this(codable);
setComparator(comparator);
}
/**
* Constructs a new IDataMap wrapping the given IDataPortable object.
* @param portable The IDataPortable object to be wrapped.
*/
public IDataMap(IDataPortable portable) {
super(portable);
}
/**
* Constructs a new IDataMap wrapping the given IDataPortable object.
* @param portable The IDataPortable object to be wrapped.
* @param comparator The IDataComparator to be used to compare IData objects.
*/
public IDataMap(IDataPortable portable, IDataComparator comparator) {
this(portable);
setComparator(comparator);
}
/**
* Constructs a new IDataMap wrapping the given ValuesCodable object.
* @param codable The ValuesCodable object to be wrapped.
*/
public IDataMap(ValuesCodable codable) {
super(codable);
}
/**
* Constructs a new IDataMap wrapping the given ValuesCodable object.
* @param codable The ValuesCodable object to be wrapped.
* @param comparator The IDataComparator to be used to compare IData objects.
*/
public IDataMap(ValuesCodable codable, IDataComparator comparator) {
this(codable);
setComparator(comparator);
}
/**
* Constructs a new IDataMap seeded with the given Map of key value entries.
* @param map The map to see this new object with.
*/
public IDataMap(Map<? extends Object, ? extends Object> map) {
super();
if (map != null) {
for (Map.Entry<? extends Object, ? extends Object> entry : map.entrySet()) {
this.put(ObjectHelper.stringify(entry.getKey()), entry.getValue());
}
}
}
/**
* Constructs a new IDataMap seeded with the given Map of key value entries.
* @param map The map to see this new object with.
* @param comparator The IDataComparator to be used to compare IData objects.
*/
public IDataMap(Map<? extends Object, ? extends Object> map, IDataComparator comparator) {
this(map);
setComparator(comparator);
}
/**
* Returns a Collection view of the values contained in this map.
* @return A collection view of the values contained in this map.
*/
@Override
public Collection<Object> values() {
return Arrays.asList(IDataHelper.getValues(this));
}
/**
* Returns a Set view of the keys contained in this map.
* @return A set view of the keys contained in this map.
*/
@Override
public Set<String> keySet() {
String[] keys = IDataHelper.getKeys(this);
Set<String> keySet = new LinkedHashSet<String>(keys.length);
keySet.addAll(Arrays.asList(keys));
return keySet;
}
/**
* Returns true if this map contains a mapping for the specified key.
* @param key A key whose presence in this map is to be tested.
* @return True if this map contains a mapping for the specified key.
*/
@Override
public boolean containsKey(Object key) {
IDataCursor cursor = this.getCursor();
boolean contains = cursor.next((String)key);
cursor.destroy();
return contains;
}
/**
* Returns true if this map maps one or more keys to the specified value.
* @param value The value whose presence in this map is to be tested.
* @return True if this map maps one or more keys to the specified value.
*/
@Override
public boolean containsValue(Object value) {
return Arrays.binarySearch(IDataHelper.getValues(this), value) >= 0;
}
/**
* Removes the mapping for a key from this map if it is present (optional operation).
* @param key A key whose mapping is to be removed from the map.
* @return The previous value associated with key, or null if there was no mapping for key.
*/
@Override
public Object remove(Object key) {
IDataCursor cursor = this.getCursor();
Object value = get(key);
IDataUtil.remove(cursor, (String) key);
return value;
}
/**
* Returns true if this map contains no key-value mappings.
* @return True if this map contains no key-value mappings.
*/
@Override
public boolean isEmpty() {
return size() == 0;
}
/**
* Returns the number of key-value mappings in this map.
* @return The number of key-value mappings in this map.
*/
@Override
public int size() {
return IDataHelper.size(this);
}
/**
* Returns a Set view of the mappings contained in this map.
* @return A set view of the mappings contained in this map.
*/
@Override
public Set<Map.Entry<String, Object>> entrySet() {
Set<Map.Entry<String, Object>> set = new LinkedHashSet<Map.Entry<String, Object>>(size());
for (Map.Entry<String, Object> entry : this) {
set.add(entry);
}
return set;
}
/**
* Associates the specified value with the specified key in this map.
* @param key Key with which the specified value is to be associated.
* @param value Value to be associated with the specified key.
* @return The previous value associated with key, or null if there was no mapping for key.
*/
@Override
public Object put(String key, Object value) {
Object previousValue = get(key);
IDataCursor cursor = this.getCursor();
IDataUtil.put(cursor, key, value);
cursor.destroy();
return previousValue;
}
/**
* Copies all of the mappings from the specified map to this map.
* @param map Mappings to be stored in this map.
*/
@Override
public void putAll(Map<? extends String,? extends Object> map) {
for (Map.Entry<? extends String, ? extends Object> entry : map.entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
/**
* Copies all of the mappings from the specified document to this map.
* @param document Mappings to be stored in this map.
*/
public void putAll(IData document) {
putAll((Map)new IDataMap(document));
}
/**
* Copies all of the mappings from the specified document to this map.
* @param document Mappings to be stored in this map.
*/
public void merge(IData document) {
putAll(document);
}
/**
* Returns the value to which the specified key is mapped, or null if this
* map contains no mapping for the key.
* @param key The key whose associated value is to be returned.
* @return The value to which the specified key is mapped, or null if
* this map contains no mapping for the key
*/
@Override
public Object get(Object key) {
IDataCursor cursor = this.getCursor();
Object value = IDataUtil.get(cursor, (String) key);
cursor.destroy();
return value;
}
/**
* Removes all of the mappings from this map. The map will be empty after
* this call returns.
*/
@Override
public void clear() {
IDataHelper.clear(this);
}
/**
* Returns an iterator over a set of elements of type Map.Entry.
* @return An iterator.
*/
@Override
public IDataIterator iterator() {
return new IDataIteratorImplementation(getIData());
}
/**
* Compares this object with the specified object for order.
* @param other The object to be compared with this object.
* @return A negative integer, zero, or a positive integer as this object is
* less than, equal to, or greater than the specified object.
*/
@Override
public int compareTo(IData other) {
return comparator.compare(document, other);
}
/**
* Returns true if this object is equal to the given object.
* @param other The object to compare to.
* @return True if this object is equal to the given object.
*/
@Override
public boolean equals(Object other) {
if (!(other instanceof IData)) return false;
return this == other || DEFAULT_COMPARATOR.compare(document, (IData)other) == 0;
}
/**
* Returns the IDataComparator used to compare IData objects.
* @return The IDataComparator used to compare IData objects.
*/
public IDataComparator getComparator() {
return comparator;
}
/**
* Sets the IDataComparator to be used when comparing IData objects.
* @param comparator The IDataComparator to be used when comparing IData objects.
*/
public void setComparator(IDataComparator comparator) {
if (comparator == null) throw new IllegalArgumentException("comparator must not be null");
this.comparator = comparator;
}
/**
* Implementation class for an IDataIterator.
*/
private static class IDataIteratorImplementation implements IDataIterator {
protected IDataCursor cursor;
/**
* Constructs a new IDataIterator object for iterating over the given IData document.
* @param document The document to be iterated over.
*/
public IDataIteratorImplementation(IData document) {
if (document != null) this.cursor = document.getCursor();
}
/**
* Returns true if the iteration has more elements. (In other words, returns true if next()
* would return an element rather than throwing an exception.)
* @return True if the iteration has more elements.
*/
@Override
public boolean hasNext() {
return cursor != null && cursor.hasMoreData();
}
/**
* Returns the next element in the iteration.
* @return The next element in the iteration.
* @throws NoSuchElementException If the iteration has no more elements.
*/
@Override
public Map.Entry<String, Object> next() throws NoSuchElementException {
if (cursor != null && cursor.next()) {
return new AbstractMap.SimpleImmutableEntry<String, Object>(cursor.getKey(), cursor.getValue());
} else {
throw new NoSuchElementException("No more elements were available for iteration in IData document");
}
}
/**
* Throws an UnsupportedOperationException because the remove operation is not supported by this
* iterator.
* @throws UnsupportedOperationException The remove operation is not supported by this iterator.
*/
@Override
public void remove() {
throw new UnsupportedOperationException("remove method is not implemented by this iterator class");
}
}
}
|
package seedu.jobs.commons.util;
import java.io.File;
import java.io.FileNotFoundException;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
/**
* Helps with reading from and writing to XML files.
*/
public class XmlUtil {
/**
* Returns the xml data in the file as an object of the specified type.
*
* @param file Points to a valid xml file containing data that match the {@code classToConvert}.
* Cannot be null.
* @param classToConvert The class corresponding to the xml data.
* Cannot be null.
* @throws FileNotFoundException Thrown if the file is missing.
* @throws JAXBException Thrown if the file is empty or does not have the correct format.
*/
@SuppressWarnings("unchecked")
public static <T> T getDataFromFile(File file, Class<T> classToConvert)
throws FileNotFoundException, JAXBException {
assert file != null;
assert classToConvert != null;
if (!FileUtil.isFileExists(file)) {
throw new FileNotFoundException("File not found : " + file.getAbsolutePath());
}
JAXBContext context = JAXBContext.newInstance(classToConvert);
Unmarshaller um = context.createUnmarshaller();
return ((T) um.unmarshal(file));
}
/**
* Saves the data in the file in xml format.
*
* @param file Points to a valid xml file containing data that match the {@code classToConvert}.
* Cannot be null.
* @throws FileNotFoundException Thrown if the file is missing.
* @throws JAXBException Thrown if there is an error during converting the data
* into xml and writing to the file.
*/
public static <T> void saveDataToFile(File file, T data) throws FileNotFoundException, JAXBException {
assert file != null;
assert data != null;
if (!file.exists()) {
throw new FileNotFoundException("File not found : " + file.getAbsolutePath());
}
JAXBContext context = JAXBContext.newInstance(data.getClass());
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
m.marshal(data, file);
}
}
|
package sunlib.turtle.api;
import fi.iki.elonen.NanoHTTPD;
import static sunlib.turtle.models.ApiRequest.Type.*;
public class SunApiMatcher extends ApiRequestTypeMatcher {
static SunApiMatcher matcher = new SunApiMatcher();
private SunApiMatcher() {
add(GET, NanoHTTPD.Method.GET, "/exercise/v1/root\\?(?=(.*&)?callback=[^&]+).*");
add(GET, NanoHTTPD.Method.GET, "/pack/v1");
/* Use cached content when available. Fetch update and cache on cache miss. Can block. */
add(GET_CACHE, NanoHTTPD.Method.GET, "/exercise/v1/(subjects|chapters|lessons)/[a-z0-9]+\\?(?=(.*&)?callback=[^&]+)(?=(.*&)?ts=[0-9]+).*");
add(GET_CACHE, NanoHTTPD.Method.GET, "/exercise/v1/lessons/[a-z0-9]+/.+\\.(png|jpg|jpeg|mp4|mp3)\\?(?=(.*&)?ts=[0-9]+).*");
add(GET_CACHE, NanoHTTPD.Method.GET, "/pack/v1/(subjects|folders|pieces)/[a-z0-9]+\\?ts=[0-9]+");
add(GET_CACHE, NanoHTTPD.Method.GET, "/pack/v1/pieces/[a-z0-9]+/[a-z0-9]+\\.(png|jpg|jpeg|mp4|mp3)\\?(?=(.*&)?ts=[0-9]+).*");
add(GET_CACHE, NanoHTTPD.Method.GET, "/exercise/v1/user_data/(subjects|chapters|lesson|achievements)/[a-z0-9]+");
add(GET_CACHE, NanoHTTPD.Method.GET, "/pack/v1/user_data/(subjects|folders|pieces|achievements)/[a-z0-9]+");
/* Update cached content and push update to server. Cannot block; queue up post requests. */
add(POST_CACHE, NanoHTTPD.Method.POST, "/exercise/v1/user_data/(subjects|chapters|lesson|achievements)/[a-z0-9]+");
add(POST_CACHE, NanoHTTPD.Method.POST, "/pack/v1/user_data/(subjects|folders|pieces|achievements)/[a-z0-9]+");
/* Prefetch all required resources base on the manifest. Cannot block; returns cache status. */
add(BATCH_CACHE, NanoHTTPD.Method.GET, "/exercise/v1/(chapters|achievements)/[a-z0-9]+\\?(?=(.*&)?callback=[^&]+)(?=(.*&)?act=(cache|status))(?=(.*&)?ts=[0-9]+).*");
// for one query string KEY=VALUE
// "URL\\?(?=(.*&)?KEY=VALUE).*"
// for two query string KEYA && KEYB
// "URL\\?(?=(.*&)?KEYA=VALUEA)(?=(.*&)?KEYB=VALUEB).*"
// for two query string KEYA || KEYB
// "URL\\?(?=((.*&)?KEYA=VALUEA)|((.*&)?KEYB=VALUEB)).*"
// for four query strings A&&B || C&&D
// "URL\\?(?=(?=(.*&)?A=[^&]*)(?=(.*&)?B=[^&]*)|(?=(.*&)?C=[^&]*)(?=(.*&)?D=[^&]*)).*"
// for four query strings (A|B) && (C|D)
// "URL\\?(?=((?=(.*&)?A=[^&]*)|(?=(.*&)?B=[^&]*)))(?=((?=(.*&)?C=[^&]*)|(?=(.*&)?D=[^&]*))).*"
}
public static SunApiMatcher getMatcher() {
return matcher;
}
}
|
package tigase.server;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SocketChannel;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.script.Bindings;
import tigase.annotations.TODO;
import tigase.conf.ConfigurationException;
import tigase.net.*;
import tigase.server.script.CommandIfc;
import tigase.stats.StatisticsList;
import tigase.util.DataTypes;
import tigase.xml.Element;
import tigase.xmpp.JID;
import tigase.xmpp.XMPPDomBuilderHandler;
import tigase.xmpp.XMPPIOService;
import static tigase.xmpp.XMPPIOService.DOM_HANDLER;
import tigase.xmpp.XMPPIOServiceListener;
/**
* Describe class ConnectionManager here.
*
*
* Created: Sun Jan 22 22:52:58 2006
*
* @param <IO>
* @author <a href="mailto:artur.hefczyc@tigase.org">Artur Hefczyc</a>
* @version $Rev$
*/
public abstract class ConnectionManager<IO extends XMPPIOService<?>>
extends AbstractMessageReceiver
implements XMPPIOServiceListener<IO> {
/** Field description */
public static final String HT_TRAFFIC_THROTTLING_PROP_KEY =
"--cm-ht-traffic-throttling";
/** Field description */
public static final String HT_TRAFFIC_THROTTLING_PROP_VAL =
"xmpp:25k:0:disc,bin:200m:0:disc";
/** Field description. */
public static final String NET_BUFFER_HT_PROP_KEY = "--net-buff-high-throughput";
/** Field description. */
public static final String NET_BUFFER_ST_PROP_KEY = "--net-buff-standard";
/** Field description. */
public static final String PORT_LOCAL_HOST_PROP_KEY = "local-host";
/** Field description */
public static final String ST_TRAFFIC_THROTTLING_PROP_KEY = "--cm-traffic-throttling";
/** Field description */
public static final String ST_TRAFFIC_THROTTLING_PROP_VAL =
"xmpp:2500:0:disc,bin:20m:0:disc";
/** Field description */
public static final String TRAFFIC_THROTTLING_PROP_KEY = "traffic-throttling";
/** Field description */
protected static final long LAST_MINUTE_BIN_LIMIT_PROP_VAL = 20000000L;
/** Field description */
protected static final long LAST_MINUTE_PACKETS_LIMIT_PROP_VAL = 2500L;
/** Field description */
protected static final String MAX_INACTIVITY_TIME = "max-inactivity-time";
/** Field description */
protected static final String MAX_RECONNECTS_PROP_KEY = "max-reconnects";
/** Field description */
protected static final int NET_BUFFER_HT_PROP_VAL = 64 * 1024;
/** Field description */
protected static final String NET_BUFFER_PROP_KEY = "net-buffer";
/** Field description */
protected static final int NET_BUFFER_ST_PROP_VAL = 2 * 1024;
/** Field description */
protected static final int NET_BUFFER_LIMIT_HT_PROP_VAL = 20*1024*1024;
/** Field description */
protected static final String NET_BUFFER_LIMIT_PROP_KEY= "net-buffer-limit";
/** Field description */
protected static final int NET_BUFFER_LIMIT_ST_PROP_VAL = 2*1024*1024;
/**
* Key name of the system property for configuration protection
* from system overload and DOS attack.
*/
public static final String ELEMENTS_NUMBER_LIMIT_PROP_KEY = "elements-number-limit";
/**
* Default value for the system property for configuration protection
* from system overload and DOS attack.
*/
public static int ELEMENTS_NUMBER_LIMIT_PROP_VAL = 1000;
/** Field description */
protected static final String PORT_CLASS_PROP_KEY = "class";
/** Field description */
protected static final String PORT_IFC_PROP_KEY = "ifc";
/** Field description */
protected static final String PORT_KEY = "port-no";
/** Field description */
protected static final String PORT_REMOTE_HOST_PROP_KEY = "remote-host";
/** Field description */
protected static final String PORT_REMOTE_HOST_PROP_VAL = "localhost";
/** Field description */
protected static final String PORT_SOCKET_PROP_KEY = "socket";
/** Field description */
protected static final String PORT_TYPE_PROP_KEY = "type";
/** Field description */
protected static final String PROP_KEY = "connections/";
/** Field description */
protected static final long TOTAL_BIN_LIMIT_PROP_VAL = 0L;
/** Field description */
protected static final long TOTAL_PACKETS_LIMIT_PROP_VAL = 0L;
/** Field description */
protected static final String WHITE_CHAR_ACK_PROP_KEY = "white-char-ack";
/** Field description */
protected static final String XMPP_ACK_PROP_KEY = "xmpp-ack";
private static final Logger log = Logger.getLogger(ConnectionManager.class
.getName());
private static ConnectionOpenThread connectThread = ConnectionOpenThread.getInstance();
/** Field description */
protected static final boolean XMPP_ACK_PROP_VAL = false;
/** Field description */
protected static final boolean WHITE_CHAR_ACK_PROP_VAL = false;
/** Field description */
protected static final String PORTS_PROP_KEY = PROP_KEY + "ports";
/** Field description */
protected static final boolean TLS_USE_PROP_VAL = true;
/** Field description */
protected static final String TLS_PROP_KEY = PROP_KEY + "tls/";
/** Field description */
protected static final String TLS_USE_PROP_KEY = TLS_PROP_KEY + "use";
/** Field description */
protected static final boolean TLS_REQUIRED_PROP_VAL = false;
/** Field description */
protected static final String TLS_REQUIRED_PROP_KEY = TLS_PROP_KEY + "required";
protected static final String WATCHDOG_DELAY = "watchdog_delay";
protected static final String WATCHDOG_TIMEOUT = "watchdog_timeout";
protected static final String WATCHDOG_PING_TYPE_KEY = "watchdog_ping_type";
protected static final Element pingElement = new Element( "iq",
new Element[] { new Element( "ping", new String[] { "xmlns" }, new String[] { "urn:xmpp:ping" } ) },
new String[] { "type", "id" },
new String[] { "get", "tigase-ping" } );
/** Field description. */
public String[] PORT_IFC_PROP_VAL = { "*" };
private long bytesReceived = 0;
private long bytesSent = 0;
private int services_size = 0;
private long socketOverflow = 0;
private Thread watchdog = null;
private long watchdogRuns = 0;
private long watchdogStopped = 0;
private long watchdogTests = 0;
protected long watchdogDelay = 10 * MINUTE; // 600 000
protected long watchdogTimeout = 29 * MINUTE; // 1 740 000
private boolean white_char_ack = WHITE_CHAR_ACK_PROP_VAL;
private boolean xmpp_ack = XMPP_ACK_PROP_VAL;
private LinkedList<Map<String, Object>> waitingTasks = new LinkedList<Map<String,
Object>>();
private long total_packets_limit =
TOTAL_PACKETS_LIMIT_PROP_VAL;
private long total_bin_limit = TOTAL_BIN_LIMIT_PROP_VAL;
/**
* Protection from the system overload and DOS attack. We want to limit number
* of elements created within a single XMPP stanza.
*
*/
protected int elements_number_limit = 0;
private ConcurrentHashMap<String, IO> services = new ConcurrentHashMap<String, IO>();
private Set<ConnectionListenerImpl> pending_open = Collections.synchronizedSet(
new HashSet<ConnectionListenerImpl>());;
private long maxInactivityTime = getMaxInactiveTime();
private long last_minute_packets_limit =
LAST_MINUTE_PACKETS_LIMIT_PROP_VAL;
private long last_minute_bin_limit =
LAST_MINUTE_BIN_LIMIT_PROP_VAL;
private int net_buffer_limit = 0;
private IOServiceStatisticsGetter ioStatsGetter = new IOServiceStatisticsGetter();
private boolean initializationCompleted = false;
/** Field description */
protected int net_buffer = NET_BUFFER_ST_PROP_VAL;
/** Field description */
protected long connectionDelay = 2 * SECOND;
private LIMIT_ACTION xmppLimitAction = LIMIT_ACTION.DISCONNECT;
protected WATCHDOG_PING_TYPE watchdogPingType = WATCHDOG_PING_TYPE.WHITESPACE;
/**
* Describe class <code>LIMIT_ACTION</code> here.
*
*/
public static enum LIMIT_ACTION { DISCONNECT, DROP_PACKETS; }
/** Holds possible types of ping to be used in watchdog service for detection
* of broken connections */
public static enum WATCHDOG_PING_TYPE { WHITESPACE, XMPP; }
/**
* Method description
*
*
* @param serv
*
*
*
* @return a value of <code>boolean</code>
*/
public boolean checkTrafficLimits(IO serv) {
boolean xmppLimitHit = false;
if (last_minute_packets_limit > 0) {
xmppLimitHit = (serv.getPacketsReceived(false) >= last_minute_packets_limit)
// || (serv.getPacketsSent(false) >= last_minute_packets_limit)
;
}
if (!xmppLimitHit && (total_packets_limit > 0)) {
xmppLimitHit = (serv.getTotalPacketsReceived() >= total_packets_limit)
// || (serv.getTotalPacketsSent() >= total_packets_limit)
;
}
if (xmppLimitHit) {
Level level = Level.FINER;
if (isHighThroughput()) {
level = Level.WARNING;
}
switch (xmppLimitAction) {
case DROP_PACKETS :
if (log.isLoggable(level)) {
log.log(level, "[[{0}]] XMPP Limits exceeded on connection {1}" +
" dropping pakcets: {2}", new Object[] { getName(),
serv, serv.getReceivedPackets() });
}
while (serv.getReceivedPackets().poll() != null);
break;
default :
if (log.isLoggable(level)) {
log.log(level, "[[{0}]] XMPP Limits exceeded on connection {1}" +
" stopping, packets dropped: {2}", new Object[] { getName(),
serv, serv.getReceivedPackets() });
}
serv.forceStop();
break;
}
return false;
}
boolean binLimitHit = false;
long bytesSent = serv.getBytesSent(false);
long bytesReceived = serv.getBytesReceived(false);
if (last_minute_bin_limit > 0) {
binLimitHit = (bytesSent >= last_minute_bin_limit) || (bytesReceived >=
last_minute_bin_limit);
}
long totalSent = serv.getTotalBytesSent();
long totalReceived = serv.getTotalBytesReceived();
if (!binLimitHit && (total_bin_limit > 0)) {
binLimitHit = (totalReceived >= total_bin_limit) || (totalSent >= total_bin_limit);
}
if (binLimitHit) {
if (log.isLoggable(Level.FINE)) {
log.log(Level.FINE, "[[{0}]] Binary Limits exceeded ({1}:{2}:{3}:{4}) on" +
" connection {5} stopping, packets dropped: {6}", new Object[] {
getName(), bytesSent, bytesReceived, totalSent, totalReceived, serv,
serv.getReceivedPackets()
});
}
serv.forceStop();
return false;
}
return true;
}
@Override
public synchronized void everyMinute() {
super.everyMinute();
// This variable used to provide statistics gets off on a busy
// services as it is handled in methods called concurrently by
// many threads. While accuracy of this variable is not critical
// for the server functions, statistics should be as accurate as
// possible to provide valuable metrics data.
// So in the watchdog thread we re-synchronize this number
int tmp = services.size();
services_size = tmp;
doForAllServices(ioStatsGetter);
}
@Override
public int hashCodeForPacket(Packet packet) {
if (packet.getStanzaTo() != null) {
return packet.getStanzaTo().hashCode();
}
if (packet.getTo() != null) {
return packet.getTo().hashCode();
}
return super.hashCodeForPacket(packet);
}
@Override
public void initBindings(Bindings binds) {
super.initBindings(binds);
binds.put(CommandIfc.SERVICES_MAP, services);
}
@Override
public void initializationCompleted() {
if (isInitializationComplete()) {
// Do we really need to do this again?
return;
}
super.initializationCompleted();
initializationCompleted = true;
for (Map<String, Object> params : waitingTasks) {
reconnectService(params, connectionDelay);
}
waitingTasks.clear();
if ( null != watchdog ){
watchdog.start();
}
}
@Override
public void packetsReady(IO serv) throws IOException {
// Under a high load data, especially lots of packets on a single
// connection it may happen that one threads started processing
// socketData and then another thread reads more packets which
// may take over earlier data depending on a thread scheduler used.
// synchronized (serv) {
if (checkTrafficLimits(serv)) {
writePacketsToSocket(serv, processSocketData(serv));
}
}
@Override
public int processingInThreads() {
return Runtime.getRuntime().availableProcessors() * 4;
}
@Override
public int processingOutThreads() {
return Runtime.getRuntime().availableProcessors() * 4;
}
@Override
public void processPacket(Packet packet) {
writePacketToSocket(packet);
}
/**
* Method description
*
*
* @param serv
*
*
*
* @return a value of {@code Queue<Packet>}
*/
public abstract Queue<Packet> processSocketData(IO serv);
/**
* Processes undelivered packets
* @param packet
* @param stamp - timestamp when packet was received to be written to XMPPIOService
* @param errorMessage
*/
public boolean processUndeliveredPacket(Packet packet, Long stamp, String errorMessage) {
return false;
}
/**
* Method description
*
*
* @param port_props
*/
public abstract void reconnectionFailed(Map<String, Object> port_props);
@Override
public void release() {
// delayedTasks.cancel();
releaseListeners();
super.release();
}
/**
* Method description
*
*
* @param service
*/
@TODO(note = "Do something if service with the same unique ID is already started, " +
"possibly kill the old one...")
public void serviceStarted(final IO service) {
// synchronized(services) {
String id = getUniqueId(service);
if (log.isLoggable(Level.FINER)) {
log.log(Level.FINER, "[[{0}]] Connection started: {1}", new Object[] { getName(),
service });
}
IO serv = services.get(id);
if (serv != null) {
if (serv == service) {
log.log(Level.WARNING,
"{0}: That would explain a lot, adding the same service twice, ID: {1}",
new Object[] { getName(),
serv });
} else {
// Is it at all possible to happen???
// let's log it for now....
log.log(Level.FINE,
"{0}: Attempt to add different service with the same ID: {1}", new Object[] {
getName(),
service });
// And stop the old service....
serv.stop();
}
}
services.put(id, service);
++services_size;
}
@Override
public boolean serviceStopped(IO service) {
// Hopefuly there is no exception at this point, but just in case...
// This is a very fresh code after all
try {
ioStatsGetter.check(service);
} catch (Exception e) {
log.log(Level.INFO,
"Nothing serious to worry about but please notify the developer.", e);
}
// synchronized(service) {
String id = getUniqueId(service);
if (log.isLoggable(Level.FINER)) {
log.log(Level.FINER, "[[{0}]] Connection stopped: {1}", new Object[] { getName(),
service });
}
// id might be null if service is stopped in accept method due to
// an exception during establishing TCP/IP connection
// IO serv = (id != null ? services.get(id) : null);
if (id != null) {
boolean result = services.remove(id, service);
if (result) {
--services_size;
} else if (log.isLoggable(Level.FINER)) {
// Is it at all possible to happen???
// let's log it for now....
log.log(Level.FINER, "[[{0}]] Attempt to stop incorrect service: {1}",
new Object[] { getName(),
service });
}
return result;
}
return false;
}
@Override
public void stop() {
this.releaseListeners();
// when stopping connection manager we need to stop all active connections as well
for (IO service : services.values()) {
service.forceStop();
}
super.stop();
}
/**
* Method description
*
*
* @param port_props
*/
public void updateConnectionDetails(Map<String, Object> port_props) {}
/**
* Method description
*
*
* @param serv
* @param packets
*/
public void writePacketsToSocket(IO serv, Queue<Packet> packets) {
if (serv != null) {
// synchronized (serv) {
if ((packets != null) && (packets.size() > 0)) {
Packet p = null;
while ((p = packets.poll()) != null) {
if (log.isLoggable(Level.FINER) &&!log.isLoggable(Level.FINEST)) {
log.log(Level.FINER, "{0}, Processing packet: {1}, type: {2}", new Object[] {
serv,
p.getElemName(), p.getType() });
}
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "{0}, Writing packet: {1}", new Object[] { serv, p });
}
serv.addPacketToSend(p);
} // end of for ()
try {
serv.processWaitingPackets();
SocketThread.addSocketService(serv);
} catch (Exception e) {
log.log(Level.WARNING, serv + "Exception during writing packets: ", e);
try {
serv.stop();
} catch (Exception e1) {
log.log(Level.WARNING, serv + "Exception stopping XMPPIOService: ", e1);
} // end of try-catch
} // end of try-catch
}
} else {
if (log.isLoggable(Level.FINE)) {
log.log(Level.FINE, "Can't find service for packets: [{0}] ", packets);
}
} // end of if (ios != null) else
}
/**
* Method description
*
*
* @param ios
* @param p
*
*
*
* @return a value of <code>boolean</code>
*/
public boolean writePacketToSocket(IO ios, Packet p) {
if (ios != null) {
if (log.isLoggable(Level.FINER) &&!log.isLoggable(Level.FINEST)) {
log.log(Level.FINER, "{0}, Processing packet: {1}, type: {2}", new Object[] { ios,
p.getElemName(), p.getType() });
}
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "{0}, Writing packet: {1}", new Object[] { ios, p });
}
// synchronized (ios) {
ios.addPacketToSend(p);
if (ios.writeInProgress.tryLock()) {
try {
ios.processWaitingPackets();
SocketThread.addSocketService(ios);
return true;
} catch (Exception e) {
log.log(Level.WARNING, ios + "Exception during writing packets: ", e);
try {
ios.stop();
} catch (Exception e1) {
log.log(Level.WARNING, ios + "Exception stopping XMPPIOService: ", e1);
} // end of try-catch
} finally {
ios.writeInProgress.unlock();
}
} else {
return true;
}
} else {
if (log.isLoggable(Level.FINE)) {
log.log(Level.FINE, "Can''t find service for packet: <{0}> {1}, service id: {2}",
new Object[] { p.getElemName(),
p.getTo(), getServiceId(p) });
}
} // end of if (ios != null) else
return false;
}
@Override
public Map<String, Object> getDefaults(Map<String, Object> params) {
log.log(Level.CONFIG, "{0} defaults: {1}", new Object[] { getName(),
params.toString() });
Map<String, Object> props = super.getDefaults(params);
props.put(TLS_USE_PROP_KEY, TLS_USE_PROP_VAL);
checkHighThroughputProperty(NET_BUFFER_HT_PROP_KEY, NET_BUFFER_HT_PROP_VAL,
NET_BUFFER_ST_PROP_KEY, NET_BUFFER_ST_PROP_VAL, NET_BUFFER_PROP_KEY,
Integer.class, params, props);
checkHighThroughputProperty(HT_TRAFFIC_THROTTLING_PROP_KEY,
getDefTrafficThrottling(), ST_TRAFFIC_THROTTLING_PROP_KEY,
getDefTrafficThrottling(), TRAFFIC_THROTTLING_PROP_KEY, String.class, params,
props);
props.put(NET_BUFFER_LIMIT_PROP_KEY, isHighThroughput()
? NET_BUFFER_LIMIT_HT_PROP_VAL : NET_BUFFER_LIMIT_ST_PROP_VAL);
if ( params.get( "--" + ELEMENTS_NUMBER_LIMIT_PROP_KEY ) != null ){
elements_number_limit = Integer.valueOf( (String)params.get( "--" + ELEMENTS_NUMBER_LIMIT_PROP_KEY ) );
} else {
elements_number_limit = ELEMENTS_NUMBER_LIMIT_PROP_VAL;
}
props.put( ELEMENTS_NUMBER_LIMIT_PROP_KEY, elements_number_limit );
if ( params.get( "--" + WATCHDOG_DELAY ) != null ){
watchdogDelay = Integer.valueOf( (String)params.get( "--" + WATCHDOG_DELAY ) );
}
props.put( WATCHDOG_DELAY, watchdogDelay);
if ( params.get( "--" + WATCHDOG_TIMEOUT ) != null ){
watchdogTimeout = Integer.valueOf( (String)params.get( "--" + WATCHDOG_TIMEOUT ) );
}
props.put( WATCHDOG_TIMEOUT, watchdogTimeout);
WATCHDOG_PING_TYPE pingtype = WATCHDOG_PING_TYPE.WHITESPACE;
if ( params.get( "--" + WATCHDOG_PING_TYPE_KEY ) != null ){
String type = (String)params.get( "--" + WATCHDOG_PING_TYPE_KEY );
pingtype = WATCHDOG_PING_TYPE.valueOf( type.toUpperCase() );
}
props.put( WATCHDOG_PING_TYPE_KEY, pingtype);
int[] ports = null;
String ports_str = (String) params.get("--" + getName() + "-ports");
if (ports_str != null) {
String[] ports_stra = ports_str.split(",");
ports = new int[ports_stra.length];
int k = 0;
for (String p : ports_stra) {
try {
ports[k++] = Integer.parseInt(p);
} catch (NumberFormatException e) {
log.warning("Incorrect ports default settings: " + p);
}
}
}
int ports_size = 0;
if (ports != null) {
log.config("Port settings preset: " + Arrays.toString(ports));
for (int port : ports) {
putDefPortParams(props, port, SocketType.plain);
} // end of for (int i = 0; i < idx; i++)
props.put(PORTS_PROP_KEY, ports);
} else {
int[] plains = getDefPlainPorts();
if (plains != null) {
ports_size += plains.length;
} // end of if (plains != null)
int[] ssls = getDefSSLPorts();
if (ssls != null) {
ports_size += ssls.length;
} // end of if (ssls != null)
if (ports_size > 0) {
ports = new int[ports_size];
} // end of if (ports_size > 0)
if (ports != null) {
int idx = 0;
if (plains != null) {
idx = plains.length;
for (int i = 0; i < idx; i++) {
ports[i] = plains[i];
putDefPortParams(props, ports[i], SocketType.plain);
} // end of for (int i = 0; i < idx; i++)
} // end of if (plains != null)
if (ssls != null) {
for (int i = idx; i < idx + ssls.length; i++) {
ports[i] = ssls[i - idx];
putDefPortParams(props, ports[i], SocketType.ssl);
} // end of for (int i = 0; i < idx + ssls.length; i++)
} // end of if (ssls != null)
props.put(PORTS_PROP_KEY, ports);
} // end of if (ports != null)
}
String acks = (String) params.get(XMPP_STANZA_ACK);
if (acks != null) {
String[] acks_arr = acks.split(",");
for (String ack_type : acks_arr) {
if (STANZA_WHITE_CHAR_ACK.equals(ack_type)) {
white_char_ack = true;
}
if (STANZA_XMPP_ACK.equals(ack_type)) {
xmpp_ack = true;
}
}
}
props.put(WHITE_CHAR_ACK_PROP_KEY, white_char_ack);
props.put(XMPP_ACK_PROP_KEY, xmpp_ack);
props.put(MAX_INACTIVITY_TIME, getMaxInactiveTime() / SECOND);
return props;
}
@Override
public void getStatistics(StatisticsList list) {
super.getStatistics(list);
list.add(getName(), "Open connections", services_size, Level.INFO);
if (list.checkLevel(Level.FINEST) || (services.size() < 1000)) {
int waitingToSendSize = 0;
for (IO serv : services.values()) {
waitingToSendSize += serv.waitingToSendSize();
}
list.add(getName(), "Waiting to send", waitingToSendSize, Level.FINE);
}
list.add(getName(), "Bytes sent", bytesSent, Level.FINE);
list.add(getName(), "Bytes received", bytesReceived, Level.FINE);
list.add(getName(), "Socket overflow", socketOverflow, Level.FINE);
list.add(getName(), "Watchdog runs", watchdogRuns, Level.FINER);
list.add(getName(), "Watchdog tests", watchdogTests, Level.FINE);
list.add(getName(), "Watchdog stopped", watchdogStopped, Level.FINE);
}
/**
* Method description
*
*
* @param serviceId
*
*
*
* @return a value of <code>IO</code>
*/
public IO getXMPPIOService(String serviceId) {
return services.get(serviceId);
}
@Override
public void setName(String name) {
super.setName(name);
setupWatchdogThread();
}
protected void setupWatchdogThread() {
watchdog = new Thread( newWatchdog(), "Watchdog - " + getName());
watchdog.setDaemon(true);
}
protected Watchdog newWatchdog() {
return new Watchdog();
}
@Override
public void setProperties(Map<String, Object> props) throws ConfigurationException {
super.setProperties(props);
if (props.get(MAX_INACTIVITY_TIME) != null) {
maxInactivityTime = (Long) props.get(MAX_INACTIVITY_TIME) * SECOND;
}
if (props.get(WHITE_CHAR_ACK_PROP_KEY) != null) {
white_char_ack = (Boolean) props.get(WHITE_CHAR_ACK_PROP_KEY);
}
if (props.get(XMPP_ACK_PROP_KEY) != null) {
xmpp_ack = (Boolean) props.get(XMPP_ACK_PROP_KEY);
}
if (props.get(NET_BUFFER_PROP_KEY) != null) {
net_buffer = (Integer) props.get(NET_BUFFER_PROP_KEY);
}
if (props.get(NET_BUFFER_LIMIT_PROP_KEY) != null) {
net_buffer_limit = (Integer) props.get(NET_BUFFER_LIMIT_PROP_KEY);
}
if (props.get(TRAFFIC_THROTTLING_PROP_KEY) != null) {
String[] tmp = ((String) props.get(TRAFFIC_THROTTLING_PROP_KEY)).split(",");
for (String tmp_s : tmp) {
String[] tmp_thr = tmp_s.split(":");
if (tmp_thr[0].equalsIgnoreCase("xmpp")) {
last_minute_packets_limit = DataTypes.parseNum(tmp_thr[1], Long.class,
LAST_MINUTE_PACKETS_LIMIT_PROP_VAL);
log.warning(getName() + " last_minute_packets_limit = " +
last_minute_packets_limit);
total_packets_limit = DataTypes.parseNum(tmp_thr[2], Long.class,
TOTAL_PACKETS_LIMIT_PROP_VAL);
log.warning(getName() + " total_packets_limit = " + total_packets_limit);
if (tmp_thr[3].equalsIgnoreCase("disc")) {
xmppLimitAction = LIMIT_ACTION.DISCONNECT;
}
if (tmp_thr[3].equalsIgnoreCase("drop")) {
xmppLimitAction = LIMIT_ACTION.DROP_PACKETS;
}
}
if (tmp_thr[0].equalsIgnoreCase("bin")) {
last_minute_bin_limit = DataTypes.parseNum(tmp_thr[1], Long.class,
LAST_MINUTE_BIN_LIMIT_PROP_VAL);
log.warning(getName() + " last_minute_bin_limit = " + last_minute_bin_limit);
total_bin_limit = DataTypes.parseNum(tmp_thr[2], Long.class,
TOTAL_BIN_LIMIT_PROP_VAL);
log.warning(getName() + " total_bin_limit = " + total_bin_limit);
}
}
}
if ( props.get (ELEMENTS_NUMBER_LIMIT_PROP_KEY ) != null ){
elements_number_limit = (int) props.get (ELEMENTS_NUMBER_LIMIT_PROP_KEY );
}
if ( props.get( WATCHDOG_DELAY ) != null ){
watchdogDelay = (long) props.get( WATCHDOG_DELAY );
}
if ( props.get( WATCHDOG_TIMEOUT ) != null ){
watchdogTimeout = (long) props.get( WATCHDOG_TIMEOUT );
}
if ( props.get( WATCHDOG_PING_TYPE_KEY ) != null ){
String value = String.valueOf( props.get( WATCHDOG_PING_TYPE_KEY ) );
watchdogPingType = WATCHDOG_PING_TYPE.valueOf( value.toUpperCase() );
}
if (props.size() == 1) {
// If props.size() == 1, it means this is a single property update and
// ConnectionManager does not support it yet.
return;
}
if (isInitializationComplete()) {
// Do we really need to do this again?
// Looks like reconfiguration for the port is not working correctly anyway
// so for now we do not want to do it.
return;
}
releaseListeners();
int[] ports = (int[]) props.get(PORTS_PROP_KEY);
if (ports != null) {
for (int i = 0; i < ports.length; i++) {
Map<String, Object> port_props = new LinkedHashMap<String, Object>(20);
for (Map.Entry<String, Object> entry : props.entrySet()) {
if (entry.getKey().startsWith(PROP_KEY + ports[i])) {
int idx = entry.getKey().lastIndexOf('/');
String key = entry.getKey().substring(idx + 1);
log.log(Level.CONFIG, "Adding port property key: {0}={1}", new Object[] { key,
entry.getValue() });
port_props.put(key, entry.getValue());
} // end of if (entry.getKey().startsWith())
} // end of for ()
port_props.put(PORT_KEY, ports[i]);
if (port_props.containsKey(PORT_TYPE_PROP_KEY)
&& !(port_props.get(PORT_TYPE_PROP_KEY) instanceof ConnectionType)) {
Object val = port_props.get(PORT_TYPE_PROP_KEY);
port_props.put(PORT_TYPE_PROP_KEY, ConnectionType.valueOf(val.toString()));
}
if (port_props.containsKey(PORT_SOCKET_PROP_KEY)
&& !(port_props.get(PORT_SOCKET_PROP_KEY) instanceof SocketType)) {
Object val = port_props.get(PORT_SOCKET_PROP_KEY);
port_props.put(PORT_SOCKET_PROP_KEY, SocketType.valueOf(val.toString()));
}
addWaitingTask(port_props);
// reconnectService(port_props, startDelay);
} // end of for (int i = 0; i < ports.length; i++)
} // end of if (ports != null)
}
/**
* Method description
*
*
* @param conn
*/
protected void addWaitingTask(Map<String, Object> conn) {
if (initializationCompleted) {
reconnectService(conn, connectionDelay);
} else {
waitingTasks.add(conn);
}
}
/**
* Method description
*
*
* @param ht_def_key
* @param ht_dev_val
* @param st_def_key
* @param st_def_val
* @param prop_key
* @param prop_val_class
* @param params
* @param props
* @param <T>
*/
protected <T> void checkHighThroughputProperty(String ht_def_key, T ht_dev_val,
String st_def_key, T st_def_val, String prop_key, Class<T> prop_val_class,
Map<String, Object> params, Map<String, Object> props) {
T tmp = st_def_val;
String str_tmp = null;
if (isHighThroughput()) {
tmp = ht_dev_val;
str_tmp = (String) params.get(ht_def_key);
} else {
tmp = st_def_val;
str_tmp = (String) params.get(st_def_key);
}
if (prop_val_class.isAssignableFrom(Integer.class)) {
tmp = prop_val_class.cast(DataTypes.parseNum(str_tmp, Integer.class,
(Integer) tmp));
}
if (prop_val_class.isAssignableFrom(Long.class)) {
tmp = prop_val_class.cast(DataTypes.parseNum(str_tmp, Long.class, (Long) tmp));
}
if (prop_val_class.isAssignableFrom(String.class)) {
tmp = prop_val_class.cast(str_tmp);
}
props.put(prop_key, tmp);
}
/**
* Returns number of active network connections (IOServices).
*
* @return number of active network connections (IOServices).
*/
protected int countIOServices() {
return services.size();
}
/**
* Perform a given action defined by ServiceChecker for all active IOService
* objects (active network connections).
*
* @param checker
* is a <code>ServiceChecker</code> instance defining an action to
* perform for all IOService objects.
*/
protected void doForAllServices(ServiceChecker<IO> checker) {
for (IO service : services.values()) {
checker.check(service);
}
}
/**
*
* @param p
*
*
* @return a value of <code>boolean</code>
*/
protected boolean writePacketToSocket(Packet p) {
IO ios = getXMPPIOService(p);
if (ios != null) {
return writePacketToSocket(ios, p);
} else {
return false;
}
}
/**
* Method description
*
*
* @param p
* @param serviceId
*
*
*
* @return a value of <code>boolean</code>
*/
protected boolean writePacketToSocket(Packet p, String serviceId) {
IO ios = getXMPPIOService(serviceId);
if (ios != null) {
return writePacketToSocket(ios, p);
} else {
return false;
}
}
/**
* Method description
*
*
* @param ios
* @param data
*/
protected void writeRawData(IO ios, String data) {
try {
ios.writeRawData(data);
SocketThread.addSocketService(ios);
} catch (Exception e) {
log.log(Level.WARNING, ios + "Exception during writing data: " + data, e);
try {
ios.stop();
} catch (Exception e1) {
log.log(Level.WARNING, ios + "Exception stopping XMPPIOService: ", e1);
} // end of try-catch
}
}
/**
* Method description
*
*
*
*
* @return a value of <code>int[]</code>
*/
protected int[] getDefPlainPorts() {
return null;
}
/**
* Method description
*
*
*
*
* @return a value of <code>int[]</code>
*/
protected int[] getDefSSLPorts() {
return null;
}
/**
* Method description
*
*
*
*
* @return a value of <code>String</code>
*/
protected String getDefTrafficThrottling() {
String result = ST_TRAFFIC_THROTTLING_PROP_VAL;
if (isHighThroughput()) {
result = HT_TRAFFIC_THROTTLING_PROP_VAL;
}
return result;
}
/**
* Method description
*
*
*
*
* @return a value of <code>long</code>
*/
protected abstract long getMaxInactiveTime();
/**
* Method description
*
*
* @param port
*
*
*
* @return a value of {@code Map<String,Object>}
*/
protected Map<String, Object> getParamsForPort(int port) {
return null;
}
/**
* Method description
*
*
* @param packet
*
*
*
* @return a value of <code>String</code>
*/
protected String getServiceId(Packet packet) {
return getServiceId(packet.getTo());
}
/**
* Method description
*
*
* @param jid
*
*
*
* @return a value of <code>String</code>
*/
protected String getServiceId(JID jid) {
return jid.getResource();
}
/**
* Method description
*
*
* @param serv
*
*
*
* @return a value of <code>String</code>
*/
protected String getUniqueId(IO serv) {
return serv.getUniqueId();
}
/**
* Method description
*
*
* @param p
*
*
*
* @return a value of <code>IO</code>
*/
protected IO getXMPPIOService(Packet p) {
String id = getServiceId(p);
if (id != null) {
return services.get(id);
}
return null;
}
/**
* Method description
*
*
*
*
* @return a value of <code>IO</code>
*/
protected abstract IO getXMPPIOServiceInstance();
/**
* Method description
*
*
*
*
* @return a value of <code>boolean</code>
*/
protected boolean isHighThroughput() {
return false;
}
private void putDefPortParams(Map<String, Object> props, int port, SocketType sock) {
log.log(Level.CONFIG, "Generating defaults for port: {0,number,#}", port);
props.put(PROP_KEY + port + "/" + PORT_TYPE_PROP_KEY, ConnectionType.accept);
props.put(PROP_KEY + port + "/" + PORT_SOCKET_PROP_KEY, sock);
props.put(PROP_KEY + port + "/" + PORT_IFC_PROP_KEY, PORT_IFC_PROP_VAL);
props.put(PROP_KEY + port + "/" + PORT_REMOTE_HOST_PROP_KEY,
PORT_REMOTE_HOST_PROP_VAL);
props.put(PROP_KEY + port + "/" + TLS_REQUIRED_PROP_KEY, TLS_REQUIRED_PROP_VAL);
Map<String, Object> extra = getParamsForPort(port);
if (extra != null) {
for (Map.Entry<String, Object> entry : extra.entrySet()) {
props.put(PROP_KEY + port + "/" + entry.getKey(), entry.getValue());
} // end of for ()
} // end of if (extra != null)
}
private void reconnectService(final Map<String, Object> port_props, long delay) {
if (log.isLoggable(Level.FINER)) {
String cid = "" + port_props.get("local-hostname") + "@" + port_props.get(
"remote-hostname");
log.log(Level.FINER,
"Reconnecting service for: {0}, scheduling next try in {1}secs, cid: {2}, props: {3}",
new Object[] { getName(), delay / 1000, cid, port_props });
}
addTimerTask(new tigase.util.TimerTask() {
@Override
public void run() {
String host = (String) port_props.get(PORT_REMOTE_HOST_PROP_KEY);
if (host == null) {
host = (String) port_props.get("remote-hostname");
}
int port = (Integer) port_props.get(PORT_KEY);
if (log.isLoggable(Level.FINE)) {
log.log(Level.FINE,
"Reconnecting service for component: {0}, to remote host: {1} on port: {2,number,
new Object[] { getName(),
host, port });
}
startService(port_props);
}
}, delay);
}
private void releaseListeners() {
for (ConnectionListenerImpl cli : pending_open) {
connectThread.removeConnectionOpenListener(cli);
}
pending_open.clear();
}
private void startService(Map<String, Object> port_props) {
if (port_props == null) {
throw new NullPointerException("port_props cannot be null.");
}
ConnectionListenerImpl cli = new ConnectionListenerImpl(port_props);
if (cli.getConnectionType() == ConnectionType.accept) {
pending_open.add(cli);
}
connectThread.addConnectionOpenListener(cli);
}
private class ConnectionListenerImpl
implements ConnectionOpenListener {
private Map<String, Object> port_props = null;
private ConnectionListenerImpl(Map<String, Object> port_props) {
this.port_props = port_props;
}
@Override
public void accept(SocketChannel sc) {
String cid = "" + port_props.get("local-hostname") + "@" + port_props.get(
"remote-hostname");
if ( log.isLoggable( Level.FINEST ) ){
log.log( Level.FINEST, "Accept called for service: {0}, port_props: {1}", new Object[] {cid, port_props} );
}
IO serv = getXMPPIOServiceInstance();
serv.setBufferLimit( net_buffer_limit );
( (XMPPDomBuilderHandler) serv.getSessionData().get( DOM_HANDLER ) ).setElementsLimit( elements_number_limit );
serv.setIOServiceListener(ConnectionManager.this);
serv.setSessionData(port_props);
try {
serv.accept(sc);
if (getSocketType() == SocketType.ssl) {
serv.startSSL(false, false, false);
} // end of if (socket == SocketType.ssl)
serviceStarted(serv);
SocketThread.addSocketService(serv);
} catch (Exception e) {
if (getConnectionType() == ConnectionType.connect) {
// Accept side for component service is not ready yet?
// Let's wait for a few secs and try again.
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "Problem reconnecting the service: {0}, port_props: {1}, exception: {2}",
new Object[] { serv, port_props, e });
}
updateConnectionDetails(port_props);
boolean reconnect = false;
Integer reconnects = (Integer) port_props.get(MAX_RECONNECTS_PROP_KEY);
if (reconnects != null) {
int recon = reconnects.intValue();
if (recon != 0) {
port_props.put(MAX_RECONNECTS_PROP_KEY, (--recon));
reconnect = true;
} // end of if (recon != 0)
}
if (reconnect) {
reconnectService(port_props, connectionDelay);
} else {
reconnectionFailed(port_props);
}
} else {
// Ignore
}
// } catch (Exception e) {
// if (log.isLoggable(Level.FINEST)) {
// log.log(Level.FINEST, "Can not accept connection cid: " + cid, e);
// log.log(Level.WARNING, "Can not accept connection.", e);
// serv.stop();
} // end of try-catch
}
@Override
public String toString() {
return port_props.toString();
}
@Override
public ConnectionType getConnectionType() {
String type = null;
if (port_props.get(PORT_TYPE_PROP_KEY) == null) {
log.warning(getName() + ": connection type is null: " + port_props.get(PORT_KEY)
.toString());
} else {
type = port_props.get(PORT_TYPE_PROP_KEY).toString();
}
return ConnectionType.valueOf(type);
}
@Override
public String[] getIfcs() {
return (String[]) port_props.get(PORT_IFC_PROP_KEY);
}
@Override
public int getPort() {
return (Integer) port_props.get(PORT_KEY);
}
@Override
public int getReceiveBufferSize() {
return net_buffer;
}
@Override
public InetSocketAddress getRemoteAddress() {
return (InetSocketAddress) port_props.get("remote-address");
}
@Override
public String getRemoteHostname() {
if (port_props.containsKey(PORT_REMOTE_HOST_PROP_KEY)) {
return (String) port_props.get(PORT_REMOTE_HOST_PROP_KEY);
}
return (String) port_props.get("remote-hostname");
}
@Override
public SocketType getSocketType() {
return SocketType.valueOf(port_props.get(PORT_SOCKET_PROP_KEY).toString());
}
@Override
public String getSRVType() {
String type = (String) this.port_props.get("srv-type");
if ((type == null) || type.isEmpty()) {
return null;
}
return type;
}
@Override
public int getTrafficClass() {
if (isHighThroughput()) {
return IPTOS_THROUGHPUT;
} else {
return DEF_TRAFFIC_CLASS;
}
}
}
private class IOServiceStatisticsGetter
implements ServiceChecker<IO> {
private StatisticsList list = new StatisticsList(Level.ALL);
@Override
public synchronized void check(IO service) {
bytesReceived += service.getBytesReceived(true);
bytesSent += service.getBytesSent(true);
socketOverflow += service.getBuffOverflow(true);
service.getPacketsReceived(true);
service.getPacketsSent(true);
// service.getStatistics(list, true);
// bytesReceived += list.getValue("socketio", "Bytes received", -1l);
// bytesSent += list.getValue("socketio", "Bytes sent", -1l);
// socketOverflow += list.getValue("socketio", "Buffers overflow", -1l);
}
}
/**
* Class looks in all established connections and checks whether any of them
* is dead by performing either whitspace or XMPP ping. If client fails to
* respond within defined time then the service is stopped.
*
*/
protected class Watchdog
implements Runnable {
Packet pingPacket;
protected long getDurationSinceLastTransfer(final XMPPIOService service) {
long curr_time = System.currentTimeMillis();
long lastTransfer;
switch (watchdogPingType) {
case XMPP:
lastTransfer = service.getLastXmppPacketReceiveTime();
break;
case WHITESPACE:
default:
lastTransfer = service.getLastTransferTime();
break;
}
return curr_time - lastTransfer;
}
@Override
public void run() {
while (true) {
try {
// Sleep...
Thread.sleep(watchdogDelay);
++watchdogRuns;
/** Walk through all connections and check whether they are really
* alive. Depending on the configuration send either whitespace or
* XMPP ping if the service is inactive for the configured period of
* time
*/
doForAllServices(new ServiceChecker<IO>() {
@Override
public void check(final XMPPIOService service) {
try {
if ( null != service ){
if ( log.isLoggable( Level.FINEST ) ){
log.log( Level.FINEST,
"Testing service: {0}, sinceLastTransfer: {1}, maxInactivityTime: {2}, watchdogTimeout: {3}, watchdogDelay: {4}, watchdogPingType: {5} ",
new Object[] { service, getDurationSinceLastTransfer( service ), maxInactivityTime, watchdogTimeout, watchdogDelay, watchdogPingType } );
}
long sinceLastTransfer = getDurationSinceLastTransfer(service);
if ( sinceLastTransfer >= maxInactivityTime ){
// Stop the service if max keep-alive time is exceeded
// for non-active connections.
if ( log.isLoggable( Level.INFO ) ){
log.log( Level.INFO,
"{0}: Max inactive time exceeded, stopping: {1}",
new Object[] { getName(),
service } );
}
++watchdogStopped;
service.stop();
} else {
if ( sinceLastTransfer >= ( watchdogTimeout ) ){
/** At least once every configured timings check if the
* connection is still alive with the use of configured
* ping type. */
switch ( watchdogPingType ) {
case XMPP:
pingPacket = Iq.packetInstance( pingElement.clone(),
JID.jidInstanceNS( (String) service.getSessionData().get( XMPPIOService.HOSTNAME_KEY ) ),
JID.jidInstanceNS( service.getUserJid() ) );
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "{0}, sending XMPP ping {1}", new Object[] { service, pingPacket });
}
if ( !writePacketToSocket( (IO) service, pingPacket ) ){
// writing failed, stopp service
++watchdogStopped;
service.stop();
}
break;
case WHITESPACE:
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "Sending whitespace ping for service {0}", new Object[] { service });
}
service.writeRawData( " " );
break;
}
++watchdogTests;
}
}
}
} catch ( IOException e ) {
// Close the service
try {
if ( service != null ){
log.info( getName() + "Found dead connection, stopping: " + service );
++watchdogStopped;
service.forceStop();
}
} catch ( Exception ignore ) {
// Do nothing here as we expect Exception to be thrown here...
}
}
}
} );
} catch ( InterruptedException e ) { /* Do nothing here */
}
}
}
}
} // ConnectionManager
//~ Formatted in Tigase Code Convention on 13/10/15
|
package ui.components;
import javafx.application.Platform;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyCombination;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import prefs.Preferences;
import util.DialogMessage;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* a central place to specify keyboard shortcuts
*
* Classes that currently have keyboard shortcut code:
* ui.components.NavigableListView
* ui.issuecolumn.ColumnControl
* ui.issuepanel.IssuePanel
* ui.MenuControl
*
* Utility Class:
* util.KeyPress
*/
public class KeyboardShortcuts {
private static final Logger logger = LogManager.getLogger(KeyboardShortcuts.class.getName());
private static Map<String, String> keyboardShortcuts = null;
private static Set<KeyCode> assignedKeys = null;
// customizable keyboard shortcuts
// ui.issuepanel.IssuePanel
public static KeyCode MARK_AS_READ;
public static KeyCode MARK_AS_UNREAD;
public static KeyCode SCROLL_TO_TOP;
public static KeyCode SCROLL_TO_BOTTOM;
public static KeyCode SCROLL_UP;
public static KeyCode SCROLL_DOWN;
//ui.issuecolumn.ColumnControl
public static KeyCode LEFT_PANEL;
public static KeyCode RIGHT_PANEL;
// ui.components.NavigableListView && ui.issuepanel.IssuePanel
public static KeyCode UP_ISSUE;
public static KeyCode DOWN_ISSUE;
// non-customizable keyboard shortcuts
// ui.issuepanel.IssuePanel
public static final KeyCombination BOX_TO_LIST =
new KeyCodeCombination(KeyCode.DOWN, KeyCombination.CONTROL_DOWN);
public static final KeyCombination LIST_TO_BOX =
new KeyCodeCombination(KeyCode.UP, KeyCombination.CONTROL_DOWN);
public static final KeyCombination MAXIMIZE_WINDOW =
new KeyCodeCombination(KeyCode.X, KeyCombination.CONTROL_DOWN);
public static final KeyCombination MINIMIZE_WINDOW =
new KeyCodeCombination(KeyCode.N, KeyCombination.CONTROL_DOWN);
public static final KeyCombination DEFAULT_SIZE_WINDOW =
new KeyCodeCombination(KeyCode.D, KeyCombination.CONTROL_DOWN);
public static final KeyCode REFRESH = KeyCode.F5;
public static final KeyCode SHOW_DOCS = KeyCode.F1;
public static final KeyCode GOTO_MODIFIER = KeyCode.G;
public static final KeyCode SHOW_LABELS = KeyCode.L;
public static final KeyCode SHOW_ISSUES = KeyCode.I;
public static final KeyCode SHOW_MILESTONES = KeyCode.M;
public static final KeyCode SHOW_PULL_REQUESTS = KeyCode.P;
public static final KeyCode SHOW_HELP = KeyCode.H;
public static final KeyCode SHOW_KEYBOARD_SHORTCUTS = KeyCode.K;
public static final KeyCode SHOW_CONTRIBUTORS = KeyCode.D;
// TODO decouple manage/show labels/milestones?
public static final KeyCode NEW_COMMENT = KeyCode.C;
public static final KeyCode MANAGE_LABELS = KeyCode.L;
public static final KeyCode MANAGE_ASSIGNEES = KeyCode.A;
public static final KeyCode MANAGE_MILESTONE = KeyCode.M;
public static final KeyCode DOUBLE_PRESS = KeyCode.SPACE;
// ui.MenuControl
public static final KeyCombination NEW_ISSUE =
new KeyCodeCombination(KeyCode.I, KeyCombination.CONTROL_DOWN);
public static final KeyCombination NEW_LABEL =
new KeyCodeCombination(KeyCode.L, KeyCombination.CONTROL_DOWN);
public static final KeyCombination NEW_MILESTONE =
new KeyCodeCombination(KeyCode.M, KeyCombination.CONTROL_DOWN);
public static final KeyCombination CREATE_LEFT_PANEL =
new KeyCodeCombination(KeyCode.P, KeyCombination.CONTROL_DOWN, KeyCombination.SHIFT_DOWN);
public static final KeyCombination CREATE_RIGHT_PANEL =
new KeyCodeCombination(KeyCode.P, KeyCombination.CONTROL_DOWN);
public static final KeyCombination CLOSE_PANEL =
new KeyCodeCombination(KeyCode.W, KeyCombination.CONTROL_DOWN);
public static Map<String, String> getDefaultKeyboardShortcuts() {
Map<String, String> defaultKeyboardShortcuts = new HashMap<>();
defaultKeyboardShortcuts.put("MARK_AS_READ", "E");
defaultKeyboardShortcuts.put("MARK_AS_UNREAD", "U");
defaultKeyboardShortcuts.put("SCROLL_TO_TOP", "I");
defaultKeyboardShortcuts.put("SCROLL_TO_BOTTOM", "N");
defaultKeyboardShortcuts.put("SCROLL_UP", "J");
defaultKeyboardShortcuts.put("SCROLL_DOWN", "K");
defaultKeyboardShortcuts.put("LEFT_PANEL", "D");
defaultKeyboardShortcuts.put("RIGHT_PANEL", "F");
defaultKeyboardShortcuts.put("UP_ISSUE", "T");
defaultKeyboardShortcuts.put("DOWN_ISSUE", "V");
return defaultKeyboardShortcuts;
}
private static void addNonCustomizableShortcutKeys() {
assignedKeys.add(KeyCode.F5); //REFRESH
assignedKeys.add(KeyCode.F1); //SHOW_DOCS
assignedKeys.add(KeyCode.G); //GOTO_MODIFIER
assignedKeys.add(KeyCode.C); //NEW_COMMENT
assignedKeys.add(KeyCode.A); //MANAGE_ASSIGNEES
assignedKeys.add(KeyCode.SPACE); //DOUBLE_PRESS
}
private static void getKeyboardShortcutsFromHashMap() {
MARK_AS_READ = getKeyCode("MARK_AS_READ");
MARK_AS_UNREAD = getKeyCode("MARK_AS_UNREAD");
SCROLL_TO_TOP = getKeyCode("SCROLL_TO_TOP");
SCROLL_TO_BOTTOM = getKeyCode("SCROLL_TO_BOTTOM");
SCROLL_UP = getKeyCode("SCROLL_UP");
SCROLL_DOWN = getKeyCode("SCROLL_DOWN");
LEFT_PANEL = getKeyCode("LEFT_PANEL");
RIGHT_PANEL = getKeyCode("RIGHT_PANEL");
UP_ISSUE = getKeyCode("UP_ISSUE");
DOWN_ISSUE = getKeyCode("DOWN_ISSUE");
}
public static void loadKeyboardShortcuts(Preferences prefs) {
assignedKeys = new HashSet<>();
if (prefs.getKeyboardShortcuts().size() == 0) {
logger.info("No user specified keyboard shortcuts found, using defaults. ");
prefs.setKeyboardShortcuts(getDefaultKeyboardShortcuts());
}
if (prefs.getKeyboardShortcuts().size() != getDefaultKeyboardShortcuts().size()) {
logger.warn("Invalid number of user specified keyboard shortcuts detected. ");
if (DialogMessage.showYesNoWarningDialog(
"Warning",
"Invalid number of shortcut keys specified",
"Do you want to reset the shortcut keys to their defaults or quit?",
"Reset to default",
"Quit")) {
keyboardShortcuts = getDefaultKeyboardShortcuts();
} else {
Platform.exit();
System.exit(0);
}
} else {
logger.info("Loading user specified keyboard shortcuts. ");
keyboardShortcuts = prefs.getKeyboardShortcuts();
}
addNonCustomizableShortcutKeys();
getKeyboardShortcutsFromHashMap();
prefs.setKeyboardShortcuts(keyboardShortcuts);
}
private static KeyCode getKeyCode(String keyboardShortcut) {
KeyCode keyCode = KeyCode.getKeyCode(getDefaultKeyboardShortcuts().get(keyboardShortcut));
if (keyboardShortcuts.containsKey(keyboardShortcut)) {
KeyCode userDefinedKeyCode = KeyCode.getKeyCode(keyboardShortcuts.get(keyboardShortcut).toUpperCase());
if (userDefinedKeyCode != null && !assignedKeys.contains(userDefinedKeyCode)) {
keyCode = userDefinedKeyCode;
} else {
logger.warn("Invalid key specified for " + keyboardShortcut +
" or it has already been used for some other shortcut. ");
if (DialogMessage.showYesNoWarningDialog(
"Warning",
"Invalid key specified for " + keyboardShortcut +
" or it has already been used for some other shortcut. ",
"Do you want to use the default key <" +
getDefaultKeyboardShortcuts().get(keyboardShortcut) + "> or quit?",
"Use default key",
"Quit")) {
keyboardShortcuts.put(keyboardShortcut, getDefaultKeyboardShortcuts().get(keyboardShortcut));
} else {
Platform.exit();
System.exit(0);
}
}
} else {
logger.warn("Could not find user defined keyboard shortcut for " + keyboardShortcut);
if (DialogMessage.showYesNoWarningDialog(
"Warning",
"Could not find user defined keyboard shortcut for " + keyboardShortcut,
"Do you want to use the default key <" +
getDefaultKeyboardShortcuts().get(keyboardShortcut) + "> or quit?",
"Use default key",
"Quit")) {
keyboardShortcuts.put(keyboardShortcut, getDefaultKeyboardShortcuts().get(keyboardShortcut));
} else {
Platform.exit();
System.exit(0);
}
}
logger.info("Assigning <" + keyCode + "> to " + keyboardShortcut);
assignedKeys.add(keyCode);
return keyCode;
}
}
|
package uk.ac.eeci;
import io.improbable.scienceos.Conductor;
import io.improbable.scienceos.Reference;
import io.improbable.scienceos.WorkerPool;
import org.apache.commons.cli.*;
public class CommandLineInterface {
private String inputFilePath;
private String outputFilePath;
public static void main(String ... args) {
Options options = new Options();
Option input = new Option("i", "input", true, "file path to scenario db");
input.setRequired(true);
options.addOption(input);
Option output = new Option("o", "output", true, "file path for output db");
output.setRequired(true);
options.addOption(output);
CommandLineParser parser = new DefaultParser();
HelpFormatter formatter = new HelpFormatter();
CommandLine cmd;
try {
cmd = parser.parse(options, args);
} catch (ParseException e) {
System.out.println(e.getMessage());
formatter.printHelp("energy-agents", options);
System.exit(1);
return;
}
CommandLineInterface cli = new CommandLineInterface();
cli.inputFilePath = cmd.getOptionValue("input");
cli.outputFilePath = cmd.getOptionValue("output");
cli.run();
}
private void run() {
Reference.pool = new WorkerPool(4); // FIXME shouldnt be here
Reference.pool.setCurrentExecutor(Reference.pool.main); // FIXME shouldnt be here
CitySimulation citySimulation = ScenarioBuilder.readScenario(this.inputFilePath, this.outputFilePath);
new Conductor(citySimulation).run();
}
}
|
package utask.staging.ui;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import org.ocpsoft.prettytime.PrettyTime;
import com.google.common.eventbus.Subscribe;
import javafx.fxml.FXML;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.OverrunStyle;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import javafx.scene.text.TextAlignment;
import utask.commons.core.EventsCenter;
import utask.commons.events.model.UTaskChangedEvent;
import utask.model.tag.Tag;
import utask.model.tag.UniqueTagList;
import utask.model.task.ReadOnlyTask;
import utask.staging.ui.helper.TagColorHelper;
public class UTTaskListCard extends StagingUiPart<Region> {
public static final double CARD_HEIGHT = 102.0;
private static final String FXML = "UTTaskListCard.fxml";
private static final String LABEL_CSS = "-fx-padding: 1 3 1 3; -fx-text-fill: WHITE; -fx-background-color: %s;";
private static final String LABEL_STRIKETHROUGH_STYLE = "label-text-done";
//UI Element use Leszynski naming convention. Prefix is the element type
@FXML
private Label lblId;
@FXML
private CheckBox chkDone;
@FXML
private Label lblName;
@FXML
private HBox hbTagContainer;
@FXML
private Label lblDate;
//TODO: Upgrade to property for observable binding instead of manually checking for UI events
private final ReadOnlyTask task;
private boolean isDone;
public UTTaskListCard(ReadOnlyTask task, int displayedIndex) {
super(FXML);
assert(task != null && displayedIndex > 0);
this.task = task;
setTaskInfoToControls(task, displayedIndex);
addStylingProperitesOnCompletion();
EventsCenter.getInstance().registerHandler(this);
}
private void setTaskInfoToControls(ReadOnlyTask task, int displayedIndex) {
lblName.setText(task.getName().fullName);
lblId.setText(displayedIndex + " ");
String friendlyDate = buildFriendlyDateToDisplay(task);
lblDate.setText(friendlyDate);
initTags(task);
}
private String buildFriendlyDateToDisplay(ReadOnlyTask task) {
StringBuilder sb = new StringBuilder();
if (!task.getFrequency().isEmpty()) {
sb.append(task.getFrequency().value + ", ");
}
if (!task.getDeadline().isEmpty()) {
sb.append(getPrettyDate(task));
}
if (!task.getTimestamp().isEmpty()) {
sb.append(", " + task.getTimestamp().value);
}
return sb.toString();
}
//@@author A0138493W
private String getPrettyDate(ReadOnlyTask task) {
assert task != null;
Date deadline = null;
try {
deadline = task.getDeadline().getDate();
} catch (ParseException e) {
assert false : "Should never have parse error, regex should check input";
}
DateFormat fmt = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH);
if (fmt.format(deadline).equals(fmt.format(new Date()))) {
return fmt.format(deadline) + ", today";
}
PrettyTime p = new PrettyTime();
return fmt.format(deadline) + ", " + p.format(deadline);
}
//@@author
private void initTags(ReadOnlyTask task) {
UniqueTagList tags = task.getTags();
for (Tag tag : tags) {
Label label = createLabel(tag.tagName);
hbTagContainer.getChildren().add(label);
}
}
private Label createLabel(String name) {
Label label = new Label(name);
addStylingPropertiesToLabel(label);
return label;
}
private void addStylingPropertiesToLabel(Label label) {
label.setAlignment(Pos.CENTER);;
label.setTextAlignment(TextAlignment.CENTER);
label.setTextOverrun(OverrunStyle.CLIP);
label.setMinWidth(15.0);
label.setStyle(String.format(LABEL_CSS, TagColorHelper.getARandomColor()));
HBox.setMargin(label, new Insets(5, 5, 5, 0));
}
private void addStylingProperitesOnCompletion() {
boolean isCompleted = task.getIsCompleted().isCompleted();
setCheckBoxAsChecked(isCompleted);
if (isCompleted) {
lblName.getStyleClass().add(LABEL_STRIKETHROUGH_STYLE);
} else {
lblName.getStyleClass().remove(LABEL_STRIKETHROUGH_STYLE);
}
}
/**
* JFoenix version 1.2.0 throws NullPointerException
* when applying transition effects
*/
private void setCheckBoxAsChecked(boolean isCompleted) {
try {
chkDone.setSelected(isCompleted);
} catch (NullPointerException e) {
}
}
@Subscribe
public void handleUTaskChangedEvent(UTaskChangedEvent e) {
addStylingProperitesOnCompletion();
}
}
|
package model.ability_management;
/**
* A collection of all possible abilities
* Enumerated with a string for parsing and view purposes
*/
public enum AbilityEnum {
MOVE_NORTH ("Move North"),
MOVE_NORTHLEFT ("Move North Left"),
MOVE_NORTHRIGHT ("Move North Right"),
MOVE_SOUTH ("Move South"),
MOVE_SOUTHLEFT ("Move South Left"),
MOVE_SOUTHRIGHT ("Move South Right"),
MOVE_NORTHWEST ("Move NorthWest"),
MOVE_NORTHWESTLEFT ("Move NorthWest Left"),
MOVE_NORTHWESTRIGHT ("Move NorthWest Right"),
MOVE_NORTHEAST ("Move NorthEast"),
MOVE_NORTHEASTLEFT ("Move NorthEast Left"),
MOVE_NORTHEASTRIGHT ("Move NorthEast Right"),
TRADE_TRANSPORT ("Trade with Transport"),
TRADE_TILE ("Trade with the Tile"),
BUILD_WAGON ("Build A Wagon"),
BUILD_TRUCK ("Build A Truck"),
BUILD_RAFT ("Build A Raft"),
BUILD_ROWBOAT ("Build A Rowboat"),
BUILD_STEAMBOAT ("Build A Steamboat"),
SCUTTLE_TRANSPORTER ("Destroy This Transporter"),
BREED_DONKEY ("Breed A Donkey"),
RESEARCH ("Perform Research"),
UPGRADE_WAGON_FACTORY ("Upgrade A Wagon Factory"),
UPGRADE_RAFT_FACTORY ("Upgrade A Raft Factory"),
UPGRADE_ROWBOAT_FACTORY ("Upgrade A Rowboat Factory"),
INPUT_RESOURCES ("Input Resources To A Secondary Producer"),
DROP_RESOURCES ("Drop Off Resources On Tile"),
PICK_UP_RESOURCES ("Pick Up Resources From Tile"),
PICK_UP_TRANSPORTER ("Pick Up Transporter From Tile"),
BUILD_CLAY_PIT ("Build A Clay Pit"),
BUILD_QUARRY ("Build A Quarry"),
BUILD_MINE ("Build A Mine"),
BUILD_OIL_RIG ("Build An Oil Rig"),
BUILD_SAWMILL ("Build A Sawmill"),
BUILD_MINT ("Build A Mint"),
BUILD_STOCK_MARKET ("Build A Stock Market"),
BUILD_WAGON_FACTORY ("Build A Wagon Factory"),
BUILD_TRUCK_FACTORY ("Build A Truck Factory"),
BUILD_RAFT_FACTORY ("Build A Raft Factory"),
BUILD_ROWBOAT_FACTORY ("Build A Rowboat Factory"),
BUILD_STEAMBOAT_FACTORY ("Build A Steamboat Factory"),
BUILD_WALL ("Make America Great Again"),
DESTROY_WALL ("Destroy A Wall"),
STRENGTHEN_WALL ("Strengthen A Wall"),
BUILD_MINE_SHAFT ("Build A Mine Shaft"),
BUILD_ROAD ("Build A Road"),
BUILD_BRIDGE ("Build A Bridge"),
BUILD_WONDER_BRICK ("Build A Wonder Brick");
// GUI description for each ability
private final String description;
// Constructor
AbilityEnum(final String s) {
this.description = s;
}
// Return the ability description
public String getDescription() { return this.description; }
}
|
package me.yokeyword.fragmentation;
import android.app.Activity;
import android.content.Intent;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.view.animation.Animation;
import me.yokeyword.fragmentation.anim.FragmentAnimator;
import me.yokeyword.fragmentation.helper.internal.AnimatorHelper;
import me.yokeyword.fragmentation.helper.internal.ResultRecord;
import me.yokeyword.fragmentation.helper.internal.TransactionRecord;
import me.yokeyword.fragmentation.helper.internal.VisibleDelegate;
public class SupportFragmentDelegate {
// Animation
private boolean mEnterAnimDisable;
boolean mIsSharedElement;
FragmentAnimator mFragmentAnimator;
AnimatorHelper mAnimHelper;
boolean mLockAnim;
private Handler mHandler;
private boolean mFirstCreateView = true;
private boolean mReplaceMode;
private boolean mIsHidden = true;
int mContainerId;
private TransactionDelegate mTransactionDelegate;
TransactionRecord mTransactionRecord;
// SupportVisible
private VisibleDelegate mVisibleDelegate;
Bundle mNewBundle;
private Bundle mSaveInstanceState;
private ISupportFragment mSupportF;
private Fragment mFragment;
protected FragmentActivity _mActivity;
private ISupportActivity mSupport;
boolean mAnimByActivity = true;
EnterAnimListener mEnterAnimListener;
public SupportFragmentDelegate(ISupportFragment support) {
if (!(support instanceof Fragment))
throw new RuntimeException("Must extends Fragment");
this.mSupportF = support;
this.mFragment = (Fragment) support;
}
/**
* Perform some extra transactions.
* TagSharedElementFragment
*/
public ExtraTransaction extraTransaction() {
if (mTransactionDelegate == null)
throw new RuntimeException(mFragment.getClass().getSimpleName() + " not attach!");
return new ExtraTransaction.ExtraTransactionImpl<>(mSupportF, mTransactionDelegate, false);
}
public void onAttach(Activity activity) {
if (activity instanceof ISupportActivity) {
this.mSupport = (ISupportActivity) activity;
this._mActivity = (FragmentActivity) activity;
mTransactionDelegate = mSupport.getSupportDelegate().getTransactionDelegate();
} else {
throw new RuntimeException(activity.getClass().getSimpleName() + " must impl ISupportActivity!");
}
}
public void onCreate(@Nullable Bundle savedInstanceState) {
getVisibleDelegate().onCreate(savedInstanceState);
Bundle bundle = mFragment.getArguments();
if (bundle != null) {
mEnterAnimDisable = bundle.getBoolean(TransactionDelegate.FRAGMENTATION_ARG_ANIM_DISABLE, false);
mIsSharedElement = bundle.getBoolean(TransactionDelegate.FRAGMENTATION_ARG_IS_SHARED_ELEMENT, false);
mContainerId = bundle.getInt(TransactionDelegate.FRAGMENTATION_ARG_CONTAINER);
mReplaceMode = bundle.getBoolean(TransactionDelegate.FRAGMENTATION_ARG_REPLACE, false);
}
if (savedInstanceState == null) {
getFragmentAnimator();
} else {
mSaveInstanceState = savedInstanceState;
mFragmentAnimator = savedInstanceState.getParcelable(TransactionDelegate.FRAGMENTATION_STATE_SAVE_ANIMATOR);
mIsHidden = savedInstanceState.getBoolean(TransactionDelegate.FRAGMENTATION_STATE_SAVE_IS_HIDDEN);
mContainerId = savedInstanceState.getInt(TransactionDelegate.FRAGMENTATION_ARG_CONTAINER);
}
// Fix the overlapping BUG on pre-24.0.0
processRestoreInstanceState(savedInstanceState);
mAnimHelper = new AnimatorHelper(_mActivity.getApplicationContext(), mFragmentAnimator);
}
public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {
if ((mSupport.getSupportDelegate().mPopMultipleNoAnim || mLockAnim)) {
if (transit == FragmentTransaction.TRANSIT_FRAGMENT_CLOSE && enter) {
return mAnimHelper.getNoneAnimFixed();
}
return mAnimHelper.getNoneAnim();
}
if (transit == FragmentTransaction.TRANSIT_FRAGMENT_OPEN) {
if (enter) {
Animation enterAnim;
if (mEnterAnimDisable) {
enterAnim = mAnimHelper.getNoneAnim();
} else {
enterAnim = mAnimHelper.enterAnim;
}
fixAnimationListener(enterAnim);
return enterAnim;
} else {
return mAnimHelper.popExitAnim;
}
} else if (transit == FragmentTransaction.TRANSIT_FRAGMENT_CLOSE) {
return enter ? mAnimHelper.popEnterAnim : mAnimHelper.exitAnim;
} else {
if (mIsSharedElement && enter) {
compatSharedElements();
}
Animation fixedAnim = mAnimHelper.getViewPagerChildFragmentAnimFixed(mFragment, enter);
if (fixedAnim != null) return fixedAnim;
return null;
}
}
public void onSaveInstanceState(Bundle outState) {
getVisibleDelegate().onSaveInstanceState(outState);
outState.putParcelable(TransactionDelegate.FRAGMENTATION_STATE_SAVE_ANIMATOR, mFragmentAnimator);
outState.putBoolean(TransactionDelegate.FRAGMENTATION_STATE_SAVE_IS_HIDDEN, mFragment.isHidden());
outState.putInt(TransactionDelegate.FRAGMENTATION_ARG_CONTAINER, mContainerId);
}
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
getVisibleDelegate().onActivityCreated(savedInstanceState);
View view = mFragment.getView();
if (view != null) {
view.setClickable(true);
setBackground(view);
}
if (savedInstanceState != null || mEnterAnimDisable || (mFragment.getTag() != null
&& mFragment.getTag().startsWith("android:switcher:")) || (mReplaceMode && !mFirstCreateView)) {
notifyEnterAnimEnd();
}
if (mFirstCreateView) {
mFirstCreateView = false;
}
}
public void onResume() {
getVisibleDelegate().onResume();
}
public void onPause() {
getVisibleDelegate().onPause();
}
public void onDestroyView() {
mSupport.getSupportDelegate().mFragmentClickable = true;
getVisibleDelegate().onDestroyView();
}
public void onDestroy() {
mTransactionDelegate.handleResultRecord(mFragment);
}
public void onHiddenChanged(boolean hidden) {
getVisibleDelegate().onHiddenChanged(hidden);
}
public void setUserVisibleHint(boolean isVisibleToUser) {
getVisibleDelegate().setUserVisibleHint(isVisibleToUser);
}
/**
* If you want to call the start()/pop()/showHideFragment() on the onCreateXX/onActivityCreated,
* call this method to deliver the transaction to the queue.
* <p>
* onCreate/onCreateView/onActivityCreated start()/pop()/showHideFragment(),
*
* @param runnable start() , pop() or showHideFragment()
*/
public void enqueueAction(Runnable runnable) {
getHandler().postDelayed(runnable, mAnimHelper == null ? 0 : mAnimHelper.enterAnim.getDuration());
}
/**
* Called when the enter-animation end.
* ,
*/
public void onEnterAnimationEnd(Bundle savedInstanceState) {
}
/**
* Lazy initialCalled when fragment is first visible.
* <p>
* ViewPager
*/
public void onLazyInitView(@Nullable Bundle savedInstanceState) {
}
/**
* Called when the fragment is visible.
* <p>
* Fragment
* <p>
* Is the combination of [onHiddenChanged() + onResume()/onPause() + setUserVisibleHint()]
*/
public void onSupportVisible() {
}
/**
* Called when the fragment is invivible.
* <p>
* Is the combination of [onHiddenChanged() + onResume()/onPause() + setUserVisibleHint()]
*/
public void onSupportInvisible() {
}
/**
* Return true if the fragment has been supportVisible.
*/
final public boolean isSupportVisible() {
return getVisibleDelegate().isSupportVisible();
}
/**
* Set fragment animation with a higher priority than the ISupportActivity
* Fragmemt,ISupportActivity
*/
public FragmentAnimator onCreateFragmentAnimator() {
return mSupport.getFragmentAnimator();
}
/**
*
*
* @return FragmentAnimator
*/
public FragmentAnimator getFragmentAnimator() {
if (mSupport == null)
throw new RuntimeException("Fragment has not been attached to Activity!");
if (mFragmentAnimator == null) {
mFragmentAnimator = mSupportF.onCreateFragmentAnimator();
if (mFragmentAnimator == null) {
mFragmentAnimator = mSupport.getFragmentAnimator();
}
}
return mFragmentAnimator;
}
/**
* Set the fragment animation.
*/
public void setFragmentAnimator(FragmentAnimator fragmentAnimator) {
this.mFragmentAnimator = fragmentAnimator;
if (mAnimHelper != null) {
mAnimHelper.notifyChanged(fragmentAnimator);
}
mAnimByActivity = false;
}
/**
* {@link Activity#setResult(int, Intent)}
* <p>
* Similar to {@link Activity#setResult(int, Intent)}
*
* @see #startForResult(ISupportFragment, int)
*/
public void setFragmentResult(int resultCode, Bundle bundle) {
Bundle args = mFragment.getArguments();
if (args == null || !args.containsKey(TransactionDelegate.FRAGMENTATION_ARG_RESULT_RECORD)) {
return;
}
ResultRecord resultRecord = args.getParcelable(TransactionDelegate.FRAGMENTATION_ARG_RESULT_RECORD);
if (resultRecord != null) {
resultRecord.resultCode = resultCode;
resultRecord.resultBundle = bundle;
}
}
/**
* {@link Activity#onActivityResult(int, int, Intent)}
* <p>
* Similar to {@link Activity#onActivityResult(int, int, Intent)}
*
* @see #startForResult(ISupportFragment, int)
*/
public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
}
/**
* start(TargetFragment,LaunchMode),SingleTask/SingleTop, TargetFragment
* {@link Activity#onNewIntent(Intent)}
* <p>
* Similar to {@link Activity#onNewIntent(Intent)}
*
* @param args putNewBundle(Bundle newBundle)
* @see #start(ISupportFragment, int)
*/
public void onNewBundle(Bundle args) {
}
/**
* NewBundle,SingleTask/SingleTop
*
* @see #start(ISupportFragment, int)
*/
public void putNewBundle(Bundle newBundle) {
this.mNewBundle = newBundle;
}
/**
* Back Event
*
* @return false, true
*/
public boolean onBackPressedSupport() {
return false;
}
public void hideSoftInput() {
SupportHelper.hideSoftInput(mFragment.getView());
}
/**
* ,,onPause
*/
public void showSoftInput(View view) {
SupportHelper.showSoftInput(view);
}
/**
* Fragment, ActivityFragment FragmentFragment
*/
public void loadRootFragment(int containerId, ISupportFragment toFragment) {
loadRootFragment(containerId, toFragment, true, false);
}
public void loadRootFragment(int containerId, ISupportFragment toFragment, boolean addToBackStack, boolean allowAnim) {
mTransactionDelegate.loadRootTransaction(getChildFragmentManager(), containerId, toFragment, addToBackStack, allowAnim);
}
/**
* Fragment,Wechat, QQ
*/
public void loadMultipleRootFragment(int containerId, int showPosition, ISupportFragment... toFragments) {
mTransactionDelegate.loadMultipleRootTransaction(getChildFragmentManager(), containerId, showPosition, toFragments);
}
/**
* showFragment,hideFragment
* Fragment,(loadMultipleRootFragment()Fragment)
* <p>
* {@link #showHideFragment(ISupportFragment, ISupportFragment)}
*/
public void showHideFragment(ISupportFragment showFragment) {
showHideFragment(showFragment, null);
}
/**
* showFragment,hideFragment ; tab
*/
public void showHideFragment(ISupportFragment showFragment, ISupportFragment hideFragment) {
mTransactionDelegate.showHideFragment(getChildFragmentManager(), showFragment, hideFragment);
}
public void start(ISupportFragment toFragment) {
start(toFragment, ISupportFragment.STANDARD);
}
/**
* @param launchMode Similar to Activity's LaunchMode.
*/
public void start(final ISupportFragment toFragment, @ISupportFragment.LaunchMode int launchMode) {
mTransactionDelegate.dispatchStartTransaction(mFragment.getFragmentManager(), mSupportF, toFragment, 0, launchMode, TransactionDelegate.TYPE_ADD);
}
/**
* Launch an fragment for which you would like a result when it poped.
*/
public void startForResult(ISupportFragment toFragment, int requestCode) {
mTransactionDelegate.dispatchStartTransaction(mFragment.getFragmentManager(), mSupportF, toFragment, requestCode, ISupportFragment.STANDARD, TransactionDelegate.TYPE_ADD_RESULT);
}
/**
* Launch a fragment while poping self.
*/
public void startWithPop(ISupportFragment toFragment) {
mTransactionDelegate.dispatchStartTransaction(mFragment.getFragmentManager(), mSupportF, toFragment, 0, ISupportFragment.STANDARD, TransactionDelegate.TYPE_ADD_WITH_POP);
}
public void replaceFragment(ISupportFragment toFragment, boolean addToBackStack) {
mTransactionDelegate.dispatchStartTransaction(mFragment.getFragmentManager(), mSupportF, toFragment, 0, ISupportFragment.STANDARD, addToBackStack ? TransactionDelegate.TYPE_REPLACE : TransactionDelegate.TYPE_REPLACE_DONT_BACK);
}
public void startChild(ISupportFragment toFragment) {
startChild(toFragment, ISupportFragment.STANDARD);
}
public void startChild(final ISupportFragment toFragment, @ISupportFragment.LaunchMode int launchMode) {
mTransactionDelegate.dispatchStartTransaction(getChildFragmentManager(), getTopFragment(), toFragment, 0, launchMode, TransactionDelegate.TYPE_ADD);
}
public void startChildForResult(ISupportFragment toFragment, int requestCode) {
mTransactionDelegate.dispatchStartTransaction(getChildFragmentManager(), getTopFragment(), toFragment, requestCode, ISupportFragment.STANDARD, TransactionDelegate.TYPE_ADD_RESULT);
}
public void startChildWithPop(ISupportFragment toFragment) {
mTransactionDelegate.dispatchStartTransaction(getChildFragmentManager(), getTopFragment(), toFragment, 0, ISupportFragment.STANDARD, TransactionDelegate.TYPE_ADD_WITH_POP);
}
public void replaceChildFragment(ISupportFragment toFragment, boolean addToBackStack) {
mTransactionDelegate.dispatchStartTransaction(getChildFragmentManager(), getTopFragment(), toFragment, 0, ISupportFragment.STANDARD, addToBackStack ? TransactionDelegate.TYPE_REPLACE : TransactionDelegate.TYPE_REPLACE_DONT_BACK);
}
public void pop() {
mTransactionDelegate.back(mFragment.getFragmentManager());
}
/**
* Pop the child fragment.
*/
public void popChild() {
mTransactionDelegate.back(getChildFragmentManager());
}
/**
* Pop the last fragment transition from the manager's fragment
* back stack.
* <p>
* fragment
*
* @param targetFragmentClass fragment
* @param includeTargetFragment fragment
*/
public void popTo(Class<?> targetFragmentClass, boolean includeTargetFragment) {
getChildFragmentManager().popBackStack();
popTo(targetFragmentClass, includeTargetFragment, null);
}
/**
* If you want to begin another FragmentTransaction immediately after popTo(), use this method.
* , FragmentTransaction
*/
public void popTo(Class<?> targetFragmentClass, boolean includeTargetFragment, Runnable afterPopTransactionRunnable) {
popTo(targetFragmentClass, includeTargetFragment, afterPopTransactionRunnable, 0);
}
public void popTo(Class<?> targetFragmentClass, boolean includeTargetFragment, Runnable afterPopTransactionRunnable, int popAnim) {
mTransactionDelegate.popTo(targetFragmentClass.getName(), includeTargetFragment, afterPopTransactionRunnable, mFragment.getFragmentManager(), popAnim);
}
public void popToChild(Class<?> targetFragmentClass, boolean includeTargetFragment) {
popToChild(targetFragmentClass, includeTargetFragment, null);
}
public void popToChild(Class<?> targetFragmentClass, boolean includeTargetFragment, Runnable afterPopTransactionRunnable) {
popToChild(targetFragmentClass, includeTargetFragment, afterPopTransactionRunnable, 0);
}
public void popToChild(Class<?> targetFragmentClass, boolean includeTargetFragment, Runnable afterPopTransactionRunnable, int popAnim) {
mTransactionDelegate.popTo(targetFragmentClass.getName(), includeTargetFragment, afterPopTransactionRunnable, getChildFragmentManager(), popAnim);
}
private FragmentManager getChildFragmentManager() {
return mFragment.getChildFragmentManager();
}
private ISupportFragment getTopFragment() {
return SupportHelper.getTopFragment(getChildFragmentManager());
}
private void processRestoreInstanceState(Bundle savedInstanceState) {
if (savedInstanceState != null) {
FragmentTransaction ft = mFragment.getFragmentManager().beginTransaction();
if (mIsHidden) {
ft.hide(mFragment);
} else {
ft.show(mFragment);
}
ft.commitAllowingStateLoss();
}
}
private void fixAnimationListener(Animation enterAnim) {
mSupport.getSupportDelegate().mFragmentClickable = false;
// AnimationListener is not reliable.
getHandler().postDelayed(new Runnable() {
@Override
public void run() {
notifyEnterAnimEnd();
}
}, enterAnim.getDuration());
if (mEnterAnimListener != null) {
getHandler().post(new Runnable() {
@Override
public void run() {
mEnterAnimListener.onEnterAnimStart();
mEnterAnimListener = null;
}
});
}
}
private void compatSharedElements() {
notifyEnterAnimEnd();
}
public void setBackground(View view) {
if ((mFragment.getTag() != null && mFragment.getTag().startsWith("android:switcher:")) ||
mEnterAnimDisable ||
view.getBackground() != null) {
return;
}
int defaultBg = mSupport.getSupportDelegate().getDefaultFragmentBackground();
if (defaultBg == 0) {
int background = getWindowBackground();
view.setBackgroundResource(background);
} else {
view.setBackgroundResource(defaultBg);
}
}
private int getWindowBackground() {
TypedArray a = _mActivity.getTheme().obtainStyledAttributes(new int[]{
android.R.attr.windowBackground
});
int background = a.getResourceId(0, 0);
a.recycle();
return background;
}
private void notifyEnterAnimEnd() {
getHandler().post(new Runnable() {
@Override
public void run() {
if (mFragment == null) return;
mSupportF.onEnterAnimationEnd(mSaveInstanceState);
}
});
mSupport.getSupportDelegate().mFragmentClickable = true;
}
private Handler getHandler() {
if (mHandler == null) {
mHandler = new Handler(Looper.getMainLooper());
}
return mHandler;
}
public VisibleDelegate getVisibleDelegate() {
if (mVisibleDelegate == null) {
mVisibleDelegate = new VisibleDelegate(mSupportF);
}
return mVisibleDelegate;
}
public FragmentActivity getActivity() {
return _mActivity;
}
interface EnterAnimListener {
void onEnterAnimStart();
}
}
|
package edu.uci.python.nodes.expression;
import static edu.uci.python.nodes.truffle.PythonTypesUtil.*;
import java.math.BigInteger;
import org.python.core.*;
import com.oracle.truffle.api.*;
import com.oracle.truffle.api.CompilerDirectives.SlowPath;
import com.oracle.truffle.api.dsl.Specialization;
import com.oracle.truffle.api.dsl.Generic;
import com.oracle.truffle.api.frame.*;
import edu.uci.python.runtime.array.*;
import edu.uci.python.runtime.datatype.*;
import edu.uci.python.runtime.misc.*;
import edu.uci.python.runtime.sequence.*;
public abstract class BinaryArithmeticNode extends BinaryOpNode {
public abstract static class AddNode extends BinaryArithmeticNode {
@Specialization(rewriteOn = ArithmeticException.class, order = 5)
int doInteger(int left, int right) {
return ExactMath.addExact(left, right);
}
@Specialization(order = 6)
BigInteger doIntegerBigInteger(int left, BigInteger right) {
return BigInteger.valueOf(left).add(right);
}
@Specialization(order = 7)
BigInteger doBigIntegerInteger(BigInteger left, int right) {
return left.add(BigInteger.valueOf(right));
}
@Specialization(order = 10)
BigInteger doBigInteger(BigInteger left, BigInteger right) {
return left.add(right);
}
@Specialization(order = 15)
double doDoubleInt(double left, int right) {
return left + right;
}
@Specialization(order = 16)
double doDoubleInt(int left, double right) {
return left + right;
}
@Specialization(order = 20)
double doDouble(double left, double right) {
return left + right;
}
@Specialization(order = 30)
PComplex doComplexInt(PComplex left, int right) {
PComplex result = new PComplex(left.getReal() + right, left.getImag());
return result;
}
@Specialization(order = 35)
PComplex doDoubleComplex(double left, PComplex right) {
PComplex result = new PComplex(left + right.getReal(), right.getImag());
return result;
}
@Specialization(order = 40)
PComplex doComplexDouble(PComplex left, double right) {
PComplex result = new PComplex(left.getReal() + right, left.getImag());
return result;
}
@Specialization(order = 45)
PComplex doComplex(BigInteger left, PComplex right) {
return new PComplex(left.doubleValue(), 0).add(right);
}
@Specialization(order = 50)
PComplex doComplex(PComplex left, PComplex right) {
return left.add(right);
}
@Specialization(order = 60)
String doString(String left, String right) {
return left + right;
}
@Specialization(order = 70)
PList doPList(PList left, PList right) {
return left.__add__(right);
}
@Specialization(order = 80)
PTuple doPTuple(PTuple left, PTuple right) {
return left.__add__(right);
}
@Specialization(order = 90)
PArray doPArray(PArray left, PArray right) {
return left.__add__(right);
}
@SuppressWarnings("unused")
@Specialization(order = 100)
int doNoneInt(PNone left, int right) {
return right;
}
@Specialization(order = 200, guards = "isEitherOperandPythonObject")
Object doPythonObject(VirtualFrame frame, Object left, Object right) {
return doSpecialMethodCall(frame, "__add__", left, right);
}
// TODO: type info for operands in type error message.
@Generic
Object doGeneric(Object left, Object right) {
throw Py.TypeError("unsupported operand type(s) for +: " + left + " " + right);
}
}
public abstract static class SubNode extends BinaryArithmeticNode {
@Specialization(rewriteOn = ArithmeticException.class, order = 0)
int doInteger(int left, int right) {
return ExactMath.subtractExact(left, right);
}
@Specialization(order = 1)
BigInteger doBigInteger(BigInteger left, BigInteger right) {
return left.subtract(right);
}
@Specialization(order = 10)
double doDouble(double left, double right) {
return left - right;
}
@Specialization(order = 11)
double doBigIntegerDouble(BigInteger left, double right) {
return left.doubleValue() - right;
}
@Specialization(order = 12)
double doBigIntegerDouble(double left, BigInteger right) {
return left - right.doubleValue();
}
@Specialization(order = 13)
PComplex doDoubleComplex(double left, PComplex right) {
PComplex result = new PComplex(left - right.getReal(), -right.getImag());
return result;
}
@Specialization(order = 14)
PComplex doComplexDoulbe(PComplex left, double right) {
PComplex result = new PComplex(left.getReal() - right, left.getImag());
return result;
}
@Specialization(order = 15)
PComplex doComplex(PComplex left, PComplex right) {
return left.sub(right);
}
@Specialization(order = 16)
PBaseSet doPBaseSet(PBaseSet left, PBaseSet right) {
return left.difference(right);
}
@Specialization(order = 20, guards = "isEitherOperandPythonObject")
Object doPythonObject(VirtualFrame frame, Object left, Object right) {
return doSpecialMethodCall(frame, "__sub__", left, right);
}
}
public abstract static class MulNode extends BinaryArithmeticNode {
@Specialization(rewriteOn = ArithmeticException.class, order = 0)
int doInteger(int left, int right) {
return ExactMath.multiplyExact(left, right);
}
@SlowPath
@Specialization(order = 1)
BigInteger doIntegerBigInteger(int left, BigInteger right) {
return BigInteger.valueOf(left).multiply(right);
}
@SlowPath
@Specialization(order = 2)
BigInteger doIntegerBigInteger(BigInteger left, int right) {
return left.multiply(BigInteger.valueOf(right));
}
@SlowPath
@Specialization(order = 3)
BigInteger doBigInteger(BigInteger left, BigInteger right) {
return left.multiply(right);
}
@Specialization(order = 4)
double doDouble(double left, double right) {
return left * right;
}
@Specialization(order = 5)
PComplex doDoubleComplex(double left, PComplex right) {
PComplex result = new PComplex(left * right.getReal(), left * right.getImag());
return result;
}
@Specialization(order = 6)
PComplex doComplexDouble(PComplex left, double right) {
PComplex result = new PComplex(left.getReal() * right, left.getImag() * right);
return result;
}
@Specialization(order = 7)
PComplex doComplex(PComplex left, PComplex right) {
return left.mul(right);
}
@Specialization(order = 8)
PList doIntPList(int left, PList right) {
return right.__mul__(left);
}
@Specialization(order = 9)
PList doPListInt(PList left, int right) {
return left.__mul__(right);
}
@Specialization(order = 10)
PTuple doIntPTuple(int left, PTuple right) {
return right.__mul__(left);
}
@Specialization(order = 11)
PTuple doPTupleInt(PTuple left, int right) {
return left.__mul__(right);
}
@Specialization(order = 12)
PArray doIntPArray(int left, PArray right) {
return right.__mul__(left);
}
@Specialization(order = 13)
PArray doPArrayInt(PArray left, int right) {
return left.__mul__(right);
}
@Specialization(order = 14)
String doIntString(int left, String right) {
String str = right;
for (int i = 0; i < left - 1; i++) {
str = str + right;
}
return str;
}
@Specialization(order = 15)
String doStringInt(String left, int right) {
String str = left;
for (int i = 0; i < right - 1; i++) {
str = str + left;
}
return str;
}
@Specialization(order = 20, guards = "isEitherOperandPythonObject")
Object doPythonObject(VirtualFrame frame, Object left, Object right) {
return doSpecialMethodCall(frame, "__mul__", left, right);
}
// TODO: better type error message.
@Generic
Object doGeneric(Object left, Object right) {
throw Py.TypeError("can't multiply " + left + left.getClass() + " by " + right);
}
}
public abstract static class DivNode extends BinaryArithmeticNode {
/*
* double division by zero in Java doesn't throw an exception, instead it yield Infinity
* (NaN).
*/
@Specialization(rewriteOn = ArithmeticException.class, order = 0)
double doInteger(int left, int right) {
if (right == 0) {
CompilerDirectives.transferToInterpreterAndInvalidate();
throw new ArithmeticException("divide by zero");
}
return (double) left / right;
}
@Specialization(order = 5)
double doBigInteger(BigInteger left, BigInteger right) {
return FastMathUtil.slowPathDivide(left, right).doubleValue();
}
@Specialization(order = 10)
double doDouble(double left, double right) {
return left / right;
}
@Specialization(order = 11)
double doBigIntegerDouble(BigInteger left, double right) {
return left.doubleValue() / right;
}
@Specialization(order = 12)
double doBigIntegerDouble(double left, BigInteger right) {
return left / right.doubleValue();
}
@Specialization(order = 13)
PComplex doDoubleComplex(double left, PComplex right) {
double opNormSq = right.getReal() * right.getReal() + right.getImag() * right.getImag();
PComplex conjugate = right.getConjugate();
double realPart = left * conjugate.getReal();
double imagPart = left * conjugate.getImag();
return new PComplex(realPart / opNormSq, imagPart / opNormSq);
}
@Specialization(order = 14)
PComplex doComplexDouble(PComplex left, double right) {
double opNormSq = right * right;
double realPart = left.getReal() * right;
double imagPart = left.getImag() * right;
return new PComplex(realPart / opNormSq, imagPart / opNormSq);
}
@Specialization(order = 15)
PComplex doComplex(PComplex left, PComplex right) {
return left.div(right);
}
@Specialization(order = 20, guards = "isEitherOperandPythonObject")
Object doPythonObject(VirtualFrame frame, Object left, Object right) {
return doSpecialMethodCall(frame, "__truediv__", left, right);
}
@Generic
Object doGeneric(Object left, Object right) {
throw Py.TypeError("Unsupported operand type for /: " + left + " and " + right);
}
}
public abstract static class FloorDivNode extends BinaryArithmeticNode {
@Specialization
int doInteger(int left, int right) {
return left / right;
}
@Specialization
BigInteger doBigInteger(BigInteger left, BigInteger right) {
return FastMathUtil.slowPathDivide(left, right);
}
@Specialization
double doDouble(double left, double right) {
return Math.floor(left / right);
}
@Specialization(order = 20, guards = "isEitherOperandPythonObject")
Object doPythonObject(VirtualFrame frame, Object left, Object right) {
return doSpecialMethodCall(frame, "__floordiv__", left, right);
}
@Generic
Object doGeneric(Object left, Object right) {
throw Py.TypeError("Unsupported operand type for //: " + left + " and " + right);
}
}
public abstract static class ModuloNode extends BinaryArithmeticNode {
@Specialization(order = 0, guards = "isLeftPositive")
int doInteger(int left, int right) {
return left % right;
}
@Specialization(order = 1)
int doIntegerNegative(int left, int right) {
return (left + right) % right;
}
@SuppressWarnings("unused")
protected static boolean isLeftPositive(int left, int right) {
return left >= 0;
}
@SuppressWarnings("unused")
protected static boolean isLeftNegative(int left, int right) {
return left < 0;
}
@SlowPath
@Specialization
BigInteger doBigInteger(BigInteger left, BigInteger right) {
return left.mod(right);
}
@Specialization
double doDouble(double left, double right) {
return left % right;
}
/**
* Delegate to Jython for String formatting.
*/
@SlowPath
@Specialization(order = 10)
Object doString(String left, Object right) {
PyString sleft = new PyString(left);
return unboxPyObject(sleft.__mod__(adaptToPyObject(right)));
}
@Specialization(order = 20, guards = "isEitherOperandPythonObject")
Object doPythonObject(VirtualFrame frame, Object left, Object right) {
return doSpecialMethodCall(frame, "__mod__", left, right);
}
@Generic
Object doGeneric(Object left, Object right) {
throw Py.TypeError("Unsupported operand type for %: " + left + " and " + right);
}
}
public abstract static class PowerNode extends BinaryArithmeticNode {
@Specialization
int doInteger(int left, int right) {
return (int) Math.pow(left, right);
}
@Specialization
BigInteger doBigInteger(BigInteger left, BigInteger right) {
double value = Math.pow(left.doubleValue(), right.doubleValue());
return BigInteger.valueOf((long) value);
}
@Specialization
double doDouble(double left, double right) {
return Math.pow(left, right);
}
@Specialization(order = 20, guards = "isEitherOperandPythonObject")
Object doPythonObject(VirtualFrame frame, Object left, Object right) {
return doSpecialMethodCall(frame, "__pow__", left, right);
}
}
}
|
package com.tinkerpop.gremlin.structure.io.graphml;
import com.tinkerpop.gremlin.structure.Direction;
import com.tinkerpop.gremlin.structure.Edge;
import com.tinkerpop.gremlin.structure.Element;
import com.tinkerpop.gremlin.structure.Graph;
import com.tinkerpop.gremlin.structure.Vertex;
import com.tinkerpop.gremlin.structure.io.GraphWriter;
import javax.xml.XMLConstants;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class GraphMLWriter implements GraphWriter {
private static final Comparator<Element> ELEMENT_COMPARATOR = Comparator.comparing(e -> e.getId().toString(), String.CASE_INSENSITIVE_ORDER);
private final XMLOutputFactory inputFactory = XMLOutputFactory.newInstance();
private final Graph graph;
private boolean normalize = false;
private final Optional<Map<String, String>> vertexKeyTypes;
private final Optional<Map<String, String>> edgeKeyTypes;
private final Optional<String> xmlSchemaLocation;
private final Optional<String> edgeLabelKey;
private GraphMLWriter(final Graph graph, final boolean normalize, final Map<String, String> vertexKeyTypes,
final Map<String, String> edgeKeyTypes, final String xmlSchemaLocation,
final String edgeLabelKey) {
this.graph = graph;
this.normalize = normalize;
this.vertexKeyTypes = Optional.ofNullable(vertexKeyTypes);
this.edgeKeyTypes = Optional.ofNullable(edgeKeyTypes);
this.xmlSchemaLocation = Optional.ofNullable(xmlSchemaLocation);
this.edgeLabelKey = Optional.ofNullable(edgeLabelKey);
}
@Override
public void writeVertex(final OutputStream outputStream, final Vertex v, Direction direction) throws IOException {
throw new UnsupportedOperationException("GraphML does not allow for a partial structure");
}
@Override
public void writeVertex(final OutputStream outputStream, final Vertex v) throws IOException {
throw new UnsupportedOperationException("GraphML does not allow for a partial structure");
}
@Override
public void writeEdge(final OutputStream outputStream, final Edge e) throws IOException {
throw new UnsupportedOperationException("GraphML does not allow for a partial structure");
}
/**
* Write the data in a Graph to a GraphML OutputStream.
*
* @param outputStream the GraphML OutputStream to write the Graph data to
* @throws java.io.IOException thrown if there is an error generating the GraphML data
*/
@Override
public void writeGraph(final OutputStream outputStream) throws IOException {
final Map<String, String> identifiedVertexKeyTypes = this.vertexKeyTypes.orElseGet(this::determineVertexTypes);
final Map<String, String> identifiedEdgeKeyTypes = this.edgeKeyTypes.orElseGet(this::determineEdgeTypes);
// adding the edge label key will push the label into the data portion of the graphml otherwise it
// will live with the edge data itself (which won't validate against the graphml schema)
if (this.edgeLabelKey.isPresent() && null == identifiedEdgeKeyTypes.get(this.edgeLabelKey.get()))
identifiedEdgeKeyTypes.put(this.edgeLabelKey.get(), GraphMLTokens.STRING);
try {
final XMLStreamWriter writer;
writer = configureWriter(outputStream);
writer.writeStartDocument();
writer.writeStartElement(GraphMLTokens.GRAPHML);
writeXmlNsAndSchema(writer);
writeTypes(identifiedVertexKeyTypes, identifiedEdgeKeyTypes, writer);
writer.writeStartElement(GraphMLTokens.GRAPH);
writer.writeAttribute(GraphMLTokens.ID, GraphMLTokens.G);
writer.writeAttribute(GraphMLTokens.EDGEDEFAULT, GraphMLTokens.DIRECTED);
writeVertices(writer);
writeEdges(writer);
writer.writeEndElement(); // graph
writer.writeEndElement(); // graphml
writer.writeEndDocument();
writer.flush();
writer.close();
} catch (XMLStreamException xse) {
throw new IOException(xse);
}
}
private XMLStreamWriter configureWriter(final OutputStream outputStream) throws XMLStreamException {
final XMLStreamWriter utf8Writer = inputFactory.createXMLStreamWriter(outputStream, "UTF8");
if (normalize) {
final XMLStreamWriter writer = new GraphMLWriterHelper.IndentingXMLStreamWriter(utf8Writer);
((GraphMLWriterHelper.IndentingXMLStreamWriter) writer).setIndentStep(" ");
return writer;
} else
return utf8Writer;
}
private void writeTypes(final Map<String, String> identifiedVertexKeyTypes,
final Map<String, String> identifiedEdgeKeyTypes,
final XMLStreamWriter writer) throws XMLStreamException {
// <key id="weight" for="edge" attr.name="weight" attr.type="float"/>
final Collection<String> vertexKeySet = getVertexKeysAndNormalizeIfRequired(identifiedVertexKeyTypes);
for (String key : vertexKeySet) {
writer.writeStartElement(GraphMLTokens.KEY);
writer.writeAttribute(GraphMLTokens.ID, key);
writer.writeAttribute(GraphMLTokens.FOR, GraphMLTokens.NODE);
writer.writeAttribute(GraphMLTokens.ATTR_NAME, key);
writer.writeAttribute(GraphMLTokens.ATTR_TYPE, identifiedVertexKeyTypes.get(key));
writer.writeEndElement();
}
final Collection<String> edgeKeySet = getEdgeKeysAndNormalizeIfRequired(identifiedEdgeKeyTypes);
for (String key : edgeKeySet) {
writer.writeStartElement(GraphMLTokens.KEY);
writer.writeAttribute(GraphMLTokens.ID, key);
writer.writeAttribute(GraphMLTokens.FOR, GraphMLTokens.EDGE);
writer.writeAttribute(GraphMLTokens.ATTR_NAME, key);
writer.writeAttribute(GraphMLTokens.ATTR_TYPE, identifiedEdgeKeyTypes.get(key));
writer.writeEndElement();
}
}
private void writeEdges(final XMLStreamWriter writer) throws XMLStreamException {
if (normalize) {
final List<Edge> edges = graph.E().toList();
Collections.sort(edges, ELEMENT_COMPARATOR);
for (Edge edge : edges) {
writer.writeStartElement(GraphMLTokens.EDGE);
writer.writeAttribute(GraphMLTokens.ID, edge.getId().toString());
writer.writeAttribute(GraphMLTokens.SOURCE, edge.getVertex(Direction.OUT).getId().toString());
writer.writeAttribute(GraphMLTokens.TARGET, edge.getVertex(Direction.IN).getId().toString());
if (this.edgeLabelKey.isPresent()) {
writer.writeStartElement(GraphMLTokens.DATA);
writer.writeAttribute(GraphMLTokens.KEY, this.edgeLabelKey.get());
writer.writeCharacters(edge.getLabel());
writer.writeEndElement();
} else {
// this will not comply with the graphml schema but is here so that the label is not
// mixed up with properties.
writer.writeAttribute(GraphMLTokens.LABEL, edge.getLabel());
}
final List<String> keys = new ArrayList<>();
keys.addAll(edge.getPropertyKeys());
Collections.sort(keys);
for (String key : keys) {
writer.writeStartElement(GraphMLTokens.DATA);
writer.writeAttribute(GraphMLTokens.KEY, key);
// technically there can't be a null here as Blueprints forbids that occurrence even if Graph
// implementations support it, but out to empty string just in case.
writer.writeCharacters(edge.getProperty(key).orElse("").toString());
writer.writeEndElement();
}
writer.writeEndElement();
}
} else {
for (Edge edge : graph.E().toList()) {
writer.writeStartElement(GraphMLTokens.EDGE);
writer.writeAttribute(GraphMLTokens.ID, edge.getId().toString());
writer.writeAttribute(GraphMLTokens.SOURCE, edge.getVertex(Direction.OUT).getId().toString());
writer.writeAttribute(GraphMLTokens.TARGET, edge.getVertex(Direction.IN).getId().toString());
writer.writeAttribute(GraphMLTokens.LABEL, edge.getLabel());
for (String key : edge.getPropertyKeys()) {
writer.writeStartElement(GraphMLTokens.DATA);
writer.writeAttribute(GraphMLTokens.KEY, key);
// technically there can't be a null here as Blueprints forbids that occurrence even if Graph
// implementations support it, but out to empty string just in case.
writer.writeCharacters(edge.getProperty(key).orElse("").toString());
writer.writeEndElement();
}
writer.writeEndElement();
}
}
}
private void writeVertices(final XMLStreamWriter writer) throws XMLStreamException {
final Iterable<Vertex> vertices = getVerticesAndNormalizeIfRequired();
for (Vertex vertex : vertices) {
writer.writeStartElement(GraphMLTokens.NODE);
writer.writeAttribute(GraphMLTokens.ID, vertex.getId().toString());
final Collection<String> keys = getElementKeysAndNormalizeIfRequired(vertex);
for (String key : keys) {
writer.writeStartElement(GraphMLTokens.DATA);
writer.writeAttribute(GraphMLTokens.KEY, key);
// technically there can't be a null here as Blueprints forbids that occurrence even if Graph
// implementations support it, but out to empty string just in case.
writer.writeCharacters(vertex.getProperty(key).orElse("").toString());
writer.writeEndElement();
}
writer.writeEndElement();
}
}
private Collection<String> getElementKeysAndNormalizeIfRequired(final Element element) {
final Collection<String> keys;
if (normalize) {
keys = new ArrayList<>();
keys.addAll(element.getPropertyKeys());
Collections.sort((List<String>) keys);
} else
keys = element.getPropertyKeys();
return keys;
}
private Iterable<Vertex> getVerticesAndNormalizeIfRequired() {
final Iterable<Vertex> vertices;
if (normalize) {
vertices = new ArrayList<>();
for (Vertex v : graph.V().toList()) {
((Collection<Vertex>) vertices).add(v);
}
Collections.sort((List<Vertex>) vertices, ELEMENT_COMPARATOR);
} else
vertices = graph.V().toList();
return vertices;
}
private Collection<String> getEdgeKeysAndNormalizeIfRequired(final Map<String, String> identifiedEdgeKeyTypes) {
final Collection<String> edgeKeySet;
if (normalize) {
edgeKeySet = new ArrayList<>();
edgeKeySet.addAll(identifiedEdgeKeyTypes.keySet());
Collections.sort((List<String>) edgeKeySet);
} else
edgeKeySet = identifiedEdgeKeyTypes.keySet();
return edgeKeySet;
}
private Collection<String> getVertexKeysAndNormalizeIfRequired(final Map<String, String> identifiedVertexKeyTypes) {
final Collection<String> keyset;
if (normalize) {
keyset = new ArrayList<>();
keyset.addAll(identifiedVertexKeyTypes.keySet());
Collections.sort((List<String>) keyset);
} else
keyset = identifiedVertexKeyTypes.keySet();
return keyset;
}
private void writeXmlNsAndSchema(final XMLStreamWriter writer) throws XMLStreamException {
writer.writeAttribute(GraphMLTokens.XMLNS, GraphMLTokens.GRAPHML_XMLNS);
//XML Schema instance namespace definition (xsi)
writer.writeAttribute(XMLConstants.XMLNS_ATTRIBUTE + ":" + GraphMLTokens.XML_SCHEMA_NAMESPACE_TAG,
XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI);
//XML Schema location
writer.writeAttribute(GraphMLTokens.XML_SCHEMA_NAMESPACE_TAG + ":" + GraphMLTokens.XML_SCHEMA_LOCATION_ATTRIBUTE,
GraphMLTokens.GRAPHML_XMLNS + " " + this.xmlSchemaLocation.orElse(GraphMLTokens.DEFAULT_GRAPHML_SCHEMA_LOCATION));
}
private Map<String, String> determineVertexTypes() {
final Map<String, String> vertexKeyTypes = new HashMap<>();
for (Vertex vertex : graph.V().toList()) {
for (String key : vertex.getPropertyKeys()) {
if (!vertexKeyTypes.containsKey(key)) {
vertexKeyTypes.put(key, GraphMLWriter.getStringType(vertex.getProperty(key).get()));
}
}
}
return vertexKeyTypes;
}
private Map<String, String> determineEdgeTypes() {
final Map<String, String> edgeKeyTypes = new HashMap<>();
for (Edge edge : graph.E().toList()) {
for (String key : edge.getPropertyKeys()) {
if (!edgeKeyTypes.containsKey(key))
edgeKeyTypes.put(key, GraphMLWriter.getStringType(edge.getProperty(key).get()));
}
}
return edgeKeyTypes;
}
private static String getStringType(final Object object) {
if (object instanceof String)
return GraphMLTokens.STRING;
else if (object instanceof Integer)
return GraphMLTokens.INT;
else if (object instanceof Long)
return GraphMLTokens.LONG;
else if (object instanceof Float)
return GraphMLTokens.FLOAT;
else if (object instanceof Double)
return GraphMLTokens.DOUBLE;
else if (object instanceof Boolean)
return GraphMLTokens.BOOLEAN;
else
return GraphMLTokens.STRING;
}
public static final class Builder {
private final Graph g;
private boolean normalize = false;
private Map<String, String> vertexKeyTypes = null;
private Map<String, String> edgeKeyTypes = null;
private String xmlSchemaLocation = null;
private String edgeLabelKey = null;
/**
* Constructs a GraphMLWriter.
*
* @param g The Graph instance to write out.
*/
public Builder(final Graph g) {
this.g = Optional.ofNullable(g).orElseThrow(() -> new IllegalArgumentException("Graph argument cannot be null"));
}
/**
* Normalized output is deterministic with respect to the order of elements and properties in the resulting
* XML document, and is compatible with line diff-based tools such as Git. Note: normalized output is
* memory-intensive and is not appropriate for very large graphs.
*
* @param normalize whether to normalize the output.
*/
public Builder setNormalize(final boolean normalize) {
this.normalize = normalize;
return this;
}
/**
* Map of the data types of the vertex keys.
*/
public Builder setVertexKeyTypes(final Map<String, String> vertexKeyTypes) {
this.vertexKeyTypes = vertexKeyTypes;
return this;
}
/**
* Map of the data types of the edge keys.
*/
public Builder setEdgeKeyTypes(final Map<String, String> edgeKeyTypes) {
this.edgeKeyTypes = edgeKeyTypes;
return this;
}
public Builder setXmlSchemaLocation(final String xmlSchemaLocation) {
this.xmlSchemaLocation = xmlSchemaLocation;
return this;
}
/**
* Set the name of the edge label in the GraphML. When this value is not set the value of the Edge.getLabel()
* is written as a "label" attribute on the edge element. This does not validate against the GraphML schema.
* If this value is set then the the value of Edge.getLabel() is written as a data element on the edge and
* the appropriate key element is added to define it in the GraphML
*
* @param edgeLabelKey if the label of an edge will be handled by the data property.
*/
public Builder setEdgeLabelKey(final String edgeLabelKey) {
this.edgeLabelKey = edgeLabelKey;
return this;
}
public GraphMLWriter build() {
return new GraphMLWriter(g, normalize, vertexKeyTypes, edgeKeyTypes, xmlSchemaLocation, edgeLabelKey);
}
}
}
|
package org.eclipse.hawkbit.amqp;
import java.util.Map;
import javax.validation.constraints.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.AmqpRejectAndDontRequeueException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.AbstractJavaTypeMapper;
import org.springframework.amqp.support.converter.MessageConversionException;
import org.springframework.amqp.support.converter.MessageConverter;
/**
* A base class which provide basis amqp staff.
*/
public class BaseAmqpService {
private static final Logger LOGGER = LoggerFactory.getLogger(BaseAmqpService.class);
private final RabbitTemplate rabbitTemplate;
/**
* Constructor.
*
* @param rabbitTemplate
* the rabbit template.
*/
public BaseAmqpService(final RabbitTemplate rabbitTemplate) {
this.rabbitTemplate = rabbitTemplate;
}
protected static void checkContentTypeJson(final Message message) {
final MessageProperties messageProperties = message.getMessageProperties();
if (messageProperties.getContentType() != null && messageProperties.getContentType().contains("json")) {
return;
}
throw new AmqpRejectAndDontRequeueException("Content-Type is not JSON compatible");
}
/**
* Is needed to convert a incoming message to is originally object type.
*
* @param message
* the message to convert.
* @param clazz
* the class of the originally object.
* @return the converted object
*/
@SuppressWarnings("unchecked")
public <T> T convertMessage(@NotNull final Message message, final Class<T> clazz) {
checkMessageBody(message);
message.getMessageProperties().getHeaders().put(AbstractJavaTypeMapper.DEFAULT_CLASSID_FIELD_NAME,
clazz.getName());
return (T) rabbitTemplate.getMessageConverter().fromMessage(message);
}
protected MessageConverter getMessageConverter() {
return rabbitTemplate.getMessageConverter();
}
private static boolean isMessageBodyEmpty(final Message message) {
return message.getBody() == null || message.getBody().length == 0;
}
protected void checkMessageBody(@NotNull final Message message) {
if (isMessageBodyEmpty(message)) {
throw new MessageConversionException("Message body cannot be null");
}
}
protected String getStringHeaderKey(final Message message, final String key, final String errorMessageIfNull) {
final Map<String, Object> header = message.getMessageProperties().getHeaders();
final Object value = header.get(key);
if (value == null) {
logAndThrowMessageError(message, errorMessageIfNull);
return null;
}
return value.toString();
}
protected static final void logAndThrowMessageError(final Message message, final String error) {
LOGGER.debug("Warning! \"{}\" reported by message: {}", error, message);
throw new AmqpRejectAndDontRequeueException(error);
}
protected RabbitTemplate getRabbitTemplate() {
return rabbitTemplate;
}
/**
* Clean message properties before sending a message.
*
* @param message
* the message to cleaned up
*/
protected void cleanMessageHeaderProperties(final Message message) {
message.getMessageProperties().getHeaders().remove(AbstractJavaTypeMapper.DEFAULT_CLASSID_FIELD_NAME);
}
}
|
package com.servinglynk.hmis.warehouse.dao;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.servinglynk.hmis.warehouse.base.util.ErrorType;
import com.servinglynk.hmis.warehouse.domain.ExportDomain;
import com.servinglynk.hmis.warehouse.domain.SyncDomain;
import com.servinglynk.hmis.warehouse.enums.DataCollectionStageEnum;
import com.servinglynk.hmis.warehouse.model.v2020.Enrollment;
import com.servinglynk.hmis.warehouse.model.v2020.Error2020;
import com.servinglynk.hmis.warehouse.model.v2020.HmisBaseModel;
import com.servinglynk.hmis.warehouse.util.BasicDataGenerator;
/**
* @author Sandeep
*
*/
public class MoveindateDaoImpl extends ParentDaoImpl implements MoveindateDao {
private static final Logger logger = LoggerFactory.getLogger(MoveindateDaoImpl.class);
@Override
public void hydrateStaging(ExportDomain domain , Map<String,HmisBaseModel> exportModelMap, Map<String,HmisBaseModel> relatedModelMap) throws Exception {
List<com.servinglynk.hmis.warehouse.domain.Sources.Source.Export.Moveindate> expMoveindate = domain.getExport().getMoveInDate();
com.servinglynk.hmis.warehouse.model.v2020.Export exportEntity = (com.servinglynk.hmis.warehouse.model.v2020.Export) getModel(com.servinglynk.hmis.warehouse.model.v2020.Export.class,String.valueOf(domain.getExport().getExportID()),getProjectGroupCode(domain),false,exportModelMap, domain.getUpload().getId());
Data data =new Data();
Map<String,HmisBaseModel> modelMap = getModelMap(com.servinglynk.hmis.warehouse.model.v2020.Moveindate.class, getProjectGroupCode(domain));
if(expMoveindate !=null && !expMoveindate.isEmpty())
{
for(com.servinglynk.hmis.warehouse.domain.Sources.Source.Export.Moveindate expMoveindates : expMoveindate)
{
com.servinglynk.hmis.warehouse.model.v2020.Moveindate moveindateModel = null;
try {
moveindateModel = getModelObject(domain, expMoveindates, data, modelMap);
moveindateModel.setMoveindate(BasicDataGenerator.getLocalDateTime(expMoveindates.getMoveInDate()));
//moveindateModel.setInpermanenthousing(MoveindateInpermanenthousin.lookupEnum((expMoveindates.getInPermanentHousing())));
moveindateModel.setSubmissionDate(BasicDataGenerator.getLocalDateTime(expMoveindates.getMoveInDate()));
moveindateModel.setDateCreated(BasicDataGenerator.getLocalDateTime(expMoveindates.getDateCreated()));
moveindateModel.setDateUpdated(BasicDataGenerator.getLocalDateTime(expMoveindates.getDateUpdated()));
Enrollment enrollmentModel = (Enrollment) getModel(Enrollment.class, expMoveindates.getEnrollmentID(),getProjectGroupCode(domain),true,relatedModelMap, domain.getUpload().getId());
moveindateModel.setEnrollmentid(enrollmentModel);
moveindateModel.setExport(exportEntity);
performSaveOrUpdate(moveindateModel,domain);
}catch(Exception e ){
String errorMessage = "Exception beause of the MoveInDate::"+expMoveindates.getMoveInDateID() +" Exception ::"+e.getMessage();
if(moveindateModel != null){
Error2020 error = new Error2020();
error.model_id = moveindateModel.getId();
error.bulk_upload_ui = domain.getUpload().getId();
error.project_group_code = domain.getUpload().getProjectGroupCode();
error.source_system_id = moveindateModel.getSourceSystemId();
error.type = ErrorType.ERROR;
error.error_description = errorMessage;
error.date_created = moveindateModel.getDateCreated();
performSave(error);
}
logger.error(errorMessage);
}
}
}
hydrateBulkUploadActivityStaging(data.i,data.j,data.ignore, com.servinglynk.hmis.warehouse.model.v2020.Moveindate.class.getSimpleName(), domain,exportEntity);
}
public com.servinglynk.hmis.warehouse.model.v2020.Moveindate getModelObject(ExportDomain domain, com.servinglynk.hmis.warehouse.domain.Sources.Source.Export.Moveindate expMoveInDate ,Data data, Map<String,HmisBaseModel> modelMap) {
com.servinglynk.hmis.warehouse.model.v2020.Moveindate modelFromDB = null;
// We always insert for a Full refresh and update if the record exists for Delta refresh
if(!isFullRefresh(domain))
modelFromDB = (com.servinglynk.hmis.warehouse.model.v2020.Moveindate) getModel(com.servinglynk.hmis.warehouse.model.v2020.Moveindate.class, expMoveInDate.getMoveInDateID(), getProjectGroupCode(domain),false,modelMap, domain.getUpload().getId());
if(domain.isReUpload()) {
if(modelFromDB != null) {
return modelFromDB;
}
modelFromDB = new com.servinglynk.hmis.warehouse.model.v2020.Moveindate();
modelFromDB.setId(UUID.randomUUID());
modelFromDB.setRecordToBeInserted(true);
return modelFromDB;
}
if(modelFromDB == null) {
modelFromDB = new com.servinglynk.hmis.warehouse.model.v2020.Moveindate();
modelFromDB.setId(UUID.randomUUID());
modelFromDB.setRecordToBeInserted(true);
}
com.servinglynk.hmis.warehouse.model.v2020.Moveindate model = new com.servinglynk.hmis.warehouse.model.v2020.Moveindate();
model.setDateUpdatedFromSource(BasicDataGenerator.getLocalDateTime(expMoveInDate.getDateUpdated()));
performMatch(domain, modelFromDB, model, data);
hydrateCommonFields(model, domain,expMoveInDate.getMoveInDateID(),data);
return model;
}
@Override
public void hydrateHBASE(SyncDomain syncDomain) {
// TODO Auto-generated method stub
}
@Override
public com.servinglynk.hmis.warehouse.model.v2020.Moveindate createMoveIdDate(com.servinglynk.hmis.warehouse.model.v2020.Moveindate moveIdDate) {
moveIdDate.setId(UUID.randomUUID());
insert(moveIdDate);
return moveIdDate;
}
@Override
public com.servinglynk.hmis.warehouse.model.v2020.Moveindate updateMoveIdDate(com.servinglynk.hmis.warehouse.model.v2020.Moveindate moveInDate) {
update(moveInDate);
return moveInDate;
}
@Override
public void deletemoveInDate(com.servinglynk.hmis.warehouse.model.v2020.Moveindate moveInDate) {
delete(moveInDate);
}
@SuppressWarnings("unchecked")
@Override
public com.servinglynk.hmis.warehouse.model.v2020.Moveindate getMoveInDateById(UUID moveInDateId) {
DetachedCriteria criteria = DetachedCriteria.forClass(com.servinglynk.hmis.warehouse.model.v2020.Moveindate.class);
criteria.add(Restrictions.eq("id", moveInDateId));
List<com.servinglynk.hmis.warehouse.model.v2020.Moveindate> moveInDate = (List<com.servinglynk.hmis.warehouse.model.v2020.Moveindate>) findByCriteria(criteria);
if(moveInDate.size()>0) return moveInDate.get(0);
return null;
}
@SuppressWarnings("unchecked")
@Override
public List<com.servinglynk.hmis.warehouse.model.v2020.Moveindate> getAllMoveInDate(UUID enrollmentId,Integer startIndex, Integer maxItems) {
DetachedCriteria criteria = DetachedCriteria.forClass(com.servinglynk.hmis.warehouse.model.v2020.Moveindate.class);
List<com.servinglynk.hmis.warehouse.model.v2020.Moveindate> moveInDate = (List<com.servinglynk.hmis.warehouse.model.v2020.Moveindate>) findByCriteria(criteria,startIndex,maxItems);
return moveInDate;
}
public long getMoveInDateCount(UUID enrollmentId){
DetachedCriteria criteria = DetachedCriteria.forClass(com.servinglynk.hmis.warehouse.model.v2020.Moveindate.class);
return countRows(criteria);
}
public List<com.servinglynk.hmis.warehouse.model.v2020.Moveindate> getAllEnrollmentResidentialmoveindates(UUID enrollmentId,Integer startIndex, Integer maxItems){
DetachedCriteria criteria=DetachedCriteria.forClass(com.servinglynk.hmis.warehouse.model.v2020.Moveindate.class);
criteria.createAlias("enrollmentid", "enrollmentid");
criteria.add(Restrictions.eq("enrollmentid.id", enrollmentId));
return (List<com.servinglynk.hmis.warehouse.model.v2020.Moveindate>) findByCriteria(criteria,startIndex,maxItems);
}
public long getEnrollmentResidentialmoveindatesCount(UUID enrollmentId){
DetachedCriteria criteria=DetachedCriteria.forClass(com.servinglynk.hmis.warehouse.model.v2020.Moveindate.class);
criteria.createAlias("enrollmentid", "enrollmentid");
criteria.add(Restrictions.eq("enrollmentid.id", enrollmentId));
return countRows(criteria);
}
}
|
package eu.amidst.huginlink.inference;
import eu.amidst.core.distribution.UnivariateDistribution;
import eu.amidst.core.inference.ImportanceSampling;
import eu.amidst.core.inference.messagepassing.VMP;
import eu.amidst.core.io.BayesianNetworkLoader;
import eu.amidst.core.models.BayesianNetwork;
import eu.amidst.core.utils.BayesianNetworkGenerator;
import eu.amidst.core.variables.Assignment;
import eu.amidst.core.variables.HashMapAssignment;
import eu.amidst.core.variables.Variable;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.math3.distribution.NormalDistribution;
import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
import static org.junit.Assert.assertTrue;
public class ImportanceSamplingExperiments {
private static Assignment randomEvidence(long seed, double evidenceRatio, BayesianNetwork bn, Variable varInterest) throws UnsupportedOperationException {
if (evidenceRatio<=0 || evidenceRatio>=1) {
throw new UnsupportedOperationException("Error: invalid ratio");
}
int numVariables = bn.getStaticVariables().getNumberOfVars();
Random random=new Random(seed); //1823716125
int numVarEvidence = (int) Math.ceil(numVariables*evidenceRatio); // Evidence on 20% of variables
//numVarEvidence = 0;
//List<Variable> varEvidence = new ArrayList<>(numVarEvidence);
double [] evidence = new double[numVarEvidence];
Variable aux;
HashMapAssignment assignment = new HashMapAssignment(2);
int[] indexesEvidence = new int[numVarEvidence+1];
indexesEvidence[0]=varInterest.getVarID();
//System.out.println(variable.getVarID());
//System.out.println("Evidence:");
for( int k=0; k<numVarEvidence; k++ ) {
int varIndex=-1;
do {
varIndex = random.nextInt( bn.getNumberOfVars() );
//System.out.println(varIndex);
aux = bn.getStaticVariables().getVariableById(varIndex);
double thisEvidence;
if (aux.isMultinomial()) {
thisEvidence = random.nextInt( aux.getNumberOfStates() );
}
else {
thisEvidence = random.nextGaussian();
}
evidence[k] = thisEvidence;
} while ( ArrayUtils.contains(indexesEvidence, varIndex) );
indexesEvidence[k+1]=varIndex;
//System.out.println(Arrays.toString(indexesEvidence));
//System.out.println("Variable " + aux.getName() + " = " + evidence[k]);
assignment.setValue(aux,evidence[k]);
}
//System.out.println();
return assignment;
}
/**
* The class constructor.
* @param args Array of options: "filename variable a b N useVMP" if variable is continuous or "filename variable w N useVMP" for discrete
*/
public static void main(String[] args) throws Exception {
/*
System.out.println(bn.toString());
System.out.println(bn.getDAG().toString());
*/
/*
System.out.println("Variable of interest: " + varname + " in interval (" + Double.toString(a) + "," + Double.toString(b) + ")");
System.out.println();
*/
/*
System.out.println("Execution time (VMP): " + Double.toString(execTimeVMP) + " seconds");
System.out.println("Execution time (IS-VMP): " + Double.toString(execTimeISVMP) + " seconds");
System.out.println("Execution time (IS): " + Double.toString(execTimeIS) + " seconds");
System.out.println("Execution time (IS-exact): " + Double.toString(execTimeISexact) + " seconds");
System.out.println("Execution time (HUGIN): " + Double.toString(execTimeHugin) + " seconds");
System.out.println();
*/
timeVMP[k]=execTimeVMP;
timeISVMP[k]=execTimeISVMP;
timeIS[k]=execTimeIS;
timeISexact[k]=execTimeISexact;
timeHUGIN[k]=execTimeHugin;
/*
System.out.println("Posterior of " + varInterest.getName() + " (VMP): " + posteriorVMP.toString());
System.out.println("Posterior of " + varInterest.getName() + " (IS-VMP): " + posteriorISVMP.toString());
System.out.println("Posterior of " + varInterest.getName() + " (IS): " + posteriorIS.toString());
System.out.println("Posterior of " + varInterest.getName() + " (IS-exact): " + posteriorISexact.toString());
System.out.println("Posterior of " + varInterest.getName() + " (HUGIN): " + posteriorHUGIN.toString());
System.out.println();
*/
/*
System.out.println("Query: P(" + Double.toString(a) + " < " + varInterest.getName() + " < " + Double.toString(b) + ")");
System.out.println("Probability (VMP): " + probVMP);
System.out.println("Probability (IS-VMP): " + probISVMP);
System.out.println("Probability (IS): " + probIS);
System.out.println("Probability (IS-exact): " + probISexact);
System.out.println("Probability (HUGIN): " + probHUGIN);
*/
probabilitiesVMP[k]=probVMP;
probabilitiesISVMP[k]=probISVMP;
probabilitiesIS[k]=probIS;
probabilitiesISexact[k]=probISexact;
probabilitiesHUGIN[k]=probHUGIN;
}
System.out.println("Number of variables" + nDiscrete+nContin);
System.out.println("Sample size:" + N);
System.out.println();
System.out.println("Execution Times: (VMP,IS-VMP,IS,IS-EXACT,HUGIN)");
System.out.println(Arrays.toString(timeVMP));
System.out.println(Arrays.toString(timeISVMP));
System.out.println(Arrays.toString(timeIS));
System.out.println(Arrays.toString(timeISexact));
System.out.println(Arrays.toString(timeHUGIN));
System.out.println();
System.out.println("Probabilities: (VMP,IS-VMP,IS,IS-EXACT,HUGIN)");
System.out.println(Arrays.toString(probabilitiesVMP));
System.out.println(Arrays.toString(probabilitiesISVMP));
System.out.println(Arrays.toString(probabilitiesIS));
System.out.println(Arrays.toString(probabilitiesISexact));
System.out.println(Arrays.toString(probabilitiesHUGIN));
System.out.println();
double meanTimeVMP = Arrays.stream(timeVMP).average().getAsDouble();
double meanTimeISVMP = Arrays.stream(timeISVMP).average().getAsDouble();
double meanTimeIS = Arrays.stream(timeIS).average().getAsDouble();
double meanTimeISexact = Arrays.stream(timeISexact).average().getAsDouble();
double meanTimeHUGIN = Arrays.stream(timeHUGIN).average().getAsDouble();
/*
double [] chi2errorVMP = new double[REP];
double [] chi2errorISVMP = new double[REP];
double [] chi2errorIS = new double[REP];
double [] chi2errorHUGIN = new double[REP];
for(int k=0; k<REP; k++) {
chi2errorVMP[k] = Math.pow(probabilitiesVMP[k] - probabilitiesISexact[k],2) /probabilitiesISexact[k];
chi2errorISVMP[k] = Math.pow(probabilitiesISVMP[k] - probabilitiesISexact[k],2) /probabilitiesISexact[k];
chi2errorIS[k] = Math.pow(probabilitiesIS[k] - probabilitiesISexact[k],2) /probabilitiesISexact[k];
chi2errorHUGIN[k] = Math.pow(probabilitiesHUGIN[k] - probabilitiesISexact[k],2) /probabilitiesISexact[k];
}
*/
double meanErrorVMP = IntStream.range(0, REP).mapToDouble(k-> Math.pow(probabilitiesVMP[k]-probabilitiesISexact[k],2)/probabilitiesISexact[k]).average().getAsDouble();
double meanErrorISVMP = IntStream.range(0, REP).mapToDouble(k-> Math.pow(probabilitiesISVMP[k]-probabilitiesISexact[k],2)/probabilitiesISexact[k]).average().getAsDouble();
double meanErrorIS = IntStream.range(0, REP).mapToDouble(k-> Math.pow(probabilitiesIS[k]-probabilitiesISexact[k],2)/probabilitiesISexact[k]).average().getAsDouble();
double meanErrorHUGIN = IntStream.range(0, REP).mapToDouble(k-> Math.pow(probabilitiesHUGIN[k]-probabilitiesISexact[k],2)/probabilitiesISexact[k]).average().getAsDouble();
System.out.println("Mean time: (VMP,IS-VMP,IS,IS-exact,HUGIN)");
System.out.println(meanTimeVMP);
System.out.println(meanTimeISVMP);
System.out.println(meanTimeIS);
System.out.println(meanTimeISexact);
System.out.println(meanTimeHUGIN);
System.out.println();
System.out.println("Mean chi2 error: (VMP,IS-VMP,IS,HUGIN), w.r.t. IS-exact");
System.out.println(meanErrorVMP);
System.out.println(meanErrorISVMP);
System.out.println(meanErrorIS);
System.out.println(meanErrorHUGIN);
}
}
|
package org.innovateuk.ifs.finance.domain;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.innovateuk.ifs.application.domain.Application;
import org.innovateuk.ifs.category.domain.ApplicationFinanceResearchCategoryLink;
import org.innovateuk.ifs.category.domain.ResearchCategory;
import org.innovateuk.ifs.file.domain.FileEntry;
import org.innovateuk.ifs.user.domain.Organisation;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
/**
* ApplicationFinance defines database relations and a model to use client side and server side.
*/
@Entity
public class ApplicationFinance extends Finance {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="applicationId", referencedColumnName="id")
private Application application;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="financeFileEntryId", referencedColumnName="id")
private FileEntry financeFileEntry;
@OneToMany(mappedBy = "applicationFinance", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<ApplicationFinanceResearchCategoryLink> researchCategories = new HashSet<>();
public ApplicationFinance() {
// no-arg constructor
}
public ApplicationFinance(Application application, Organisation organisation) {
super(organisation);
this.application = application;
}
public ApplicationFinance(long id, Application application, Organisation organisation) {
super(id, organisation);
this.application = application;
}
@JsonIgnore
public Application getApplication() {
return application;
}
public FileEntry getFinanceFileEntry() {
return financeFileEntry;
}
public void setFinanceFileEntry(FileEntry financeFileEntry) {
this.financeFileEntry = financeFileEntry;
}
public void setApplication(Application application) {
this.application = application;
}
public Set<ResearchCategory> getResearchCategories() {
return researchCategories.stream().map(ApplicationFinanceResearchCategoryLink::getCategory).collect(Collectors.toSet());
}
public void addResearchCategory(ResearchCategory researchCategory) {
researchCategories.clear();
researchCategories.add(new ApplicationFinanceResearchCategoryLink(this, researchCategory));
}
}
|
package com.almasb.fxgl.physics.box2d.common;
import com.almasb.fxgl.core.math.Vec2;
import java.io.Serializable;
/**
* A 2-by-2 matrix. Stored in column-major order.
*/
public final class Mat22 implements Serializable {
private static final long serialVersionUID = 2L;
// [ ex.x ey.x ]
// [ ex.y ey.y ]
public final Vec2 ex = new Vec2();
public final Vec2 ey = new Vec2();
/**
* Set as the zero matrix.
*/
public void setZero() {
ex.x = 0.0f;
ey.x = 0.0f;
ex.y = 0.0f;
ey.y = 0.0f;
}
public void invertToOut(Mat22 out) {
float a = ex.x;
float b = ey.x;
float c = ex.y;
float d = ey.y;
float det = a * d - b * c;
det = 1.0f / det;
out.ex.x = det * d;
out.ey.x = -det * b;
out.ex.y = -det * c;
out.ey.y = det * a;
}
public void solveToOut(Vec2 b, Vec2 out) {
float a11 = ex.x;
float a12 = ey.x;
float a21 = ex.y;
float a22 = ey.y;
float det = a11 * a22 - a12 * a21;
if (det != 0.0f) {
det = 1.0f / det;
}
float tempy = det * (a11 * b.y - a21 * b.x);
out.x = det * (a22 * b.x - a12 * b.y);
out.y = tempy;
}
public static void mulToOutUnsafe(Mat22 R, Vec2 v, Vec2 out) {
out.x = R.ex.x * v.x + R.ey.x * v.y;
out.y = R.ex.y * v.x + R.ey.y * v.y;
}
@Override
public int hashCode() {
int prime = 31;
int result = 1;
result = prime * result + ex.hashCode();
result = prime * result + ey.hashCode();
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
Mat22 other = (Mat22) obj;
if (ex == null) {
if (other.ex != null) return false;
} else if (!ex.equals(other.ex)) return false;
if (ey == null) {
if (other.ey != null) return false;
} else if (!ey.equals(other.ey)) return false;
return true;
}
@Override
public String toString() {
return "[" + ex.x + "," + ey.x + "]\n"
+"[" + ex.y + "," + ey.y + "]";
}
}
|
package org.sagebionetworks;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.sagebionetworks.client.Synapse;
import org.sagebionetworks.client.exceptions.SynapseException;
import org.sagebionetworks.repo.model.PaginatedResults;
import org.sagebionetworks.repo.model.UserGroup;
import org.sagebionetworks.repo.model.UserProfile;
import org.sagebionetworks.repo.model.search.Hit;
import org.sagebionetworks.repo.model.search.SearchResults;
import org.sagebionetworks.repo.model.search.query.KeyValue;
import org.sagebionetworks.repo.model.search.query.SearchQuery;
/**
* Run this integration test as a sanity check to ensure our Synapse Java Client
* is working
*
* @author deflaux
*/
@Ignore
public class IT510SynapseJavaClientSearchTest {
private static Synapse synapse = null;
/**
* @throws Exception
*
*/
@BeforeClass
public static void beforeClass() throws Exception {
synapse = new Synapse();
synapse.setAuthEndpoint(StackConfiguration
.getAuthenticationServicePrivateEndpoint());
synapse.setRepositoryEndpoint(StackConfiguration
.getRepositoryServiceEndpoint());
synapse.login(StackConfiguration.getIntegrationTestUserOneName(),
StackConfiguration.getIntegrationTestUserOnePassword());
}
/**
* @throws Exception
*/
@Test
public void testSearch() throws Exception {
SearchQuery searchQuery = new SearchQuery();
List<String> queryTerms = new ArrayList<String>();
queryTerms.add("cancer");
searchQuery.setQueryTerm(queryTerms);
List<String> returnFields = new ArrayList<String>();
returnFields.add("id");
returnFields.add("name");
searchQuery.setReturnFields(returnFields);
SearchResults results = synapse.search(searchQuery);
assertTrue(10 < results.getFound());
}
/**
* @throws Exception
*/
@Test
public void testAllReturnFields() throws Exception {
SearchQuery searchQuery = new SearchQuery();
List<String> queryTerms = new ArrayList<String>();
queryTerms.add("syn4494");
searchQuery.setQueryTerm(queryTerms);
List<String> returnFields = new ArrayList<String>();
returnFields.add("id");
returnFields.add("name");
returnFields.add("path");
returnFields.add("description");
returnFields.add("etag");
returnFields.add("modified_on");
returnFields.add("created_on");
returnFields.add("num_samples");
returnFields.add("created_by_r");
returnFields.add("modified_by_r");
returnFields.add("node_type_r");
returnFields.add("disease_r");
returnFields.add("tissue_r");
searchQuery.setReturnFields(returnFields);
SearchResults results = synapse.search(searchQuery);
assertTrue(new Long(0) < results.getFound());
Hit hit = results.getHits().get(0);
assertNotNull(hit.getId());
assertNotNull(hit.getName());
assertNotNull(hit.getPath());
assertNotNull(hit.getDescription());
assertNotNull(hit.getEtag());
assertNotNull(hit.getModified_on());
assertNotNull(hit.getCreated_on());
assertNotNull(hit.getNum_samples());
assertNotNull(hit.getCreated_by());
assertNotNull(hit.getModified_by());
assertNotNull(hit.getNode_type());
assertNotNull(hit.getDisease());
assertNotNull(hit.getTissue());
}
/**
* @throws Exception
*/
@Test
public void testFacetedSearch() throws Exception {
SearchQuery searchQuery = new SearchQuery();
List<String> queryTerms = new ArrayList<String>();
queryTerms.add("cancer");
searchQuery.setQueryTerm(queryTerms);
List<String> returnFields = new ArrayList<String>();
returnFields.add("id");
returnFields.add("name");
returnFields.add("description");
searchQuery.setReturnFields(returnFields);
List<String> facets = new ArrayList<String>();
facets.add("node_type");
facets.add("disease");
facets.add("species");
facets.add("tissue");
facets.add("platform");
facets.add("num_samples");
facets.add("created_by");
facets.add("modified_by");
facets.add("created_on");
facets.add("modified_on");
facets.add("acl");
facets.add("reference");
searchQuery.setFacet(facets);
SearchResults results = synapse.search(searchQuery);
assertNotNull(results.getHits().get(0).getName());
assertNotNull(results.getFacets());
assertTrue(11 <= results.getFacets().size());
}
/**
* @throws Exception
*/
@Test
public void testNoResultsFacetedSearch() throws Exception {
SearchQuery searchQuery = new SearchQuery();
List<String> queryTerms = new ArrayList<String>();
queryTerms.add("cancer");
searchQuery.setQueryTerm(queryTerms);
List<String> returnFields = new ArrayList<String>();
returnFields.add("id");
returnFields.add("name");
returnFields.add("description");
searchQuery.setReturnFields(returnFields);
List<String> facets = new ArrayList<String>();
facets.add("node_type");
facets.add("disease");
facets.add("species");
facets.add("tissue");
facets.add("platform");
facets.add("num_samples");
facets.add("created_by");
facets.add("modified_by");
facets.add("created_on");
facets.add("modified_on");
facets.add("acl");
facets.add("reference");
searchQuery.setFacet(facets);
KeyValue doesNotExist = new KeyValue();
doesNotExist.setKey("node_type");
doesNotExist.setValue("DoesNotExist");
List<KeyValue> booleanQuery = new ArrayList<KeyValue>();
booleanQuery.add(doesNotExist);
searchQuery.setBooleanQuery(booleanQuery);
SearchResults results = synapse.search(searchQuery);
assertEquals(new Long(0), results.getFound());
assertEquals(0, results.getHits().size());
assertEquals(0, results.getFacets().size());
}
/**
* @throws Exception
*/
@Test
public void testMultiWordFreeTextSearch() throws Exception {
SearchQuery searchQuery = new SearchQuery();
List<String> queryTerms = new ArrayList<String>();
queryTerms.add("prostate cancer");
searchQuery.setQueryTerm(queryTerms);
List<String> returnFields = new ArrayList<String>();
returnFields.add("name");
searchQuery.setReturnFields(returnFields);
KeyValue booleanQueryClause = new KeyValue();
booleanQueryClause.setKey("node_type");
booleanQueryClause.setValue("study");
List<KeyValue> booleanQuery = new ArrayList<KeyValue>();
booleanQuery.add(booleanQueryClause);
searchQuery.setBooleanQuery(booleanQuery);
SearchResults results = synapse.search(searchQuery);
assertTrue(1 <= results.getFound());
// try url-escaped space too
queryTerms = new ArrayList<String>();
queryTerms.add("prostate+cancer");
searchQuery.setQueryTerm(queryTerms);
results = synapse.search(searchQuery);
assertTrue(1 <= results.getFound());
}
/**
* @throws Exception
*/
@Test
public void testBooleanQuerySearch() throws Exception {
SearchQuery searchQuery = new SearchQuery();
List<String> queryTerms = new ArrayList<String>();
queryTerms.add("cancer");
searchQuery.setQueryTerm(queryTerms);
List<String> returnFields = new ArrayList<String>();
returnFields.add("name");
searchQuery.setReturnFields(returnFields);
KeyValue booleanQueryClause = new KeyValue();
booleanQueryClause.setKey("node_type");
booleanQueryClause.setValue("study");
List<KeyValue> booleanQuery = new ArrayList<KeyValue>();
booleanQuery.add(booleanQueryClause);
searchQuery.setBooleanQuery(booleanQuery);
SearchResults results = synapse.search(searchQuery);
assertTrue(1 <= results.getFound());
}
/**
* @throws Exception
*/
@Test
public void testParentIdBooleanQuerySearch() throws Exception {
SearchQuery searchQuery = new SearchQuery();
KeyValue booleanQueryClause = new KeyValue();
booleanQueryClause.setKey("parent_id");
booleanQueryClause.setValue("syn4492");
List<KeyValue> booleanQuery = new ArrayList<KeyValue>();
booleanQuery.add(booleanQueryClause);
searchQuery.setBooleanQuery(booleanQuery);
SearchResults results = synapse.search(searchQuery);
assertTrue(5 <= results.getFound());
}
/**
* @throws Exception
*/
@Ignore
@Test
public void testUpdateACLBooleanQuerySearch() throws Exception {
SearchQuery searchQuery = new SearchQuery();
KeyValue booleanQueryClause = new KeyValue();
booleanQueryClause.setKey("update_acl");
booleanQueryClause.setValue("Sage Curators");
List<KeyValue> booleanQuery = new ArrayList<KeyValue>();
booleanQuery.add(booleanQueryClause);
searchQuery.setBooleanQuery(booleanQuery);
SearchResults results = synapse.search(searchQuery);
assertTrue(1 <= results.getFound());
}
private static String getGroupPrincipalIdFromGroupName(String groupName) throws SynapseException {
PaginatedResults<UserGroup> paginated = synapse.getGroups(0,100);
int total = (int)paginated.getTotalNumberOfResults();
List<UserGroup> groups = paginated.getResults();
if (groups.size()<total) throw new RuntimeException("System has "+total+" total users but we've only retrieved "+groups.size());
for (UserGroup group : groups) {
if (group.getName().equalsIgnoreCase(groupName)) return group.getId();
}
throw new RuntimeException("Cannot find "+groupName+" among groups.");
}
/**
* @throws Exception
*/
@Test
public void testSearchAuthorizationFilter() throws Exception {
UserProfile myProfile = synapse.getMyProfile();
assertNotNull(myProfile);
String myPrincipalId = myProfile.getOwnerId();
assertNotNull(myPrincipalId);
SearchQuery searchQuery = new SearchQuery();
List<String> queryTerms = new ArrayList<String>();
queryTerms.add("cancer");
searchQuery.setQueryTerm(queryTerms);
List<String> returnFields = new ArrayList<String>();
returnFields.add("name");
searchQuery.setReturnFields(returnFields);
SearchResults results = synapse.search(searchQuery);
String cloudSearchMatchExpr = results.getMatchExpression();
assertTrue(-1 < cloudSearchMatchExpr.indexOf("(or acl:"));
assertTrue(-1 < cloudSearchMatchExpr
.indexOf("acl:'" + myPrincipalId + "'"));
assertTrue(-1 < cloudSearchMatchExpr
.indexOf("acl:'"+getGroupPrincipalIdFromGroupName("AUTHENTICATED_USERS")+"'"));
assertTrue(-1 < cloudSearchMatchExpr.indexOf("acl:'"+getGroupPrincipalIdFromGroupName("PUBLIC")+"'"));
}
/**
* @throws Exception
*/
@Test
public void testAnonymousSearchAuthorizationFilter() throws Exception {
synapse.login(StackConfiguration.getIntegrationTestUserOneName(),
StackConfiguration.getIntegrationTestUserOnePassword());
String publicPrincipalId = getGroupPrincipalIdFromGroupName("PUBLIC");
// now 'log out'
synapse.setSessionToken(null);
SearchQuery searchQuery = new SearchQuery();
List<String> queryTerms = new ArrayList<String>();
queryTerms.add("prostate");
searchQuery.setQueryTerm(queryTerms);
List<String> returnFields = new ArrayList<String>();
returnFields.add("name");
searchQuery.setReturnFields(returnFields);
SearchResults results = synapse.search(searchQuery);
String cloudSearchMatchExpr = results.getMatchExpression();
assertTrue(-1 < cloudSearchMatchExpr.indexOf("(or acl:"));
// TODO reenable the following line, which depends on how the 'display name' for 'anonymous' is configured
//assertTrue(-1 < cloudSearchMatchExpr.indexOf("acl:'anonymous@sagebase.org'", 0));
assertTrue(-1 < cloudSearchMatchExpr.indexOf("acl:'"+publicPrincipalId+"'"));
// We are reusing this client, so restore the prior logged in user
synapse.login(StackConfiguration.getIntegrationTestUserOneName(),
StackConfiguration.getIntegrationTestUserOnePassword());
}
/**
* @throws Exception
*/
@Test
public void testAdminSearchAuthorizationFilter() throws Exception {
// Login as an administrator
synapse.login(StackConfiguration.getIntegrationTestUserAdminName(),
StackConfiguration.getIntegrationTestUserAdminPassword());
SearchQuery searchQuery = new SearchQuery();
List<String> queryTerms = new ArrayList<String>();
queryTerms.add("prostate");
searchQuery.setQueryTerm(queryTerms);
List<String> returnFields = new ArrayList<String>();
returnFields.add("name");
searchQuery.setReturnFields(returnFields);
SearchResults results = synapse.search(searchQuery);
String cloudSearchMatchExpr = results.getMatchExpression();
// We don't add an authorization filter for admin users
assertEquals(-1, cloudSearchMatchExpr.indexOf("acl"));
// We are reusing this client, so restore the prior logged in user
synapse.login(StackConfiguration.getIntegrationTestUserOneName(),
StackConfiguration.getIntegrationTestUserOnePassword());
}
/**
* @throws Exception
*/
@Test
public void testDescription() throws Exception {
// When descriptions are not null, make sure they are not just an empty
// json array (this was an old bug)
SearchQuery searchQuery = new SearchQuery();
List<String> returnFields = new ArrayList<String>();
returnFields.add("description");
searchQuery.setReturnFields(returnFields);
KeyValue booleanQueryClause = new KeyValue();
booleanQueryClause.setKey("node_type");
booleanQueryClause.setValue("*");
List<KeyValue> booleanQuery = new ArrayList<KeyValue>();
booleanQuery.add(booleanQueryClause);
searchQuery.setBooleanQuery(booleanQuery);
SearchResults results = synapse.search(searchQuery);
assertTrue(1 <= results.getFound());
for (Hit hit : results.getHits()) {
String description = hit.getDescription();
if (null != description) {
assertFalse("[]".equals(description));
}
}
}
}
|
package org.intermine.webservice.client.lists;
import java.util.AbstractSet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import static org.apache.commons.collections.CollectionUtils.collect;
import static org.apache.commons.collections.TransformerUtils.invokerTransformer;
import static org.apache.commons.collections.TransformerUtils.stringValueTransformer;
import org.intermine.pathquery.Constraints;
import org.intermine.pathquery.PathQuery;
import org.intermine.webservice.client.core.ServiceFactory;
import org.intermine.webservice.client.results.Item;
import org.intermine.webservice.client.services.ListService.ListCreationInfo;
import org.intermine.webservice.client.services.ListService.ListOperationInfo;
import org.intermine.webservice.client.util.PQUtil;
/**
* A representation of a list of objects stored on the server.
*
* The object is not meant to be directly instantiated nor modified. Rather it
* should be retrieved from the originating web-service, and only modified through
* the available methods (appending new items, and renaming the list).
*
* See {@link InterMineBag}
* @author Alex Kalderimis
*/
public class ItemList extends AbstractSet<Item> implements Iterable<Item>
{
private final ServiceFactory services;
private String name;
private int size;
private String type;
private String description;
private String status;
private List<String> tags;
private boolean authorized;
private Date createdAt;
private Set<String> unmatchedIds = new HashSet<String>();
private List<Item> items = null;
/**
* Get the identifiers used in creating or appending to this list that
* could not be resolved to any objects. This set will be updated
* whenever new requests are made to append to this list.
* @return A set of unmatched identifiers.
*/
public Set<String> getUnmatchedIdentifiers() {
return new HashSet<String>(unmatchedIds);
}
/**
* Get the date when this list was created.
* @return The list's creation date.
*/
public Date getCreatedAt() {
return createdAt;
}
/**
* Add a new unmatched id to the set of unmatched identifiers.
*
* This is meant for use by the service modules.
* @param id The id to add.
*/
protected void addUnmatchedId(String id) {
unmatchedIds.add(id);
}
/**
* Add some new unmatched ids to the set of unmatched identifiers.
*
* This is meant for use by the service modules.
* @param ids the ids to add.
*/
public void addUnmatchedIds(Collection<String> ids) {
unmatchedIds.addAll(ids);
}
/**
* @return Whether the current user has the authority to modify this list.
*/
public boolean isAuthorized() {
return authorized;
}
/**
* Modifying the returned set will not change the underlying tags collection.
* @return the tags this list has.
*/
public Set<String> getTags() {
return new HashSet<String>(tags);
}
/**
* Make sure that the tags on this object are up-to-date with those
* stored on the server.
*/
public void updateTags() {
tags = services.getListService().getTags(this);
}
/**
* Add some new tags to this list. After adding, list will have an
* updated set of tags, and the tags will be stored on the server.
* @param newTags The tags to add.
*/
public void addTags(String... newTags) {
tags = services.getListService().addTags(this, newTags);
}
/**
* Remove some tags from this list. After removing, the list will have
* an updated set of tags, and the tags will be synchronised with those on
* the server.
* @param removeThese The tags to remove.
*/
public void removeTags(String... removeThese) {
tags = services.getListService().removeTags(this, removeThese);
}
/**
* Get the name of this list.
* @return The list's name.
*/
public String getName() {
return name;
}
/**
* @return the number of items in this list.
*/
public int getSize() {
return size;
}
/**
* Synonym for getSize()
* @return the size of the list.
**/
@Override
public int size() {
return getSize();
}
/**
* @return return the type of the list.
*/
public String getType() {
return type;
}
/**
* @return The description of the list, or null.
*/
public String getDescription() {
return description;
}
/**
* Any status other than <code>CURRENT</code>
* indicated this list needs manual attention in the
* webapp.
* @return the current status if the list.
*/
public String getStatus() {
return status;
}
/**
* Construct the ItemList object.
*
* @param fac A reference to the ServiceFactory for the web-service.
* @param name The name of the list.
* @param desc The list's description.
* @param size The number of objects in the list.
* @param type The class of the objects in the list.
* @param tags The tags this list is associated with.
* @param authorized Whether the user can modify this list.
* @param createdAt When the list was created.
* @param status The upgrade status of the list.
*/
ItemList(ServiceFactory fac, String name, String desc, int size,
String type, List<String> tags, boolean authorized, Date createdAt, String status) {
assert (name != null);
assert (type != null);
this.services = fac;
this.name = name;
this.description = desc;
this.size = size;
this.type = type;
this.tags = tags;
this.authorized = authorized;
this.createdAt = createdAt;
this.status = status;
}
@Override
public String toString() {
return name + " (" + description + " - " + size + " " + type
+ "s) created at: " + createdAt + ", tags: " + tags
+ ", authorized: " + authorized;
}
private List<Item> getItems() {
if (items == null) {
items = new ArrayList<Item>();
for (Item i: this) {
items.add(i);
}
}
return items;
}
/**
* Get an item by its index. Note that while the order of elements is
* determinate, it is difficult to predict what that order may be.
*
* @param index The index of the element to get.
* @return an Item representing one of the elements in the list.
*/
public Item get(int index) {
return getItems().get(index);
}
private void update(ItemList updated) {
items = null;
this.size = updated.size();
this.unmatchedIds.addAll(updated.getUnmatchedIdentifiers());
}
/**
* Add new items to the list by resolving the identifiers of objects.
*
* This method will update the size of the list, and clear the items cache.
* @param ids The identifiers to use to find objects to add.
*/
public void append(String... ids) {
update(services.getListService().append(this, ids));
}
/**
* Add new items to the list by resolving the identifiers of objects.
*
* This method will update the size of the list, and clear the items cache.
* @param ids The identifiers to use to find objects to add.
**/
public void append(Collection<? extends String> ids) {
update(services.getListService().append(this, ids.toArray(new String[ids.size()])));
}
/**
* Add new items to the list.
*
* This method will update the size of the list, and clear the items cache.
* @param items The items to add.
**/
public void append(Item... items) {
appendItems(Arrays.asList(items));
}
/**
* Add new items to the list by resolving the identifiers of objects.
*
* This method will update the size of the list, and clear the items cache.
* @param pq The query to run to find objects with.
**/
public void append(PathQuery pq) {
update(services.getListService().append(this, pq));
}
@Override
public boolean add(Item i) {
return addAll(Arrays.asList(i));
}
@SuppressWarnings("unchecked")
@Override
public boolean addAll(@SuppressWarnings("rawtypes") Collection items) {
int priorSize = getSize();
appendItems(items);
return priorSize != getSize();
}
/**
* Add items to this list by using a query.
* @param items The items to add to the list.
*/
private void appendItems(Iterable<Item> items) {
PathQuery pq = new PathQuery(services.getModel());
pq.addViews(getType() + ".id");
Set<String> values = new HashSet<String>();
for (Item i: items) {
values.add(Integer.toString(i.getId()));
}
pq.addConstraint(Constraints.oneOfValues(getType() + ".id", values));
update(services.getListService().append(this, pq));
}
// -- SUBTRACTION
@Override
public boolean remove(Object i) {
int priorSize = getSize();
if (i instanceof Item) {
Item item = (Item) i;
String path = item.getType() + ".id";
PathQuery pq = new PathQuery(services.getModel());
pq.addView(path);
pq.addConstraint(Constraints.eq(path, Integer.toString(item.getId())));
createListAndSubtract(pq);
}
return priorSize != getSize();
}
@SuppressWarnings("unchecked")
@Override
public boolean removeAll(@SuppressWarnings("rawtypes") Collection c) {
int priorSize = getSize();
if (c instanceof ItemList) {
ItemList res = subtract(((ItemList) c));
update(res);
delete();
res.rename(getName());
} else if (!c.isEmpty()) {
try {
Item[] is = (Item[]) c.toArray(new Item[0]);
String path = is[0].getType() + ".id";
PathQuery pq = new PathQuery(services.getModel());
pq.addView(path);
pq.addConstraint(Constraints.oneOfValues(path, collect(
collect(Arrays.asList(is), invokerTransformer("getId")),
stringValueTransformer())));
createListAndSubtract(pq);
} catch (ArrayStoreException e) {
// Do nothing - we didn't get a collection of items.
}
}
return priorSize != getSize();
}
private void createListAndSubtract(PathQuery pq) {
ListCreationInfo info = services.getListService().new ListCreationInfo(pq);
ItemList removalList = null;
try {
removalList = services.getListService().createList(info);
ItemList res = subtract(removalList);
update(res);
delete();
res.rename(getName());
} finally {
try {
removalList.delete();
} catch (Exception e) {
// Ignore
}
}
}
/**
* Call for this list to be deleted on the server. As soon as the call returns,
* this list should no longer be used for any operation.
*/
public void delete() {
services.getListService().deleteList(this);
}
/**
* Remove the items in the given lists from this list.
*
* This call performs the operation of asymmetric difference on the current list
* and returns the result. For operations that alter the
* current list see {@link #removeAll(Collection)}
* @param lists The lists to subtract from this list.
* @return A new list
*/
public ItemList subtract(ItemList... lists) {
return services.getListService().subtract(
Collections.singleton(this), Arrays.asList(lists));
}
/**
* Remove the items in the given lists from this list.
*
* This call performs the operation of asymmetric difference on the current list
* and returns the result. For operations that alter the
* current list see {@link #removeAll(Collection)}
* @param lists The lists to subtract from this list.
* @param info The options describing the new list.
* @return A new list
*/
public ItemList subtract(ListOperationInfo info, ItemList... lists) {
return services.getListService().subtract(info,
Collections.singleton(this), Arrays.asList(lists));
}
/**
* Remove the items in the given lists from this list.
*
* This call performs the operation of asymmetric difference on the current list
* and returns the result. For operations that alter the
* current list see {@link #removeAll(Collection)}
* @param lists The lists to subtract from this list.
* @return A new list
*/
public ItemList subtract(Collection<ItemList> lists) {
return services.getListService().subtract(Collections.singleton(this), lists);
}
/**
* Remove the items in the given lists from this list.
*
* This call performs the operation of asymmetric difference on the current list
* and returns the result. For operations that alter the
* current list see {@link #removeAll(Collection)}
* @param lists The lists to subtract from this list.
* @param info The options describing the new list.
* @return A new list
*/
public ItemList subtract(ListOperationInfo info, Collection<ItemList> lists) {
return services.getListService().subtract(info, Collections.singleton(this), lists);
}
// -- RENAMING
/**
* Rename this list on the server.
*
* This method will update the name of the list stored on the server, and
* also change of the name returned by this object.
* @param newName The new name to give this list.
*/
public void rename(String newName) {
ItemList updated = services.getListService().rename(this, newName);
this.name = updated.getName();
}
@Override
public boolean contains(Object o) {
if (o == null) {
return false;
}
if (o instanceof Item) {
Item i = (Item) o;
return containsAll(Arrays.asList(i));
}
return false;
}
@SuppressWarnings("unchecked")
@Override
public boolean containsAll(@SuppressWarnings("rawtypes") Collection c) {
if (c == null) {
return false;
}
Item[] candidates;
try {
candidates = (Item[]) c.toArray(new Item[c.size()]);
} catch (ArrayStoreException e) {
return false;
}
return services.getListService().contains(this, candidates);
}
/**
* Convenience method for finding members of a collection matching certain properties.
*
* This search is implemented with a query that performs case-insensitive matching on values.
* Null constraints will be honoured, but other lookups will be converted to strings. Wild-cards
* are permitted wherever they are permitted in path-queries.
* <br/>
* Using a query to back the search means that finding matching members is efficient even over
* large lists - you will not need to pull in and iterate over thousands of rows of data to find
* items if you have specific conditions.
* <br/>
* These conditions must all match for the result to be included. For more specific and flexible
* searching strategies, please see the {@link PathQuery} API.
*
* @param conditions The properties these elements should have.
* @return A list of matching items.
*/
public List<Item> find(Map<String, Object> conditions) {
List<Item> ret = new ArrayList<Item>();
PathQuery q = new PathQuery(services.getModel());
q.addViews(PQUtil.getStar(services.getModel(), type));
q.addConstraint(Constraints.in(type, name));
for (Entry<String, Object> condition: conditions.entrySet()) {
String path = type + "." + condition.getKey();
if (condition.getValue() == null) {
q.addConstraint(Constraints.isNull(path));
} else {
q.addConstraint(Constraints.eq(path, condition.getValue().toString()));
}
}
List<Map<String, Object>> results = services.getQueryService().getRowsAsMaps(q);
for (Map<String, Object> result: results) {
ret.add(new Item(services, type, result));
}
return ret;
}
@Override
public Iterator<Item> iterator() {
PathQuery pq = new PathQuery(services.getModel());
pq.addViews(PQUtil.getStar(services.getModel(), getType()));
pq.addConstraint(Constraints.in(type, name));
Iterator<Map<String, Object>> it = services.getQueryService().getRowMapIterator(pq);
return new ItemIterator(it);
}
private class ItemIterator implements Iterator<Item>
{
Iterator<Map<String, Object>> results;
ItemIterator(Iterator<Map<String, Object>> results) {
this.results = results;
}
@Override
public boolean hasNext() {
return results.hasNext();
}
@Override
public Item next() {
return new Item(services, type, results.next());
}
@Override
public void remove() {
throw new UnsupportedOperationException("removal is not supported");
}
}
}
|
package com.akh.algorithms.stringAlgorithms.slidingWindow;
import static org.junit.Assert.assertEquals;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
public class Minimum_Window_Substring_76 {
public String minWindow_Using_1_Map_Best(String s, String t) {
if( s==null || t==null || s.length() <= 0 || t.length() <=0 || t.length()>s.length())
return "";
Map<Character, Integer> needToFind = new HashMap<>();
for(char c : t.toCharArray()) {
needToFind.put(c, needToFind.getOrDefault(c, 0)+1);
}
int minLen = Integer.MAX_VALUE;
int minLenIndx = 0;
int reqCharsCount = 0;
int left, right;
left = right = 0;
while(right < s.length()) {
char expandChar = s.charAt(right);
if(needToFind.containsKey(expandChar)) {
if(needToFind.get(expandChar) > 0){
// One valid char found
reqCharsCount++;
}
//If more than required then MAP val will be negative. STARRED_STEP 1
needToFind.put(expandChar, needToFind.get(expandChar)-1);
}
/** At end of this step MAP val shd be
* - '0' for required and found exact count
* - '-ve' for required and found extra count
*/
//Requirement of 't' satisfied - Now cut down junk chars
while(left <= right && reqCharsCount == t.length()) {
//Calculate the min window length
if(minLen > right-left+1) {
minLen = Math.min(minLen, right-left+1);
minLenIndx = left;
}
char shrinkChar = s.charAt(left);
if(needToFind.containsKey(shrinkChar)) {
if(needToFind.get(shrinkChar) == 0) {
// One valid char lost
reqCharsCount
}
// Reverse of STARRED_STEP 1
// If extra count then Map.value will incr from negative towards 0
needToFind.put(shrinkChar, needToFind.get(shrinkChar)+1);
}
left++;
}
//Do at the bottom. Or else will mess up minLen calculation
right++;
}
return minLen == Integer.MAX_VALUE ? "" : s.substring(minLenIndx, minLenIndx+minLen);
}
@Test
public void test_1() {
String s = "acbbaca";
String t = "aba";
String expected = "baca";
assertEquals(expected, minWindow_Using_1_Map_Best(s, t));
}
@Test
public void test_2() {
String s = "ADOBECODEBANC";
String t = "ABC";
String expected = "BANC";
assertEquals(expected, minWindow_Using_1_Map_Best(s, t));
}
@Test
public void test_3() {
String s = "a";
String t = "aa";
String expected = "";
assertEquals(expected, minWindow_Using_1_Map_Best(s, t));
}
@Test
public void test_4() {
String s = "a";
String t = "b";
String expected = "";
assertEquals(expected, minWindow_Using_1_Map_Best(s, t));
}
@Test
public void test_5() {
String s = "abcdefghyyyyyyyyijklmnopqrstuvwxyzabcdopqrstuvwxyzabcdefghiaaaaaaaaabbbbbbbjklmcccccccccccnopqrstuvwefghijklmnxyz";
String t = "efijmn";
String expected = "efghijklmn";
assertEquals(expected, minWindow_Using_1_Map_Best(s, t));
}
|
package org.spine3.server.storage.datastore;
import com.google.cloud.datastore.Entity;
import com.google.cloud.datastore.Key;
import com.google.cloud.datastore.Query;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.base.Strings;
import com.google.common.collect.Collections2;
import com.google.common.collect.Iterables;
import com.google.protobuf.Any;
import com.google.protobuf.Message;
import org.spine3.base.Event;
import org.spine3.base.EventContext;
import org.spine3.base.EventId;
import org.spine3.base.Events;
import org.spine3.base.FieldFilter;
import org.spine3.protobuf.AnyPacker;
import org.spine3.server.event.EventFilter;
import org.spine3.server.event.EventStorage;
import org.spine3.server.event.EventStreamQuery;
import org.spine3.type.TypeName;
import org.spine3.type.TypeUrl;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import static com.google.cloud.datastore.StructuredQuery.CompositeFilter.and;
import static com.google.cloud.datastore.StructuredQuery.Filter;
import static com.google.cloud.datastore.StructuredQuery.PropertyFilter.eq;
import static com.google.cloud.datastore.StructuredQuery.PropertyFilter.gt;
import static com.google.cloud.datastore.StructuredQuery.PropertyFilter.lt;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Collections2.transform;
import static java.util.Collections.singleton;
import static org.spine3.base.Identifiers.idToString;
import static org.spine3.protobuf.Timestamps2.convertToDate;
import static org.spine3.server.event.storage.EventField.event_type;
import static org.spine3.server.storage.EntityField.timestamp_nanos;
import static org.spine3.server.storage.datastore.DsIdentifiers.of;
import static org.spine3.server.storage.datastore.DsProperties.addAggregateIdProperty;
import static org.spine3.server.storage.datastore.DsProperties.addEventTypeProperty;
import static org.spine3.server.storage.datastore.DsProperties.addTimestampNanosProperty;
import static org.spine3.server.storage.datastore.DsProperties.addTimestampProperty;
import static org.spine3.server.storage.datastore.DsProperties.makeEventContextProperties;
import static org.spine3.server.storage.datastore.DsProperties.makeEventFieldProperties;
import static org.spine3.server.storage.datastore.Entities.entityToMessage;
import static org.spine3.server.storage.datastore.Entities.messageToEntity;
/**
* Storage for event records based on Google Cloud Datastore.
*
* @author Alexander Litus
* @author Dmytro Dashenkov
* @see DatastoreStorageFactory
*/
@SuppressWarnings("WeakerAccess") // Part of API
public class DsEventStorage extends EventStorage {
private final DatastoreWrapper datastore;
private static final String KIND = TypeName.from(Event.getDescriptor())
.value();
private static final TypeUrl RECORD_TYPE_URL = TypeUrl.from(Event.getDescriptor());
private static final Function<Entity, Event> ENTITY_TO_EVENT_RECORD
= new Function<Entity, Event>() {
@Nullable
@Override
public Event apply(@Nullable Entity entityResult) {
if (entityResult == null) {
return Event.getDefaultInstance();
}
final Event message = entityToMessage(entityResult, RECORD_TYPE_URL);
return message;
}
};
private static final Comparator<Event> EVENT_RECORD_HISTORICAL_COMPARATOR =
new Comparator<Event>() {
@Override
public int compare(Event left, Event right) {
return Events.eventComparator()
.compare(left, right);
}
};
private static final Function<Any, String> ID_TRANSFORMER = new Function<Any, String>() {
@Nullable
@Override
public String apply(@Nullable Any input) {
if (input == null) {
return null;
}
return idToString(input);
}
};
public DsEventStorage(DatastoreWrapper datastore, boolean multitenant) {
super(multitenant);
this.datastore = datastore;
}
private static Predicate<Event> eventPredicate(
@SuppressWarnings("TypeMayBeWeakened") EventStreamQuery query) {
return new EventPredicate(query.getFilterList());
}
@Override
public Iterator<Event> iterator(EventStreamQuery eventStreamQuery) {
checkNotClosed();
final Iterable<Query<Entity>> queries = toEventIteratorQueries(eventStreamQuery);
final Collection<Entity> entities = new LinkedList<>();
for (Query<Entity> query : queries) {
final Collection<Entity> queryResults = datastore.read(query);
entities.addAll(queryResults);
}
// Transform and filter order does not matter since both operations are performed lazily
Collection<Event> events = transform(entities, ENTITY_TO_EVENT_RECORD);
events = Collections2.filter(events, eventPredicate(eventStreamQuery));
final List<Event> sortedEvents = new ArrayList<>(events);
Collections.sort(sortedEvents, EVENT_RECORD_HISTORICAL_COMPARATOR);
final Iterator<Event> iterator = sortedEvents.iterator();
return iterator;
}
private static Iterable<Query<Entity>> toEventIteratorQueries(EventStreamQuery query) {
final long lower = convertToDate(query.getAfter()).getTime();
final long upper = query.hasBefore()
? convertToDate(query.getBefore()).getTime()
: Long.MAX_VALUE;
final Filter greaterThen = gt(timestamp_nanos.toString(), lower);
final Filter lessThen = lt(timestamp_nanos.toString(), upper);
final Filter timeFilter = and(greaterThen, lessThen);
final Collection<Query<Entity>> result = new HashSet<>(query.getFilterCount());
for (EventFilter eventFilter : query.getFilterList()) {
final String eventType = eventFilter.getEventType();
if (eventType.isEmpty()) {
continue;
}
final Filter typeFilter = eq(event_type.toString(), eventType);
final Filter filter = and(typeFilter, timeFilter);
final Query<Entity> queryForType = queryWithFilter(filter);
result.add(queryForType);
}
if (result.isEmpty()) {
final Query<Entity> queryForAllTypes = queryWithFilter(timeFilter);
return singleton(queryForAllTypes);
}
return result;
}
private static Query<Entity> queryWithFilter(Filter filter) {
final Query<Entity> query = Query.newEntityQueryBuilder()
.setKind(KIND)
.setFilter(filter)
.build();
return query;
}
@Override
public void write(EventId id, Event record) {
checkNotNull(id);
checkNotNull(record);
checkNotClosed();
final Key key = DsIdentifiers.keyFor(datastore, KIND, of(id));
final Entity entity = messageToEntity(record, key);
final EventContext context = record.getContext();
final Entity.Builder builder = Entity.newBuilder(entity);
addTimestampProperty(context.getTimestamp(), builder);
addTimestampNanosProperty(context.getTimestamp(), builder);
final Message aggregateId = AnyPacker.unpack(record.getContext()
.getProducerId());
addAggregateIdProperty(aggregateId, builder);
final Message message = AnyPacker.unpack(record.getMessage());
final String eventTypeName = TypeName.of(message)
.value();
addEventTypeProperty(eventTypeName, builder);
makeEventContextProperties(record.getContext(), builder);
makeEventFieldProperties(record, builder);
datastore.createOrUpdate(builder.build());
}
@Override
public Optional<Event> read(EventId eventId) {
checkNotNull(eventId);
checkNotClosed();
final Key key = DsIdentifiers.keyFor(datastore, KIND, of(eventId));
final Entity response = datastore.read(key);
if (response == null) {
return Optional.absent();
}
final Event result = entityToMessage(response, RECORD_TYPE_URL);
return Optional.of(result);
}
@Override
public Iterator<EventId> index() {
checkNotClosed();
return Indexes.indexIterator(datastore, KIND, EventId.class);
}
/**
* Provides an access to the GAE Datastore with an API, specific to the Spine framework.
*
* <p>Allows the customization of the storage behavior in descendants.
*
* @return the wrapped instance of Datastore
*/
protected DatastoreWrapper getDatastore() {
return datastore;
}
private static class EventPredicate implements Predicate<Event> {
private final Collection<EventFilter> eventFilters;
private EventPredicate(Collection<EventFilter> eventFilters) {
this.eventFilters = eventFilters;
}
@Override
public boolean apply(@Nullable Event event) {
if (event == null) {
return false;
}
if (eventFilters.isEmpty()) {
return true;
}
final Predicate<EventFilter> filterPredicate = new EventFilterChecker(event);
final boolean result = Iterables.any(eventFilters, filterPredicate);
return result;
}
}
/**
* Predicate matching {@linkplain EventFilter EventFilters} to the given {@linkplain Event}.
*/
private static class EventFilterChecker implements Predicate<EventFilter> {
private final Event event;
private EventFilterChecker(Event event) {
this.event = event;
}
private static boolean checkFilterEmpty(Collection<String> aggregateIds,
Collection<FieldFilter> eventFieldFilters,
Collection<FieldFilter> contextFieldFilters) {
return aggregateIds.isEmpty()
&& eventFieldFilters.isEmpty()
&& contextFieldFilters.isEmpty();
}
// Defined as nullable, parameter `event` is actually non null.
@SuppressWarnings({"NullableProblems", "MethodWithMoreThanThreeNegations", "MethodWithMultipleLoops"})
@Override
public boolean apply(@Nonnull EventFilter eventFilter) {
final Collection<String> aggregateIds = transform(eventFilter.getAggregateIdList(), ID_TRANSFORMER);
final Collection<FieldFilter> eventFieldFilters = eventFilter.getEventFieldFilterList();
final Collection<FieldFilter> contextFieldFilters = eventFilter.getContextFieldFilterList();
if (checkFilterEmpty(aggregateIds, eventFieldFilters, contextFieldFilters)) {
return true;
}
final Any eventWrapped = event.getMessage();
final Message eventMessage = AnyPacker.unpack(eventWrapped);
// Check aggregate ID
final String aggregateId = idToString(event.getContext()
.getProducerId());
final boolean idMatches = aggregateIds.isEmpty()
|| aggregateIds.contains(aggregateId);
if (!idMatches) {
return false;
}
// Check event fields
for (FieldFilter filter : eventFieldFilters) {
final boolean matchesFilter = checkFields(eventMessage, filter);
if (!matchesFilter) {
return false;
}
}
// Check context fields
final EventContext context = event.getContext();
for (FieldFilter filter : contextFieldFilters) {
final boolean matchesFilter = checkFields(context, filter);
if (!matchesFilter) {
return false;
}
}
return true;
}
private static boolean checkFields(Message object, FieldFilter filter) {
final String fieldPath = filter.getFieldPath();
final String fieldName = fieldPath.substring(fieldPath.lastIndexOf('.') + 1);
checkArgument(!Strings.isNullOrEmpty(fieldName), "Field filter " + filter.toString() + " is invalid");
final String fieldGetterName = "get" + fieldName.substring(0, 1)
.toUpperCase() + fieldName.substring(1);
final Collection<Any> expectedAnys = filter.getValueList();
final Collection<Message> expectedValues = transform(expectedAnys, AnyPacker.unpackFunc());
Message actualValue;
try {
final Class<?> messageClass = object.getClass();
final Method fieldGetter = messageClass.getDeclaredMethod(fieldGetterName);
actualValue = (Message) fieldGetter.invoke(object);
if (actualValue instanceof Any) {
actualValue = AnyPacker.unpack((Any) actualValue);
}
} catch (@SuppressWarnings("OverlyBroadCatchBlock") ReflectiveOperationException e) {
throw new IllegalStateException(e);
}
final boolean result = expectedValues.contains(actualValue);
return result;
}
}
}
|
package com.github.kingargyle.plexappclient.ui.video.player;
import com.bugsense.trace.BugSenseHandler;
import com.github.kingargyle.plexapp.PlexappFactory;
import com.github.kingargyle.plexappclient.R;
import com.github.kingargyle.plexappclient.SerenityApplication;
import com.github.kingargyle.plexappclient.ui.video.player.MediaController.MediaPlayerControl;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.RelativeLayout;
/**
* A view that handles the internal video playback and representation of a movie
* or tv show.
*
* @author dcarver
*
*/
public class SerenitySurfaceViewVideoActivity extends Activity implements
SurfaceHolder.Callback {
private static final int PROGRESS_UPDATE_DELAY = 5000;
static final String TAG = "SerenitySurfaceViewVideoActivity";
static final int CONTROLLER_DELAY = 16000; // Sixteen seconds
private MediaPlayer mediaPlayer;
private String videoURL;
private SurfaceView surfaceView;
private MediaController mediaController;
private String aspectRatio;
private String videoId;
private int resumeOffset;
private Handler progressReportinghandler = new Handler();
private Runnable progressRunnable = new Runnable() {
public void run() {
try {
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
new UpdateProgressRequest().execute();
progressReportinghandler.postDelayed(this,
PROGRESS_UPDATE_DELAY); // Update progress every 5
// seconds
}
} catch (IllegalStateException ex) {
Log.w(getClass().getName(), "Illegalstate exception occurred durring progress update. No further updates will occur.", ex);
BugSenseHandler.sendException(ex);
}
};
};
/*
* (non-Javadoc)
*
* @see
* android.view.SurfaceHolder.Callback#surfaceChanged(android.view.SurfaceHolder
* , int, int, int)
*/
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
/*
* (non-Javadoc)
*
* @see
* android.view.SurfaceHolder.Callback#surfaceCreated(android.view.SurfaceHolder
* )
*/
public void surfaceCreated(SurfaceHolder holder) {
try {
mediaPlayer.setDisplay(holder);
mediaPlayer.setDataSource(videoURL);
mediaPlayer.setOnPreparedListener(new VideoPlayerPrepareListener(
this));
mediaPlayer.prepareAsync();
} catch (Exception ex) {
Log.e(TAG, "Video Playback Error. ", ex);
}
}
/**
* Setup the aspect ratio for the SurfaceView
*
* @return
*/
protected android.view.ViewGroup.LayoutParams setupAspectRatio() {
RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) surfaceView
.getLayoutParams();
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this);
boolean preferPlexAspectRatio = prefs.getBoolean("plex_aspect_ratio",
false);
int surfaceViewHeight = surfaceView.getHeight();
int surfaceViewWidth = surfaceView.getWidth();
float videoWidth = mediaPlayer.getVideoWidth();
float videoHeight = mediaPlayer.getVideoHeight();
float ratioWidth = surfaceViewWidth / videoWidth;
float ratioHeight = surfaceViewHeight / videoHeight;
float aspectRatio = videoWidth / videoHeight;
if (videoHeight == 480 && videoWidth == 720) {
aspectRatio = (float) 1.78;
}
if (preferPlexAspectRatio && this.aspectRatio != null) {
aspectRatio = Float.parseFloat(this.aspectRatio);
}
if (ratioWidth > ratioHeight) {
lp.width = (int) (surfaceViewHeight * aspectRatio);
lp.height = surfaceViewHeight;
} else {
lp.width = surfaceViewWidth;
lp.height = (int) (surfaceViewWidth / aspectRatio);
}
if (lp.width > surfaceViewWidth) {
lp.width = surfaceViewWidth;
}
if (lp.height > surfaceViewHeight) {
lp.height = surfaceViewHeight;
}
return lp;
}
/*
* (non-Javadoc)
*
* @see android.view.SurfaceHolder.Callback#surfaceDestroyed(android.view.
* SurfaceHolder)
*/
public void surfaceDestroyed(SurfaceHolder holder) {
mediaPlayer.release();
}
/*
* (non-Javadoc)
*
* @see android.app.Activity#onCreate(android.os.Bundle)
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.video_playback);
init();
}
/**
* Initialize the mediaplayer and mediacontroller.
*/
protected void init() {
Bundle extras = getIntent().getExtras();
videoURL = extras.getString("videoUrl");
videoId = extras.getString("id");
String summary = extras.getString("summary");
String title = extras.getString("title");
String posterURL = extras.getString("posterUrl");
aspectRatio = extras.getString("aspectRatio");
String videoFormat = extras.getString("videoFormat");
String videoResolution = extras.getString("videoResolution");
String audioFormat = extras.getString("audioFormat");
String audioChannels = extras.getString("audioChannels");
resumeOffset = extras.getInt("resumeOffset");
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnErrorListener(new SerenityOnErrorListener());
surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
surfaceView.setKeepScreenOn(true);
SurfaceHolder holder = surfaceView.getHolder();
holder.addCallback(this);
holder.setSizeFromLayout();
mediaController = new MediaController(this, summary, title, posterURL,
videoResolution, videoFormat, audioFormat, audioChannels);
mediaController.setAnchorView(surfaceView);
mediaController.setMediaPlayer(new SerenityMediaPlayerControl());
}
/*
* (non-Javadoc)
*
* @see android.app.Activity#finish()
*/
@Override
public void finish() {
super.finish();
progressReportinghandler.removeCallbacks(progressRunnable);
}
/*
* (non-Javadoc)
*
* @see android.app.Activity#onKeyDown(int, android.view.KeyEvent)
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (mediaController.isShowing()) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
mediaController.hide();
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
return super.onKeyDown(keyCode, event);
}
} else {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
return super.onKeyDown(keyCode, event);
}
}
if (keyCode == KeyEvent.KEYCODE_INFO) {
if (mediaController.isShowing()) {
mediaController.hide();
} else {
mediaController.show(CONTROLLER_DELAY);
}
return true;
}
if (keyCode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE
|| keyCode == KeyEvent.KEYCODE_MEDIA_PAUSE
|| keyCode == KeyEvent.KEYCODE_MEDIA_PLAY) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
mediaController.show(CONTROLLER_DELAY);
progressReportinghandler.removeCallbacks(progressRunnable);
} else {
mediaPlayer.start();
mediaController.hide();
progressReportinghandler.postDelayed(progressRunnable, 5000);
}
return true;
}
if (keyCode == KeyEvent.KEYCODE_MEDIA_FAST_FORWARD
|| keyCode == KeyEvent.KEYCODE_MEDIA_NEXT) {
int skipOffset = 10000 + mediaPlayer.getCurrentPosition();
int duration = mediaPlayer.getDuration();
if (skipOffset > duration) {
skipOffset = duration - 1;
}
if (!mediaController.isShowing()) {
mediaController.show(CONTROLLER_DELAY);
}
mediaPlayer.seekTo(skipOffset);
return true;
}
if (keyCode == KeyEvent.KEYCODE_MEDIA_REWIND
|| keyCode == KeyEvent.KEYCODE_MEDIA_PREVIOUS) {
int skipOffset = mediaPlayer.getCurrentPosition() - 10000;
if (skipOffset < 0) {
skipOffset = 0;
}
if (!mediaController.isShowing()) {
mediaController.show(CONTROLLER_DELAY);
}
mediaPlayer.seekTo(skipOffset);
return true;
}
if (keyCode == KeyEvent.KEYCODE_MEDIA_STOP) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
if (!mediaController.isShowing()) {
mediaController.show(CONTROLLER_DELAY);
}
}
return true;
}
return super.onKeyDown(keyCode, event);
}
/**
* A simple media player control. Handles the main events that can occur
* while using the player to play a video.
*
* @author dcarver
*
*/
protected class SerenityMediaPlayerControl implements MediaPlayerControl {
public void start() {
mediaPlayer.start();
}
public void seekTo(long pos) {
mediaPlayer.seekTo((int) pos);
}
public void pause() {
mediaPlayer.pause();
}
public boolean isPlaying() {
return mediaPlayer.isPlaying();
}
public long getDuration() {
return mediaPlayer.getDuration();
}
public long getCurrentPosition() {
return mediaPlayer.getCurrentPosition();
}
public int getBufferPercentage() {
return 0;
}
public boolean canSeekForward() {
return true;
}
public boolean canSeekBackward() {
return true;
}
public boolean canPause() {
return true;
}
}
/**
* A task that updates the watched status of a video.
*
* @author dcarver
*
*/
protected class WatchedVideoRequest extends AsyncTask<Void, Void, Void> {
protected String scrobbleKey;
public WatchedVideoRequest(String key) {
scrobbleKey = key;
}
@Override
protected Void doInBackground(Void... params) {
PlexappFactory factory = SerenityApplication.getPlexFactory();
factory.setWatched(scrobbleKey);
return null;
}
}
/**
* A task that updates the progress position of a video while it is being
* played.
*
* @author dcarver
*
*/
protected class UpdateProgressRequest extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
PlexappFactory factory = SerenityApplication.getPlexFactory();
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
String offset = Integer.valueOf(
mediaPlayer.getCurrentPosition()).toString();
factory.setProgress(videoId, offset);
}
return null;
}
}
/**
* A prepare listener that handles how a video should start playing.
*
* It checks to see if the video has been previously viewed and if so will
* present a dialog to allow resuming of a video from where it was
* previously last viewed. Otherwise it will start play back of the video.
* It also launches the Watched status update task and the progress update
* handler.
*
* @author dcarver
*
*/
protected class VideoPlayerPrepareListener implements OnPreparedListener {
private Context context;
public VideoPlayerPrepareListener(Context context) {
this.context = context;
}
public void onPrepared(MediaPlayer mp) {
android.view.ViewGroup.LayoutParams lp = setupAspectRatio();
surfaceView.setLayoutParams(lp);
mediaController.setEnabled(true);
if (resumeOffset > 0) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
alertDialogBuilder.setTitle("Resume Video");
alertDialogBuilder
.setMessage("Resume the video or start from beginning?")
.setCancelable(false)
.setPositiveButton("Resume",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
}
mediaPlayer.seekTo(resumeOffset);
setMetaData();
}
})
.setNegativeButton("Restart",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
mediaPlayer.start();
setMetaData();
}
});
alertDialogBuilder.create();
alertDialogBuilder.show();
return;
} else {
mediaPlayer.start();
setMetaData();
}
}
protected void setMetaData() {
new WatchedVideoRequest(videoId).execute();
mediaController.show(CONTROLLER_DELAY);
if (progressReportinghandler != null) {
progressReportinghandler.postDelayed(progressRunnable, 5000);
}
}
}
protected class SerenityOnErrorListener implements OnErrorListener {
/*
* (non-Javadoc)
*
* @see android.media.MediaPlayer.OnErrorListener#onError(android.media.
* MediaPlayer, int, int)
*/
public boolean onError(MediaPlayer mp, int what, int extra) {
String error_msg = "What: " + what + "Extra: " + extra;
if (what == MediaPlayer.MEDIA_ERROR_UNKNOWN) {
error_msg = "Unknown Media Player Error. Extra Code: " + extra;
}
if (what == MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK) {
error_msg = "Media not valid for progessive playback. Extra Code: "
+ extra;
}
if (what == MediaPlayer.MEDIA_ERROR_SERVER_DIED) {
error_msg = "Server croaked. Extra Code: " + extra;
}
Log.e(getClass().getName(), error_msg);
return true;
}
}
/*
* (non-Javadoc)
*
* @see android.app.Activity#onTouchEvent(android.view.MotionEvent)
*/
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (mediaController.isShowing()) {
mediaController.hide();
} else {
mediaController.show();
}
}
return super.onTouchEvent(event);
}
}
|
package io.georocket.storage;
import java.util.List;
import java.util.stream.Collectors;
import io.georocket.util.XMLStartElement;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
/**
* Metadata for an XML chunk
* @since 1.0.0
* @author Michel Kraemer
*/
public class XMLChunkMeta extends ChunkMeta {
/**
* The mime type for XML chunks
*/
public static final String MIME_TYPE = "application/xml";
private final List<XMLStartElement> parents;
/**
* Create a new metadata object
* @param parents the chunk's parents (i.e. the XML start elements the
* chunk is wrapped in)
* @param start the position in the stored blob where the chunk starts
* (typically right after all its parent XML elements)
* @param end the position in the stored blob where the chunk ends (typically
* right before all its parent XML elements are closed)
*/
public XMLChunkMeta(List<XMLStartElement> parents, int start, int end) {
super(start, end, MIME_TYPE);
this.parents = parents;
}
/**
* Create a new metadata object from a JsonObject
* @param json the JsonObject
*/
public XMLChunkMeta(JsonObject json) {
super(json);
this.parents = json.getJsonArray("parents").stream()
.map(e -> XMLStartElement.fromJsonObject((JsonObject)e))
.collect(Collectors.toList());
}
/**
* @return the chunk's parents (i.e. the XML start elements the
* chunk is wrapped in)
*/
public List<XMLStartElement> getParents() {
return parents;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((parents == null) ? 0 : parents.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!super.equals(obj)) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
XMLChunkMeta other = (XMLChunkMeta)obj;
if (parents == null) {
if (other.parents != null) {
return false;
}
} else if (!parents.equals(other.parents)) {
return false;
}
return true;
}
/**
* @return this object as a {@link JsonObject}
*/
public JsonObject toJsonObject() {
JsonArray ps = new JsonArray();
parents.forEach(p -> ps.add(p.toJsonObject()));
return super.toJsonObject()
.put("parents", ps);
}
}
|
/*
* Derived from com.android.mms.ui.ComposeMessageActivity
* (tag android-4.4.4_r2.0.1)
*/
package ca.bmaupin.merge.sms.ui;
import static com.android.mms.ui.MessageListAdapter.COLUMN_ID;
import java.util.ArrayList;
import com.android.mms.LogTag;
import com.android.mms.data.Contact;
import com.android.mms.data.ContactList;
import com.android.mms.data.Conversation.ConversationQueryHandler;
import com.android.mms.transaction.MessagingNotification;
import com.android.mms.ui.ComposeMessageActivity;
import com.android.mms.ui.ConversationList;
import com.android.mms.widget.MmsWidgetProvider;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import ca.bmaupin.merge.sms.R;
import ca.bmaupin.merge.sms.data.Conversation;
public class ComposeMessageActivity extends Activity {
private ContentResolver mContentResolver;
// private BackgroundQueryHandler mBackgroundQueryHandler;
private MessageListView mMsgListView; // ListView for messages in this conversation
public MessageListAdapter mMsgListAdapter; // and its corresponding ListAdapter
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO
// mIsSmsEnabled = MmsConfig.isSmsEnabled(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.compose_message_activity);
setProgressBarVisibility(false);
// Initialize members for UI elements.
initResourceRefs();
// TODO
mContentResolver = getContentResolver();
// mBackgroundQueryHandler = new BackgroundQueryHandler(mContentResolver);
// TODO
// initialize(savedInstanceState, 0);
}
// Private methods
/**
* Initialize all UI elements from resources.
*/
private void initResourceRefs() {
mMsgListView = (MessageListView) findViewById(R.id.history);
mMsgListView.setDivider(null); // no divider so we look like IM conversation.
// called to enable us to show some padding between the message list and the
// input field but when the message list is scrolled that padding area is filled
// in with message content
mMsgListView.setClipToPadding(false);
}
private final class BackgroundQueryHandler extends ConversationQueryHandler {
public BackgroundQueryHandler(ContentResolver contentResolver) {
super(contentResolver);
}
@Override
protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
switch(token) {
case MESSAGE_LIST_QUERY_TOKEN:
mConversation.blockMarkAsRead(false);
// check consistency between the query result and 'mConversation'
long tid = (Long) cookie;
if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("
}
if (tid != mConversation.getThreadId()) {
log("onQueryComplete: msg history query result is for threadId " +
tid + ", but mConversation has threadId " +
mConversation.getThreadId() + " starting a new query");
if (cursor != null) {
cursor.close();
}
startMsgListQuery();
return;
}
// check consistency b/t mConversation & mWorkingMessage.mConversation
ComposeMessageActivity.this.sanityCheckConversation();
int newSelectionPos = -1;
long targetMsgId = getIntent().getLongExtra("select_id", -1);
if (targetMsgId != -1) {
if (cursor != null) {
cursor.moveToPosition(-1);
while (cursor.moveToNext()) {
long msgId = cursor.getLong(COLUMN_ID);
if (msgId == targetMsgId) {
newSelectionPos = cursor.getPosition();
break;
}
}
}
} else if (mSavedScrollPosition != -1) {
// mSavedScrollPosition is set when this activity pauses. If equals maxint,
// it means the message list was scrolled to the end. Meanwhile, messages
// could have been received. When the activity resumes and we were
// previously scrolled to the end, jump the list so any new messages are
// visible.
if (mSavedScrollPosition == Integer.MAX_VALUE) {
int cnt = mMsgListAdapter.getCount();
if (cnt > 0) {
// Have to wait until the adapter is loaded before jumping to
// the end.
newSelectionPos = cnt - 1;
mSavedScrollPosition = -1;
}
} else {
// remember the saved scroll position before the activity is paused.
// reset it after the message list query is done
newSelectionPos = mSavedScrollPosition;
mSavedScrollPosition = -1;
}
}
mMsgListAdapter.changeCursor(cursor);
if (newSelectionPos != -1) {
mMsgListView.setSelection(newSelectionPos); // jump the list to the pos
} else {
int count = mMsgListAdapter.getCount();
long lastMsgId = 0;
if (cursor != null && count > 0) {
cursor.moveToLast();
lastMsgId = cursor.getLong(COLUMN_ID);
}
// mScrollOnSend is set when we send a message. We always want to scroll
// the message list to the end when we send a message, but have to wait
// until the DB has changed. We also want to scroll the list when a
// new message has arrived.
smoothScrollToEnd(mScrollOnSend || lastMsgId != mLastMessageId, 0);
mLastMessageId = lastMsgId;
mScrollOnSend = false;
}
// Adjust the conversation's message count to match reality. The
// conversation's message count is eventually used in
// WorkingMessage.clearConversation to determine whether to delete
// the conversation or not.
mConversation.setMessageCount(mMsgListAdapter.getCount());
// Once we have completed the query for the message history, if
// there is nothing in the cursor and we are not composing a new
// message, we must be editing a draft in a new conversation (unless
// mSentMessage is true).
// Show the recipients editor to give the user a chance to add
// more people before the conversation begins.
if (cursor != null && cursor.getCount() == 0
&& !isRecipientsEditorVisible() && !mSentMessage) {
initRecipientsEditor();
}
// FIXME: freshing layout changes the focused view to an unexpected
// one, set it back to TextEditor forcely.
mTextEditor.requestFocus();
invalidateOptionsMenu(); // some menu items depend on the adapter's count
return;
}
}
}
public static Intent createIntent(Context context, long threadId) {
Intent intent = new Intent(context, ComposeMessageActivity.class);
if (threadId > 0) {
intent.setData(Conversation.getUri(threadId));
}
return intent;
}
}
|
package de.factoryfx.javafx.widget.table;
import java.text.DecimalFormat;
import de.factoryfx.data.util.TextSearchSupport;
import de.factoryfx.javafx.util.UniformDesign;
import de.factoryfx.javafx.widget.Widget;
import javafx.animation.FadeTransition;
import javafx.beans.InvalidationListener;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import javafx.geometry.Insets;
import javafx.geometry.Orientation;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.CheckMenuItem;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.Separator;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TablePosition;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.DataFormat;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyCombination;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.util.Duration;
public class TableControlWidget<T> implements Widget {
private final HBox target = new HBox();
private final TableView<T> tableView;
TextField filterField;
private final UniformDesign uniformDesign;
public TableControlWidget(TableView<T> tableView, UniformDesign uniformDesign) {
this.tableView = tableView;
this.uniformDesign = uniformDesign;
tableView.setTableMenuButtonVisible(true);
setupTableControls();
tableView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
MenuItem item = new MenuItem("Copy cell");
item.setOnAction(event -> {
copyTableCell(tableView);
});
item.setAccelerator(new KeyCodeCombination(KeyCode.C, KeyCombination.CONTROL_DOWN));//don't work on ContextMenu but keep is for the display text
KeyCodeCombination keyCodeCombination = new KeyCodeCombination(KeyCode.C, KeyCombination.CONTROL_DOWN);
this.tableView.addEventFilter(KeyEvent.KEY_RELEASED, event -> {
if (keyCodeCombination.match(event)) {
copyTableCell(tableView);
}
});
MenuItem export = new MenuItem("Copy table (csv)");
export.setOnAction(event -> {
exportTable(tableView);
});
CheckMenuItem toggleVisible = new CheckMenuItem("Filter visible");
toggleVisible.selectedProperty().bindBidirectional(target.visibleProperty());
ContextMenu menu = new ContextMenu();
menu.getItems().add(item);
menu.getItems().add(export);
menu.getItems().add(toggleVisible);
tableView.setContextMenu(menu);
}
public void clearFilter() {
filterField.clear();
}
private void copyTableCell(final TableView<?> tableView) {
StringBuilder clipboardString = new StringBuilder();
for (TablePosition<?, ?> tablePosition : tableView.getSelectionModel().getSelectedCells()) {
Object cell = tableView.getColumns().get(tablePosition.getColumn()).getCellData(tablePosition.getRow());
clipboardString.append(cell);
}
final ClipboardContent content = new ClipboardContent();
content.putString(clipboardString.toString());
Clipboard.getSystemClipboard().setContent(content);
}
@Override
public Node createContent() {
return target;
}
private String escapeCsvString(String s) {
return "\"" +
s.replace("\"", "\"\"") +
"\"";
}
private void exportTable(final TableView<?> tableView) {
StringBuilder clipboardString = new StringBuilder();
for (TableColumn<?, ?> column : tableView.getColumns()) {
clipboardString.append(escapeCsvString(column.getText())).append("\t");
}
clipboardString.append("\n");
for (int i = 0; i < tableView.getItems().size(); i++) {
for (TableColumn<?, ?> column : tableView.getColumns()) {
Object cellData = column.getCellData(i);
String data = "";
if (cellData != null) {
data = cellData.toString();
}
clipboardString.append(escapeCsvString(data)).append("\t");
}
clipboardString.append("\n");
}
final ClipboardContent content = new ClipboardContent();
content.put(DataFormat.PLAIN_TEXT, clipboardString.toString());
Clipboard.getSystemClipboard().setContent(content);
}
public TableControlWidget hide() {
target.visibleProperty().set(false);
return this;
}
public void setFilterText(String filter) {
filterField.setText(filter);
}
private void setupTableControls() {
filterField = new TextField();//(CustomTextField) TextFields.createClearableTextField();
// filterField.leftProperty().set(uniformDesign.createIcon(FontAwesome.Glyph.FILTER));
filterField.disableProperty().bind(tableView.disabledProperty().or(tableView.itemsProperty().isNull()));
filterField.setMinWidth(50);
HBox.setHgrow(filterField, Priority.ALWAYS);
final Label count = new Label("");
FilterTextFieldListener<T> filterTextFieldListener = new FilterTextFieldListener<>();
filterField.textProperty().addListener(filterTextFieldListener);
InvalidationListener listener = (observableItems) -> {
@SuppressWarnings("unchecked") ObservableList<T> list = ((SimpleObjectProperty<ObservableList<T>>) observableItems).get();
if (!(list instanceof SortedList) && list != null) {
FilteredList<T> filteredData = new FilteredList<>(list, p -> true);
SortedList<T> sortedData = new SortedList<>(filteredData);
tableView.setItems(sortedData);
sortedData.comparatorProperty().bind(tableView.comparatorProperty());
filterTextFieldListener.setFilteredData(filteredData);
count.setText("" + filteredData.size());
tableView.getItems().addListener((ListChangeListener<T>) c -> {
if (c != null) {
StringBuilder format = new StringBuilder();
for (int i = 0; i < String.valueOf(filteredData.getSource().size()).length(); i++) {
format.append("0");
}
DecimalFormat decimalFormat = new DecimalFormat(format.toString());
count.setText(decimalFormat.format(filteredData.size()));
}
});
}
if (list == null) {
count.setText("0");
}
};
tableView.itemsProperty().addListener(listener);
listener.invalidated(tableView.itemsProperty());
target.getChildren().add(filterField);
target.getChildren().add(new Separator(Orientation.VERTICAL));
target.getChildren().add(count);
target.setSpacing(3);
target.setAlignment(Pos.CENTER_LEFT);
target.setPadding(new Insets(2));
target.setOpacity(0.35);
int fadeTransitionDuration = 350;
double minFadeValue = 0.20;
ChangeListener<Boolean> focusChangeListener = (observable, oldValue, newValue) -> {
target.getStyleClass().remove("selectedTableViewControl");
if (newValue) {
if (!filterField.focusedProperty().get()) {
target.getStyleClass().add("selectedTableViewControl");
}
if (target.getOpacity() < 0.999999) {
FadeTransition ft = new FadeTransition(Duration.millis(fadeTransitionDuration), target);
ft.setFromValue(minFadeValue);
ft.setToValue(1.0);
ft.play();
}
} else {
if (!filterField.focusedProperty().get() && !tableView.focusedProperty().get()) {
target.getStyleClass().remove("selectedTableViewControl");
FadeTransition ft = new FadeTransition(Duration.millis(fadeTransitionDuration), target);
ft.setFromValue(1.0);
ft.setToValue(minFadeValue);
ft.play();
}
}
};
tableView.focusedProperty().addListener(focusChangeListener);
filterField.focusedProperty().addListener(focusChangeListener);
}
private static class FilterTextFieldListener<T> implements ChangeListener<String> {
FilteredList<T> filteredData;
public FilterTextFieldListener() {
}
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
filteredData.setPredicate(data -> {
// If filter text is empty, display all.
if (newValue==null || newValue.isEmpty()) {
return true;
}
if (data instanceof TextSearchSupport){
return ((TextSearchSupport)data).matchSearchText(newValue);
}
return true;
});
}
public FilteredList<T> getFilteredData() {
return filteredData;
}
public void setFilteredData(FilteredList<T> filteredData) {
this.filteredData = filteredData;
}
}
}
|
package io.bisq.gui.main.offer.createoffer;
import de.jensd.fx.fontawesome.AwesomeDude;
import de.jensd.fx.fontawesome.AwesomeIcon;
import io.bisq.common.UserThread;
import io.bisq.common.app.DevEnv;
import io.bisq.common.locale.Res;
import io.bisq.common.locale.TradeCurrency;
import io.bisq.common.util.Tuple2;
import io.bisq.common.util.Tuple3;
import io.bisq.common.util.Utilities;
import io.bisq.core.offer.Offer;
import io.bisq.core.offer.OfferPayload;
import io.bisq.core.payment.PaymentAccount;
import io.bisq.core.payment.payload.PaymentMethod;
import io.bisq.core.user.DontShowAgainLookup;
import io.bisq.gui.Navigation;
import io.bisq.gui.common.view.ActivatableViewAndModel;
import io.bisq.gui.common.view.FxmlView;
import io.bisq.gui.components.*;
import io.bisq.gui.main.MainView;
import io.bisq.gui.main.account.AccountView;
import io.bisq.gui.main.account.content.arbitratorselection.ArbitratorSelectionView;
import io.bisq.gui.main.account.content.fiataccounts.FiatAccountsView;
import io.bisq.gui.main.account.settings.AccountSettingsView;
import io.bisq.gui.main.dao.DaoView;
import io.bisq.gui.main.dao.wallet.BsqWalletView;
import io.bisq.gui.main.dao.wallet.receive.BsqReceiveView;
import io.bisq.gui.main.funds.FundsView;
import io.bisq.gui.main.funds.withdrawal.WithdrawalView;
import io.bisq.gui.main.offer.OfferView;
import io.bisq.gui.main.overlays.popups.Popup;
import io.bisq.gui.main.overlays.windows.FeeOptionWindow;
import io.bisq.gui.main.overlays.windows.OfferDetailsWindow;
import io.bisq.gui.main.overlays.windows.QRCodeWindow;
import io.bisq.gui.main.portfolio.PortfolioView;
import io.bisq.gui.main.portfolio.openoffer.OpenOffersView;
import io.bisq.gui.util.*;
import javafx.beans.value.ChangeListener;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.*;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.*;
import javafx.scene.text.Font;
import javafx.stage.Window;
import javafx.util.StringConverter;
import net.glxn.qrgen.QRCode;
import net.glxn.qrgen.image.ImageType;
import org.bitcoinj.core.Coin;
import org.controlsfx.control.PopOver;
import org.fxmisc.easybind.EasyBind;
import org.fxmisc.easybind.Subscription;
import org.jetbrains.annotations.NotNull;
import javax.inject.Inject;
import java.io.ByteArrayInputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static io.bisq.gui.util.FormBuilder.*;
import static javafx.beans.binding.Bindings.createStringBinding;
@FxmlView
public class CreateOfferView extends ActivatableViewAndModel<AnchorPane, CreateOfferViewModel> {
private final Navigation navigation;
private final Transitions transitions;
private final OfferDetailsWindow offerDetailsWindow;
private final BSFormatter btcFormatter;
private final BsqFormatter bsqFormatter;
private ScrollPane scrollPane;
private GridPane gridPane;
private TitledGroupBg payFundsTitledGroupBg, setDepositTitledGroupBg;
private BusyAnimation waitingForFundsBusyAnimation;
private Button nextButton, cancelButton1, cancelButton2, placeOfferButton;
private ToggleButton fixedPriceButton, useMarketBasedPriceButton;
private InputTextField buyerSecurityDepositInputTextField, amountTextField, minAmountTextField,
fixedPriceTextField, marketBasedPriceTextField, volumeTextField;
private TextField currencyTextField;
private AddressTextField addressTextField;
private BalanceTextField balanceTextField;
private FundsTextField totalToPayTextField;
private Label directionLabel, amountDescriptionLabel, addressLabel, balanceLabel, totalToPayLabel,
priceCurrencyLabel, volumeCurrencyLabel, priceDescriptionLabel,
volumeDescriptionLabel, currencyTextFieldLabel, buyerSecurityDepositLabel, currencyComboBoxLabel,
waitingForFundsLabel, marketBasedPriceLabel, xLabel;
private ComboBox<PaymentAccount> paymentAccountsComboBox;
private ComboBox<TradeCurrency> currencyComboBox;
private ImageView imageView, qrCodeImageView;
private VBox fixedPriceBox, percentagePriceBox;
private HBox fundingHBox, firstRowHBox, secondRowHBox, toggleButtonsHBox,
buyerSecurityDepositValueCurrencyBox;
private Subscription isWaitingForFundsSubscription, balanceSubscription, cancelButton2StyleSubscription;
private ChangeListener<Boolean> amountFocusedListener, minAmountFocusedListener, volumeFocusedListener,
buyerSecurityDepositFocusedListener, priceFocusedListener, placeOfferCompletedListener,
priceAsPercentageFocusedListener;
private ChangeListener<String> tradeCurrencyCodeListener, errorMessageListener;
private ChangeListener<Number> marketPriceAvailableListener;
private EventHandler<ActionEvent> currencyComboBoxSelectionHandler, paymentAccountsComboBoxSelectionHandler;
private OfferView.CloseHandler closeHandler;
private int gridRow = 0;
private final List<Node> editOfferElements = new ArrayList<>();
private boolean clearXchangeWarningDisplayed, isActivated;
// Constructor, lifecycle
@Inject
private CreateOfferView(CreateOfferViewModel model, Navigation navigation, Transitions transitions,
OfferDetailsWindow offerDetailsWindow, BSFormatter btcFormatter, BsqFormatter bsqFormatter) {
super(model);
this.navigation = navigation;
this.transitions = transitions;
this.offerDetailsWindow = offerDetailsWindow;
this.btcFormatter = btcFormatter;
this.bsqFormatter = bsqFormatter;
}
@Override
protected void initialize() {
addScrollPane();
addGridPane();
addPaymentGroup();
addAmountPriceGroup();
addOptionsGroup();
addFundingGroup();
createListeners();
balanceTextField.setFormatter(model.getBtcFormatter());
paymentAccountsComboBox.setConverter(new StringConverter<PaymentAccount>() {
@Override
public String toString(PaymentAccount paymentAccount) {
TradeCurrency singleTradeCurrency = paymentAccount.getSingleTradeCurrency();
String code = singleTradeCurrency != null ? singleTradeCurrency.getCode() : "";
return paymentAccount.getAccountName() + " (" + code + ", " +
Res.get(paymentAccount.getPaymentMethod().getId()) + ")";
}
@Override
public PaymentAccount fromString(String s) {
return null;
}
});
}
@Override
protected void activate() {
if (model.dataModel.isTabSelected)
doActivate();
}
private void doActivate() {
if (!isActivated) {
isActivated = true;
currencyComboBox.setPrefWidth(250);
paymentAccountsComboBox.setPrefWidth(250);
addBindings();
addListeners();
addSubscriptions();
if (waitingForFundsBusyAnimation != null)
waitingForFundsBusyAnimation.play();
directionLabel.setText(model.getDirectionLabel());
amountDescriptionLabel.setText(model.getAmountDescription());
addressTextField.setAddress(model.getAddressAsString());
addressTextField.setPaymentLabel(model.getPaymentLabel());
paymentAccountsComboBox.setItems(model.dataModel.getPaymentAccounts());
paymentAccountsComboBox.getSelectionModel().select(model.getPaymentAccount());
onPaymentAccountsComboBoxSelected();
balanceTextField.setTargetAmount(model.dataModel.totalToPayAsCoinProperty().get());
updateMarketPriceAvailable();
}
}
@Override
protected void deactivate() {
if (isActivated) {
isActivated = false;
removeBindings();
removeListeners();
removeSubscriptions();
if (waitingForFundsBusyAnimation != null)
waitingForFundsBusyAnimation.stop();
}
}
// API
public void onTabSelected(boolean isSelected) {
if (isSelected && !model.dataModel.isTabSelected)
doActivate();
else
deactivate();
isActivated = isSelected;
model.dataModel.onTabSelected(isSelected);
}
public void initWithData(OfferPayload.Direction direction, TradeCurrency tradeCurrency) {
boolean result = model.initWithData(direction, tradeCurrency);
if (!result) {
new Popup<>().headLine(Res.get("popup.warning.noTradingAccountSetup.headline"))
.instruction(Res.get("popup.warning.noTradingAccountSetup.msg"))
.actionButtonTextWithGoTo("navigation.account")
.onAction(() -> {
navigation.setReturnPath(navigation.getCurrentPath());
//noinspection unchecked
navigation.navigateTo(MainView.class, AccountView.class, AccountSettingsView.class, FiatAccountsView.class);
}).show();
}
if (direction == OfferPayload.Direction.BUY) {
imageView.setId("image-buy-large");
placeOfferButton.setId("buy-button-big");
placeOfferButton.setText(Res.get("createOffer.placeOfferButton", Res.get("shared.buy")));
nextButton.setId("buy-button");
} else {
imageView.setId("image-sell-large");
placeOfferButton.setId("sell-button-big");
placeOfferButton.setText(Res.get("createOffer.placeOfferButton", Res.get("shared.sell")));
nextButton.setId("sell-button");
}
updateMarketPriceAvailable();
if (!model.dataModel.isMakerFeeValid() && model.dataModel.getMakerFee() != null)
showInsufficientBsqFundsForBtcFeePaymentPopup();
}
// called form parent as the view does not get notified when the tab is closed
public void onClose() {
// we use model.placeOfferCompleted to not react on close which was triggered by a successful placeOffer
if (model.dataModel.getBalance().get().isPositive() && !model.placeOfferCompleted.get()) {
model.dataModel.swapTradeToSavings();
String key = "CreateOfferCancelAndFunded";
if (model.dataModel.preferences.showAgain(key)) {
//noinspection unchecked
new Popup<>().information(Res.get("createOffer.alreadyFunded"))
.actionButtonTextWithGoTo("navigation.funds.availableForWithdrawal")
.onAction(() -> navigation.navigateTo(MainView.class, FundsView.class, WithdrawalView.class))
.dontShowAgainId(key)
.show();
}
}
}
public void setCloseHandler(OfferView.CloseHandler closeHandler) {
this.closeHandler = closeHandler;
}
// UI actions
private void onPlaceOffer() {
if (model.isReadyForTxBroadcast()) {
if (model.dataModel.isMakerFeeValid()) {
if (model.hasAcceptedArbitrators()) {
Offer offer = model.createAndGetOffer();
//noinspection PointlessBooleanExpression
if (!DevEnv.DEV_MODE) {
offerDetailsWindow.onPlaceOffer(() ->
model.onPlaceOffer(offer, offerDetailsWindow::hide))
.show(offer);
} else {
balanceSubscription.unsubscribe();
model.onPlaceOffer(offer, () -> {
});
}
} else {
new Popup<>().headLine(Res.get("popup.warning.noArbitratorSelected.headline"))
.instruction(Res.get("popup.warning.noArbitratorSelected.msg"))
.actionButtonTextWithGoTo("navigation.arbitratorSelection")
.onAction(() -> {
navigation.setReturnPath(navigation.getCurrentPath());
//noinspection unchecked
navigation.navigateTo(MainView.class, AccountView.class, AccountSettingsView.class, ArbitratorSelectionView.class);
}).show();
}
} else {
showInsufficientBsqFundsForBtcFeePaymentPopup();
}
} else {
model.showNotReadyForTxBroadcastPopups();
}
}
private void showInsufficientBsqFundsForBtcFeePaymentPopup() {
Coin makerFee = model.dataModel.getMakerFee(false);
String message = null;
if (makerFee != null) {
message = Res.get("popup.warning.insufficientBsqFundsForBtcFeePayment",
bsqFormatter.formatCoinWithCode(makerFee.subtract(model.dataModel.getBsqBalance())));
} else if (model.dataModel.getBsqBalance().isZero())
message = Res.get("popup.warning.noBsqFundsForBtcFeePayment");
if (message != null)
//noinspection unchecked
new Popup<>().warning(message)
.actionButtonTextWithGoTo("navigation.dao.wallet.receive")
.onAction(() -> navigation.navigateTo(MainView.class, DaoView.class, BsqWalletView.class, BsqReceiveView.class))
.show();
}
private void onShowPayFundsScreen() {
nextButton.setVisible(false);
nextButton.setManaged(false);
nextButton.setOnAction(null);
cancelButton1.setVisible(false);
cancelButton1.setManaged(false);
cancelButton1.setOnAction(null);
int delay = 500;
int diff = 100;
transitions.fadeOutAndRemove(setDepositTitledGroupBg, delay, (event) -> {
});
delay -= diff;
transitions.fadeOutAndRemove(buyerSecurityDepositLabel, delay);
transitions.fadeOutAndRemove(buyerSecurityDepositValueCurrencyBox, delay);
model.onShowPayFundsScreen();
editOfferElements.stream().forEach(node -> {
node.setMouseTransparent(true);
node.setFocusTraversable(false);
});
balanceTextField.setTargetAmount(model.dataModel.totalToPayAsCoinProperty().get());
//noinspection PointlessBooleanExpression
if (!DevEnv.DEV_MODE) {
String key = "securityDepositInfo";
new Popup<>().backgroundInfo(Res.get("popup.info.securityDepositInfo"))
.actionButtonText(Res.get("shared.faq"))
.onAction(() -> GUIUtil.openWebPage("https://bisq.network/faq
.useIUnderstandButton()
.dontShowAgainId(key)
.show();
key = "createOfferFundWalletInfo";
String tradeAmountText = model.isSellOffer() ?
Res.get("createOffer.createOfferFundWalletInfo.tradeAmount", model.getTradeAmount()) : "";
String message = Res.get("createOffer.createOfferFundWalletInfo.msg",
model.totalToPay.get(),
tradeAmountText,
model.getSecurityDepositInfo(),
model.getMakerFee(),
model.getTxFee()
);
new Popup<>().headLine(Res.get("createOffer.createOfferFundWalletInfo.headline"))
.instruction(message)
.dontShowAgainId(key)
.show();
}
waitingForFundsBusyAnimation.play();
payFundsTitledGroupBg.setVisible(true);
totalToPayLabel.setVisible(true);
totalToPayTextField.setVisible(true);
addressLabel.setVisible(true);
addressTextField.setVisible(true);
qrCodeImageView.setVisible(true);
balanceLabel.setVisible(true);
balanceTextField.setVisible(true);
cancelButton2.setVisible(true);
totalToPayTextField.setInfoPopOver(createInfoPopover());
final byte[] imageBytes = QRCode
.from(getBitcoinURI())
.withSize(98, 98) // code has 41 elements 8 px is border with 98 we get double scale and min. border
.to(ImageType.PNG)
.stream()
.toByteArray();
Image qrImage = new Image(new ByteArrayInputStream(imageBytes));
qrCodeImageView.setImage(qrImage);
}
private void maybeShowClearXchangeWarning(PaymentAccount paymentAccount) {
if (paymentAccount.getPaymentMethod().getId().equals(PaymentMethod.CLEAR_X_CHANGE_ID) &&
!clearXchangeWarningDisplayed) {
clearXchangeWarningDisplayed = true;
UserThread.runAfter(GUIUtil::showClearXchangeWarning,
500, TimeUnit.MILLISECONDS);
}
}
private void onPaymentAccountsComboBoxSelected() {
PaymentAccount paymentAccount = paymentAccountsComboBox.getSelectionModel().getSelectedItem();
if (paymentAccount != null) {
maybeShowClearXchangeWarning(paymentAccount);
currencyComboBox.setVisible(paymentAccount.hasMultipleCurrencies());
if (paymentAccount.hasMultipleCurrencies()) {
final List<TradeCurrency> tradeCurrencies = paymentAccount.getTradeCurrencies();
currencyComboBox.setItems(FXCollections.observableArrayList(tradeCurrencies));
// we select comboBox following the user currency, if user currency not available in account, we select first
TradeCurrency tradeCurrency = model.getTradeCurrency();
if (tradeCurrencies.contains(tradeCurrency))
currencyComboBox.getSelectionModel().select(tradeCurrency);
else
currencyComboBox.getSelectionModel().select(tradeCurrencies.get(0));
model.onPaymentAccountSelected(paymentAccount);
} else {
TradeCurrency singleTradeCurrency = paymentAccount.getSingleTradeCurrency();
if (singleTradeCurrency != null)
currencyTextField.setText(singleTradeCurrency.getNameAndCode());
model.onPaymentAccountSelected(paymentAccount);
model.onCurrencySelected(model.dataModel.getTradeCurrency());
}
} else {
currencyComboBox.setVisible(false);
currencyTextField.setText("");
}
}
private void onCurrencyComboBoxSelected() {
model.onCurrencySelected(currencyComboBox.getSelectionModel().getSelectedItem());
}
// Navigation
private void close() {
if (closeHandler != null)
closeHandler.close();
}
// Bindings, Listeners
private void addBindings() {
priceCurrencyLabel.textProperty().bind(createStringBinding(() -> btcFormatter.getCounterCurrency(model.tradeCurrencyCode.get()), model.tradeCurrencyCode));
marketBasedPriceLabel.prefWidthProperty().bind(priceCurrencyLabel.widthProperty());
volumeCurrencyLabel.textProperty().bind(model.tradeCurrencyCode);
priceDescriptionLabel.textProperty().bind(createStringBinding(() -> btcFormatter.getPriceWithCurrencyCode(model.tradeCurrencyCode.get()), model.tradeCurrencyCode));
xLabel.setText("x");
volumeDescriptionLabel.textProperty().bind(createStringBinding(model.volumeDescriptionLabel::get, model.tradeCurrencyCode, model.volumeDescriptionLabel));
amountTextField.textProperty().bindBidirectional(model.amount);
minAmountTextField.textProperty().bindBidirectional(model.minAmount);
fixedPriceTextField.textProperty().bindBidirectional(model.price);
marketBasedPriceTextField.textProperty().bindBidirectional(model.marketPriceMargin);
volumeTextField.textProperty().bindBidirectional(model.volume);
volumeTextField.promptTextProperty().bind(model.volumePromptLabel);
totalToPayTextField.amountProperty().bind(model.totalToPay);
addressTextField.amountAsCoinProperty().bind(model.dataModel.getMissingCoin());
buyerSecurityDepositInputTextField.textProperty().bindBidirectional(model.buyerSecurityDeposit);
// Validation
amountTextField.validationResultProperty().bind(model.amountValidationResult);
minAmountTextField.validationResultProperty().bind(model.minAmountValidationResult);
fixedPriceTextField.validationResultProperty().bind(model.priceValidationResult);
volumeTextField.validationResultProperty().bind(model.volumeValidationResult);
buyerSecurityDepositInputTextField.validationResultProperty().bind(model.buyerSecurityDepositValidationResult);
// funding
fundingHBox.visibleProperty().bind(model.dataModel.getIsBtcWalletFunded().not().and(model.showPayFundsScreenDisplayed));
fundingHBox.managedProperty().bind(model.dataModel.getIsBtcWalletFunded().not().and(model.showPayFundsScreenDisplayed));
waitingForFundsLabel.textProperty().bind(model.waitingForFundsText);
placeOfferButton.visibleProperty().bind(model.dataModel.getIsBtcWalletFunded().and(model.showPayFundsScreenDisplayed));
placeOfferButton.managedProperty().bind(model.dataModel.getIsBtcWalletFunded().and(model.showPayFundsScreenDisplayed));
placeOfferButton.disableProperty().bind(model.isPlaceOfferButtonDisabled);
cancelButton2.disableProperty().bind(model.cancelButtonDisabled);
// trading account
currencyComboBox.prefWidthProperty().bind(paymentAccountsComboBox.widthProperty());
currencyComboBox.managedProperty().bind(currencyComboBox.visibleProperty());
currencyComboBoxLabel.visibleProperty().bind(currencyComboBox.visibleProperty());
currencyComboBoxLabel.managedProperty().bind(currencyComboBox.visibleProperty());
currencyTextField.visibleProperty().bind(currencyComboBox.visibleProperty().not());
currencyTextField.managedProperty().bind(currencyComboBox.visibleProperty().not());
currencyTextFieldLabel.visibleProperty().bind(currencyComboBox.visibleProperty().not());
currencyTextFieldLabel.managedProperty().bind(currencyComboBox.visibleProperty().not());
}
private void removeBindings() {
priceCurrencyLabel.textProperty().unbind();
fixedPriceTextField.disableProperty().unbind();
priceCurrencyLabel.disableProperty().unbind();
marketBasedPriceTextField.disableProperty().unbind();
marketBasedPriceLabel.disableProperty().unbind();
volumeCurrencyLabel.textProperty().unbind();
priceDescriptionLabel.textProperty().unbind();
xLabel.textProperty().unbind();
volumeDescriptionLabel.textProperty().unbind();
amountTextField.textProperty().unbindBidirectional(model.amount);
minAmountTextField.textProperty().unbindBidirectional(model.minAmount);
fixedPriceTextField.textProperty().unbindBidirectional(model.price);
marketBasedPriceTextField.textProperty().unbindBidirectional(model.marketPriceMargin);
marketBasedPriceLabel.prefWidthProperty().unbind();
volumeTextField.textProperty().unbindBidirectional(model.volume);
volumeTextField.promptTextProperty().unbindBidirectional(model.volume);
totalToPayTextField.amountProperty().unbind();
addressTextField.amountAsCoinProperty().unbind();
buyerSecurityDepositInputTextField.textProperty().unbindBidirectional(model.buyerSecurityDeposit);
// Validation
amountTextField.validationResultProperty().unbind();
minAmountTextField.validationResultProperty().unbind();
fixedPriceTextField.validationResultProperty().unbind();
volumeTextField.validationResultProperty().unbind();
buyerSecurityDepositInputTextField.validationResultProperty().unbind();
// funding
fundingHBox.visibleProperty().unbind();
fundingHBox.managedProperty().unbind();
waitingForFundsLabel.textProperty().unbind();
placeOfferButton.visibleProperty().unbind();
placeOfferButton.managedProperty().unbind();
placeOfferButton.disableProperty().unbind();
cancelButton2.disableProperty().unbind();
// trading account
currencyComboBox.managedProperty().unbind();
currencyComboBox.prefWidthProperty().unbind();
currencyComboBoxLabel.visibleProperty().unbind();
currencyComboBoxLabel.managedProperty().unbind();
currencyTextField.visibleProperty().unbind();
currencyTextField.managedProperty().unbind();
currencyTextFieldLabel.visibleProperty().unbind();
currencyTextFieldLabel.managedProperty().unbind();
}
private void addSubscriptions() {
isWaitingForFundsSubscription = EasyBind.subscribe(model.isWaitingForFunds, isWaitingForFunds -> {
waitingForFundsBusyAnimation.setIsRunning(isWaitingForFunds);
waitingForFundsLabel.setVisible(isWaitingForFunds);
waitingForFundsLabel.setManaged(isWaitingForFunds);
});
cancelButton2StyleSubscription = EasyBind.subscribe(placeOfferButton.visibleProperty(),
isVisible -> cancelButton2.setId(isVisible ? "cancel-button" : null));
balanceSubscription = EasyBind.subscribe(model.dataModel.getBalance(), balanceTextField::setBalance);
}
private void removeSubscriptions() {
isWaitingForFundsSubscription.unsubscribe();
cancelButton2StyleSubscription.unsubscribe();
balanceSubscription.unsubscribe();
}
private void createListeners() {
amountFocusedListener = (o, oldValue, newValue) -> {
model.onFocusOutAmountTextField(oldValue, newValue);
amountTextField.setText(model.amount.get());
};
minAmountFocusedListener = (o, oldValue, newValue) -> {
model.onFocusOutMinAmountTextField(oldValue, newValue);
minAmountTextField.setText(model.minAmount.get());
};
priceFocusedListener = (o, oldValue, newValue) -> {
model.onFocusOutPriceTextField(oldValue, newValue);
fixedPriceTextField.setText(model.price.get());
};
priceAsPercentageFocusedListener = (o, oldValue, newValue) -> {
model.onFocusOutPriceAsPercentageTextField(oldValue, newValue);
marketBasedPriceTextField.setText(model.marketPriceMargin.get());
};
volumeFocusedListener = (o, oldValue, newValue) -> {
model.onFocusOutVolumeTextField(oldValue, newValue);
volumeTextField.setText(model.volume.get());
};
buyerSecurityDepositFocusedListener = (o, oldValue, newValue) -> {
model.onFocusOutBuyerSecurityDepositTextField(oldValue, newValue);
buyerSecurityDepositInputTextField.setText(model.buyerSecurityDeposit.get());
};
errorMessageListener = (o, oldValue, newValue) -> {
if (newValue != null)
UserThread.runAfter(() -> new Popup<>().error(Res.get("createOffer.amountPriceBox.error.message", model.errorMessage.get()))
.show(), 100, TimeUnit.MILLISECONDS);
};
paymentAccountsComboBoxSelectionHandler = e -> onPaymentAccountsComboBoxSelected();
currencyComboBoxSelectionHandler = e -> onCurrencyComboBoxSelected();
tradeCurrencyCodeListener = (observable, oldValue, newValue) -> {
fixedPriceTextField.clear();
marketBasedPriceTextField.clear();
volumeTextField.clear();
};
placeOfferCompletedListener = (o, oldValue, newValue) -> {
if (DevEnv.DEV_MODE) {
close();
} else if (newValue) {
// We need a bit of delay to avoid issues with fade out/fade in of 2 popups
String key = "createOfferSuccessInfo";
if (DontShowAgainLookup.showAgain(key)) {
UserThread.runAfter(() -> new Popup<>().headLine(Res.get("createOffer.success.headline"))
.feedback(Res.get("createOffer.success.info"))
.dontShowAgainId(key)
.actionButtonTextWithGoTo("navigation.portfolio.myOpenOffers")
.onAction(() -> {
//noinspection unchecked
UserThread.runAfter(() ->
navigation.navigateTo(MainView.class, PortfolioView.class,
OpenOffersView.class),
100, TimeUnit.MILLISECONDS);
close();
})
.onClose(this::close)
.show(),
1);
} else {
close();
}
}
};
marketPriceAvailableListener = (observable, oldValue, newValue) -> updateMarketPriceAvailable();
}
private void updateMarketPriceAvailable() {
int marketPriceAvailableValue = model.marketPriceAvailableProperty.get();
if (marketPriceAvailableValue > -1) {
boolean isMarketPriceAvailable = marketPriceAvailableValue == 1;
percentagePriceBox.setVisible(isMarketPriceAvailable);
percentagePriceBox.setManaged(isMarketPriceAvailable);
toggleButtonsHBox.setVisible(isMarketPriceAvailable);
toggleButtonsHBox.setManaged(isMarketPriceAvailable);
boolean fixedPriceSelected = !model.dataModel.getUseMarketBasedPrice().get() || !isMarketPriceAvailable;
updatePriceToggleButtons(fixedPriceSelected);
}
}
private void addListeners() {
model.tradeCurrencyCode.addListener(tradeCurrencyCodeListener);
model.marketPriceAvailableProperty.addListener(marketPriceAvailableListener);
// focus out
amountTextField.focusedProperty().addListener(amountFocusedListener);
minAmountTextField.focusedProperty().addListener(minAmountFocusedListener);
fixedPriceTextField.focusedProperty().addListener(priceFocusedListener);
marketBasedPriceTextField.focusedProperty().addListener(priceAsPercentageFocusedListener);
volumeTextField.focusedProperty().addListener(volumeFocusedListener);
buyerSecurityDepositInputTextField.focusedProperty().addListener(buyerSecurityDepositFocusedListener);
// warnings
model.errorMessage.addListener(errorMessageListener);
// model.dataModel.feeFromFundingTxProperty.addListener(feeFromFundingTxListener);
model.placeOfferCompleted.addListener(placeOfferCompletedListener);
// UI actions
paymentAccountsComboBox.setOnAction(paymentAccountsComboBoxSelectionHandler);
currencyComboBox.setOnAction(currencyComboBoxSelectionHandler);
}
private void removeListeners() {
model.tradeCurrencyCode.removeListener(tradeCurrencyCodeListener);
model.marketPriceAvailableProperty.removeListener(marketPriceAvailableListener);
// focus out
amountTextField.focusedProperty().removeListener(amountFocusedListener);
minAmountTextField.focusedProperty().removeListener(minAmountFocusedListener);
fixedPriceTextField.focusedProperty().removeListener(priceFocusedListener);
marketBasedPriceTextField.focusedProperty().removeListener(priceAsPercentageFocusedListener);
volumeTextField.focusedProperty().removeListener(volumeFocusedListener);
buyerSecurityDepositInputTextField.focusedProperty().removeListener(buyerSecurityDepositFocusedListener);
// warnings
model.errorMessage.removeListener(errorMessageListener);
// model.dataModel.feeFromFundingTxProperty.removeListener(feeFromFundingTxListener);
model.placeOfferCompleted.removeListener(placeOfferCompletedListener);
// UI actions
paymentAccountsComboBox.setOnAction(null);
currencyComboBox.setOnAction(null);
}
// Build UI elements
private void addScrollPane() {
scrollPane = new ScrollPane();
scrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
scrollPane.setVbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED);
scrollPane.setFitToWidth(true);
scrollPane.setFitToHeight(true);
scrollPane.setOnScroll(e -> InputTextField.hideErrorMessageDisplay());
AnchorPane.setLeftAnchor(scrollPane, 0d);
AnchorPane.setTopAnchor(scrollPane, 0d);
AnchorPane.setRightAnchor(scrollPane, 0d);
AnchorPane.setBottomAnchor(scrollPane, 0d);
root.getChildren().add(scrollPane);
}
private void addGridPane() {
gridPane = new GridPane();
gridPane.setPadding(new Insets(30, 25, -1, 25));
gridPane.setHgap(5);
gridPane.setVgap(5);
ColumnConstraints columnConstraints1 = new ColumnConstraints();
columnConstraints1.setHalignment(HPos.RIGHT);
columnConstraints1.setHgrow(Priority.NEVER);
columnConstraints1.setMinWidth(200);
ColumnConstraints columnConstraints2 = new ColumnConstraints();
columnConstraints2.setHgrow(Priority.ALWAYS);
ColumnConstraints columnConstraints3 = new ColumnConstraints();
columnConstraints3.setHgrow(Priority.NEVER);
gridPane.getColumnConstraints().addAll(columnConstraints1, columnConstraints2, columnConstraints3);
scrollPane.setContent(gridPane);
}
private void addPaymentGroup() {
TitledGroupBg titledGroupBg = addTitledGroupBg(gridPane, gridRow, 2, Res.get("shared.selectTradingAccount"));
GridPane.setColumnSpan(titledGroupBg, 3);
//noinspection unchecked
paymentAccountsComboBox = addLabelComboBox(gridPane, gridRow, Res.getWithCol("shared.tradingAccount"), Layout.FIRST_ROW_DISTANCE).second;
paymentAccountsComboBox.setPromptText(Res.get("shared.selectTradingAccount"));
paymentAccountsComboBox.setMinWidth(300);
editOfferElements.add(paymentAccountsComboBox);
// we display either currencyComboBox (multi currency account) or currencyTextField (single)
Tuple2<Label, ComboBox> currencyComboBoxTuple = addLabelComboBox(gridPane, ++gridRow, Res.getWithCol("shared.currency"));
currencyComboBoxLabel = currencyComboBoxTuple.first;
editOfferElements.add(currencyComboBoxLabel);
//noinspection unchecked
currencyComboBox = currencyComboBoxTuple.second;
editOfferElements.add(currencyComboBox);
currencyComboBox.setPromptText(Res.get("list.currency.select"));
currencyComboBox.setConverter(new StringConverter<TradeCurrency>() {
@Override
public String toString(TradeCurrency tradeCurrency) {
return tradeCurrency.getNameAndCode();
}
@Override
public TradeCurrency fromString(String s) {
return null;
}
});
Tuple2<Label, TextField> currencyTextFieldTuple = addLabelTextField(gridPane, gridRow, Res.getWithCol("shared.currency"), "", 5);
currencyTextFieldLabel = currencyTextFieldTuple.first;
editOfferElements.add(currencyTextFieldLabel);
currencyTextField = currencyTextFieldTuple.second;
editOfferElements.add(currencyTextField);
}
private void addAmountPriceGroup() {
TitledGroupBg titledGroupBg = addTitledGroupBg(gridPane, ++gridRow, 2, Res.get("createOffer.setAmountPrice"), Layout.GROUP_DISTANCE);
GridPane.setColumnSpan(titledGroupBg, 3);
imageView = new ImageView();
imageView.setPickOnBounds(true);
directionLabel = new AutoTooltipLabel();
directionLabel.setAlignment(Pos.CENTER);
directionLabel.setPadding(new Insets(-5, 0, 0, 0));
directionLabel.setId("direction-icon-label");
VBox imageVBox = new VBox();
imageVBox.setAlignment(Pos.CENTER);
imageVBox.setSpacing(12);
imageVBox.getChildren().addAll(imageView, directionLabel);
GridPane.setRowIndex(imageVBox, gridRow);
GridPane.setRowSpan(imageVBox, 2);
GridPane.setMargin(imageVBox, new Insets(Layout.FIRST_ROW_AND_GROUP_DISTANCE, 10, 10, 10));
gridPane.getChildren().add(imageVBox);
addAmountPriceFields();
addSecondRow();
}
private void addOptionsGroup() {
setDepositTitledGroupBg = addTitledGroupBg(gridPane, ++gridRow, 2, Res.get("createOffer.setDeposit"), Layout.GROUP_DISTANCE);
addBuyerSecurityDepositRow();
Tuple2<Button, Button> tuple = add2ButtonsAfterGroup(gridPane, ++gridRow,
Res.get("shared.nextStep"), Res.get("shared.cancel"));
nextButton = tuple.first;
editOfferElements.add(nextButton);
nextButton.disableProperty().bind(model.isNextButtonDisabled);
cancelButton1 = tuple.second;
editOfferElements.add(cancelButton1);
cancelButton1.setDefaultButton(false);
cancelButton1.setOnAction(e -> {
close();
model.dataModel.swapTradeToSavings();
});
cancelButton1.setId("cancel-button");
GridPane.setMargin(nextButton, new Insets(-35, 0, 0, 0));
nextButton.setOnAction(e -> {
if (model.isPriceInRange()) {
if (DevEnv.DAO_TRADING_ACTIVATED)
showFeeOption();
else
onShowPayFundsScreen();
}
});
}
private void showFeeOption() {
Coin makerFee = model.dataModel.getMakerFee(false);
String missingBsq = null;
if (makerFee != null) {
missingBsq = Res.get("popup.warning.insufficientBsqFundsForBtcFeePayment",
bsqFormatter.formatCoinWithCode(makerFee.subtract(model.dataModel.getBsqBalance())));
} else if (model.dataModel.getBsqBalance().isZero())
missingBsq = Res.get("popup.warning.noBsqFundsForBtcFeePayment");
new FeeOptionWindow(model.makerFeeWithCode,
model.dataModel.isCurrencyForMakerFeeBtc(),
model.dataModel.isBsqForFeeAvailable(),
missingBsq,
navigation,
this::onShowPayFundsScreen)
.onSelectionChangedHandler(model::setIsCurrencyForMakerFeeBtc)
.onAction(this::onShowPayFundsScreen)
.hideCloseButton()
.show();
}
private void addBuyerSecurityDepositRow() {
final double top = model.dataModel.isBsqForFeeAvailable() ? 0 : Layout.FIRST_ROW_AND_GROUP_DISTANCE;
buyerSecurityDepositLabel = addLabel(gridPane, ++gridRow,
Res.getWithCol("shared.securityDepositBox.description", Res.get("shared.buyer")),
top);
Tuple3<HBox, InputTextField, Label> tuple = getEditableValueCurrencyBox(
Res.get("createOffer.securityDeposit.prompt"));
buyerSecurityDepositValueCurrencyBox = tuple.first;
buyerSecurityDepositInputTextField = tuple.second;
Label buyerSecurityDepositBtcLabel = tuple.third;
editOfferElements.add(buyerSecurityDepositInputTextField);
editOfferElements.add(buyerSecurityDepositBtcLabel);
GridPane.setRowIndex(buyerSecurityDepositValueCurrencyBox, gridRow);
GridPane.setColumnIndex(buyerSecurityDepositValueCurrencyBox, 1);
GridPane.setColumnSpan(buyerSecurityDepositValueCurrencyBox, 2);
GridPane.setMargin(buyerSecurityDepositValueCurrencyBox, new Insets(top, 0, 0, 0));
gridPane.getChildren().add(buyerSecurityDepositValueCurrencyBox);
}
private void addFundingGroup() {
// don't increase gridRow as we removed button when this gets visible
payFundsTitledGroupBg = addTitledGroupBg(gridPane, gridRow, 3,
Res.get("createOffer.fundsBox.title"), Layout.GROUP_DISTANCE);
GridPane.setColumnSpan(payFundsTitledGroupBg, 3);
payFundsTitledGroupBg.setVisible(false);
Tuple2<Label, FundsTextField> fundsTuple = addLabelFundsTextfield(gridPane, gridRow,
Res.get("shared.totalsNeeded"), Layout.FIRST_ROW_AND_GROUP_DISTANCE);
totalToPayLabel = fundsTuple.first;
totalToPayLabel.setVisible(false);
totalToPayTextField = fundsTuple.second;
totalToPayTextField.setVisible(false);
qrCodeImageView = new ImageView();
qrCodeImageView.setVisible(false);
qrCodeImageView.getStyleClass().add("qr-code");
Tooltip.install(qrCodeImageView, new Tooltip(Res.get("shared.openLargeQRWindow")));
qrCodeImageView.setOnMouseClicked(e -> GUIUtil.showFeeInfoBeforeExecute(
() -> UserThread.runAfter(
() -> new QRCodeWindow(getBitcoinURI()).show(),
200, TimeUnit.MILLISECONDS)));
GridPane.setRowIndex(qrCodeImageView, gridRow);
GridPane.setColumnIndex(qrCodeImageView, 2);
GridPane.setRowSpan(qrCodeImageView, 3);
GridPane.setMargin(qrCodeImageView, new Insets(Layout.FIRST_ROW_AND_GROUP_DISTANCE - 9, 0, 0, 5));
gridPane.getChildren().add(qrCodeImageView);
Tuple2<Label, AddressTextField> addressTuple = addLabelAddressTextField(gridPane, ++gridRow,
Res.get("shared.tradeWalletAddress"));
addressLabel = addressTuple.first;
addressLabel.setVisible(false);
addressTextField = addressTuple.second;
addressTextField.setVisible(false);
Tuple2<Label, BalanceTextField> balanceTuple = addLabelBalanceTextField(gridPane, ++gridRow,
Res.get("shared.tradeWalletBalance"));
balanceLabel = balanceTuple.first;
balanceLabel.setVisible(false);
balanceTextField = balanceTuple.second;
balanceTextField.setVisible(false);
fundingHBox = new HBox();
fundingHBox.setVisible(false);
fundingHBox.setManaged(false);
fundingHBox.setSpacing(10);
Button fundFromSavingsWalletButton = new AutoTooltipButton(Res.get("shared.fundFromSavingsWalletButton"));
fundFromSavingsWalletButton.setDefaultButton(false);
fundFromSavingsWalletButton.setOnAction(e -> model.fundFromSavingsWallet());
Label label = new AutoTooltipLabel(Res.get("shared.OR"));
label.setPadding(new Insets(5, 0, 0, 0));
Button fundFromExternalWalletButton = new AutoTooltipButton(Res.get("shared.fundFromExternalWalletButton"));
fundFromExternalWalletButton.setDefaultButton(false);
fundFromExternalWalletButton.setOnAction(e -> GUIUtil.showFeeInfoBeforeExecute(this::openWallet));
waitingForFundsBusyAnimation = new BusyAnimation();
waitingForFundsLabel = new AutoTooltipLabel();
waitingForFundsLabel.setPadding(new Insets(5, 0, 0, 0));
fundingHBox.getChildren().addAll(fundFromSavingsWalletButton, label, fundFromExternalWalletButton, waitingForFundsBusyAnimation, waitingForFundsLabel);
GridPane.setRowIndex(fundingHBox, ++gridRow);
GridPane.setColumnIndex(fundingHBox, 1);
GridPane.setMargin(fundingHBox, new Insets(15, 10, 0, 0));
gridPane.getChildren().add(fundingHBox);
placeOfferButton = addButtonAfterGroup(gridPane, gridRow, "");
placeOfferButton.setOnAction(e -> onPlaceOffer());
placeOfferButton.setMinHeight(40);
placeOfferButton.setPadding(new Insets(0, 20, 0, 20));
cancelButton2 = addButton(gridPane, ++gridRow, Res.get("shared.cancel"));
cancelButton2.setOnAction(e -> {
if (model.dataModel.getIsBtcWalletFunded().get()) {
new Popup<>().warning(Res.get("createOffer.warnCancelOffer"))
.closeButtonText(Res.get("shared.no"))
.actionButtonText(Res.get("shared.yesCancel"))
.onAction(() -> {
close();
model.dataModel.swapTradeToSavings();
})
.show();
} else {
close();
model.dataModel.swapTradeToSavings();
}
});
cancelButton2.setDefaultButton(false);
cancelButton2.setVisible(false);
}
private void openWallet() {
try {
Utilities.openURI(URI.create(getBitcoinURI()));
} catch (Exception ex) {
log.warn(ex.getMessage());
new Popup<>().warning(Res.get("shared.openDefaultWalletFailed")).show();
}
}
@NotNull
private String getBitcoinURI() {
return GUIUtil.getBitcoinURI(addressTextField.getAddress(), model.dataModel.getMissingCoin().get(),
model.getPaymentLabel());
}
private void addAmountPriceFields() {
// amountBox
Tuple3<HBox, InputTextField, Label> amountValueCurrencyBoxTuple = getEditableValueCurrencyBox(Res.get("createOffer.amount.prompt"));
HBox amountValueCurrencyBox = amountValueCurrencyBoxTuple.first;
amountTextField = amountValueCurrencyBoxTuple.second;
editOfferElements.add(amountTextField);
Label amountBtcLabel = amountValueCurrencyBoxTuple.third;
editOfferElements.add(amountBtcLabel);
Tuple2<Label, VBox> amountInputBoxTuple = getTradeInputBox(amountValueCurrencyBox, model.getAmountDescription());
amountDescriptionLabel = amountInputBoxTuple.first;
editOfferElements.add(amountDescriptionLabel);
VBox amountBox = amountInputBoxTuple.second;
xLabel = new AutoTooltipLabel();
xLabel.setFont(Font.font("Helvetica-Bold", 20));
xLabel.setPadding(new Insets(14, 3, 0, 3));
xLabel.setMinWidth(14);
xLabel.setMaxWidth(14);
// price as percent
Tuple3<HBox, InputTextField, Label> priceAsPercentageTuple = getEditableValueCurrencyBox(Res.get("createOffer.price.prompt"));
HBox priceAsPercentageValueCurrencyBox = priceAsPercentageTuple.first;
marketBasedPriceTextField = priceAsPercentageTuple.second;
editOfferElements.add(marketBasedPriceTextField);
marketBasedPriceLabel = priceAsPercentageTuple.third;
editOfferElements.add(marketBasedPriceLabel);
Tuple2<Label, VBox> priceAsPercentageInputBoxTuple = getTradeInputBox(priceAsPercentageValueCurrencyBox,
Res.get("shared.distanceInPercent"));
priceAsPercentageInputBoxTuple.first.setPrefWidth(200);
percentagePriceBox = priceAsPercentageInputBoxTuple.second;
// Fixed/Percentage toggle
ToggleGroup toggleGroup = new ToggleGroup();
fixedPriceButton = new AutoTooltipToggleButton(Res.get("createOffer.fixed"));
editOfferElements.add(fixedPriceButton);
fixedPriceButton.setId("toggle-price-left");
fixedPriceButton.setToggleGroup(toggleGroup);
fixedPriceButton.selectedProperty().addListener((ov, oldValue, newValue) -> {
updatePriceToggleButtons(newValue);
});
useMarketBasedPriceButton = new AutoTooltipToggleButton(Res.get("createOffer.percentage"));
editOfferElements.add(useMarketBasedPriceButton);
useMarketBasedPriceButton.setId("toggle-price-right");
useMarketBasedPriceButton.setToggleGroup(toggleGroup);
useMarketBasedPriceButton.selectedProperty().addListener((ov, oldValue, newValue) -> {
updatePriceToggleButtons(!newValue);
});
toggleButtonsHBox = new HBox();
toggleButtonsHBox.setPadding(new Insets(16, 0, 0, 0));
toggleButtonsHBox.getChildren().addAll(fixedPriceButton, useMarketBasedPriceButton);
Label resultLabel = new AutoTooltipLabel("=");
resultLabel.setFont(Font.font("Helvetica-Bold", 20));
resultLabel.setPadding(new Insets(14, 2, 0, 2));
// volume
Tuple3<HBox, InputTextField, Label> volumeValueCurrencyBoxTuple = getEditableValueCurrencyBox(Res.get("createOffer.volume.prompt"));
HBox volumeValueCurrencyBox = volumeValueCurrencyBoxTuple.first;
volumeTextField = volumeValueCurrencyBoxTuple.second;
editOfferElements.add(volumeTextField);
volumeCurrencyLabel = volumeValueCurrencyBoxTuple.third;
editOfferElements.add(volumeCurrencyLabel);
Tuple2<Label, VBox> volumeInputBoxTuple = getTradeInputBox(volumeValueCurrencyBox, model.volumeDescriptionLabel.get());
volumeDescriptionLabel = volumeInputBoxTuple.first;
editOfferElements.add(volumeDescriptionLabel);
VBox volumeBox = volumeInputBoxTuple.second;
firstRowHBox = new HBox();
firstRowHBox.setSpacing(5);
firstRowHBox.setAlignment(Pos.CENTER_LEFT);
firstRowHBox.getChildren().addAll(amountBox, xLabel, percentagePriceBox, toggleButtonsHBox, resultLabel, volumeBox);
GridPane.setRowIndex(firstRowHBox, gridRow);
GridPane.setColumnIndex(firstRowHBox, 1);
GridPane.setMargin(firstRowHBox, new Insets(Layout.FIRST_ROW_AND_GROUP_DISTANCE, 10, 0, 0));
GridPane.setColumnSpan(firstRowHBox, 2);
gridPane.getChildren().add(firstRowHBox);
}
private void updatePriceToggleButtons(boolean fixedPriceSelected) {
int marketPriceAvailable = model.marketPriceAvailableProperty.get();
fixedPriceSelected = fixedPriceSelected || (marketPriceAvailable == 0);
if (marketPriceAvailable == 1) {
model.dataModel.setUseMarketBasedPrice(!fixedPriceSelected);
if (!fixedPriceButton.isSelected() && fixedPriceSelected)
fixedPriceButton.setSelected(true);
if (useMarketBasedPriceButton.isSelected() && !fixedPriceSelected)
useMarketBasedPriceButton.setSelected(false);
}
fixedPriceButton.setMouseTransparent(fixedPriceSelected);
useMarketBasedPriceButton.setMouseTransparent(!fixedPriceSelected);
fixedPriceButton.getStyleClass().removeAll("toggle-button-active","toggle-button-inactive");
useMarketBasedPriceButton.getStyleClass().removeAll("toggle-button-active","toggle-button-inactive");
fixedPriceButton.getStyleClass().add(fixedPriceSelected ?
"toggle-button-active" : "toggle-button-inactive");
useMarketBasedPriceButton.getStyleClass().add(!fixedPriceSelected ?
"toggle-button-active" : "toggle-button-inactive");
if (fixedPriceSelected) {
if (firstRowHBox.getChildren().contains(percentagePriceBox))
firstRowHBox.getChildren().remove(percentagePriceBox);
if (secondRowHBox.getChildren().contains(fixedPriceBox))
secondRowHBox.getChildren().remove(fixedPriceBox);
if (!firstRowHBox.getChildren().contains(fixedPriceBox))
firstRowHBox.getChildren().add(2, fixedPriceBox);
if (!secondRowHBox.getChildren().contains(percentagePriceBox))
secondRowHBox.getChildren().add(2, percentagePriceBox);
} else {
if (firstRowHBox.getChildren().contains(fixedPriceBox))
firstRowHBox.getChildren().remove(fixedPriceBox);
if (secondRowHBox.getChildren().contains(percentagePriceBox))
secondRowHBox.getChildren().remove(percentagePriceBox);
if (!firstRowHBox.getChildren().contains(percentagePriceBox))
firstRowHBox.getChildren().add(2, percentagePriceBox);
if (!secondRowHBox.getChildren().contains(fixedPriceBox))
secondRowHBox.getChildren().add(2, fixedPriceBox);
}
}
private void addSecondRow() {
// price as fiat
Tuple3<HBox, InputTextField, Label> priceValueCurrencyBoxTuple = getEditableValueCurrencyBox(
Res.get("createOffer.price.prompt"));
HBox priceValueCurrencyBox = priceValueCurrencyBoxTuple.first;
fixedPriceTextField = priceValueCurrencyBoxTuple.second;
editOfferElements.add(fixedPriceTextField);
priceCurrencyLabel = priceValueCurrencyBoxTuple.third;
editOfferElements.add(priceCurrencyLabel);
Tuple2<Label, VBox> priceInputBoxTuple = getTradeInputBox(priceValueCurrencyBox, "");
priceDescriptionLabel = priceInputBoxTuple.first;
editOfferElements.add(priceDescriptionLabel);
fixedPriceBox = priceInputBoxTuple.second;
marketBasedPriceTextField.setPromptText(Res.get("shared.enterPercentageValue"));
marketBasedPriceLabel.setText("%");
marketBasedPriceLabel.getStyleClass().add("percentage-label");
Tuple3<HBox, InputTextField, Label> amountValueCurrencyBoxTuple = getEditableValueCurrencyBox(
Res.get("createOffer.amount.prompt"));
HBox amountValueCurrencyBox = amountValueCurrencyBoxTuple.first;
minAmountTextField = amountValueCurrencyBoxTuple.second;
editOfferElements.add(minAmountTextField);
Label minAmountBtcLabel = amountValueCurrencyBoxTuple.third;
editOfferElements.add(minAmountBtcLabel);
Tuple2<Label, VBox> amountInputBoxTuple = getTradeInputBox(amountValueCurrencyBox,
Res.get("createOffer.amountPriceBox.minAmountDescription"));
Label xLabel = new AutoTooltipLabel("x");
xLabel.setFont(Font.font("Helvetica-Bold", 20));
xLabel.setPadding(new Insets(14, 3, 0, 3));
xLabel.setVisible(false); // we just use it to get the same layout as the upper row
secondRowHBox = new HBox();
secondRowHBox.setSpacing(5);
secondRowHBox.setAlignment(Pos.CENTER_LEFT);
secondRowHBox.getChildren().addAll(amountInputBoxTuple.second, xLabel, fixedPriceBox);
GridPane.setRowIndex(secondRowHBox, ++gridRow);
GridPane.setColumnIndex(secondRowHBox, 1);
GridPane.setMargin(secondRowHBox, new Insets(0, 10, 0, 0));
GridPane.setColumnSpan(secondRowHBox, 2);
gridPane.getChildren().add(secondRowHBox);
}
// PayInfo
private GridPane createInfoPopover() {
GridPane infoGridPane = new GridPane();
infoGridPane.setHgap(5);
infoGridPane.setVgap(5);
infoGridPane.setPadding(new Insets(10, 10, 10, 10));
int i = 0;
if (model.isSellOffer())
addPayInfoEntry(infoGridPane, i++, Res.getWithCol("shared.tradeAmount"), model.tradeAmount.get());
addPayInfoEntry(infoGridPane, i++, Res.getWithCol("shared.yourSecurityDeposit"), model.getSecurityDepositInfo());
addPayInfoEntry(infoGridPane, i++, Res.get("createOffer.fundsBox.offerFee"), model.getMakerFee());
addPayInfoEntry(infoGridPane, i++, Res.get("createOffer.fundsBox.networkFee"), model.getTxFee());
Separator separator = new Separator();
separator.setOrientation(Orientation.HORIZONTAL);
separator.getStyleClass().add("offer-separator");
GridPane.setConstraints(separator, 1, i++);
infoGridPane.getChildren().add(separator);
addPayInfoEntry(infoGridPane, i, Res.getWithCol("shared.total"), model.getTotalToPayInfo());
return infoGridPane;
}
private void addPayInfoEntry(GridPane infoGridPane, int row, String labelText, String value) {
Label label = new AutoTooltipLabel(labelText);
TextField textField = new TextField(value);
textField.setMinWidth(500);
textField.setEditable(false);
textField.setFocusTraversable(false);
textField.setId("payment-info");
GridPane.setConstraints(label, 0, row, 1, 1, HPos.RIGHT, VPos.CENTER);
GridPane.setConstraints(textField, 1, row);
infoGridPane.getChildren().addAll(label, textField);
}
}
|
package com.google.gwt.query.vm;
// import org.apache.http.impl.client.HttpClientBuilder;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.query.client.Binder;
import com.google.gwt.query.client.Function;
import com.google.gwt.query.client.GQ;
import com.google.gwt.query.client.GQuery;
import com.google.gwt.query.client.Promise;
import com.google.gwt.query.client.plugins.ajax.Ajax.AjaxTransport;
import com.google.gwt.query.client.plugins.ajax.Ajax.Settings;
import com.google.gwt.query.client.plugins.deferred.PromiseFunction;
import com.google.gwt.user.server.Base64Utils;
public class AjaxTransportJre implements AjaxTransport {
private static String localDomain = null;
public static void enableCORS(String domain) {
localDomain = domain;
System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
}
private final String USER_AGENT = "Mozilla/5.0";
private final String jsonpCbRexp = "(?ms)^.*jre_callback\\((.*)\\).*$";
public Promise getJsonP(final Settings settings) {
String url = settings.getUrl().replaceFirst("callback=[^&]*", "");
url += (url.contains("?") ? "&" : "?") + "callback=jre_callback";
settings.setUrl(url);
if (settings.getTimeout() < 1) {
settings.setTimeout(10000);
}
return getXhr(settings, false)
.then(new Function() {
public Object f(Object... args) {
Response response = arguments(0);
if (response.getText().matches(jsonpCbRexp)) {
return GQ.create(response.getText().replaceFirst(jsonpCbRexp, "$1"));
} else {
return GQuery.Deferred().reject().promise();
}
}
});
}
public Promise getLoadScript(Settings settings) {
return getXhr(settings, false);
}
public Promise getXhr(final Settings settings) {
return getXhr(settings, true);
}
private Promise getXhr(final Settings settings, final boolean cors) {
return new PromiseFunction() {
public void f(Deferred dfd) {
try {
Response response = httpClient(settings, cors);
int status = response.getStatusCode();
if (status <= 0 || status >= 400) {
String statusText = status <= 0 ? "Bad CORS" : response.getStatusText();
dfd.reject(null, new RequestException("HTTP ERROR: " + status + " " + statusText + "\n" + response.getText()));
} else {
dfd.resolve(response, null);
}
} catch (Exception e) {
dfd.reject(e, null);
}
}
};
}
private Response httpClient(Settings s, boolean cors) throws Exception {
String url = s.getUrl();
assert url.toLowerCase().startsWith("http");
URL u = new URL(url);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod(s.getType());
c.setRequestProperty("User-Agent", USER_AGENT);
if (s.getUsername() != null && s.getPassword() != null) {
c.setRequestProperty ("Authorization", "Basic " + Base64Utils.toBase64((s.getUsername() + ":" + s.getPassword()).getBytes()));
}
boolean isCORS = cors && localDomain != null && !s.getUrl().contains(localDomain);
if (isCORS) {
// TODO: fetch options previously to the request
// >> OPTIONS
// Access-Control-Allow-Credentials: true
// Access-Control-Request-Headers: content-type
// Access-Control-Allow-Headers
// Access-Control-Request-Method
// Access-Control-Allow-Methods: POST, GET
// Allow: GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS
// >> POST/GET
// Access-Control-Allow-Credentials: true
c.setRequestProperty("Origin", localDomain);
}
if (s.getTimeout() > 0) {
c.setConnectTimeout(s.getTimeout());
c.setReadTimeout(s.getTimeout());
}
Binder headers = s.getHeaders();
if (headers != null) {
for (String h : headers.getFieldNames()) {
c.setRequestProperty(h, "" + headers.get(h));
}
}
if (s.getType().matches("POST|PUT")) {
String ctype = s.getDataType();
if (s.getDataType().toLowerCase().startsWith("json")) {
ctype = "application/json; charset=utf-8";
}
c.setRequestProperty("Content-Type", ctype);
c.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(c.getOutputStream());
wr.writeBytes(s.getDataString());
wr.flush();
wr.close();
}
int code = c.getResponseCode();
if (isCORS && !localDomain.equals(c.getHeaderField("Access-Control-Allow-Origin"))) {
code = 0;
}
BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine + "\n");
}
in.close();
return new ResponseJre(code, c.getResponseMessage(), response.toString(), c.getHeaderFields());
}
}
|
package dr.app.beast;
import org.virion.jam.components.WholeNumberField;
import org.virion.jam.html.SimpleLinkListener;
import org.virion.jam.panels.OptionsPanel;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
public class BeastDialog {
private final JFrame frame;
private final OptionsPanel optionPanel;
private final WholeNumberField seedText = new WholeNumberField((long)1, Long.MAX_VALUE);
private final JCheckBox beagleCheckBox = new JCheckBox("Use BEAGLE library if available:");
private final JCheckBox beagleInfoCheckBox = new JCheckBox("Show list of available BEAGLE resources and Quit");
private final JComboBox beagleResourceCombo = new JComboBox(new Object[] { "GPU", "CPU" });
private final JComboBox beaglePrecisionCombo = new JComboBox(new Object[] { "Single", "Double" });
private final JComboBox threadsCombo = new JComboBox(new Object[] { "Automatic", 0, 1, 2, 3, 4, 5, 6, 7, 8 });
private File inputFile = null;
public BeastDialog(final JFrame frame, final String titleString, final Icon icon) {
this.frame = frame;
optionPanel = new OptionsPanel(12, 12);
//this.frame = frame;
JPanel panel = new JPanel(new BorderLayout());
panel.setOpaque(false);
final JLabel titleText = new JLabel(titleString);
titleText.setIcon(icon);
optionPanel.addSpanningComponent(titleText);
titleText.setFont(new Font("sans-serif", 0, 12));
final JButton inputFileButton = new JButton("Choose File...");
final JTextField inputFileNameText = new JTextField("not selected", 16);
inputFileButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent ae) {
FileDialog dialog = new FileDialog(frame,
"Select target file...",
FileDialog.LOAD);
dialog.setVisible(true);
if (dialog.getFile() == null) {
// the dialog was cancelled...
return;
}
inputFile = new File(dialog.getDirectory(), dialog.getFile());
inputFileNameText.setText(inputFile.getName());
}});
inputFileNameText.setEditable(false);
JPanel panel1 = new JPanel(new BorderLayout(0,0));
panel1.add(inputFileNameText, BorderLayout.CENTER);
panel1.add(inputFileButton, BorderLayout.EAST);
optionPanel.addComponentWithLabel("BEAST XML File: ", panel1);
optionPanel.addSeparator();
seedText.setColumns(12);
optionPanel.addComponentWithLabel("Random number seed: ", seedText);
optionPanel.addComponentWithLabel("Thread pool size: ", threadsCombo);
optionPanel.addSeparator();
optionPanel.addSpanningComponent(beagleCheckBox);
beagleCheckBox.setSelected(true);
final OptionsPanel optionPanel1 = new OptionsPanel(0,12);
// optionPanel1.setBorder(BorderFactory.createEmptyBorder());
optionPanel1.setBorder(new TitledBorder(""));
OptionsPanel optionPanel2 = new OptionsPanel(0,12);
optionPanel2.setBorder(BorderFactory.createEmptyBorder());
final JLabel label1 = optionPanel2.addComponentWithLabel("Prefer use of: ", beagleResourceCombo);
final JLabel label2 = optionPanel2.addComponentWithLabel("Prefer precision: ", beaglePrecisionCombo);
optionPanel2.addComponent(beagleInfoCheckBox);
optionPanel1.addComponent(optionPanel2);
final JEditorPane beagleInfo = new JEditorPane("text/html",
"<html><div style=\"font-family:sans-serif;font-size:12;\"><p>BEAGLE is a high-performance phylogenetic library that can make use of<br>" +
"additional computational resources such as graphics boards. It must be<br>" +
"downloaded and installed independently of BEAST:</p>" +
"<pre><a href=\"http:
beagleInfo.setOpaque(false);
beagleInfo.setEditable(false);
beagleInfo.addHyperlinkListener(new SimpleLinkListener());
optionPanel1.addComponent(beagleInfo);
optionPanel.addSpanningComponent(optionPanel1);
beagleInfoCheckBox.setEnabled(false);
beagleCheckBox.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
beagleInfo.setEnabled(beagleCheckBox.isSelected());
beagleInfoCheckBox.setEnabled(beagleCheckBox.isSelected());
label1.setEnabled(beagleCheckBox.isSelected());
beagleResourceCombo.setEnabled(beagleCheckBox.isSelected());
label2.setEnabled(beagleCheckBox.isSelected());
beaglePrecisionCombo.setEnabled(beagleCheckBox.isSelected());
}
});
beagleResourceCombo.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (beagleResourceCombo.getSelectedItem().equals("GPU")) {
beaglePrecisionCombo.setSelectedItem("Single");
label2.setEnabled(false);
beaglePrecisionCombo.setEnabled(false);
} else {
label2.setEnabled(true);
beaglePrecisionCombo.setEnabled(true);
}
}
});
beagleCheckBox.setSelected(false);
beagleResourceCombo.setSelectedItem("GPU");
}
public boolean showDialog(String title, long seed) {
JOptionPane optionPane = new JOptionPane(optionPanel,
JOptionPane.PLAIN_MESSAGE,
JOptionPane.OK_CANCEL_OPTION,
null,
new String[] { "Run", "Quit" },
"Run");
optionPane.setBorder(new EmptyBorder(12, 12, 12, 12));
seedText.setValue(seed);
final JDialog dialog = optionPane.createDialog(frame, title);
//dialog.setResizable(true);
dialog.pack();
dialog.setVisible(true);
return optionPane.getValue().equals("Run");
}
public int getSeed() {
return seedText.getValue();
}
public boolean useBeagle() {
return beagleCheckBox.isSelected();
}
public boolean preferBeagleGPU() {
return beagleResourceCombo.getSelectedItem().equals("GPU");
}
public boolean preferBeagleCPU() {
return beagleResourceCombo.getSelectedItem().equals("CPU");
}
public boolean preferBeagleSingle() {
return beaglePrecisionCombo.getSelectedItem().equals("Single");
}
public boolean preferBeagleDouble() {
return beaglePrecisionCombo.getSelectedItem().equals("Double");
}
public boolean showBeagleInfo() {
return beagleInfoCheckBox.isSelected();
}
public int getThreadPoolSize() {
if (threadsCombo.getSelectedIndex() == 0) {
// Automatic
return -1;
}
return (Integer)threadsCombo.getSelectedItem();
}
public File getInputFile() {
return inputFile;
}
}
|
package editor;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import abstracts.Tile;
import editor.EditorConstants.Metadata;
public class LevelEditor extends JFrame {
private static final long serialVersionUID = -8739477187675627751L;
public static final int WIDTH = 160;
public static final int HEIGHT = 144;
public static final int SIZE = 4;
private ArrayList<Data> filepaths = new ArrayList<Data>();
public ControlPanel controlPanel;
public FileControl fileControlPanel;
public DrawingBoard drawingBoardPanel;
public TilePropertiesPanel propertiesPanel;
public StatusPanel statusPanel;
public Properties properties;
public String message;
public boolean running;
public EditorInput input;
public LevelEditor(String name) {
super(name);
running = true;
Dimension size = new Dimension(WIDTH * SIZE, HEIGHT * SIZE);
this.setSize(size);
this.setPreferredSize(size);
this.setMinimumSize(size);
this.setMaximumSize(size);
this.setLayout(new BorderLayout());
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setVisible(true);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent event) {
running = false;
}
});
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (input == null) {
input = new EditorInput(editor.LevelEditor.this);
addMouseListener(input);
addMouseMotionListener(input);
}
if (fileControlPanel == null) {
fileControlPanel = new FileControl(editor.LevelEditor.this);
fileControlPanel.addMouseListener(input);
fileControlPanel.addMouseMotionListener(input);
add(fileControlPanel, BorderLayout.NORTH);
validate();
}
if (controlPanel == null) {
controlPanel = new ControlPanel(editor.LevelEditor.this);
controlPanel.addMouseListener(input);
controlPanel.addMouseMotionListener(input);
add(controlPanel, BorderLayout.WEST);
validate();
}
if (drawingBoardPanel == null) {
drawingBoardPanel = new DrawingBoard(editor.LevelEditor.this);
drawingBoardPanel.addMouseListener(input);
drawingBoardPanel.addMouseMotionListener(input);
drawingBoardPanel.setSize(20, 20);
add(drawingBoardPanel, BorderLayout.CENTER);
drawingBoardPanel.start();
}
// TODO: Add Trigger properties here.
if (properties == null) {
properties = new Properties(editor.LevelEditor.this);
properties.addMouseListener(input);
properties.addMouseMotionListener(input);
add(properties, BorderLayout.EAST);
validate();
}
if (statusPanel == null) {
statusPanel = new StatusPanel();
statusPanel.addMouseListener(input);
statusPanel.addMouseMotionListener(input);
add(statusPanel, BorderLayout.SOUTH);
validate();
}
initialize();
}
});
}
@Override
public void validate() {
super.validate();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (statusPanel != null) {
StringBuilder builder = new StringBuilder();
builder.append("Picked: " + editor.LevelEditor.this.controlPanel.getPickedEntityName() + " ");
if (!input.isDragging()) {
// This is how we do the [panning + pixel position] math.
int w = 0;
int h = 0;
try {
w = (input.offsetX + input.mouseX) / Tile.WIDTH;
}
catch (Exception e) {
w = (input.offsetX + input.mouseX) / (WIDTH * SIZE);
}
try {
h = (input.offsetY + input.mouseY) / Tile.HEIGHT;
}
catch (Exception e) {
h = (input.offsetY + input.mouseY) / (WIDTH * SIZE);
}
statusPanel.setMousePositionText(w, h);
}
else {
try {
statusPanel.setMousePositionText(input.oldX / drawingBoardPanel.getBitmapWidth(), input.oldY / drawingBoardPanel.getBitmapHeight());
}
catch (Exception e) {
statusPanel.setMousePositionText(0, 0);
}
}
statusPanel.setStatusMessageText(builder.toString());
}
if (LevelEditor.this.controlPanel != null)
LevelEditor.this.controlPanel.validate();
if (LevelEditor.this.fileControlPanel != null)
LevelEditor.this.fileControlPanel.validate();
if (LevelEditor.this.drawingBoardPanel != null)
LevelEditor.this.drawingBoardPanel.validate();
if (LevelEditor.this.properties != null)
LevelEditor.this.properties.validate();
if (LevelEditor.this.statusPanel != null)
LevelEditor.this.statusPanel.validate();
}
});
}
public final void initialize(){
EditorConstants.metadata = Metadata.Pixel_Data;
this.drawingBoardPanel.newImage(5, 5);
}
public ArrayList<Data> getResourceFilePaths() {
return this.filepaths;
}
public static void main(String[] args) {
new LevelEditor("Level Editor (Hobby)");
}
}
|
package org.intermine.web.logic.results;
import java.io.Serializable;
import org.intermine.model.InterMineObject;
import org.intermine.objectstore.ObjectStore;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.pathquery.Path;
import org.intermine.util.TypeUtil;
import org.intermine.util.Util;
/**
* Cell of results table containing information
* for the parent Object
*
* @author Xavier Watkins
*/
public class ResultElement implements Serializable
{
protected Object field;
protected Class typeCls;
protected Integer id;
protected String htmlId;
private final boolean keyField;
private final ObjectStore os;
private final Path path;
private boolean isSelected = false;
/**
* Constructs a new ResultCell object
* @param os the ObjectStore to use in getInterMineObject()
* @param value the value of the field from the results table
* @param id the id of the InterMineObject this field belongs to
* @param typeCls the Class of the InterMineObject this field belongs to
* @param path the Path
* @param isKeyField should be true if this is an identifying field
*/
public ResultElement(ObjectStore os, Object value, Integer id, Class typeCls,
Path path, boolean isKeyField) {
this.os = os;
this.field = value;
this.id = id;
this.typeCls = typeCls;
this.keyField = isKeyField;
this.path = path;
}
/**
* Create a ResultElement that displays a single raw value.
* @param fieldValue the value to hold in this object
*/
public ResultElement(Object fieldValue) {
this.field = fieldValue;
this.path = null;
this.os = null;
this.keyField = false;
}
/**
* Get the field value
* @return the value
*/
public Object getField() {
return field;
}
/**
* Set the field value
* @param field the field
*/
public void setField(Object field) {
this.field = field;
}
/**
* Get the type
* @return the type
*/
public String getType() {
return TypeUtil.unqualifiedName(typeCls.getName());
}
/**
* Get the type
* @return the type
*/
public Class getTypeClass() {
return typeCls;
}
/**
* Set the type
* @param typeCls the type
*/
public void setTypeClass(Class typeCls) {
this.typeCls = typeCls;
}
/**
* Return true if this object represents a field that is an identifying field (according to
* ClassKeyHelper.isKeyField())
* @return true if this is a key field
*/
public boolean isKeyField() {
return keyField;
}
/**
* Get the Id
* @return the id
*/
public Integer getId() {
return id;
}
/**
* Set the Id
* @param id the id
*/
public void setId(Integer id) {
this.id = id;
}
/**
* @return the path
*/
public Path getPath() {
return path;
}
/**
* Return the InterMineObject that contains this result element.
* @return the InterMineObject
* @throws ObjectStoreException if there is a problem getting the object from the ObjectStore
*/
public InterMineObject getInterMineObject() throws ObjectStoreException {
return os.getObjectById(getId());
}
/**
* Set the selected status of results element
* @param isSelected whether or not the element is selected
* @Deprecated selected elements are stored in the PagedTable
*/
@Deprecated public void setSelected(boolean isSelected) {
this.isSelected = isSelected;
}
/**
* Find the selected status of this element.
* @return true if this element has been selected
* @Deprecated selected elements are stored in the PagedTable
*/
@Deprecated public boolean isSelected() {
return isSelected;
}
/**
* Returns a String representation of the ResultElement
* @return a String
*/
public String toString() {
return " " + field + " " + id + " " + TypeUtil.unqualifiedName(typeCls.getName());
}
/**
* (non-Javadoc)
* {@inheritDoc}
*/
public boolean equals(Object obj) {
try {
ResultElement cell = (ResultElement) obj;
return (Util.equals(field, cell.getField()) && id.equals(cell.getId())
&& typeCls.equals(cell.getTypeClass()));
} catch (ClassCastException e) {
throw new ClassCastException("Comparing a ResultsElement with a "
+ obj.getClass().getName());
} catch (NullPointerException e) {
throw new NullPointerException("field = " + field + ", id = " + id + ", type = "
+ TypeUtil.unqualifiedName(typeCls.getName()));
}
}
/**
* (non-Javadoc)
* {@inheritDoc}
*/
public int hashCode() {
return (field == null ? 0 : field.hashCode()) + 3 * id.hashCode()
+ 7 * typeCls.hashCode();
}
/**
* Get the unqualified class name as a string
* @return a String
*/
public String getTypeClsString() {
return TypeUtil.unqualifiedName(typeCls.getName());
}
}
|
package org.intermine.web.logic.widget;
import org.apache.log4j.Logger;
/**
* Calculates p-values for go terms using the hypergeometric distribution.
* See online documentation for detailed information about what this class is and what it does.
*/
public class Hypergeometric
{
static double[] factorials;
private static final Logger LOG = Logger.getLogger(Hypergeometric.class);
/**
* Builds an array of factorials so we don't have to calculate it each time.
* @param numGenes the number of genes in the list
**/
public Hypergeometric(int numGenes) {
factorials = new double[numGenes + 1];
factorials[0] = 0;
double current = 0;
for (int i = 1; i < numGenes + 1; i++) {
current += Math.log(i);
factorials[i] = current;
}
}
private static double logChoose(int n, int r) {
if (n == 0) {
if (r == 0) {
return 0;
} else {
LOG.error("Can't calculate log using n = " + n + " and r = " + r);
return Double.NEGATIVE_INFINITY;
}
}
if (r == 0) {
return 0;
}
if (r == 1) {
return Math.log(n);
}
if (n < r) {
LOG.error("Can't calculate log using n = " + n + " and r = " + r);
return Double.NEGATIVE_INFINITY;
}
return factorials[n] - (factorials[r] + factorials[n - r]);
}
public static double calculateP(int n, int k, int bigM, int bigN) {
double p = 0;
for (int i = n; i >= k; i
p +=
Math.exp(logChoose(bigM, i) + logChoose(bigN - bigM, n - i) - logChoose(bigN, n));
}
return p;
}
}
|
package org.csstudio.archive.channelarchiver;
import java.util.Hashtable;
import java.util.Vector;
import org.apache.xmlrpc.XmlRpcClient;
import org.apache.xmlrpc.XmlRpcException;
import org.csstudio.archive.ArchiveValues;
import org.csstudio.platform.data.IEnumeratedMetaData;
import org.csstudio.platform.data.IMetaData;
import org.csstudio.platform.data.INumericMetaData;
import org.csstudio.platform.data.ITimestamp;
import org.csstudio.platform.data.IValue;
import org.csstudio.platform.data.TimestampFactory;
import org.csstudio.platform.data.ValueFactory;
/** Handles the "archiver.values" request and its results.
* @author Kay Kasemir
*/
@SuppressWarnings("nls")
public class ValuesRequest
{
final private ArchiveServer server;
final private int key;
final private String channels[];
final private ITimestamp start, end;
final private int how;
final private Object parms[];
final private IValue.Quality quality;
// Possible 'type' IDs for the received values.
final private static int TYPE_STRING = 0;
final private static int TYPE_ENUM = 1;
final private static int TYPE_INT = 2;
final private static int TYPE_DOUBLE = 3;
// The result of the query
private ArchiveValues archived_samples[];
private boolean min_max_avg_request;
/** Constructor for new value request.
* <p>
* Details regarding the meaning of 'count' for the different 'how'
* values are in the XML-RPC description in the ChannelArchiver manual.
*
* @param key Archive key
* @param channels Vector of channel names
* @param start Start time for retrieval
* @param end End time for retrieval
* @param how How to retrieve
* @param parms Detailed parameters.
*/
public ValuesRequest(ArchiveServer server,
int key, String channels[],
ITimestamp start, ITimestamp end, int how, Object parms[])
throws Exception
{
final String req_type = server.getRequestTypes()[how];
min_max_avg_request = req_type.equals(ArchiveServer.GET_AVERAGE);
// Check parms
if (min_max_avg_request)
{
quality = IValue.Quality.Interpolated;
if (! (parms.length == 1 && parms[0] instanceof Double))
throw new Exception("Expected 'Double delta' for GET_AVERAGE");
// We got the Double as per javadoc for the request type,
// but the server actually only handles int...
final double secs = ((Double)parms[0]).doubleValue();
parms = new Object[] { new Integer((int)secs) };
}
else
{ // All others (for now) use 'Integer count'
if (! (parms.length == 1 && parms[0] instanceof Integer))
throw new Exception("Expected 'Integer count' for " + req_type);
// Raw == Original, all else is somehow interpolated
if (req_type.equals(ArchiveServer.GET_RAW))
quality = IValue.Quality.Original;
else
quality = IValue.Quality.Interpolated;
}
this.server = server;
this.key = key;
this.channels = channels;
this.start = start;
this.end = end;
this.how = how;
this.parms = parms;
}
/** @see org.csstudio.archive.channelarchiver.ClientRequest#read() */
public void read(XmlRpcClient xmlrpc) throws Exception
{
Vector result;
try
{
final Vector<Object> params = new Vector<Object>(8);
params.add(new Integer(key));
params.add(channels);
params.add(new Integer((int)start.seconds()));
params.add(new Integer((int)start.nanoseconds()));
params.add(new Integer((int)end.seconds()));
params.add(new Integer((int)end.nanoseconds()));
params.add(parms[0]);
params.add(new Integer(how));
result = (Vector)xmlrpc.execute("archiver.values", params);
}
catch (XmlRpcException e)
{
throw new Exception("archiver.values call failed", e);
}
// result := { string name, meta, int32 type,
// int32 count, values }[]
final int num_returned_channels = result.size();
archived_samples = new ArchiveValues[num_returned_channels];
for (int channel_idx=0; channel_idx<num_returned_channels; ++channel_idx)
{
final Hashtable channel_data = (Hashtable) result.get(channel_idx);
final String name = (String)channel_data.get("name");
final int type = (Integer)channel_data.get("type");
final int count = (Integer)channel_data.get("count");
IMetaData meta;
IValue samples[];
try
{
meta = decodeMetaData(type, (Hashtable)channel_data.get("meta"));
samples = decodeValues(type, count, meta,
(Vector)channel_data.get("values"));
}
catch (Exception e)
{
throw new Exception("Error while decoding values for channel '"
+ name + "': " + e.getMessage(), e);
}
archived_samples[channel_idx] =
new ArchiveValues(server, name, samples);
}
}
/** Parse the MetaData from the received XML-RPC response. */
private IMetaData decodeMetaData(int value_type, Hashtable meta_hash)
throws Exception
{
// meta := { int32 type;
// type==0: string states[],
// type==1: double disp_high,
// double disp_low,
// double alarm_high,
// double alarm_low,
// double warn_high,
// double warn_low,
// int prec, string units
final int meta_type = (Integer) meta_hash.get("type");
if (meta_type < 0 || meta_type > 1)
throw new Exception("Invalid 'meta' type " + meta_type);
if (meta_type == 1)
{
// The 2.8.1 server will give 'ENUM' type values
// with Numeric meta data, units = "<No data>"
// as an error message.
if (value_type == TYPE_ENUM)
throw new Exception(
"Received numeric meta information for value type "
+ value_type);
return ValueFactory.createNumericMetaData(
(Double) meta_hash.get("disp_low"),
(Double) meta_hash.get("disp_high"),
(Double) meta_hash.get("warn_low"),
(Double) meta_hash.get("warn_high"),
(Double) meta_hash.get("alarm_low"),
(Double) meta_hash.get("alarm_high"),
(Integer) meta_hash.get("prec"),
(String) meta_hash.get("units"));
}
// else
if (! (value_type == TYPE_ENUM || value_type == TYPE_STRING))
throw new Exception(
"Received enumerated meta information for value type "
+ value_type);
final Vector state_vec = (Vector) meta_hash.get("states");
final int N = state_vec.size();
final String states[] = new String[N];
// Silly loop because of type warnings from state_vec.toArray(states)
for (int i=0; i<N; ++i)
states[i] = (String) state_vec.get(i);
return ValueFactory.createEnumeratedMetaData(states);
}
/** Parse the values from the received XML-RPC response. */
private IValue [] decodeValues(int type, int count, IMetaData meta,
Vector value_vec) throws Exception
{
// values := { int32 stat, int32 sevr,
// int32 secs, int32 nano,
// <type> value[] } []
// [{secs=1137596340, stat=0, nano=344419666, value=[0.79351], sevr=0},
// {secs=1137596400, stat=0, nano=330619666, value=[0.79343], sevr=0},..]
final int num_samples = value_vec.size();
final IValue samples[] = new IValue[num_samples];
for (int si=0; si<num_samples; ++si)
{
final Hashtable sample_hash = (Hashtable) value_vec.get(si);
final long secs = (Integer)sample_hash.get("secs");
final long nano = (Integer)sample_hash.get("nano");
final ITimestamp time = TimestampFactory.createTimestamp(secs, nano);
final int stat_code = (Integer)sample_hash.get("stat");
final int sevr_code = (Integer)sample_hash.get("sevr");
final SeverityImpl sevr = server.getSeverity(sevr_code);
final String stat = server.getStatus(sevr, stat_code);
final Vector vv = (Vector)sample_hash.get("value");
if (type == TYPE_DOUBLE)
{
final double values[] = new double[count];
for (int vi=0; vi<count; ++vi)
values[vi] = (Double)vv.get(vi);
// Check for "min", "max".
// Only handles min/max for double, but that's OK
// since for now that's all that the server does as well.
if (sample_hash.containsKey("min") &&
sample_hash.containsKey("max"))
{ // It's a min/max double, certainly interpolated
final double min = (Integer)sample_hash.get("min");
final double max = (Integer)sample_hash.get("max");
samples[si] = ValueFactory.createMinMaxDoubleValue(
time, sevr, stat, (INumericMetaData)meta,
IValue.Quality.Interpolated, values, min, max);
}
else
{ // Was this from a min/max/avg request?
// Yes: Then we ran into a raw value.
// No: Then it's whatever quality we expected in general
IValue.Quality q = min_max_avg_request ?
IValue.Quality.Original : quality;
samples[si] = ValueFactory.createDoubleValue(
time, sevr, stat, (INumericMetaData)meta,
q, values);
}
}
else if (type == TYPE_ENUM)
{
final int values[] = new int[count];
for (int vi=0; vi<count; ++vi)
values[vi] = (Integer)vv.get(vi);
samples[si] = ValueFactory.createEnumeratedValue(time, sevr, stat,
(IEnumeratedMetaData)meta, quality, values);
}
else if (type == TYPE_STRING)
{
final String value = (String)vv.get(0);
samples[si] = ValueFactory.createStringValue(time, sevr, stat,
quality, value);
}
else if (type == TYPE_INT)
{
final int values[] = new int[count];
for (int vi=0; vi<count; ++vi)
values[vi] = (Integer)vv.get(vi);
samples[si] = ValueFactory.createIntegerValue(time, sevr, stat,
(INumericMetaData)meta, quality, values);
}
else
throw new Exception("Unknown value type " + type);
}
return samples;
}
/** @return Returns one <code>ArchivedSamples</code> per channel. */
public ArchiveValues[] getArchivedSamples()
{
return archived_samples;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.