answer
stringlengths 17
10.2M
|
|---|
package org.broad.igv.ui.panel;
import org.broad.igv.charts.ScatterPlotUtils;
import org.broad.igv.feature.RegionOfInterest;
import org.broad.igv.track.RegionScoreType;
import org.broad.igv.track.TrackType;
import org.broad.igv.ui.IGV;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Set;
/**
* @author jrobinso
* @date Sep 18, 2010
*/
public class RegionMenu extends JPopupMenu {
RegionOfInterest roi;
ReferenceFrame frame;
public RegionMenu(final RegionOfInterest roi, final ReferenceFrame frame) {
this(roi, frame, null);
}
public RegionMenu(final RegionOfInterest roi, final ReferenceFrame frame, String title) {
this.roi = roi;
this.frame = frame;
if (title != null) {
JLabel heading = new JLabel("<html> <b>" + title);
//heading.setFont(UIConstants.boldFont);
add(heading);
addSeparator();
}
Set<TrackType> loadedTypes = IGV.getInstance().getLoadedTypes();
if (loadedTypes.contains(TrackType.COPY_NUMBER) ||
loadedTypes.contains(TrackType.ALLELE_SPECIFIC_COPY_NUMBER) ||
loadedTypes.contains(TrackType.CNV)) {
JMenuItem item = new JMenuItem("Sort by amplification");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
IGV.getInstance().sortByRegionScore(roi, RegionScoreType.AMPLIFICATION, frame);
}
});
add(item);
item = new JMenuItem("Sort by deletion");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
IGV.getInstance().sortByRegionScore(roi, RegionScoreType.DELETION, frame);
IGV.getInstance().getContentPane().repaint();
}
});
add(item);
item = new JMenuItem("Sort by breakpoint amplitudes");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
IGV.getInstance().sortByRegionScore(roi, RegionScoreType.FLUX, frame);
IGV.getInstance().getContentPane().repaint();
}
});
add(item);
}
if (loadedTypes.contains(TrackType.GENE_EXPRESSION)) {
JMenuItem item = new JMenuItem("Sort by expression");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
IGV.getInstance().sortByRegionScore(roi, RegionScoreType.EXPRESSION, frame);
IGV.getInstance().getContentPane().repaint();
}
});
add(item);
}
if (loadedTypes.contains(TrackType.MUTATION)) {
JMenuItem item = new JMenuItem("Sort by mutation count");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
IGV.getInstance().sortByRegionScore(roi, RegionScoreType.MUTATION_COUNT, frame);
IGV.getInstance().getContentPane().repaint();
}
});
add(item);
}
JMenuItem item = new JMenuItem("Sort by value");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
IGV.getInstance().sortByRegionScore(roi, RegionScoreType.SCORE, frame);
IGV.getInstance().getContentPane().repaint();
}
});
add(item);
if (ScatterPlotUtils.hasPlottableTracks()) {
addSeparator();
item = new JMenuItem("Scatter Plot ...");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String chr = roi.getChr();
int start = roi.getStart();
int end = roi.getEnd();
int zoom = frame.getZoom();
ScatterPlotUtils.openPlot(chr, start, end, zoom);
}
});
add(item);
}
}
}
|
package org.hihan.girinoscope.comm;
import com.fazecast.jSerialComm.SerialPort;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
public class Serial implements Closeable {
private static final Logger logger = Logger.getLogger(Serial.class.getName());
/**
* The ports we're normally going to use: USB (or Bluetooth) to serial
* adapters.
*/
private static final Pattern[] ACCEPTABLE_PORT_NAMES = {
Pattern.compile("\\.*tty\\.usbserial-.+"), // Mac OS X
Pattern.compile("\\.*cu\\.wchusbserial.+"), // Mac OS X
Pattern.compile("\\.*tty\\.usbmodem.+"), // Mac OS X
Pattern.compile("\\.*ttyACM\\d+"), // Raspberry Pi
Pattern.compile("\\.*ttyUSB\\d+"), // Linux
Pattern.compile("\\.*rfcomm\\d+"), // Linux Bluetooth
Pattern.compile("\\.*COM\\d+"), // Windows
};
/**
* Milliseconds to block while waiting for port open.
*/
private static final int TIME_OUT = 2000;
/**
* Default bits per second for COM port.
*/
private static final int DATA_RATE = 115200;
/**
* Milliseconds to wait when no input is available.
*/
private static final int READ_DELAY = 200;
private SerialPort port;
private InputStream input;
private OutputStream output;
public static List<SerialPort> enumeratePorts() {
List<SerialPort> ports = new LinkedList<>();
for (SerialPort port : SerialPort.getCommPorts()) {
String portName = port.getSystemPortName();
for (Pattern acceptablePortName : ACCEPTABLE_PORT_NAMES) {
if (acceptablePortName.matcher(portName).matches()) {
ports.add(port);
}
}
}
return ports;
}
public Serial(SerialPort port) {
port.openPort();
port.setComPortTimeouts(SerialPort.TIMEOUT_READ_BLOCKING, TIME_OUT, TIME_OUT);
port.setComPortParameters(DATA_RATE, 8, SerialPort.ONE_STOP_BIT, SerialPort.NO_PARITY);
port.setFlowControl(SerialPort.FLOW_CONTROL_DISABLED);
this.port = port;
output = port.getOutputStream();
input = port.getInputStream();
}
@Override
public void close() throws IOException {
if (port != null) {
try {
output.flush();
} catch (IOException e) {
logger.log(Level.WARNING, "When flushing output before closing serial.", e);
}
port.closePort();
port = null;
}
}
public String readLine() throws IOException, InterruptedException {
StringBuilder line = new StringBuilder();
int length = 0;
try {
while (true) {
int c;
if ((input.available() > 0 || line.length() > 0) && (c = input.read()) >= 0) {
line.append((char) c);
++length;
boolean eol = length >= 2 && line.charAt(length - 2) == '\r' && line.charAt(length - 1) == '\n';
if (eol) {
line.setLength(length - 2);
break;
}
} else {
/*
* Sleeping here allows us to be interrupted (the serial
* input is not interruptible itself).
*/
Thread.sleep(READ_DELAY);
}
}
} catch (InterruptedException e) {
logger.log(Level.FINE, "Read aborted");
throw e;
}
logger.log(Level.FINE, "< ({0})", line);
return line.toString();
}
public int readBytes(byte[] buffer) throws IOException, InterruptedException {
int offset = 0;
try {
while (offset < buffer.length) {
if (input.available() > 0 || offset > 0) {
int size = input.read(buffer, offset, buffer.length - offset);
if (size < 0) {
break;
}
offset += size;
} else {
/*
* Sleeping here allows us to be interrupted (the serial
* input is not interruptible itself).
*/
Thread.sleep(READ_DELAY);
}
}
} catch (InterruptedException e) {
logger.log(Level.FINE, "Read aborted");
throw e;
}
logger.log(Level.FINE, "< {0} byte(s)", offset);
return offset;
}
public void writeLine(String line) throws IOException {
for (int i = 0; i < line.length(); ++i) {
output.write(line.charAt(i));
}
output.flush();
logger.log(Level.FINE, "> ({0})", line);
}
}
|
package org.jdcoffre.mlc.server;
import io.dropwizard.Application;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import org.jdcoffre.mlc.server.api.Cellar;
import org.jdcoffre.mlc.server.resource.Bottles;
import org.jdcoffre.mlc.server.resource.Cellars;
import org.jdcoffre.mlc.server.resource.Racks;
public class MlcServer extends Application<MlcConfiguration> {
public static final String MLC_NAME = "My Little Cellar";
public static void main(String[] args) throws Exception {
new MlcServer().run(args);
}
@Override
public String getName() {
return MLC_NAME;
}
@Override
public void initialize(Bootstrap<MlcConfiguration> bootstrap) {
// nothing to do yet
}
@Override
public void run(MlcConfiguration mlcConfiguration, Environment environment) throws Exception {
final Bottles bottlesResource = new Bottles();
environment.jersey().register(bottlesResource);
final Cellars cellarsResource = new Cellars();
environment.jersey().register(cellarsResource);
final Racks racksResource = new Racks();
environment.jersey().register(racksResource);
}
}
|
package org.jtrfp.trcl.coll;
import org.apache.commons.collections4.map.AbstractReferenceMap.ReferenceStrength;
import org.jtrfp.trcl.tools.Util;
import com.ochafik.util.Adapter;
public abstract class CachedAdapter<U,V> implements Adapter<U, V> {
private final BidiReferenceMap<U,V> cache;
private volatile boolean tolerateNull = false;
public CachedAdapter(){
this(new BidiReferenceMap<U,V>(ReferenceStrength.WEAK));
}
public CachedAdapter(BidiReferenceMap<U,V> cache){
this.cache=cache;
}
public com.ochafik.util.listenable.Adapter<U,V> toForward(){
return Util.bidi2Forward(this);
}
public com.ochafik.util.listenable.Adapter<V,U> toBackward(){
return Util.bidi2Backward(this);
}
@Override
public final V adapt(U key) {
if(key==null){
if(tolerateNull)
return null;
else throw new NullPointerException("Key is intolerably null.");
}//end if(key null)
synchronized(cache){
V result = cache.get(key);
if(!cache.containsKey(key)){
V v = _adapt(key);
if(v==null){
if(tolerateNull)
return null;
else throw new NullPointerException("Adapted value is intolerably null.");
}//end if(key null)
cache.put(key, v);
result = v;
}//end if(null)
return result;
}//end sync(cache)
}//end adapt()
@Override
public final U reAdapt(V value) {
if(value==null){
if(tolerateNull)
return null;
else throw new NullPointerException("Value is intolerably null.");
}//end if(key null)
synchronized(cache){
U result = cache.getKey(value);
if(!cache.containsValue(value)){
U key = _reAdapt(value);
if(key==null){
if(tolerateNull)
return null;
else throw new NullPointerException("Re-Adapted key is intolerably null.");
}//end if(key null)
cache.put(key, value);
result = key;
}//end if(null)
return result;
}//end sync(cache)
}//end reAdapt(...)
protected abstract V _adapt (U value) throws UnsupportedOperationException;
protected abstract U _reAdapt(V value) throws UnsupportedOperationException;
public static <U,V> CachedAdapter<U,V> decorate(final Adapter<U,V> adapter, BidiReferenceMap<U,V> mapToUse){
return new CachedAdapter<U,V>(mapToUse){
@Override
protected V _adapt(U value) throws UnsupportedOperationException {
return adapter.adapt(value);
}
@Override
protected U _reAdapt(V value) throws UnsupportedOperationException {
return adapter.reAdapt(value);
}};
}
public static <U,V> CachedAdapter<U,V> decorate(final Adapter<U,V> adapter){
return new CachedAdapter<U,V>(){
@Override
protected V _adapt(U value) throws UnsupportedOperationException {
return adapter.adapt(value);
}
@Override
protected U _reAdapt(V value) throws UnsupportedOperationException {
return adapter.reAdapt(value);
}};
}
/**
* @return the tolerateNull
*/
public boolean isTolerateNull() {
return tolerateNull;
}
/**
* @param tolerateNull the tolerateNull to set
*/
public CachedAdapter<U,V> setTolerateNull(boolean tolerateNull) {
this.tolerateNull = tolerateNull;
return this;
}
}//end CachedAdapter
|
package org.lightmare.cache;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import javax.persistence.EntityManagerFactory;
import org.apache.log4j.Logger;
import org.lightmare.config.Configuration;
import org.lightmare.deploy.MetaCreator;
import org.lightmare.ejb.exceptions.BeanInUseException;
import org.lightmare.libraries.LibraryLoader;
import org.lightmare.rest.providers.RestProvider;
import org.lightmare.utils.CollectionUtils;
import org.lightmare.utils.LogUtils;
import org.lightmare.utils.ObjectUtils;
import org.lightmare.utils.fs.WatchUtils;
/**
* Container class to save {@link MetaData} for bean interface {@link Class} and
* connections ({@link EntityManagerFactory}) for unit names
*
* @author Levan Tsinadze
* @since 0.0.45-SNAPSHOT
*/
public class MetaContainer {
// Cached instance of MetaCreator
private static MetaCreator creator;
/**
* {@link Configuration} container class for server
*/
public static final Map<String, Configuration> CONFIGS = new ConcurrentHashMap<String, Configuration>();
// Cached bean meta data
private static final ConcurrentMap<String, MetaData> EJBS = new ConcurrentHashMap<String, MetaData>();
// Cached bean class name by its URL for undeploy processing
private static final ConcurrentMap<URL, Collection<String>> EJB_URLS = new ConcurrentHashMap<URL, Collection<String>>();
private static final Logger LOG = Logger.getLogger(MetaContainer.class);
/**
* Gets cached {@link MetaCreator} object
*
* @return
*/
public static MetaCreator getCreator() {
synchronized (MetaContainer.class) {
return creator;
}
}
/**
* Caches {@link MetaCreator} object
*
* @param metaCreator
*/
public static void setCreator(MetaCreator metaCreator) {
synchronized (MetaContainer.class) {
creator = metaCreator;
}
}
/**
* Caches {@link Configuration} for specific {@link URL} array
*
* @param archives
* @param config
*/
public static void putConfig(URL[] archives, Configuration config) {
if (CollectionUtils.valid(archives)) {
boolean containsPath;
for (URL archive : archives) {
String path = WatchUtils.clearPath(archive.getFile());
containsPath = CONFIGS.containsKey(path);
if (ObjectUtils.notTrue(containsPath)) {
CONFIGS.put(path, config);
}
}
}
}
/**
* Gets {@link Configuration} from cache for specific {@link URL} array
*
* @param archives
* @param config
*/
public static Configuration getConfig(URL[] archives) {
Configuration config;
URL archive = CollectionUtils.getFirst(archives);
if (ObjectUtils.notNull(archive)) {
String path = WatchUtils.clearPath(archive.getFile());
config = CONFIGS.get(path);
} else {
config = null;
}
return config;
}
/**
* Adds {@link MetaData} to cache on specified bean name if absent and
* returns previous value on this name or null if such value does not exists
*
* @param beanName
* @param metaData
* @return
*/
public static MetaData addMetaData(String beanName, MetaData metaData) {
return EJBS.putIfAbsent(beanName, metaData);
}
/**
* Check if {@link MetaData} is ceched for specified bean name if true
* throws {@link BeanInUseException}
*
* @param beanName
* @param metaData
* @throws BeanInUseException
*/
public static void checkAndAddMetaData(String beanName, MetaData metaData)
throws BeanInUseException {
MetaData tmpMeta = addMetaData(beanName, metaData);
if (ObjectUtils.notNull(tmpMeta)) {
throw BeanInUseException.get(beanName);
}
}
/**
* Checks if bean with associated name deployed and if yes if is deployment
* in progress
*
* @param beanName
* @return boolean
*/
public static boolean checkMetaData(String beanName) {
boolean check;
MetaData metaData = EJBS.get(beanName);
check = metaData == null;
if (ObjectUtils.notTrue(check)) {
check = metaData.isInProgress();
}
return check;
}
/**
* Checks if bean with associated name deployed
*
* @param beanName
* @return boolean
*/
public boolean checkBean(String beanName) {
return EJBS.containsKey(beanName);
}
/**
* Waits while passed {@link MetaData} instance is in progress
*
* @param inProgress
* @param metaData
* @throws IOException
*/
private static void awaitProgress(boolean inProgress, MetaData metaData)
throws IOException {
while (inProgress) {
try {
metaData.wait();
inProgress = metaData.isInProgress();
} catch (InterruptedException ex) {
throw new IOException(ex);
}
}
}
/**
* Waits while {@link MetaData#isInProgress()} is true
*
* @param metaData
* @throws IOException
*/
public static void awaitMetaData(MetaData metaData) throws IOException {
boolean inProgress = metaData.isInProgress();
if (inProgress) {
synchronized (metaData) {
awaitProgress(inProgress, metaData);
}
}
}
/**
* Gets deployed bean {@link MetaData} by name without checking deployment
* progress
*
* @param beanName
* @return {@link MetaData}
*/
public static MetaData getMetaData(String beanName) {
return EJBS.get(beanName);
}
/**
* Check if {@link MetaData} with associated name deployed and if it is
* waits while {@link MetaData#isInProgress()} true before return it
*
* @param beanName
* @return {@link MetaData}
* @throws IOException
*/
public static MetaData getSyncMetaData(String beanName) throws IOException {
MetaData metaData = getMetaData(beanName);
if (metaData == null) {
throw new IOException(String.format("Bean %s is not deployed",
beanName));
}
awaitMetaData(metaData);
return metaData;
}
/**
* Gets bean name by containing archive {@link URL} address
*
* @param url
* @return
*/
public static Collection<String> getBeanNames(URL url) {
synchronized (MetaContainer.class) {
return EJB_URLS.get(url);
}
}
/**
* checks containing archive {@link URL} address
*
* @param url
* @return
*/
public static boolean chackDeployment(URL url) {
synchronized (MetaContainer.class) {
return EJB_URLS.containsKey(url);
}
}
/**
* Removes cached bean names {@link Collection} by containing file
* {@link URL} as key
*
* @param url
*/
public static void removeBeanNames(URL url) {
synchronized (MetaContainer.class) {
EJB_URLS.remove(url);
}
}
/**
* Caches bean name by {@link URL} of jar ear or any file
*
* @param beanName
*/
public static void addBeanName(URL url, String beanName) {
synchronized (MetaContainer.class) {
Collection<String> beanNames = EJB_URLS.get(url);
if (CollectionUtils.invalid(beanNames)) {
beanNames = new HashSet<String>();
EJB_URLS.put(url, beanNames);
}
beanNames.add(beanName);
}
}
/**
* Lists set for deployed application {@link URL}'s
*
* @return {@link Set}<URL>
*/
public static Set<URL> listApplications() {
Set<URL> apps = EJB_URLS.keySet();
return apps;
}
/**
* Clears connection from cache
*
* @param metaData
* @throws IOException
*/
private static void clearConnection(MetaData metaData) throws IOException {
Collection<ConnectionData> connections = metaData.getConnections();
if (CollectionUtils.valid(connections)) {
for (ConnectionData connection : connections) {
// Gets connection to clear
String unitName = connection.getUnitName();
ConnectionSemaphore semaphore = connection.getConnection();
if (semaphore == null) {
semaphore = ConnectionContainer.getConnection(unitName);
}
if (ObjectUtils.notNull(semaphore)
&& semaphore.decrementUser() <= ConnectionSemaphore.MINIMAL_USERS) {
ConnectionContainer.removeConnection(unitName);
}
}
}
}
/**
* Removes bean (removes it's {@link MetaData} from cache) by bean class
* name
*
* @param beanName
* @throws IOException
*/
public static void undeployBean(String beanName) throws IOException {
MetaData metaData = null;
try {
metaData = getSyncMetaData(beanName);
} catch (IOException ex) {
LogUtils.error(LOG, ex, "Could not get bean resources %s cause %s",
beanName, ex.getMessage());
}
// Removes MetaData from cache
removeMeta(beanName);
if (ObjectUtils.notNull(metaData)) {
// Removes appropriated resource class from REST service
if (RestContainer.hasRest()) {
RestProvider.remove(metaData.getBeanClass());
}
clearConnection(metaData);
ClassLoader loader = metaData.getLoader();
LibraryLoader.closeClassLoader(loader);
metaData = null;
}
}
/**
* Removes bean (removes it's {@link MetaData} from cache) by {@link URL} of
* archive file
*
* @param url
* @throws IOException
*/
public static boolean undeploy(URL url) throws IOException {
boolean valid;
synchronized (MetaContainer.class) {
Collection<String> beanNames = getBeanNames(url);
valid = CollectionUtils.valid(beanNames);
if (valid) {
for (String beanName : beanNames) {
undeployBean(beanName);
}
}
removeBeanNames(url);
}
return valid;
}
/**
* Removes bean (removes it's {@link MetaData} from cache) by {@link File}
* of archive file
*
* @param file
* @throws IOException
*/
public static boolean undeploy(File file) throws IOException {
boolean valid;
URL url = file.toURI().toURL();
valid = undeploy(url);
return valid;
}
/**
* Removes bean (removes it's {@link MetaData} from cache) by {@link File}
* path of archive file
*
* @param path
* @throws IOException
*/
public static boolean undeploy(String path) throws IOException {
boolean valid;
File file = new File(path);
valid = undeploy(file);
return valid;
}
/**
* Removed {@link MetaData} from cache
*
* @param beanName
*/
public static void removeMeta(String beanName) {
EJBS.remove(beanName);
}
/**
* Gets {@link java.util.Iterator}<MetaData> over all cached
* {@link org.lightmare.cache.MetaData}
*
* @return {@link java.util.Iterator}<MetaData>
*/
public static Iterator<MetaData> getBeanClasses() {
return EJBS.values().iterator();
}
/**
* Removes all cached resources
*/
public static void clear() {
if (ObjectUtils.notNull(creator)) {
synchronized (MetaContainer.class) {
if (ObjectUtils.notNull(creator)) {
creator.clear();
creator = null;
}
}
}
CONFIGS.clear();
EJBS.clear();
EJB_URLS.clear();
}
}
|
package org.lightmare.cache;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import javax.persistence.EntityManagerFactory;
import org.apache.log4j.Logger;
import org.lightmare.config.Configuration;
import org.lightmare.deploy.MetaCreator;
import org.lightmare.ejb.exceptions.BeanInUseException;
import org.lightmare.libraries.LibraryLoader;
import org.lightmare.rest.providers.RestProvider;
import org.lightmare.utils.ObjectUtils;
import org.lightmare.utils.fs.WatchUtils;
/**
* Container class to save {@link MetaData} for bean interface {@link Class} and
* connections {@link EntityManagerFactory}es for unit names
*
* @author Levan
*
*/
public class MetaContainer {
// Cached instance of MetaCreator
private static MetaCreator creator;
/**
* {@link Configuration} container class for server
*/
public static final Map<String, Configuration> CONFIGS = new ConcurrentHashMap<String, Configuration>();
// Cached bean meta data
private static final ConcurrentMap<String, MetaData> EJBS = new ConcurrentHashMap<String, MetaData>();
// Cached bean class name by its URL for undeploy processing
private static final ConcurrentMap<URL, Collection<String>> EJB_URLS = new ConcurrentHashMap<URL, Collection<String>>();
private static final Logger LOG = Logger.getLogger(MetaContainer.class);
/**
* Gets cached {@link MetaCreator} object
*
* @return
*/
public static MetaCreator getCreator() {
synchronized (MetaContainer.class) {
return creator;
}
}
/**
* Caches {@link MetaCreator} object
*
* @param metaCreator
*/
public static void setCreator(MetaCreator metaCreator) {
synchronized (MetaContainer.class) {
creator = metaCreator;
}
}
/**
* Caches {@link Configuration} for specific {@link URL} array
*
* @param archives
* @param config
*/
public static void putConfig(URL[] archives, Configuration config) {
if (ObjectUtils.available(archives)) {
for (URL archive : archives) {
String path = WatchUtils.clearPath(archive.getFile());
if (CONFIGS.containsKey(path)) {
continue;
}
CONFIGS.put(path, config);
}
}
}
/**
* Gets {@link Configuration} from cache for specific {@link URL} array
*
* @param archives
* @param config
*/
public static Configuration getConfig(URL[] archives) {
Configuration config;
URL archive = ObjectUtils.getFirst(archives);
if (ObjectUtils.notNull(archive)) {
String path = WatchUtils.clearPath(archive.getFile());
config = CONFIGS.get(path);
} else {
config = null;
}
return config;
}
/**
* Adds {@link MetaData} to cache on specified bean name if absent and
* returns previous value on this name or null if such value does not exists
*
* @param beanName
* @param metaData
* @return
*/
public static MetaData addMetaData(String beanName, MetaData metaData) {
return EJBS.putIfAbsent(beanName, metaData);
}
/**
* Check if {@link MetaData} is ceched for specified bean name if true
* throws {@link BeanInUseException}
*
* @param beanName
* @param metaData
* @throws BeanInUseException
*/
public static void checkAndAddMetaData(String beanName, MetaData metaData)
throws BeanInUseException {
MetaData tmpMeta = addMetaData(beanName, metaData);
if (ObjectUtils.notNull(tmpMeta)) {
throw new BeanInUseException(String.format(
"bean %s is alredy in use", beanName));
}
}
/**
* Checks if bean with associated name deployed and if yes if is deployment
* in progress
*
* @param beanName
* @return boolean
*/
public static boolean checkMetaData(String beanName) {
boolean check;
MetaData metaData = EJBS.get(beanName);
check = metaData == null;
if (ObjectUtils.notTrue(check)) {
check = metaData.isInProgress();
}
return check;
}
/**
* Checks if bean with associated name deployed
*
* @param beanName
* @return boolean
*/
public boolean checkBean(String beanName) {
return EJBS.containsKey(beanName);
}
/**
* Waits while {@link MetaData#isInProgress()} is true
*
* @param metaData
* @throws IOException
*/
public static void awaitMetaData(MetaData metaData) throws IOException {
boolean inProgress = metaData.isInProgress();
if (inProgress) {
synchronized (metaData) {
while (inProgress) {
try {
metaData.wait();
inProgress = metaData.isInProgress();
} catch (InterruptedException ex) {
throw new IOException(ex);
}
}
}
}
}
/**
* Gets deployed bean {@link MetaData} by name without checking deployment
* progress
*
* @param beanName
* @return {@link MetaData}
*/
public static MetaData getMetaData(String beanName) {
return EJBS.get(beanName);
}
/**
* Check if {@link MetaData} with associated name deployed and if it is
* waits while {@link MetaData#isInProgress()} true before return it
*
* @param beanName
* @return {@link MetaData}
* @throws IOException
*/
public static MetaData getSyncMetaData(String beanName) throws IOException {
MetaData metaData = getMetaData(beanName);
if (metaData == null) {
throw new IOException(String.format("Bean %s is not deployed",
beanName));
}
awaitMetaData(metaData);
return metaData;
}
/**
* Gets bean name by containing archive {@link URL} address
*
* @param url
* @return
*/
public static Collection<String> getBeanNames(URL url) {
synchronized (MetaContainer.class) {
return EJB_URLS.get(url);
}
}
/**
* checks containing archive {@link URL} address
*
* @param url
* @return
*/
public static boolean chackDeployment(URL url) {
synchronized (MetaContainer.class) {
return EJB_URLS.containsKey(url);
}
}
/**
* Removes cached bean names {@link Collection} by containing file
* {@link URL} as key
*
* @param url
*/
public static void removeBeanNames(URL url) {
synchronized (MetaContainer.class) {
EJB_URLS.remove(url);
}
}
/**
* Caches bean name by {@link URL} of jar ear or any file
*
* @param beanName
*/
public static void addBeanName(URL url, String beanName) {
synchronized (MetaContainer.class) {
Collection<String> beanNames = EJB_URLS.get(url);
if (ObjectUtils.notAvailable(beanNames)) {
beanNames = new HashSet<String>();
EJB_URLS.put(url, beanNames);
}
beanNames.add(beanName);
}
}
/**
* Lists set for deployed application {@link URL}'s
*
* @return {@link Set}<URL>
*/
public static Set<URL> listApplications() {
Set<URL> apps = EJB_URLS.keySet();
return apps;
}
/**
* Clears connection from cache
*
* @param metaData
* @throws IOException
*/
private static void clearConnection(MetaData metaData) throws IOException {
Collection<ConnectionData> connections = metaData.getConnections();
if (ObjectUtils.available(connections)) {
for (ConnectionData connection : connections) {
// Gets connection to clear
String unitName = connection.getUnitName();
ConnectionSemaphore semaphore = connection.getConnection();
if (semaphore == null) {
semaphore = ConnectionContainer.getConnection(unitName);
}
if (ObjectUtils.notNull(semaphore)
&& semaphore.decrementUser() <= ConnectionSemaphore.MINIMAL_USERS) {
ConnectionContainer.removeConnection(unitName);
}
}
}
}
/**
* Removes bean (removes it's {@link MetaData} from cache) by bean class
* name
*
* @param beanName
* @throws IOException
*/
public static void undeployBean(String beanName) throws IOException {
MetaData metaData = null;
try {
metaData = getSyncMetaData(beanName);
} catch (IOException ex) {
LOG.error(String.format("Could not get bean resources %s cause %s",
beanName, ex.getMessage()), ex);
}
// Removes MetaData from cache
removeMeta(beanName);
if (ObjectUtils.notNull(metaData)) {
// Removes appropriated resource class from REST service
if (RestContainer.hasRest()) {
RestProvider.remove(metaData.getBeanClass());
}
clearConnection(metaData);
ClassLoader loader = metaData.getLoader();
LibraryLoader.closeClassLoader(loader);
metaData = null;
}
}
/**
* Removes bean (removes it's {@link MetaData} from cache) by {@link URL} of
* archive file
*
* @param url
* @throws IOException
*/
public static boolean undeploy(URL url) throws IOException {
synchronized (MetaContainer.class) {
Collection<String> beanNames = getBeanNames(url);
boolean valid = ObjectUtils.available(beanNames);
if (valid) {
for (String beanName : beanNames) {
undeployBean(beanName);
}
}
removeBeanNames(url);
return valid;
}
}
/**
* Removes bean (removes it's {@link MetaData} from cache) by {@link File}
* of archive file
*
* @param file
* @throws IOException
*/
public static boolean undeploy(File file) throws IOException {
URL url = file.toURI().toURL();
boolean valid = undeploy(url);
return valid;
}
/**
* Removes bean (removes it's {@link MetaData} from cache) by {@link File}
* path of archive file
*
* @param path
* @throws IOException
*/
public static boolean undeploy(String path) throws IOException {
File file = new File(path);
boolean valid = undeploy(file);
return valid;
}
/**
* Removed {@link MetaData} from cache
*
* @param beanName
*/
public static void removeMeta(String beanName) {
EJBS.remove(beanName);
}
/**
* Gets {@link java.util.Iterator}<MetaData> over all cached
* {@link org.lightmare.cache.MetaData}
*
* @return {@link java.util.Iterator}<MetaData>
*/
public static Iterator<MetaData> getBeanClasses() {
return EJBS.values().iterator();
}
/**
* Removes all cached resources
*/
public static void clear() {
if (ObjectUtils.notNull(creator)) {
synchronized (MetaContainer.class) {
if (ObjectUtils.notNull(creator)) {
creator.clear();
creator = null;
}
}
}
CONFIGS.clear();
EJBS.clear();
EJB_URLS.clear();
}
}
|
package org.lightmare.cache;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import javax.persistence.EntityManagerFactory;
import org.apache.log4j.Logger;
import org.lightmare.config.Configuration;
import org.lightmare.deploy.MetaCreator;
import org.lightmare.ejb.exceptions.BeanInUseException;
import org.lightmare.libraries.LibraryLoader;
import org.lightmare.rest.providers.RestProvider;
import org.lightmare.utils.CollectionUtils;
import org.lightmare.utils.LogUtils;
import org.lightmare.utils.ObjectUtils;
import org.lightmare.utils.fs.WatchUtils;
/**
* Container class to save {@link MetaData} for bean interface {@link Class} and
* connections ({@link EntityManagerFactory}) for unit names
*
* @author Levan
*
*/
public class MetaContainer {
// Cached instance of MetaCreator
private static MetaCreator creator;
/**
* {@link Configuration} container class for server
*/
public static final Map<String, Configuration> CONFIGS = new ConcurrentHashMap<String, Configuration>();
// Cached bean meta data
private static final ConcurrentMap<String, MetaData> EJBS = new ConcurrentHashMap<String, MetaData>();
// Cached bean class name by its URL for undeploy processing
private static final ConcurrentMap<URL, Collection<String>> EJB_URLS = new ConcurrentHashMap<URL, Collection<String>>();
private static final Logger LOG = Logger.getLogger(MetaContainer.class);
/**
* Gets cached {@link MetaCreator} object
*
* @return
*/
public static MetaCreator getCreator() {
synchronized (MetaContainer.class) {
return creator;
}
}
/**
* Caches {@link MetaCreator} object
*
* @param metaCreator
*/
public static void setCreator(MetaCreator metaCreator) {
synchronized (MetaContainer.class) {
creator = metaCreator;
}
}
/**
* Caches {@link Configuration} for specific {@link URL} array
*
* @param archives
* @param config
*/
public static void putConfig(URL[] archives, Configuration config) {
if (CollectionUtils.valid(archives)) {
boolean containsPath;
for (URL archive : archives) {
String path = WatchUtils.clearPath(archive.getFile());
containsPath = CONFIGS.containsKey(path);
if (ObjectUtils.notTrue(containsPath)) {
CONFIGS.put(path, config);
}
}
}
}
/**
* Gets {@link Configuration} from cache for specific {@link URL} array
*
* @param archives
* @param config
*/
public static Configuration getConfig(URL[] archives) {
Configuration config;
URL archive = CollectionUtils.getFirst(archives);
if (ObjectUtils.notNull(archive)) {
String path = WatchUtils.clearPath(archive.getFile());
config = CONFIGS.get(path);
} else {
config = null;
}
return config;
}
/**
* Adds {@link MetaData} to cache on specified bean name if absent and
* returns previous value on this name or null if such value does not exists
*
* @param beanName
* @param metaData
* @return
*/
public static MetaData addMetaData(String beanName, MetaData metaData) {
return EJBS.putIfAbsent(beanName, metaData);
}
/**
* Check if {@link MetaData} is ceched for specified bean name if true
* throws {@link BeanInUseException}
*
* @param beanName
* @param metaData
* @throws BeanInUseException
*/
public static void checkAndAddMetaData(String beanName, MetaData metaData)
throws BeanInUseException {
MetaData tmpMeta = addMetaData(beanName, metaData);
if (ObjectUtils.notNull(tmpMeta)) {
throw BeanInUseException.get("bean %s is alredy in use", beanName);
}
}
/**
* Checks if bean with associated name deployed and if yes if is deployment
* in progress
*
* @param beanName
* @return boolean
*/
public static boolean checkMetaData(String beanName) {
boolean check;
MetaData metaData = EJBS.get(beanName);
check = metaData == null;
if (ObjectUtils.notTrue(check)) {
check = metaData.isInProgress();
}
return check;
}
/**
* Checks if bean with associated name deployed
*
* @param beanName
* @return boolean
*/
public boolean checkBean(String beanName) {
return EJBS.containsKey(beanName);
}
/**
* Waits while passed {@link MetaData} instance is in progress
*
* @param inProgress
* @param metaData
* @throws IOException
*/
private static void awaitProgress(boolean inProgress, MetaData metaData)
throws IOException {
while (inProgress) {
try {
metaData.wait();
inProgress = metaData.isInProgress();
} catch (InterruptedException ex) {
throw new IOException(ex);
}
}
}
/**
* Waits while {@link MetaData#isInProgress()} is true
*
* @param metaData
* @throws IOException
*/
public static void awaitMetaData(MetaData metaData) throws IOException {
boolean inProgress = metaData.isInProgress();
if (inProgress) {
synchronized (metaData) {
awaitProgress(inProgress, metaData);
}
}
}
/**
* Gets deployed bean {@link MetaData} by name without checking deployment
* progress
*
* @param beanName
* @return {@link MetaData}
*/
public static MetaData getMetaData(String beanName) {
return EJBS.get(beanName);
}
/**
* Check if {@link MetaData} with associated name deployed and if it is
* waits while {@link MetaData#isInProgress()} true before return it
*
* @param beanName
* @return {@link MetaData}
* @throws IOException
*/
public static MetaData getSyncMetaData(String beanName) throws IOException {
MetaData metaData = getMetaData(beanName);
if (metaData == null) {
throw new IOException(String.format("Bean %s is not deployed",
beanName));
}
awaitMetaData(metaData);
return metaData;
}
/**
* Gets bean name by containing archive {@link URL} address
*
* @param url
* @return
*/
public static Collection<String> getBeanNames(URL url) {
synchronized (MetaContainer.class) {
return EJB_URLS.get(url);
}
}
/**
* checks containing archive {@link URL} address
*
* @param url
* @return
*/
public static boolean chackDeployment(URL url) {
synchronized (MetaContainer.class) {
return EJB_URLS.containsKey(url);
}
}
/**
* Removes cached bean names {@link Collection} by containing file
* {@link URL} as key
*
* @param url
*/
public static void removeBeanNames(URL url) {
synchronized (MetaContainer.class) {
EJB_URLS.remove(url);
}
}
/**
* Caches bean name by {@link URL} of jar ear or any file
*
* @param beanName
*/
public static void addBeanName(URL url, String beanName) {
synchronized (MetaContainer.class) {
Collection<String> beanNames = EJB_URLS.get(url);
if (CollectionUtils.invalid(beanNames)) {
beanNames = new HashSet<String>();
EJB_URLS.put(url, beanNames);
}
beanNames.add(beanName);
}
}
/**
* Lists set for deployed application {@link URL}'s
*
* @return {@link Set}<URL>
*/
public static Set<URL> listApplications() {
Set<URL> apps = EJB_URLS.keySet();
return apps;
}
/**
* Clears connection from cache
*
* @param metaData
* @throws IOException
*/
private static void clearConnection(MetaData metaData) throws IOException {
Collection<ConnectionData> connections = metaData.getConnections();
if (CollectionUtils.valid(connections)) {
for (ConnectionData connection : connections) {
// Gets connection to clear
String unitName = connection.getUnitName();
ConnectionSemaphore semaphore = connection.getConnection();
if (semaphore == null) {
semaphore = ConnectionContainer.getConnection(unitName);
}
if (ObjectUtils.notNull(semaphore)
&& semaphore.decrementUser() <= ConnectionSemaphore.MINIMAL_USERS) {
ConnectionContainer.removeConnection(unitName);
}
}
}
}
/**
* Removes bean (removes it's {@link MetaData} from cache) by bean class
* name
*
* @param beanName
* @throws IOException
*/
public static void undeployBean(String beanName) throws IOException {
MetaData metaData = null;
try {
metaData = getSyncMetaData(beanName);
} catch (IOException ex) {
LogUtils.error(LOG, ex, "Could not get bean resources %s cause %s",
beanName, ex.getMessage());
}
// Removes MetaData from cache
removeMeta(beanName);
if (ObjectUtils.notNull(metaData)) {
// Removes appropriated resource class from REST service
if (RestContainer.hasRest()) {
RestProvider.remove(metaData.getBeanClass());
}
clearConnection(metaData);
ClassLoader loader = metaData.getLoader();
LibraryLoader.closeClassLoader(loader);
metaData = null;
}
}
/**
* Removes bean (removes it's {@link MetaData} from cache) by {@link URL} of
* archive file
*
* @param url
* @throws IOException
*/
public static boolean undeploy(URL url) throws IOException {
synchronized (MetaContainer.class) {
Collection<String> beanNames = getBeanNames(url);
boolean valid = CollectionUtils.valid(beanNames);
if (valid) {
for (String beanName : beanNames) {
undeployBean(beanName);
}
}
removeBeanNames(url);
return valid;
}
}
/**
* Removes bean (removes it's {@link MetaData} from cache) by {@link File}
* of archive file
*
* @param file
* @throws IOException
*/
public static boolean undeploy(File file) throws IOException {
URL url = file.toURI().toURL();
boolean valid = undeploy(url);
return valid;
}
/**
* Removes bean (removes it's {@link MetaData} from cache) by {@link File}
* path of archive file
*
* @param path
* @throws IOException
*/
public static boolean undeploy(String path) throws IOException {
File file = new File(path);
boolean valid = undeploy(file);
return valid;
}
/**
* Removed {@link MetaData} from cache
*
* @param beanName
*/
public static void removeMeta(String beanName) {
EJBS.remove(beanName);
}
/**
* Gets {@link java.util.Iterator}<MetaData> over all cached
* {@link org.lightmare.cache.MetaData}
*
* @return {@link java.util.Iterator}<MetaData>
*/
public static Iterator<MetaData> getBeanClasses() {
return EJBS.values().iterator();
}
/**
* Removes all cached resources
*/
public static void clear() {
if (ObjectUtils.notNull(creator)) {
synchronized (MetaContainer.class) {
if (ObjectUtils.notNull(creator)) {
creator.clear();
creator = null;
}
}
}
CONFIGS.clear();
EJBS.clear();
EJB_URLS.clear();
}
}
|
package org.opencloudb.route;
import java.sql.SQLNonTransientException;
import java.sql.SQLSyntaxErrorException;
import java.util.Locale;
import org.apache.log4j.Logger;
import org.opencloudb.cache.CachePool;
import org.opencloudb.cache.CacheService;
import org.opencloudb.cache.LayerCachePool;
import org.opencloudb.config.model.SchemaConfig;
import org.opencloudb.config.model.SystemConfig;
import org.opencloudb.route.factory.RouteStrategyFactory;
import org.opencloudb.route.handler.HintHandler;
import org.opencloudb.route.handler.HintHandlerFactory;
import org.opencloudb.route.handler.HintSQLHandler;
import org.opencloudb.server.ServerConnection;
import org.opencloudb.server.parser.ServerParse;
public class RouteService {
private static final Logger LOGGER = Logger
.getLogger(RouteService.class);
private final CachePool sqlRouteCache;
private final LayerCachePool tableId2DataNodeCache;
private final String OLD_MYCAT_HINT = "/*!mycat:"; // , /*!mycat: type = value */ sql
private final String NEW_MYCAT_HINT = "/*#mycat:"; // :/* !mycat: type = value */ sqloldMycatHintmysql
private final String HINT_SPLIT = "=";
public RouteService(CacheService cachService) {
sqlRouteCache = cachService.getCachePool("SQLRouteCache");
tableId2DataNodeCache = (LayerCachePool) cachService
.getCachePool("TableID2DataNodeCache");
}
public LayerCachePool getTableId2DataNodeCache() {
return tableId2DataNodeCache;
}
public RouteResultset route(SystemConfig sysconf, SchemaConfig schema,
int sqlType, String stmt, String charset, ServerConnection sc)
throws SQLNonTransientException {
RouteResultset rrs = null;
String cacheKey = null;
/**
* SELECT SQL,
*/
if (sqlType == ServerParse.SELECT) {
cacheKey = schema.getName() + stmt;
rrs = (RouteResultset) sqlRouteCache.get(cacheKey);
if (rrs != null) {
return rrs;
}
}
/*!mycat: sql = select name from aa */
/*!mycat: schema = test */
boolean isMatchOldHint = stmt.startsWith(OLD_MYCAT_HINT);
boolean isMatchNewHint = stmt.startsWith(NEW_MYCAT_HINT);
if (isMatchOldHint || isMatchNewHint ) {
int endPos = stmt.indexOf("*/");
if (endPos > 0) {
// !mycat:
int hintLength = isMatchOldHint ? OLD_MYCAT_HINT.length() : NEW_MYCAT_HINT.length();
String hint = stmt.substring(hintLength, endPos).trim();
int firstSplitPos = hint.indexOf(HINT_SPLIT);
if(firstSplitPos > 0 ){
String hintType = hint.substring(0,firstSplitPos).trim().toLowerCase(Locale.US);
String hintSql = hint.substring(firstSplitPos + HINT_SPLIT.length()).trim();
if( hintSql.length() == 0 ) {
LOGGER.warn("comment int sql must meet :/*!mycat:type=value*/ or /*#mycat:type=value*/: "+stmt);
throw new SQLSyntaxErrorException("comment int sql must meet :/*!mycat:type=value*/ or /*#mycat:type=value*/: "+stmt);
}
String realSQL = stmt.substring(endPos + "*/".length()).trim();
HintHandler hintHandler = HintHandlerFactory.getHintHandler(hintType);
if( hintHandler != null ) {
if ( hintHandler instanceof HintSQLHandler) {
/**
* SQL sqlType SQL sqlType hint=SELECTreal=INSERT
* fixed by zhuam
*/
int hintSqlType = ServerParse.parse( hintSql ) & 0xff;
rrs = hintHandler.route(sysconf, schema, hintSqlType, realSQL, charset, sc, tableId2DataNodeCache, hintSql);
} else {
rrs = hintHandler.route(sysconf, schema, sqlType, realSQL, charset, sc, tableId2DataNodeCache, hintSql);
}
}else{
LOGGER.warn("TODO , support hint sql type : " + hintType);
}
}else{//fixed by runfriends@126.com
LOGGER.warn("comment in sql must meet :/*!mycat:type=value*/ or /*#mycat:type=value*/: "+stmt);
throw new SQLSyntaxErrorException("comment in sql must meet :/*!mcat:type=value*/ or /*#mycat:type=value*/: "+stmt);
}
}
} else {
stmt = stmt.trim();
rrs = RouteStrategyFactory.getRouteStrategy().route(sysconf, schema, sqlType, stmt,
charset, sc, tableId2DataNodeCache);
}
if (rrs != null && sqlType == ServerParse.SELECT && rrs.isCacheAble()) {
sqlRouteCache.putIfAbsent(cacheKey, rrs);
}
return rrs;
}
}
|
package org.orecruncher.dsurround;
public final class ModInfo {
public static final String MOD_ID = "dsurround";
public static final String API_ID = MOD_ID + "API";
public static final String RESOURCE_ID = "dsurround";
public static final String MOD_NAME = "Dynamic Surroundings";
public static final String VERSION = "@VERSION@";
public static final String MINECRAFT_VERSIONS = "[1.12.2,)";
public static final String GUI_FACTORY = "org.orecruncher.dsurround.client.gui.ConfigGuiFactory";
public static final String UPDATE_URL = "@UPDATEURL@";
public static final String FINGERPRINT = "@FINGERPRINT@";
public static final String REMOTE_VERSIONS = "*";
//@formatter:off
public static final String DEPENDENCIES =
"required-after:forge@[14.23.5.2768,);" +
"required-after:dsurroundcore;" +
"required-after:orelib@[3.5.2.3,);" +
"after:sereneseasons@[1.2.18,);" +
"after:animania@[1.7.2,);" +
"after:galacticraftcore;" +
"after:ambientsounds;";
//@formatter:on
}
|
package org.riderzen.flume.sink;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.lang.StringUtils;
import org.apache.flume.Channel;
import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.EventDeliveryException;
import org.apache.flume.Transaction;
import org.apache.flume.conf.Configurable;
import org.apache.flume.sink.AbstractSink;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.DateTimeFormatterBuilder;
import org.joda.time.format.DateTimeParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.mongodb.BasicDBObject;
import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.CommandResult;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.util.JSON;
public class MongoSink extends AbstractSink implements Configurable {
private static Logger logger = LoggerFactory.getLogger(MongoSink.class);
private static DateTimeParser[] parsers = {
DateTimeFormat.forPattern("yyyy-MM-dd").getParser(),
DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").getParser(),
DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS").getParser(),
DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss Z").getParser(),
DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS Z").getParser(),
DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ").getParser(),
DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ").getParser(),
DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssz").getParser(),
DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSz").getParser(),
};
public static DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder().append(null, parsers).toFormatter();
public static final String HOST = "host";
public static final String PORT = "port";
public static final String AUTHENTICATION_ENABLED = "authenticationEnabled";
public static final String USERNAME = "username";
public static final String PASSWORD = "password";
public static final String MODEL = "model";
public static final String DB_NAME = "db";
public static final String COLLECTION = "collection";
public static final String NAME_PREFIX = "MongSink_";
public static final String BATCH_SIZE = "batch";
public static final String AUTO_WRAP = "autoWrap";
public static final String WRAP_FIELD = "wrapField";
public static final String TIMESTAMP_FIELD = "timestampField";
public static final String OPERATION = "op";
public static final String PK = "_id";
public static final String OP_INC = "$inc";
public static final String OP_SET = "$set";
public static final String OP_SET_ON_INSERT = "$setOnInsert";
public static final boolean DEFAULT_AUTHENTICATION_ENABLED = false;
public static final String DEFAULT_HOST = "localhost";
public static final int DEFAULT_PORT = 27017;
public static final String DEFAULT_DB = "events";
public static final String DEFAULT_COLLECTION = "events";
public static final int DEFAULT_BATCH = 100;
private static final Boolean DEFAULT_AUTO_WRAP = false;
public static final String DEFAULT_WRAP_FIELD = "log";
public static final String DEFAULT_TIMESTAMP_FIELD = null;
public static final char NAMESPACE_SEPARATOR = '.';
public static final String OP_UPSERT = "upsert";
public static final String EXTRA_FIELDS_PREFIX = "extraFields.";
private static AtomicInteger counter = new AtomicInteger();
private Mongo mongo;
private DB db;
private String host;
private int port;
private boolean authentication_enabled;
private String username;
private String password;
private CollectionModel model;
private String dbName;
private String collectionName;
private int batchSize;
private boolean autoWrap;
private String wrapField;
private String timestampField;
private final Map<String, String> extraInfos = new ConcurrentHashMap<String, String>();
@Override
public void configure(Context context) {
setName(NAME_PREFIX + counter.getAndIncrement());
host = context.getString(HOST, DEFAULT_HOST);
port = context.getInteger(PORT, DEFAULT_PORT);
authentication_enabled = context.getBoolean(AUTHENTICATION_ENABLED, DEFAULT_AUTHENTICATION_ENABLED);
if (authentication_enabled) {
username = context.getString(USERNAME);
password = context.getString(PASSWORD);
} else {
username = "";
password = "";
}
model = CollectionModel.valueOf(context.getString(MODEL, CollectionModel.SINGLE.name()));
dbName = context.getString(DB_NAME, DEFAULT_DB);
collectionName = context.getString(COLLECTION, DEFAULT_COLLECTION);
batchSize = context.getInteger(BATCH_SIZE, DEFAULT_BATCH);
autoWrap = context.getBoolean(AUTO_WRAP, DEFAULT_AUTO_WRAP);
wrapField = context.getString(WRAP_FIELD, DEFAULT_WRAP_FIELD);
timestampField = context.getString(TIMESTAMP_FIELD, DEFAULT_TIMESTAMP_FIELD);
extraInfos.putAll(context.getSubProperties(EXTRA_FIELDS_PREFIX));
logger.info("MongoSink {} context { host:{}, port:{}, authentication_enabled:{}, username:{}, password:{}, model:{}, dbName:{}, collectionName:{}, batch: {}, autoWrap: {}, wrapField: {}, timestampField: {} }",
new Object[]{getName(), host, port, authentication_enabled, username, password, model, dbName, collectionName, batchSize, autoWrap, wrapField, timestampField});
}
@Override
public synchronized void start() {
logger.info("Starting {}...", getName());
try {
mongo = new Mongo(host, port);
db = mongo.getDB(dbName);
} catch (UnknownHostException e) {
logger.error("Can't connect to mongoDB", e);
return;
}
if (authentication_enabled) {
boolean result = db.authenticate(username, password.toCharArray());
if (result) {
logger.info("Authentication attempt successful.");
} else {
logger.error("CRITICAL FAILURE: Unable to authenticate. Check username and Password, or use another unauthenticated DB. Not starting MongoDB sink.\n");
return;
}
}
super.start();
logger.info("Started {}.", getName());
}
@Override
public Status process() throws EventDeliveryException {
logger.debug("{} start to process event", getName());
Status status = Status.READY;
try {
status = parseEvents();
} catch (Exception e) {
logger.error("can't process events", e);
}
logger.debug("{} processed event", getName());
return status;
}
private void saveEvents(Map<String, List<DBObject>> eventMap) {
if (eventMap.isEmpty()) {
logger.debug("eventMap is empty");
return;
}
for (Map.Entry<String, List<DBObject>> entry : eventMap.entrySet()) {
List<DBObject> docs = entry.getValue();
if (logger.isDebugEnabled()) {
logger.debug("collection: {}, length: {}", entry.getKey(), docs.size());
}
int separatorIndex = entry.getKey().indexOf(NAMESPACE_SEPARATOR);
String eventDb = entry.getKey().substring(0, separatorIndex);
String collectionNameVar = entry.getKey().substring(separatorIndex + 1);
//Warning: please change the WriteConcern level if you need high datum consistence.
DB dbRef = mongo.getDB(eventDb);
if (authentication_enabled) {
boolean authResult = dbRef.authenticate(username, password.toCharArray());
if (!authResult) {
logger.error("Failed to authenticate user: " + username + " with password: " + password + ". Unable to write events.");
return;
}
}
try {
CommandResult result = dbRef.getCollection(collectionNameVar)
.insert(docs, WriteConcern.SAFE).getLastError();
if (result.ok()) {
String errorMessage = result.getErrorMessage();
if (errorMessage != null) {
logger.error("can't insert documents with error: {} ",
errorMessage);
logger.error("with exception", result.getException());
throw new MongoException(errorMessage);
}
} else {
logger.error("can't get last error");
}
} catch (Exception e) {
if (!(e instanceof com.mongodb.MongoException.DuplicateKey)) {
logger.error("can't process event batch ", e);
logger.debug("can't process doc:{}", docs);
}
for (DBObject doc : docs) {
try {
dbRef.getCollection(collectionNameVar).insert(doc,
WriteConcern.SAFE);
} catch (Exception ee) {
if (!(e instanceof com.mongodb.MongoException.DuplicateKey)) {
logger.error(doc.toString());
logger.error("can't process events, drop it!", ee);
}
}
}
}
}
}
private Status parseEvents() throws EventDeliveryException {
Status status = Status.READY;
Channel channel = getChannel();
Transaction tx = null;
Map<String, List<DBObject>> eventMap = new HashMap<String, List<DBObject>>();
Map<String, List<DBObject>> upsertMap = new HashMap<String, List<DBObject>>();
try {
tx = channel.getTransaction();
tx.begin();
for (int i = 0; i < batchSize; i++) {
Event event = channel.take();
if (event == null) {
status = Status.BACKOFF;
break;
} else {
String operation = event.getHeaders().get(OPERATION);
if (logger.isDebugEnabled()) {
logger.debug("event operation is {}", operation);
}
if (OP_UPSERT.equalsIgnoreCase(operation)) {
processEvent(upsertMap, event);
} else if (StringUtils.isNotBlank(operation)) {
logger.error("non-supports operation {}", operation);
} else {
processEvent(eventMap, event);
}
}
}
if (!eventMap.isEmpty()) {
saveEvents(eventMap);
}
if (!upsertMap.isEmpty()) {
doUpsert(upsertMap);
}
tx.commit();
} catch (Exception e) {
logger.error("can't process events, drop it!", e);
if (tx != null) {
tx.commit();// commit to drop bad event, otherwise it will enter dead loop.
}
throw new EventDeliveryException(e);
} finally {
if (tx != null) {
tx.close();
}
}
return status;
}
private void doUpsert(Map<String, List<DBObject>> eventMap) {
if (eventMap.isEmpty()) {
logger.debug("eventMap is empty");
return;
}
for (Map.Entry<String, List<DBObject>> entry : eventMap.entrySet()) {
List<DBObject> docs = entry.getValue();
if (logger.isDebugEnabled()) {
logger.debug("collection: {}, length: {}", entry.getKey(), docs.size());
}
int separatorIndex = entry.getKey().indexOf(NAMESPACE_SEPARATOR);
String eventDb = entry.getKey().substring(0, separatorIndex);
String collectionName = entry.getKey().substring(separatorIndex + 1);
//Warning: please change the WriteConcern level if you need high datum consistence.
DB dbRef = mongo.getDB(eventDb);
if (authentication_enabled) {
boolean authResult = dbRef.authenticate(username, password.toCharArray());
if (!authResult) {
logger.error("Failed to authenticate user: " + username + " with password: " + password + ". Unable to write events.");
return;
}
}
DBCollection collection = dbRef.getCollection(collectionName);
for (DBObject doc : docs) {
if (logger.isDebugEnabled()) {
logger.debug("doc: {}", doc);
}
DBObject query = BasicDBObjectBuilder.start()
.add(PK, doc.get(PK)).get();
BasicDBObjectBuilder doc_builder = BasicDBObjectBuilder.start();
if (doc.keySet().contains(OP_INC)) {
doc_builder.add(OP_INC, doc.get(OP_INC));
}
if (doc.keySet().contains(OP_SET)) {
doc_builder.add(OP_SET, doc.get(OP_SET));
}
if (doc.keySet().contains(OP_SET_ON_INSERT)) {
doc_builder.add(OP_SET_ON_INSERT, doc.get(OP_SET_ON_INSERT));
}
doc = doc_builder.get();
//logger.debug("query: {}", query);
//logger.debug("new doc: {}", doc);
CommandResult result = collection.update(query, doc, true,
false, WriteConcern.SAFE).getLastError();
if (result.ok()) {
String errorMessage = result.getErrorMessage();
if (errorMessage != null) {
logger.error("can't upsert documents with error: {} ",
errorMessage);
logger.error("with exception", result.getException());
throw new MongoException(errorMessage);
}
} else {
logger.error("can't get last error");
}
}
}
}
private void processEvent(Map<String, List<DBObject>> eventMap, Event event) {
switch (model) {
case SINGLE:
putSingleEvent(eventMap, event);
break;
case DYNAMIC:
putDynamicEvent(eventMap, event);
break;
default:
logger.error("can't support model: {}, please check configuration.", model);
}
}
private void putDynamicEvent(Map<String, List<DBObject>> eventMap, Event event) {
String eventCollection;
Map<String, String> headers = event.getHeaders();
String eventDb = headers.get(DB_NAME);
eventCollection = headers.get(COLLECTION);
if (!StringUtils.isEmpty(eventDb)) {
eventCollection = eventDb + NAMESPACE_SEPARATOR + eventCollection;
} else {
eventCollection = dbName + NAMESPACE_SEPARATOR + eventCollection;
}
if (!eventMap.containsKey(eventCollection)) {
eventMap.put(eventCollection, new ArrayList<DBObject>());
}
List<DBObject> documents = eventMap.get(eventCollection);
addEventToList(documents, event);
}
private void putSingleEvent(Map<String, List<DBObject>> eventMap, Event event) {
String eventCollection;
eventCollection = dbName + NAMESPACE_SEPARATOR + collectionName;
if (!eventMap.containsKey(eventCollection)) {
eventMap.put(eventCollection, new ArrayList<DBObject>());
}
List<DBObject> docs = eventMap.get(eventCollection);
addEventToList(docs, event);
}
private List<DBObject> addEventToList(List<DBObject> documents, Event event) {
if (documents == null) {
documents = new ArrayList<DBObject>(batchSize);
}
DBObject eventJson;
byte[] body = event.getBody();
if (autoWrap) {
eventJson = new BasicDBObject(wrapField, new String(body));
} else {
try {
eventJson = (DBObject) JSON.parse(new String(body));
} catch (Exception e) {
logger.error("Can't parse events: " + new String(body), e);
return documents;
}
}
if (!event.getHeaders().containsKey(OPERATION) && timestampField != null) {
Date timestamp;
if (eventJson.containsField(TIMESTAMP_FIELD)) {
try {
String dateText = (String) eventJson.get(TIMESTAMP_FIELD);
timestamp = dateTimeFormatter.parseDateTime(dateText).toDate();
eventJson.removeField(TIMESTAMP_FIELD);
} catch (Exception e) {
logger.error("can't parse date ", e);
timestamp = new Date();
}
} else {
timestamp = new Date();
}
eventJson.put(TIMESTAMP_FIELD, timestamp);
}
for(Map.Entry<String, String> entry : extraInfos.entrySet()) {
eventJson.put(entry.getKey(), entry.getValue());
}
documents.add(eventJson);
return documents;
}
public enum CollectionModel {
DYNAMIC, SINGLE
}
}
|
package org.scribe.builder.api;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.scribe.exceptions.OAuthException;
import org.scribe.extractors.AccessTokenExtractor;
import org.scribe.extractors.TokenExtractor20Impl;
import org.scribe.model.OAuthConfig;
import org.scribe.model.Request;
import org.scribe.model.Token;
import org.scribe.utils.OAuthEncoder;
import org.scribe.utils.Preconditions;
public class IHealthApi extends DefaultApi20 {
private static final String URL_USERAUTHORIZATION_SANDBOX = "http://sandboxapi.ihealthlabs.com/OpenApiV2/OAuthv2/userauthorization/";
private static final String URL_USERAUTHORIZATION_PRODUCTION = "https://api.ihealthlabs.com:8443/OpenApiV2/OAuthv2/userauthorization/";
@Override
public String getAccessTokenEndpoint() {
//TODO doesn't work with sandbox
return "https://api.ihealthlabs.com:8443/OpenApiV2/OAuthv2/userauthorization/";
}
private String urlEncode(String text) {
try {
return URLEncoder.encode(text, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e.getMessage());
}
}
@Override
public String getAuthorizationUrl(OAuthConfig config) {
String url = config.isSandbox() ? URL_USERAUTHORIZATION_SANDBOX : URL_USERAUTHORIZATION_PRODUCTION;
return String.format(url + "?response_type=code&client_id=%s&APIName=%s&redirect_uri=%s",
urlEncode(config.getApiKey()),
urlEncode(config.getScope()),
urlEncode(config.getCallback()));
}
@Override
public AccessTokenExtractor getAccessTokenExtractor() {
return new AccessTokenExtractor() {
private static final String TOKEN_REGEX = "\"AccessToken\"\\s*:\\s*\"([^\"]+)";
private static final String EMPTY_SECRET = "";
private static final String REFRESH_TOKEN_REGEX = "\"RefreshToken\"\\s*:\\s*\"([^\"]+)";
public Token extract(String response)
{
Preconditions.checkEmptyString(response, "Response body is incorrect. Can't extract a token from an empty string");
Matcher matcher = Pattern.compile(TOKEN_REGEX).matcher(response);
Matcher matcherRefresh = Pattern.compile(REFRESH_TOKEN_REGEX).matcher(response);
if (matcher.find() && matcherRefresh.find())
{
String token = OAuthEncoder.decode(matcher.group(1));
String refreshToken = OAuthEncoder.decode(matcherRefresh.group(1));
return new Token(token, EMPTY_SECRET, response, refreshToken);
}
else
{
throw new OAuthException("Response body is incorrect. Can't extract a token from this: '" + response + "'", null);
}
}
};
}
@Override
public void signRequest(Token accessToken, Request request)
{
request.addHeader("Authorization", "Bearer " + accessToken.getToken());
}
}
|
/**
* @author Khalid Alharbi
*/
package org.sikuli.slides.utils;
import java.io.File;
/**
* This class contains constants.
*/
public class Constants {
/**
* The working directory absolute path.
* This holds the sikuli slides working directory in the operating system's temp directory.
*/
public static String workingDirectoryPath;
/**
* The current project directory name that contains the imported and extracted .pptx file.
*/
public static String projectDirectory;
/**
* The relative directory path to the embedding resources icons for the GUIs.
*/
public static final String RESOURCES_ICON_DIR="/org/sikuli/slides/gui/icons/";
/**
* The name of the directory that sikuli-slides creates in the operating system's tmp directory.
*/
public static final String SIKULI_SLIDES_ROOT_DIRECTORY="org.sikuli.SikuliSlides";
/**
* The name of the directory that contains all sikuli related files in the .pptx file.
*/
public static final String SIKULI_DIRECTORY=File.separator+"sikuli";
/**
* The name of the images directory that contains the cropped target images.
*/
public static final String IMAGES_DIRECTORY=File.separator+"images";
/**
* The slides directory that contains the XML files for each slide in the .pptx file.
*/
public static final String SLIDES_DIRECTORY=File.separator+"ppt"+File.separator+"slides";
/**
* The slides directory that contains the media files for each slide in the .pptx file.
*/
public static final String MEDIA_DIRECTORY=File.separator+"ppt"+File.separator+"media";
/**
* The slides directory that contains the slide notes.
*/
public static final String SLIDE_NOTES_DIRECTORY=File.separator+"ppt"+File.separator+"notesSlides";
/**
* The presentaion.xml absolute path name.
*/
public static final String PRESENTATION_DIRECTORY=File.separator+"ppt"+File.separator+"presentation.xml";
/**
* The relationship directory that contains info about the duplicated media files in the presentation slides.
*/
public static final String RELATIONSHIP_DIRECTORY=File.separator+"ppt"+File.separator+"slides"+File.separator+"_rels";
/**
* The key name for maximum wait time to find target on the screen.
*/
public static final String MAX_WAIT_TIME_MS = "max_wait_time_ms";
/**
* The default key value for maximum wait time in milliseconds to find target on the screen.
*/
public static int MAX_WAIT_TIME_MS_DEFAULT = 15000;
/**
* The key name for the time to display a label on the screen.
*/
public static final String LABEL_DISPLAY_TIME_SEC = "label_display_time_sec";
/**
* The default key value for the time, in seconds, to display a label on the screen.
*/
public static final int LABEL_DISPLAY_TIME_SEC_DEFAULT = 3;
/**
* The key name for the instruction hint (tooltip) font size.
*/
public static final String INSTRUCTION_HINT_FONT_SIZE="instruction_hint_font_size";
/**
* The default key value of the instruction hint (tooltip) font size.
*/
public static int INSTRUCTION_HINT_FONT_SIZE_DEFAULT=18;
/**
* The key name for the canvas width size.
*/
public static final String CANVAS_WIDTH_SIZE="canvas_width_size";
/**
* The default key value of the canvas width size.
*/
public static int CANVAS_WIDTH_SIZE_DEFAULT=5;
/**
* Screen id. Use this constant to run the test on a secondary monitor,
* 0 means the default monitor and 1 means the secondary monitor.
*/
public static int ScreenId=0;
/**
* This control how fuzzy the image search is. A value of 1 means the search
* is very precise and less fuzzy
*/
public static double MinScore=0.7;
/**
* Flag for the old syntax. Prior to version 1.2.0, we use special shapes to represent each action.
*/
public static boolean UseOldSyntax=false;
/**
* Desktop input events
*/
public enum DesktopEvent {
LEFT_CLICK, RIGHT_CLICK, DOUBLE_CLICK, DRAG_N_DROP, KEYBOARD_TYPING, LAUNCH_BROWSER,
EXIST, NOT_EXIST, WAIT
}
/**
* Running modes
*/
public static boolean ACTION_MODE=false;
public static boolean HELP_MODE=false;
public static boolean TUTORIAL_MODE=false;
public static boolean DEVELOPMENT_MODE=false;
/**
* Execution start time in milliseconds.
*/
public static long Execution_Start_Time;
/**
* Tutorial mode previous step.
*/
public static boolean IsPreviousStep=false;
/**
* Tutorial mode next step.
*/
public static boolean IsNextStep=false;
/**
* Wait action.
*/
public static boolean IsWaitAction=false;
/**
* Total steps in the tutorial mode
*/
public static int Steps_Total=0;
/**
* Tutorial mode navigation status
*/
public enum NavigationStatus {
NEXT, PREVIOUS
}
}
|
package org.threeten.extra.chrono;
import static java.time.temporal.ChronoField.EPOCH_DAY;
import static java.time.temporal.ChronoField.YEAR;
import static org.threeten.extra.chrono.PaxChronology.DAYS_IN_MONTH;
import static org.threeten.extra.chrono.PaxChronology.DAYS_IN_WEEK;
import static org.threeten.extra.chrono.PaxChronology.DAYS_IN_YEAR;
import static org.threeten.extra.chrono.PaxChronology.MONTHS_IN_YEAR;
import static org.threeten.extra.chrono.PaxChronology.WEEKS_IN_LEAP_MONTH;
import static org.threeten.extra.chrono.PaxChronology.WEEKS_IN_MONTH;
import static org.threeten.extra.chrono.PaxChronology.WEEKS_IN_YEAR;
import java.io.Serializable;
import java.time.Clock;
import java.time.DateTimeException;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.chrono.ChronoLocalDate;
import java.time.chrono.ChronoPeriod;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;
import java.time.temporal.Temporal;
import java.time.temporal.TemporalAccessor;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalAmount;
import java.time.temporal.TemporalField;
import java.time.temporal.TemporalQueries;
import java.time.temporal.TemporalQuery;
import java.time.temporal.TemporalUnit;
import java.time.temporal.ValueRange;
public final class PaxDate
extends AbstractDate
implements ChronoLocalDate, Serializable {
/**
* Serialization version.
*/
private static final long serialVersionUID = -2229133057743750072L;
/**
* The difference between the ISO and Pax epoch day count (Pax 0001-01-01 to ISO 1970-01-01).
*/
private static final int PAX_0001_TO_ISO_1970 = 719163;
/**
* The days per 400 year cycle.
*/
private static final int DAYS_PER_LONG_CYCLE = (DAYS_IN_YEAR * 400) + (DAYS_IN_WEEK * 71);
/**
* The days per 100 year cycle.
*/
private static final int DAYS_PER_CYCLE = (DAYS_IN_YEAR * 100) + (DAYS_IN_WEEK * 18);
/**
* The days per 6 year cycle.
*/
private static final int DAYS_PER_SIX_CYCLE = (DAYS_IN_YEAR * 6) + (DAYS_IN_WEEK * 1);
/**
* Number of years in a decade.
*/
private static final int YEARS_IN_DECADE = 10;
/**
* Number of years in a century.
*/
private static final int YEARS_IN_CENTURY = 100;
/**
* Number of years in a millennium.
*/
private static final int YEARS_IN_MILLENNIUM = 1000;
/**
* The proleptic year.
*/
private final int prolepticYear;
/**
* The month.
*/
private final short month;
/**
* The day.
*/
private final short day;
/**
* Obtains the current {@code PaxDate} from the system clock in the default time-zone.
* <p>
* This will query the {@link Clock#systemDefaultZone() system clock} in the default
* time-zone to obtain the current date.
* <p>
* Using this method will prevent the ability to use an alternate clock for testing
* because the clock is hard-coded.
*
* @return the current date using the system clock and default time-zone, not null
*/
public static PaxDate now() {
return now(Clock.systemDefaultZone());
}
/**
* Obtains the current {@code PaxDate} from the system clock in the specified time-zone.
* <p>
* This will query the {@link Clock#system(ZoneId) system clock} to obtain the current date.
* Specifying the time-zone avoids dependence on the default time-zone.
* <p>
* Using this method will prevent the ability to use an alternate clock for testing
* because the clock is hard-coded.
*
* @param zone the zone ID to use, not null
* @return the current date using the system clock, not null
*/
public static PaxDate now(ZoneId zone) {
return now(Clock.system(zone));
}
/**
* Obtains the current {@code PaxDate} from the specified clock.
* <p>
* This will query the specified clock to obtain the current date - today.
* Using this method allows the use of an alternate clock for testing.
* The alternate clock may be introduced using {@linkplain Clock dependency injection}.
*
* @param clock the clock to use, not null
* @return the current date, not null
* @throws DateTimeException if the current date cannot be obtained
*/
public static PaxDate now(Clock clock) {
LocalDate now = LocalDate.now(clock);
return PaxDate.ofEpochDay(now.toEpochDay());
}
/**
* Obtains a {@code PaxDate} representing a date in the Pax calendar
* system from the proleptic-year, month-of-year and day-of-month fields.
* <p>
* This returns a {@code PaxDate} with the specified fields.
* The day must be valid for the year and month, otherwise an exception will be thrown.
*
* @param prolepticYear the Pax proleptic-year
* @param month the Pax month-of-year, from 1 to 14
* @param dayOfMonth the Pax day-of-month, from 1 to 28
* @return the date in Pax calendar system, not null
* @throws DateTimeException if the value of any field is out of range,
* or if the day-of-month is invalid for the month-year
*/
public static PaxDate of(int prolepticYear, int month, int dayOfMonth) {
YEAR.checkValidValue(prolepticYear);
if (month < 1 || month > MONTHS_IN_YEAR + 1) {
throw new DateTimeException("Invalid month " + month);
} else if (month == MONTHS_IN_YEAR + 1 && !PaxChronology.INSTANCE.isLeapYear(prolepticYear)) {
throw new DateTimeException("Invalid month 14 as " + prolepticYear + "is not a leap year");
}
if (dayOfMonth < 1 || dayOfMonth > DAYS_IN_MONTH) {
throw new DateTimeException("Invalid day-of-month " + dayOfMonth);
} else if (dayOfMonth > DAYS_IN_WEEK && month == MONTHS_IN_YEAR && PaxChronology.INSTANCE.isLeapYear(prolepticYear)) {
throw new DateTimeException("Invalid date during Pax as " + prolepticYear + " is a leap year");
}
return new PaxDate(prolepticYear, month, dayOfMonth);
}
public static PaxDate from(TemporalAccessor temporal) {
if (temporal instanceof PaxDate) {
return (PaxDate) temporal;
}
return PaxDate.ofEpochDay(temporal.getLong(EPOCH_DAY));
}
/**
* Obtains a {@code PaxDate} representing a date in the Pax calendar
* system from the proleptic-year and day-of-year fields.
* <p>
* This returns a {@code PaxDate} with the specified fields.
* The day must be valid for the year, otherwise an exception will be thrown.
*
* @param prolepticYear the Pax proleptic-year
* @param dayOfYear the Pax day-of-year, from 1 to 371
* @return the date in Pax calendar system, not null
* @throws DateTimeException if the value of any field is out of range,
* or if the day-of-year is invalid for the year
*/
static PaxDate ofYearDay(int prolepticYear, int dayOfYear) {
YEAR.checkValidValue(prolepticYear);
if (dayOfYear < 1 || dayOfYear > DAYS_IN_YEAR + DAYS_IN_WEEK) {
throw new DateTimeException("Inavlid date 'DayOfYear " + dayOfYear + "'");
}
boolean leap = PaxChronology.INSTANCE.isLeapYear(prolepticYear);
if (dayOfYear > DAYS_IN_YEAR && !leap) {
throw new DateTimeException("Invalid date 'DayOfYear " + dayOfYear + "' as '" + prolepticYear + "' is not a leap year");
}
int month = ((dayOfYear - 1) / DAYS_IN_MONTH) + 1;
// In leap years, the leap-month is shorter than the following month, so needs to be adjusted.
if (leap && month == MONTHS_IN_YEAR && dayOfYear >= (DAYS_IN_YEAR + DAYS_IN_WEEK) - DAYS_IN_MONTH + 1) {
month++;
}
// Subtract days-at-start-of-month from days in year
int dayOfMonth = dayOfYear - (month - 1) * DAYS_IN_MONTH;
// Adjust for shorter inserted leap-month.
if (month == MONTHS_IN_YEAR + 1) {
dayOfMonth += (DAYS_IN_MONTH - DAYS_IN_WEEK);
}
return of(prolepticYear, month, dayOfMonth);
}
/**
* Obtains a {@code PaxDate} representing a date in the Pax calendar
* system from the epoch-day.
*
* @param epochDay the epoch day to convert based on 1970-01-01 (ISO)
* @return the date in Pax calendar system, not null
* @throws DateTimeException if the epoch-day is out of range
*/
static PaxDate ofEpochDay(long epochDay) {
EPOCH_DAY.range().checkValidValue(epochDay, EPOCH_DAY);
// use of Pax 0001 makes non-leap century at end of (long) cycle.
long paxEpochDay = epochDay + PAX_0001_TO_ISO_1970;
int longCycle = (int) Math.floorDiv(paxEpochDay, DAYS_PER_LONG_CYCLE);
int cycle = (int) (paxEpochDay - longCycle * DAYS_PER_LONG_CYCLE) / DAYS_PER_CYCLE;
int dayOfCycle = (int) Math.floorMod(paxEpochDay - longCycle * DAYS_PER_LONG_CYCLE, DAYS_PER_CYCLE);
if (dayOfCycle >= DAYS_PER_CYCLE - DAYS_IN_YEAR - DAYS_IN_WEEK) {
// Is in the century year
int dayOfYear = dayOfCycle - (DAYS_PER_CYCLE - DAYS_IN_YEAR - DAYS_IN_WEEK) + 1;
return ofYearDay(longCycle * 400 + cycle * 100 + 100, dayOfYear);
}
// For negative years, the cycle of leap years runs the other direction for 99s and 6s.
if (paxEpochDay >= 0) {
if (dayOfCycle >= DAYS_PER_CYCLE - 2 * DAYS_IN_YEAR - 2 * DAYS_IN_WEEK) {
// Is in the '99 year
int dayOfYear = dayOfCycle - (DAYS_PER_CYCLE - 2 * DAYS_IN_YEAR - 2 * DAYS_IN_WEEK) + 1;
return ofYearDay(longCycle * 400 + cycle * 100 + 99, dayOfYear);
}
// Otherwise, part of the regular 6-year cycle.
int sixCycle = dayOfCycle / DAYS_PER_SIX_CYCLE;
int dayOfSixCycle = dayOfCycle % DAYS_PER_SIX_CYCLE;
int year = dayOfSixCycle / DAYS_IN_YEAR + 1;
int dayOfYear = dayOfSixCycle % DAYS_IN_YEAR + 1;
if (year == 7) {
year
dayOfYear += DAYS_IN_YEAR;
}
return ofYearDay(longCycle * 400 + cycle * 100 + sixCycle * 6 + year, dayOfYear);
} else {
if (dayOfCycle < DAYS_IN_YEAR + DAYS_IN_WEEK) {
// -'99 year is at _start_ of cycle (first year encountered).
return ofYearDay(longCycle * 400 + cycle * 100 + (100 - 99), dayOfCycle + 1);
}
// Otherwise, part of the regular 6-year cycle, but offset -'96 to be end of six-year-cycle first.
int offsetCycle = dayOfCycle + 2 * DAYS_IN_YEAR - DAYS_IN_WEEK;
int sixCycle = offsetCycle / DAYS_PER_SIX_CYCLE;
int dayOfSixCycle = offsetCycle % DAYS_PER_SIX_CYCLE;
int year = dayOfSixCycle / DAYS_IN_YEAR + 1;
int dayOfYear = dayOfSixCycle % DAYS_IN_YEAR + 1;
if (year == 7) {
year
dayOfYear += DAYS_IN_YEAR;
}
return ofYearDay(longCycle * 400 + cycle * 100 + (100 - (99 + 3 - (sixCycle * 6 + year))), dayOfYear);
}
}
private static PaxDate resolvePreviousValid(int year, int month, int day) {
int monthR = Math.min(month, MONTHS_IN_YEAR + (PaxChronology.INSTANCE.isLeapYear(year) ? 1 : 0));
int dayR = Math.min(day, month == MONTHS_IN_YEAR && PaxChronology.INSTANCE.isLeapYear(year) ? DAYS_IN_WEEK : DAYS_IN_MONTH);
return PaxDate.of(year, monthR, dayR);
}
/**
* Get the count of leap months since proleptic month 0.
* <p>
* This number is negative if the month is prior to Pax year 0.
** <p>
* Remember that if using this for things like turning months into days, you must first subtract this number from the proleptic month count.
*
* @param prolepticMonth The month.
* @return The number of leap months since proleptic month 0.
*/
private static long getLeapMonthsBefore(long prolepticMonth) {
long offsetMonth = prolepticMonth - (prolepticMonth <= 0 ? 13 : 13 - 1);
// First, see getLeapYearsBefore(...) for explanations.
// return 18 * Math.floorDiv(offsetMonth, 100 * MONTHS_IN_YEAR + (getLeapYearsBefore(100) + 1))
// - Math.floorDiv(offsetMonth, 400 * MONTHS_IN_YEAR + (getLeapYearsBefore(400) + 1))
// + (((Math.floorMod(offsetMonth, 100 * MONTHS_IN_YEAR + (getLeapYearsBefore(100) + 1)) - (offsetMonth <= 0 ? 100 * MONTHS_IN_YEAR + getLeapYearsBefore(100) : 0))
// / (99 * MONTHS_IN_YEAR + (getLeapYearsBefore(99) + 1))) + (offsetMonth <= 0 ? 1 : 0))
// + (Math.floorMod(offsetMonth, 100 * MONTHS_IN_YEAR + (getLeapYearsBefore(100) + 1)) + (offsetMonth <= 0 ? 2 * MONTHS_IN_YEAR - 1 : 0)) / (6 * MONTHS_IN_YEAR + 1);
return 18L * Math.floorDiv(offsetMonth, 1318)
- Math.floorDiv(offsetMonth, 5272)
+ (((Math.floorMod(offsetMonth, 1318) - (offsetMonth <= 0 ? 1317 : 0)) / 1304) + (offsetMonth <= 0 ? 1 : 0))
+ (Math.floorMod(offsetMonth, 1318) + (offsetMonth <= 0 ? 25 : 0)) / 79;
}
/**
* Get the count of leap years since Pax year 0.
* <p>
* This number is negative if the year is prior to Pax year 0.
*
* @param prolepticYear The year.
* @return The number of leap years since Pax year 0.
*/
private static long getLeapYearsBefore(long prolepticYear) {
// Some explanations are in order:
// - First, because this calculates "leap years from 0 to the start of the year",
// The 'current' year must be counted when the year is negative (hence Math.floorDiv(...)).
// - However, this means that there's a negative count which must be offset for the in-century years,
// which still occur at the "last two digits divisible by 6" (or 99) point.
// - Math.floorMod(...) returns a nicely positive result for negative years, counting 'down', but
// thus needs to be offset to make sure the first leap year is -6, and not -4...
// The second line, which calculates the '99 occurrences, runs "backwards", so must first be reversed, then the results flipped.
return 18L * Math.floorDiv(prolepticYear - 1, 100) - Math.floorDiv(prolepticYear - 1, 400) +
(Math.floorMod(prolepticYear - 1, 100) - (prolepticYear <= 0 ? 99 : 0)) / 99 + (prolepticYear <= 0 ? 1 : 0) +
((Math.floorMod(prolepticYear - 1, 100) + (prolepticYear <= 0 ? 2 : 0)) / 6);
}
/**
* Creates an instance from validated data.
*
* @param prolepticYear the Pax proleptic-year
* @param month the Pax month, from 1 to 14
* @param dayOfMonth the Pax day-of-month, from 1 to 28
*/
private PaxDate(int prolepticYear, int month, int dayOfMonth) {
this.prolepticYear = prolepticYear;
this.month = (short) month;
this.day = (short) dayOfMonth;
}
/**
* Validates the object.
*
* @return the resolved date, not null
*/
private Object readResolve() {
return PaxDate.of(prolepticYear, month, day);
}
@Override
int getProlepticYear() {
return prolepticYear;
}
@Override
int getMonth() {
return month;
}
@Override
int getDayOfMonth() {
return day;
}
@Override
int getDayOfYear() {
return (getMonth() - 1) * DAYS_IN_MONTH
- (getMonth() == MONTHS_IN_YEAR + 1 ? DAYS_IN_MONTH - DAYS_IN_WEEK : 0) + getDayOfMonth();
}
@Override
AbstractDate withDayOfYear(int value) {
return plusDays(value - getDayOfYear());
}
@Override
int lengthOfYearInMonths() {
return MONTHS_IN_YEAR + (isLeapYear() ? 1 : 0);
}
@Override
ValueRange rangeAlignedWeekOfMonth() {
return ValueRange.of(1, getMonth() == MONTHS_IN_YEAR && isLeapYear() ? WEEKS_IN_LEAP_MONTH : WEEKS_IN_MONTH);
}
@Override
PaxDate resolvePrevious(int newYear, int newMonth, int dayOfMonth) {
return resolvePreviousValid(newYear, newMonth, dayOfMonth);
}
@Override
public ValueRange range(TemporalField field) {
if (field == ChronoField.ALIGNED_WEEK_OF_YEAR) {
return ValueRange.of(1, WEEKS_IN_YEAR + (isLeapYear() ? 1 : 0));
} else if (field == ChronoField.MONTH_OF_YEAR) {
return ValueRange.of(1, MONTHS_IN_YEAR + (isLeapYear() ? 1 : 0));
}
return super.range(field);
}
/**
* Get the proleptic month from the start of the epoch (Pax 0000).
*
* @return The proleptic month.
*/
@Override
long getProlepticMonth() {
return ((long) getProlepticYear()) * MONTHS_IN_YEAR + getLeapYearsBefore(getProlepticYear()) + getMonth() - 1;
}
/**
* Gets the chronology of this date, which is the Pax calendar system.
* <p>
* The {@code Chronology} represents the calendar system in use.
* The era and other fields in {@link ChronoField} are defined by the chronology.
*
* @return the Pax chronology, not null
*/
@Override
public PaxChronology getChronology() {
return PaxChronology.INSTANCE;
}
/**
* Returns the length of the month represented by this date.
* <p>
* This returns the length of the month in days.
* Month lengths do not match those of the ISO calendar system.
*
* @return the length of the month in days, from 7 to 28
*/
@Override
public int lengthOfMonth() {
switch (month) {
case 13:
return (isLeapYear() ? DAYS_IN_WEEK : DAYS_IN_MONTH);
default:
return DAYS_IN_MONTH;
}
}
@Override
public int lengthOfYear() {
return DAYS_IN_YEAR + (isLeapYear() ? DAYS_IN_WEEK : 0);
}
@Override
public PaxDate with(TemporalAdjuster adjuster) {
return (PaxDate) adjuster.adjustInto(this);
}
@Override
public PaxDate with(TemporalField field, long newValue) {
// Evaluate years as a special case, to deal with inserted leap months.
if (field == ChronoField.YEAR) {
return plusYears(newValue - getProlepticYear());
}
return (PaxDate) super.with(field, newValue);
}
@Override
public PaxDate plus(TemporalAmount amount) {
return (PaxDate) amount.addTo(this);
}
@Override
public PaxDate plus(long amountToAdd, TemporalUnit unit) {
return (PaxDate) super.plus(amountToAdd, unit);
}
/**
* Returns a copy of this {@code PaxDate} with the specified period in years added.
* <p>
* This method adds the specified amount to the years field in two steps:
* <ol>
* <li>Add the input years to the year field</li>
* <li>If necessary, shift the index to account for the inserted/deleted leap-month.</li>
* </ol>
* <p>
* In the Pax Calendar, the month of December is 13 in non-leap-years, and 14 in leap years.
* Shifting the index of the month thus means the month would still be the same.
* <p>
* In the case of moving from the inserted leap-month (destination year is non-leap), the month index is retained.
* This has the effect of retaining the same day-of-year.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param yearsToAdd the years to add, may be negative
* @return a {@code PaxDate} based on this date with the years added, not null
* @throws DateTimeException if the result exceeds the supported date range
*/
@Override
PaxDate plusYears(long yearsToAdd) {
if (yearsToAdd == 0) {
return this;
}
int newYear = YEAR.checkValidIntValue(getProlepticYear() + yearsToAdd);
// Retain actual month (not index) in the case where a leap month is to be inserted.
if (getMonth() == MONTHS_IN_YEAR && !isLeapYear() && PaxChronology.INSTANCE.isLeapYear(newYear)) {
return of(newYear, MONTHS_IN_YEAR + 1, getDayOfMonth());
}
// Otherwise, one of the following is true:
// 1 - Before the leap month, nothing to do (most common)
// 2 - Both source and destination in leap-month, nothing to do
// 3 - Both source and destination after leap month in leap year, nothing to do
// 4 - Source in leap month, but destination year not leap. Retain month index, preserving day-of-year.
// 5 - Source after leap month, but destination year not leap. Move month index back.
return resolvePreviousValid(newYear, month, day);
}
/**
* Returns a copy of this {@code PaxDate} with the specified period in months added.
* <p>
* This method adds the specified amount to the months field in three steps:
* <ol>
* <li>Add the input months to the month-of-year field</li>
* <li>Check if the resulting date would be invalid</li>
* <li>Adjust the day-of-month to the last valid day if necessary</li>
* </ol>
* <p>
* For example, 2006-12-13 plus one month would result in the invalid date 2006-13-13.
* Instead of returning an invalid result, the last valid day of the month, 2006-13-07, is selected instead.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param monthsToAdd the months to add, may be negative
* @return a {@code PaxDate} based on this date with the months added, not null
* @throws DateTimeException if the result exceeds the supported date range
*/
@Override
PaxDate plusMonths(long monthsToAdd) {
if (monthsToAdd == 0) {
return this;
}
long calcMonths = Math.addExact(getProlepticMonth(), monthsToAdd);
// "Regularize" the month count, as if years were all 13 months long.
long monthsRegularized = calcMonths - getLeapMonthsBefore(calcMonths);
int newYear = YEAR.checkValidIntValue(Math.floorDiv(monthsRegularized, MONTHS_IN_YEAR));
int newMonth = Math.toIntExact(calcMonths - (newYear * MONTHS_IN_YEAR + getLeapYearsBefore(newYear)) + 1);
return resolvePreviousValid(newYear, newMonth, getDayOfMonth());
}
@Override
public PaxDate minus(TemporalAmount amount) {
return (PaxDate) amount.subtractFrom(this);
}
@Override
public PaxDate minus(long amountToSubtract, TemporalUnit unit) {
return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit));
}
@Override
public long until(Temporal endExclusive, TemporalUnit unit) {
return until(JulianDate.from(endExclusive), unit);
}
@Override
long until(AbstractDate end, TemporalUnit unit) {
if (unit instanceof ChronoUnit) {
PaxDate paxEnd = PaxDate.from(end);
switch ((ChronoUnit) unit) {
case YEARS:
return yearsUntil(paxEnd);
case DECADES:
return yearsUntil(paxEnd) / YEARS_IN_DECADE;
case CENTURIES:
return yearsUntil(paxEnd) / YEARS_IN_CENTURY;
case MILLENNIA:
return yearsUntil(paxEnd) / YEARS_IN_MILLENNIUM;
default:
break;
}
}
return super.until(end, unit);
}
/**
* Get the number of years from this date to the given day.
*
* @param end The end date.
* @return The number of years from this date to the given day.
*/
long yearsUntil(PaxDate end) {
// If either date is after the inserted leap month, and the other year isn't leap, simulate the effect of the inserted month.
long startYear = getProlepticYear() * 512L + getDayOfYear() + (this.getMonth() == MONTHS_IN_YEAR && !this.isLeapYear() && end.isLeapYear() ? DAYS_IN_WEEK : 0);
long endYear = end.getProlepticYear() * 512L + end.getDayOfYear() + (end.getMonth() == MONTHS_IN_YEAR && !end.isLeapYear() && this.isLeapYear() ? DAYS_IN_WEEK : 0);
return (endYear - startYear) / 512L;
}
@Override
public ChronoPeriod until(ChronoLocalDate endDate) {
PaxDate end = PaxDate.from(endDate);
int years = Math.toIntExact(yearsUntil(end));
// Get to the same "whole" year.
PaxDate sameYearEnd = end.plusYears(years);
int months = (int) monthsUntil(sameYearEnd);
int days = (int) daysUntil(sameYearEnd.plusMonths(months));
return getChronology().period(years, months, days);
}
@Override
public long toEpochDay() {
long days = ((long) getProlepticYear() - 1) * DAYS_IN_YEAR + getLeapYearsBefore(getProlepticYear()) * DAYS_IN_WEEK + getDayOfYear() - 1;
// Rebase to ISO 1970.
return days - PAX_0001_TO_ISO_1970;
}
}
|
package org.voovan.tools.reflect;
import javafx.print.Collation;
import org.voovan.tools.TDateTime;
import org.voovan.tools.TObject;
import org.voovan.tools.TString;
import org.voovan.tools.json.JSON;
import org.voovan.tools.json.annotation.NotJSON;
import org.voovan.tools.reflect.annotation.NotSerialization;
import sun.jvm.hotspot.gc_interface.CollectedHeap;
import java.lang.reflect.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map.Entry;
public class TReflect {
/**
* Field
*
* @param clazz
* @return Field
*/
public static Field[] getFields(Class<?> clazz) {
List<Field> fields = new ArrayList<Field>();
for( ; clazz != Object.class ; clazz = clazz.getSuperclass()) {
Field[] tmpFields = clazz.getDeclaredFields();
fields.addAll(Arrays.asList(tmpFields));
}
return fields.toArray(new Field[]{});
}
/**
* Field
*
* @param clazz
* @param fieldName field
* @return field
* @throws NoSuchFieldException Field
* @throws SecurityException
*/
public static Field findField(Class<?> clazz, String fieldName)
throws ReflectiveOperationException {
try {
return clazz.getDeclaredField(fieldName);
}catch(NoSuchFieldException ex){
Class superClazz = clazz.getSuperclass();
if( superClazz != Object.class ) {
return findField(clazz.getSuperclass(), fieldName);
}else{
return null;
}
}
}
/**
* Field
* ,
* @param clazz
* @param fieldName Field
* @return Field
* @throws ReflectiveOperationException
*/
public static Field findFieldIgnoreCase(Class<?> clazz, String fieldName)
throws ReflectiveOperationException{
for(Field field : getFields(clazz)){
if(field.getName().equalsIgnoreCase(fieldName)){
return field;
}
}
return null;
}
/**
* Field
* @param field field
* @return
* @throws ClassNotFoundException
*/
public static Class[] getFieldGenericType(Field field) throws ClassNotFoundException {
Class[] result = null;
Type fieldType = field.getGenericType();
if(fieldType instanceof ParameterizedType){
ParameterizedType parameterizedFieldType = (ParameterizedType)fieldType;
Type[] actualType = parameterizedFieldType.getActualTypeArguments();
result = new Class[actualType.length];
for(int i=0;i<actualType.length;i++){
result[i] = Class.forName(actualType[i].getTypeName());
}
return result;
}
return null;
}
/**
* Field
* @param <T>
* @param obj
* @param fieldName Field
* @return Field
* @throws ReflectiveOperationException
*/
@SuppressWarnings("unchecked")
static public <T> T getFieldValue(Object obj, String fieldName)
throws ReflectiveOperationException {
Field field = findField(obj.getClass(), fieldName);
field.setAccessible(true);
return (T) field.get(obj);
}
/**
* Field
* : private
*
* @param obj
* @param fieldName field
* @param fieldValue field
* @throws ReflectiveOperationException
*/
public static void setFieldValue(Object obj, String fieldName,
Object fieldValue) throws ReflectiveOperationException {
Field field = findField(obj.getClass(), fieldName);
field.setAccessible(true);
field.set(obj, fieldValue);
}
/**
* fieldMap (static)
*
* @param obj
* @return field - Map
* @throws ReflectiveOperationException
*/
public static Map<Field, Object> getFieldValues(Object obj)
throws ReflectiveOperationException {
HashMap<Field, Object> result = new HashMap<Field, Object>();
Field[] fields = getFields(obj.getClass());
for (Field field : fields) {
if (!Modifier.isStatic(field.getModifiers()) &&
field.getAnnotation(NotJSON.class)==null &&
field.getAnnotation(NotSerialization.class)==null) {
Object value = getFieldValue(obj, field.getName());
result.put(field, value);
}
}
return result;
}
/**
*
* @param clazz
* @param name
* @param paramTypes
* @return
* @throws ReflectiveOperationException
*/
public static Method findMethod(Class<?> clazz, String name,
Class<?>... paramTypes) throws ReflectiveOperationException {
return clazz.getDeclaredMethod(name, paramTypes);
}
/**
* ()
* @param clazz
* @param name
* @param paramCount
* @return
* @throws ReflectiveOperationException
*/
public static Method[] findMethod(Class<?> clazz, String name,
int paramCount) throws ReflectiveOperationException {
ArrayList<Method> result = new ArrayList<Method>();
Method[] methods = getMethods(clazz,name);
for(Method method : methods){
if(method.getParameters().length == paramCount){
result.add(method);
}
}
return result.toArray(new Method[]{});
}
/**
*
* @param clazz
* @return Method
*/
public static Method[] getMethods(Class<?> clazz) {
List<Method> methods = new ArrayList<Method>();
for( ; clazz != Object.class ; clazz = clazz.getSuperclass()) {
Method[] tmpMethods = clazz.getDeclaredMethods();
methods.addAll(Arrays.asList(tmpMethods));
}
return methods.toArray(new Method[]{});
}
/**
*
*
* @param clazz
* @param name
* @return Method
*/
public static Method[] getMethods(Class<?> clazz,String name) {
ArrayList<Method> methods = new ArrayList<Method>();
Method[] allMethod = getMethods(clazz);
for(Method method : allMethod){
if(method.getName().equals(name) )
methods.add(method);
}
return methods.toArray(new Method[0]);
}
/**
*
* @param method method
* @param parameterIndex (0)[0,], (-1)
* @return
* @throws ClassNotFoundException
*/
public static Class[] getMethodParameterGenericType(Method method,int parameterIndex) throws ClassNotFoundException {
Class[] result = null;
Type parameterType;
if(parameterIndex == -1){
parameterType = method.getGenericReturnType();
}else{
parameterType = method.getGenericParameterTypes()[parameterIndex];
}
if(parameterType instanceof ParameterizedType){
ParameterizedType parameterizedFieldType = (ParameterizedType)parameterType;
Type[] actualType = parameterizedFieldType.getActualTypeArguments();
result = new Class[actualType.length];
for(int i=0;i<actualType.length;i++){
result[i] = Class.forName(actualType[i].getTypeName());
}
return result;
}
return null;
}
/**
*
* Method
* @param obj
* @param method
* @param parameters
* @return
* @throws ReflectiveOperationException
*/
public static Object invokeMethod(Object obj, Method method, Object... parameters)
throws ReflectiveOperationException {
return method.invoke(obj, parameters);
}
/**
*
* ,
*
* @param obj , Class
* @param name
* @param parameters
* @return
* @throws ReflectiveOperationException
*/
public static Object invokeMethod(Object obj, String name, Object... parameters)
throws ReflectiveOperationException {
Class<?>[] parameterTypes = getArrayClasses(parameters);
Method method = null;
Class objClass = (obj instanceof Class) ? (Class)obj : obj.getClass();
try {
method = findMethod(objClass, name, parameterTypes);
method.setAccessible(true);
return method.invoke(obj, parameters);
}catch(Exception e){
Method[] methods = findMethod(objClass,name,parameterTypes.length);
for(Method similarMethod : methods){
Parameter[] methodParams = similarMethod.getParameters();
if(methodParams.length == parameters.length){
Object[] convertedParams = new Object[parameters.length];
for(int i=0;i<methodParams.length;i++){
Parameter parameter = methodParams[i];
String value = "";
Class parameterClass = parameters[i].getClass();
// JSON,
if(parameters[i] instanceof Collection ||
parameters[i] instanceof Map ||
parameterClass.isArray() ||
!parameterClass.getCanonicalName().startsWith("java.lang")){
value = JSON.toJSON(parameters[i]);
}else{
value = parameters[i].toString();
}
convertedParams[i] = TString.toObject(value, parameter.getType());
}
method = similarMethod;
try{
method.setAccessible(true);
return method.invoke(obj, convertedParams);
}catch(Exception ex){
continue;
}
}
}
throw e;
}
}
/**
*
* parameters,
* @param <T>
* @param clazz
* @param parameters
* @return
* @throws ReflectiveOperationException
*/
public static <T> T newInstance(Class<T> clazz, Object ...parameters)
throws ReflectiveOperationException {
Class<?>[] parameterTypes = getArrayClasses(parameters);
Constructor<T> constructor = null;
try {
if (parameters.length == 0) {
constructor = clazz.getConstructor();
} else {
constructor = clazz.getConstructor(parameterTypes);
}
return constructor.newInstance(parameters);
}catch(Exception e){
Constructor[] constructors = clazz.getConstructors();
for(Constructor similarConstructor : constructors){
Parameter[] methodParams = similarConstructor.getParameters();
if(methodParams.length == parameters.length){
Object[] convertedParams = new Object[parameters.length];
for(int i=0;i<methodParams.length;i++){
Parameter parameter = methodParams[i];
String value = "";
Class parameterClass = parameters[i].getClass();
// JSON,
if(parameters[i] instanceof Collection ||
parameters[i] instanceof Map ||
parameterClass.isArray() ||
!parameterClass.getCanonicalName().startsWith("java.lang")){
value = JSON.toJSON(parameters[i]);
}else{
value = parameters[i].toString();
}
convertedParams[i] = TString.toObject(value, parameter.getType());
}
constructor = similarConstructor;
try{
return constructor.newInstance(convertedParams);
}catch(Exception ex){
continue;
}
}
}
throw e;
}
}
/**
*
* @param <T>
* @param className
* @param parameters
* @return
* @throws ReflectiveOperationException
*/
public static <T> T newInstance(String className, Object ...parameters) throws ReflectiveOperationException {
@SuppressWarnings("unchecked")
Class<T> clazz = (Class<T>) Class.forName(className);
return newInstance(clazz,parameters);
}
/**
* ,
* @param objs
* @return
*/
public static Class<?>[] getArrayClasses(Object[] objs){
Class<?>[] parameterTypes= new Class<?>[objs.length];
for(int i=0;i<objs.length;i++){
parameterTypes[i] = objs[i].getClass();
}
return parameterTypes;
}
/**
* Map
*
* @param clazz
* @param mapArg Map
* @param ignoreCase
* @return
* @throws ReflectiveOperationException
* @throws ParseException
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static Object getObjectFromMap(Class<?> clazz,
Map<String, ?> mapArg,boolean ignoreCase) throws ReflectiveOperationException, ParseException {
Object obj = null;
if(mapArg==null){
return obj;
}
if(mapArg.isEmpty()){
return TReflect.newInstance(clazz,new Object[]{});
}
Object singleValue = mapArg.values().iterator().next();
// java
if (clazz.isPrimitive() || clazz == Object.class){
obj = singleValue;
}
//java
else if(isExtendsByClass(clazz,Date.class)){
// Map.Values
String value = singleValue==null?null:singleValue.toString();
SimpleDateFormat dateFormat = new SimpleDateFormat(TDateTime.STANDER_DATETIME_TEMPLATE);
obj = singleValue!=null?dateFormat.parse(value.toString()):null;
}
//Map
else if(isImpByInterface(clazz,Map.class)){
if(Modifier.isAbstract(clazz.getModifiers()) && Modifier.isInterface(clazz.getModifiers())){
clazz = HashMap.class;
}
Map mapObject = TObject.cast(newInstance(clazz));
mapObject.putAll(mapArg);
obj = mapObject;
}
//Collection
else if(isImpByInterface(clazz,Collection.class)){
if(Modifier.isAbstract(clazz.getModifiers()) || Modifier.isInterface(clazz.getModifiers())){
clazz = ArrayList.class;
}
Collection listObject = TObject.cast(newInstance(clazz));
if(singleValue!=null){
listObject.addAll((Collection) TObject.cast(singleValue));
}
obj = listObject;
}
//Array
else if(clazz.isArray()){
Class arrayClass = clazz.getComponentType();
Object tempArrayObj = Array.newInstance(arrayClass, 0);
return ((Collection)singleValue).toArray((Object[])tempArrayObj);
}
//java
else if (clazz.getName().startsWith("java.lang")) {
// Map.Values
String value = singleValue==null?null:singleValue.toString();
obj = singleValue==null?null:newInstance(clazz, value);
}
else {
obj = newInstance(clazz);
for(Entry<String,?> argEntry : mapArg.entrySet()){
String key = argEntry.getKey();
Object value = argEntry.getValue();
Field field = null;
if(ignoreCase) {
field = findFieldIgnoreCase(clazz, key);
}else{
field = findField(clazz, key);
}
if(field!=null) {
String fieldName = field.getName();
Class<?> fieldType = field.getType();
try {
// Map ,,
if(isImpByInterface(fieldType,Map.class) && value instanceof Map){
Class[] mapGenericTypes = getFieldGenericType(field);
if(mapGenericTypes!=null) {
HashMap result = new HashMap();
Map mapValue = (Map) value;
Iterator iterator = mapValue.entrySet().iterator();
while(iterator.hasNext() ) {
Entry entry = (Entry) iterator.next();
Map keyMap = null;
Map valueMap = null;
if(entry.getKey() instanceof Map){
keyMap = (Map)entry.getKey();
}else{
keyMap = TObject.newMap("value",entry.getKey());
}
if(entry.getValue() instanceof Map){
valueMap = (Map)entry.getValue();
}else{
valueMap = TObject.newMap("value",entry.getValue());
}
Object keyObj = getObjectFromMap(mapGenericTypes[0], keyMap, ignoreCase);
Object valueObj = getObjectFromMap(mapGenericTypes[1], valueMap, ignoreCase);
result.put(keyObj, valueObj);
}
mapValue.clear();
mapValue.putAll(result);
}
}
// Collection ,,
else if(isImpByInterface(fieldType,Collection.class) && value instanceof Collation){
Class[] listGenericTypes = getFieldGenericType(field);
if(listGenericTypes!=null) {
ArrayList result = new ArrayList();
List listValue = (List)value;
for(Object listItem : listValue){
Map valueMap = null;
if(listValue instanceof Map){
valueMap = (Map)listValue;
}else{
valueMap = TObject.newMap("value",listValue);
}
Object item = getObjectFromMap(listGenericTypes[0],valueMap,ignoreCase);
result.add(item);
}
listValue.clear();
listValue.addAll(result);
}
}else if(value instanceof Map){
value = getObjectFromMap(fieldType,(Map<String, ?>)value, ignoreCase);
} else {
value = getObjectFromMap(fieldType, TObject.newMap("value", value), ignoreCase);
}
setFieldValue(obj, fieldName, value);
}catch(Exception e){
throw new ReflectiveOperationException("Fill object " + obj.getClass().getCanonicalName() +
"#"+fieldName+" failed",e);
}
}
}
}
return obj;
}
/**
* Map
* key
* value
* @param obj
* @return Map
* @throws ReflectiveOperationException
*/
public static Map<String, Object> getMapfromObject(Object obj) throws ReflectiveOperationException{
Map<String, Object> mapResult = new HashMap<String, Object>();
Map<Field, Object> fieldValues = TReflect.getFieldValues(obj);
// java
if(obj.getClass().getName().startsWith("java.lang")
|| obj.getClass().isPrimitive()){
mapResult.put("value", obj);
}
// Collection
else if(obj instanceof Collection){
Collection collection = (Collection) newInstance(obj.getClass());
for(Object collectionItem : (Collection)obj) {
collection.add(getMapfromObject(collectionItem));
}
mapResult.put("value", collection);
}
// Map
else if(obj instanceof Map){
Map mapObject = (Map)obj;
Map map = (Map)newInstance(obj.getClass());
for(Object key : mapObject.keySet()) {
map.put(getMapfromObject(key),getMapfromObject(mapObject.get(key)));
}
mapResult.put("value", map);
}
else{
for(Entry<Field,Object> entry : fieldValues.entrySet()){
String key = entry.getKey().getName();
Object value = entry.getValue();
if(value == null){
mapResult.put(key, value);
}else if(!key.contains("$")){
String valueClass = entry.getValue().getClass().getName();
if(valueClass.startsWith("java")){
mapResult.put(key, value);
}else {
Map resultMap = getMapfromObject(value);
if(resultMap.size()==1 && resultMap.containsKey("value")){
mapResult.put(key, resultMap.values().iterator().next());
}else{
mapResult.put(key,resultMap);
}
}
}
}
}
return mapResult;
}
/**
*
*
* @param type
* @param interfaceClass
* @return
*/
public static boolean isImpByInterface(Class<?> type,Class<?> interfaceClass){
if(type==interfaceClass){
return true;
}
Class<?>[] interfaces= type.getInterfaces();
for (Class<?> interfaceItem : interfaces) {
if (interfaceItem.equals(interfaceClass)) {
return true;
}
else{
return isImpByInterface(interfaceItem,interfaceClass);
}
}
return false;
}
/**
*
*
* @param type
* @param extendsClass
* @return
*/
public static boolean isExtendsByClass(Class<?> type,Class<?> extendsClass){
if(extendsClass == type){
return true;
}
Class<?> superClass = type;
do{
if(superClass.equals(extendsClass)){
return true;
}
superClass = superClass.getSuperclass();
}while(superClass!=null && !superClass.equals(extendsClass) && !superClass.equals(Object.class));
return false;
}
/**
*
* @param type Class
* @return
*/
public static Class[] getAllExtendAndInterfaceClass(Class<?> type){
if(type == null){
return null;
}
ArrayList<Class> classes = new ArrayList<Class>();
Class<?> superClass = type;
do{
superClass = superClass.getSuperclass();
classes.addAll(Arrays.asList(superClass.getInterfaces()));
classes.add(superClass);
}while(!Object.class.equals(superClass));
return classes.toArray(new Class[]{});
}
/**
* json
* @param clazz Class
* @return json
*/
public static String getClazzJSONModel(Class clazz){
StringBuilder jsonStrBuilder = new StringBuilder();
if(clazz.getName().startsWith("java") || clazz.isPrimitive()){
jsonStrBuilder.append(clazz.getName());
} else if(clazz.getName().startsWith("[L")){
String clazzName = clazz.getName();
clazzName = clazzName.substring(clazzName.lastIndexOf(".")+1,clazzName.length()-2)+"[]";
jsonStrBuilder.append(clazzName);
} else {
jsonStrBuilder.append("{");
for (Field field : TReflect.getFields(clazz)) {
jsonStrBuilder.append("\"");
jsonStrBuilder.append(field.getName());
jsonStrBuilder.append("\":");
String filedValueModel = getClazzJSONModel(field.getType());
if(filedValueModel.startsWith("{") && filedValueModel.endsWith("}")) {
jsonStrBuilder.append(filedValueModel);
jsonStrBuilder.append(",");
} else if(filedValueModel.startsWith("[") && filedValueModel.endsWith("]")) {
jsonStrBuilder.append(filedValueModel);
jsonStrBuilder.append(",");
} else {
jsonStrBuilder.append("\"");
jsonStrBuilder.append(filedValueModel);
jsonStrBuilder.append("\",");
}
}
jsonStrBuilder.deleteCharAt(jsonStrBuilder.length()-1);
jsonStrBuilder.append("}");
}
return jsonStrBuilder.toString();
}
}
|
package sc.iview.commands.edit;
import static org.scijava.widget.ChoiceWidget.LIST_BOX_STYLE;
import static sc.iview.commands.MenuWeights.EDIT;
import static sc.iview.commands.MenuWeights.EDIT_PROPERTIES;
import com.jogamp.opengl.math.Quaternion;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import graphics.scenery.*;
import graphics.scenery.volumes.Volume;
import graphics.scenery.volumes.bdv.BDVVolume;
import org.scijava.command.Command;
import org.scijava.command.InteractiveCommand;
import org.scijava.module.MutableModuleItem;
import org.scijava.plugin.Menu;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
import org.scijava.ui.UIService;
import org.scijava.util.ColorRGB;
import org.scijava.widget.NumberWidget;
import sc.iview.SciView;
import cleargl.GLVector;
/**
* A command for interactively editing a node's properties.
* <ul>
* <li>TODO: If the list of sceneNode changes while this dialog is open, it may
* not be notified and thus, may cause strange behaviours. Furthermore,
* refreshing the list of choises does not work. :(</li>
* <li>Todo: Change the order of the property items. Scene node must be on top,
* as the user selects here which object to manipulate.</li>
* <li>Todo: As soon as object selection in Scenery itself works, the node
* pulldown may be removed entirely.</li>
* </ul>
*
* @author Robert Haase, Scientific Computing Facility, MPI-CBG Dresden
* @author Curtis Rueden
* @author Kyle Harrington
* @author Ulrik Guenther
*/
@Plugin(type = Command.class, initializer = "initValues", menuRoot = "SciView",
menu = { @Menu(label = "Edit", weight = EDIT),
@Menu(label = "Properties...", weight = EDIT_PROPERTIES) },
visible = false)
public class Properties extends InteractiveCommand {
private static final String PI_NEG = "-3.142";
private static final String PI_POS = "3.142";
@Parameter
private UIService uiSrv;
@Parameter
private SciView sciView;
@Parameter(required = false, style = LIST_BOX_STYLE, callback = "refreshSceneNodeInDialog")
private String sceneNode;
@Parameter(callback = "updateNodeProperties")
private boolean visible;
@Parameter(required = false, callback = "updateNodeProperties")
private ColorRGB colour;
@Parameter(label = "Name", callback = "updateNodeProperties")
private String name;
@Parameter(label = "Timepoint", callback = "updateNodeProperties")
private int timepoint = 0;
@Parameter(label = "Intensity", style = NumberWidget.SPINNER_STYLE,
stepSize = "0.1", callback = "updateNodeProperties")
private float intensity = 0;
@Parameter(label = "Position X", style = NumberWidget.SPINNER_STYLE,
stepSize = "0.1", callback = "updateNodeProperties")
private float positionX = 0;
@Parameter(label = "Position Y", style = NumberWidget.SPINNER_STYLE,
stepSize = "0.1", callback = "updateNodeProperties")
private float positionY = 0;
@Parameter(label = "Position Z", style = NumberWidget.SPINNER_STYLE,
stepSize = "0.1", callback = "updateNodeProperties")
private float positionZ = 0;
@Parameter(label = "Scale X", style = NumberWidget.SPINNER_STYLE,
stepSize = "0.1", callback = "updateNodeProperties")
private float scaleX = 1;
@Parameter(label = "Scale Y", style = NumberWidget.SPINNER_STYLE,
stepSize = "0.1", callback = "updateNodeProperties")
private float scaleY = 1;
@Parameter(label = "Scale Z", style = NumberWidget.SPINNER_STYLE,
stepSize = "0.1", callback = "updateNodeProperties")
private float scaleZ = 1;
@Parameter(label = "Global Renderscale", style = NumberWidget.SPINNER_STYLE,
stepSize = "0.1", callback = "updateNodeProperties")
private float renderscale = 1;
@Parameter(label = "Rotation Phi", style = NumberWidget.SPINNER_STYLE,
min = PI_NEG, max = PI_POS, stepSize = "0.01", callback = "updateNodeProperties")
private float rotationPhi;
@Parameter(label = "Rotation Theta", style = NumberWidget.SPINNER_STYLE,
min = PI_NEG, max = PI_POS, stepSize = "0.01", callback = "updateNodeProperties")
private float rotationTheta;
@Parameter(label = "Rotation Psi", style = NumberWidget.SPINNER_STYLE,
min = PI_NEG, max = PI_POS, stepSize = "0.01", callback = "updateNodeProperties")
private float rotationPsi;
/* Volume properties */
@Parameter(label = "Rendering Mode", style = LIST_BOX_STYLE, callback = "updateNodeProperties")
private String renderingMode;
@Parameter(label = "AO steps", style = NumberWidget.SPINNER_STYLE, callback = "updateNodeProperties")
private int occlusionSteps;
/* Bounding Grid properties */
@Parameter(label = "Grid Color", callback = "updateNodeProperties")
private ColorRGB gridColor;
@Parameter(label = "Ticks only", callback = "updateNodeProperties")
private boolean ticksOnly;
/* TextBoard properties */
@Parameter(label = "Text", callback = "updateNodeProperties")
private String text;
@Parameter(label = "Text Color", callback = "updateNodeProperties")
private ColorRGB fontColor;
@Parameter(label = "Background Color", callback = "updateNodeProperties")
private ColorRGB backgroundColor;
@Parameter(label = "Transparent Background", callback = "updateNodeProperties")
private boolean transparentBackground;
private List renderingModeChoices = Arrays.asList("Local Maximum Projection", "Maximum Projection", "Alpha Blending");
boolean fieldsUpdating = true;
ArrayList<String> sceneNodeChoices = new ArrayList<>();
private Node currentSceneNode;
/**
* Nothing happens here, as cancelling the dialog is not possible.
*/
@Override
public void cancel() {
}
/**
* Nothing is done here, as the refreshing of the objects properties works via
* callback methods.
*/
@Override
public void run() {
}
public void setSceneNode( final Node node ) {
currentSceneNode = node;
updateCommandFields();
}
protected void initValues() {
rebuildSceneObjectChoiceList();
refreshSceneNodeInDialog();
updateCommandFields();
}
private void rebuildSceneObjectChoiceList() {
fieldsUpdating = true;
sceneNodeChoices = new ArrayList<>();
int count = 0;
// here, we want all nodes of the scene, not excluding PointLights and Cameras
for( final Node node : sciView.getSceneNodes( n -> true ) ) {
sceneNodeChoices.add( makeIdentifier( node, count ) );
count++;
}
final MutableModuleItem<String> sceneNodeSelector = getInfo().getMutableInput( "sceneNode", String.class );
sceneNodeSelector.setChoices( sceneNodeChoices );
//todo: if currentSceneNode is set, put it here as current item
sceneNodeSelector.setValue( this, sceneNodeChoices.get( sceneNodeChoices.size() - 1 ) );
refreshSceneNodeInDialog();
fieldsUpdating = false;
}
/**
* find out, which node is currently selected in the dialog.
*/
private void refreshSceneNodeInDialog() {
final String identifier = sceneNode; //sceneNodeSelector.getValue(this);
currentSceneNode = null;
int count = 0;
for( final Node node : sciView.getSceneNodes( n -> true ) ) {
if( identifier.equals( makeIdentifier( node, count ) ) ) {
currentSceneNode = node;
//System.out.println("current node found");
break;
}
count++;
}
// update property fields according to scene node properties
updateCommandFields();
if( sceneNodeChoices.size() != sciView.getSceneNodes( n -> true ).length ) {
rebuildSceneObjectChoiceList();
}
}
/** Updates command fields to match current scene node properties. */
private void updateCommandFields() {
if( currentSceneNode == null ) return;
fieldsUpdating = true;
// update colour
if( currentSceneNode.getMaterial() != null && currentSceneNode.getMaterial().getDiffuse() != null ) {
GLVector colourVector;
if( currentSceneNode instanceof PointLight ) {
colourVector = ( ( PointLight ) currentSceneNode ).getEmissionColor();
} else {
colourVector = currentSceneNode.getMaterial().getDiffuse();
}
colour = new ColorRGB( ( int ) ( colourVector.get( 0 ) * 255 ),
( int ) ( colourVector.get( 1 ) * 255 ),
( int ) ( colourVector.get( 2 ) * 255 ) );
}
// update visibility
visible = currentSceneNode.getVisible();
// update position
final GLVector position = currentSceneNode.getPosition();
positionX = position.get( 0 );
positionY = position.get( 1 );
positionZ = position.get( 2 );
// update rotation
final float[] eulerAngles = new float[3];
currentSceneNode.getRotation().toEuler( eulerAngles );
rotationPhi = eulerAngles[0];
rotationTheta = eulerAngles[1];
rotationPsi = eulerAngles[2];
// update scale
final GLVector scale = currentSceneNode.getScale();
scaleX = scale.x();
scaleY = scale.y();
scaleZ = scale.z();
renderscale = currentSceneNode.getRenderScale();
name = currentSceneNode.getName();
if(currentSceneNode instanceof Volume) {
final MutableModuleItem<String> renderingModeInput = getInfo().getMutableInput( "renderingMode", String.class );
renderingModeInput.setChoices(renderingModeChoices);
renderingMode = (String)renderingModeChoices.get(((Volume)currentSceneNode).getRenderingMethod());
occlusionSteps = ((Volume)currentSceneNode).getOcclusionSteps();
} else {
getInfo().removeInput(getInfo().getMutableInput( "renderingMode", String.class ));
}
if(currentSceneNode instanceof PointLight) {
intensity = ((PointLight)currentSceneNode).getIntensity();
} else {
getInfo().removeInput(getInfo().getMutableInput( "intensity", Float.class ));
}
if(currentSceneNode instanceof BoundingGrid) {
gridColor = new ColorRGB((int)((BoundingGrid)currentSceneNode).getGridColor().x() * 255,
(int)((BoundingGrid)currentSceneNode).getGridColor().y() * 255,
(int)((BoundingGrid)currentSceneNode).getGridColor().z() * 255);
ticksOnly = ((BoundingGrid)currentSceneNode).getTicksOnly() > 0;
} else {
getInfo().removeInput(getInfo().getMutableInput( "gridColor", ColorRGB.class ));
getInfo().removeInput(getInfo().getMutableInput( "ticksOnly", Boolean.class ));
}
if(currentSceneNode instanceof TextBoard) {
text = ((TextBoard)currentSceneNode).getText();
fontColor = new ColorRGB((int)((TextBoard)currentSceneNode).getFontColor().x() * 255,
(int)((TextBoard)currentSceneNode).getFontColor().y() * 255,
(int)((TextBoard)currentSceneNode).getFontColor().z() * 255);
backgroundColor = new ColorRGB((int)((TextBoard)currentSceneNode).getBackgroundColor().x() * 255,
(int)((TextBoard)currentSceneNode).getBackgroundColor().y() * 255,
(int)((TextBoard)currentSceneNode).getBackgroundColor().z() * 255);
transparentBackground = ((TextBoard)currentSceneNode).getTransparent() > 0;
} else {
getInfo().removeInput(getInfo().getMutableInput( "fontColor", ColorRGB.class ));
getInfo().removeInput(getInfo().getMutableInput( "backgroundColor", ColorRGB.class ));
getInfo().removeInput(getInfo().getMutableInput( "transparentBackground", Boolean.class ));
getInfo().removeInput(getInfo().getMutableInput( "text", String.class ));
}
if(currentSceneNode instanceof BDVVolume) {
timepoint = ((BDVVolume)currentSceneNode).getCurrentTimepoint();
getInfo().getMutableInput("timepoint", Integer.class).setMinimumValue(0);
getInfo().getMutableInput("timepoint", Integer.class).setMaximumValue(((BDVVolume) currentSceneNode).getMaxTimepoint());
} else {
getInfo().removeInput(getInfo().getMutableInput("timepoint", Integer.class));
}
fieldsUpdating = false;
}
/** Updates current scene node properties to match command fields. */
protected void updateNodeProperties() {
if( currentSceneNode == null || fieldsUpdating ) return;
// update visibility
currentSceneNode.setVisible( visible );
// update rotation
currentSceneNode.setRotation( new Quaternion().setFromEuler( rotationPhi,
rotationTheta,
rotationPsi ) );
// update colour
final GLVector cVector = new GLVector( colour.getRed() / 255f,
colour.getGreen() / 255f,
colour.getBlue() / 255f );
if( currentSceneNode instanceof PointLight ) {
( ( PointLight ) currentSceneNode ).setEmissionColor( cVector );
} else {
final Material material = currentSceneNode.getMaterial();
if (material != null) material.setDiffuse( cVector );
}
// update position
final GLVector position = currentSceneNode.getPosition();
position.set( 0, ( positionX ) );
position.set( 1, ( positionY ) );
position.set( 2, ( positionZ ) );
currentSceneNode.setPosition( position );
// update scale
final GLVector scale = currentSceneNode.getScale();
scale.set( 0, scaleX );
scale.set( 1, scaleY );
scale.set( 2, scaleZ );
currentSceneNode.setScale(scale);
// update render scale
currentSceneNode.setRenderScale(renderscale);
currentSceneNode.setName(name);
if(currentSceneNode instanceof PointLight) {
((PointLight) currentSceneNode).setIntensity(intensity);
}
if(currentSceneNode instanceof Volume) {
final int mode = renderingModeChoices.indexOf(renderingMode);
if(mode != -1) {
((Volume) currentSceneNode).setRenderingMethod(mode);
}
((Volume)currentSceneNode).setOcclusionSteps(occlusionSteps);
}
if(currentSceneNode instanceof BoundingGrid) {
int ticks;
if(ticksOnly) {
ticks = 1;
} else {
ticks = 0;
}
((BoundingGrid)currentSceneNode).setTicksOnly(ticks);
((BoundingGrid)currentSceneNode).setGridColor(new GLVector(gridColor.getRed()/255.0f, gridColor.getGreen()/255.0f, gridColor.getBlue()/255.0f));
}
if(currentSceneNode instanceof TextBoard) {
int transparent;
if(transparentBackground) {
transparent = 1;
} else {
transparent = 0;
}
((TextBoard)currentSceneNode).setTransparent(transparent);
((TextBoard)currentSceneNode).setText(text);
((TextBoard)currentSceneNode).setFontColor(new GLVector(fontColor.getRed()/255.0f, fontColor.getGreen()/255.0f, fontColor.getBlue()/255.0f));
((TextBoard)currentSceneNode).setBackgroundColor(new GLVector(backgroundColor.getRed()/255.0f, backgroundColor.getGreen()/255.0f, backgroundColor.getBlue()/255.0f));
}
if(currentSceneNode instanceof BDVVolume) {
((BDVVolume) currentSceneNode).goToTimePoint(timepoint);
}
}
private String makeIdentifier( final Node node, final int count ) {
return "" + node.getName() + "[" + count + "]";
}
}
|
package seedu.address.commons.core;
import java.util.Objects;
import java.util.logging.Level;
/**
* Config values used by the app
*/
public class Config {
public static final String DEFAULT_CONFIG_FILE = "config.json";
// Config values customizable through config file
private String appTitle = "Task App";
private Level logLevel = Level.INFO;
private String userPrefsFilePath = "preferences.json";
private String taskManagerFilePath = "data/addressbook.xml";
private String taskManagerName = "MyTaskManager";
public String getAppTitle() {
return appTitle;
}
public void setAppTitle(String appTitle) {
this.appTitle = appTitle;
}
public Level getLogLevel() {
return logLevel;
}
public void setLogLevel(Level logLevel) {
this.logLevel = logLevel;
}
public String getUserPrefsFilePath() {
return userPrefsFilePath;
}
public void setUserPrefsFilePath(String userPrefsFilePath) {
this.userPrefsFilePath = userPrefsFilePath;
}
public String getTaskManagerFilePath() {
return taskManagerFilePath;
}
public void setTaskManagerFilePath(String taskManagerFilePath) {
this.taskManagerFilePath = taskManagerFilePath;
}
public String getTaskManagerName() {
return taskManagerName;
}
public void setTaskManagerName(String taskManagerName) {
this.taskManagerName = taskManagerName;
}
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if (!(other instanceof Config)) { //this handles null as well.
return false;
}
Config o = (Config) other;
return Objects.equals(appTitle, o.appTitle)
&& Objects.equals(logLevel, o.logLevel)
&& Objects.equals(userPrefsFilePath, o.userPrefsFilePath)
&& Objects.equals(taskManagerFilePath, o.taskManagerFilePath)
&& Objects.equals(taskManagerName, o.taskManagerName);
}
@Override
public int hashCode() {
return Objects.hash(appTitle, logLevel, userPrefsFilePath, taskManagerFilePath, taskManagerName);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("App title : " + appTitle);
sb.append("\nCurrent log level : " + logLevel);
sb.append("\nPreference file Location : " + userPrefsFilePath);
sb.append("\nLocal data file location : " + taskManagerFilePath);
sb.append("\nTaskManager name : " + taskManagerName);
return sb.toString();
}
}
|
package seedu.task.storage;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import javax.xml.bind.annotation.XmlElement;
import seedu.task.commons.exceptions.IllegalValueException;
import seedu.task.model.tag.Tag;
import seedu.task.model.tag.UniqueTagList;
import seedu.task.model.task.TaskDate;
import seedu.task.model.task.TaskName;
import seedu.task.model.task.TaskStatus;
import seedu.task.model.task.Task;
import seedu.task.model.task.ReadOnlyTask;
import seedu.task.model.task.TaskTime;
//@@author A0146757R
/**
* JAXB-friendly version of the Task.
*/
public class XmlAdaptedTask {
@XmlElement(required = true)
private String taskName;
@XmlElement(required = true)
private String taskDate;
@XmlElement(required = true)
private String taskStartTime;
@XmlElement(required = true)
private String taskEndTime;
@XmlElement(required = true)
private String taskDescription;
@XmlElement(required = true)
private String taskStatus;
@XmlElement
private List<XmlAdaptedTag> tagged = new ArrayList<>();
//@@author
/**
* Constructs an XmlAdaptedTask. This is the no-arg constructor that is
* required by JAXB.
*/
public XmlAdaptedTask() {
}
/**
* Converts a given Task into this class for JAXB use.
*
* @param source
* future changes to this will not affect the created
* XmlAdaptedTask
*/
public XmlAdaptedTask(ReadOnlyTask source) {
if (source.getTaskName() != null) {
taskName = source.getTaskName().fullTaskName;
}
if (source.getTaskDate() != null) {
taskDate = source.getTaskDate().value;
}
if (source.getTaskStartTime() != null) {
taskStartTime = source.getTaskStartTime().value;
}
if (source.getTaskEndTime() != null) {
taskEndTime = source.getTaskEndTime().value;
}
if (source.getTaskDescription() != null) {
taskDescription = source.getTaskDescription();
}
if (source.getTaskStatus() != null) {
taskStatus = source.getTaskStatus().toString();
}
tagged = new ArrayList<>();
for (Tag tag : source.getTags()) {
tagged.add(new XmlAdaptedTag(tag));
}
}
public Task toModelType() throws IllegalValueException {
final List<Tag> taskTags = new ArrayList<>();
for (XmlAdaptedTag tag : tagged) {
taskTags.add(tag.toModelType());
}
final TaskName taskName = new TaskName(this.taskName);
final Optional<TaskDate> taskDateOpt;
final Optional<TaskTime> taskStartTimeOpt;
final Optional<TaskTime> taskEndTimeOpt;
final Optional<String> taskDescriptionOpt;
final Optional<TaskStatus> taskStatusOpt;
if (this.taskDate == null) {
taskDateOpt = Optional.ofNullable(null);
} else {
taskDateOpt = Optional.ofNullable(new TaskDate(this.taskDate));
}
if (this.taskStartTime == null) {
taskStartTimeOpt = Optional.ofNullable(null);
} else {
taskStartTimeOpt = Optional.ofNullable(new TaskTime(this.taskStartTime));
}
if (this.taskEndTime == null) {
taskEndTimeOpt = Optional.ofNullable(null);
} else {
taskEndTimeOpt = Optional.ofNullable(new TaskTime(this.taskEndTime));
}
if (this.taskDescription == null) {
taskDescriptionOpt = Optional.ofNullable(null);
} else {
taskDescriptionOpt = Optional.ofNullable(this.taskDescription);
}
if (this.taskStatus == null) {
taskStatusOpt = Optional.ofNullable(null);
} else {
taskStatusOpt = Optional.ofNullable(new TaskStatus(this.taskStatus));
}
final UniqueTagList listOfTags = new UniqueTagList(taskTags);
return new Task(taskName, taskDateOpt, taskStartTimeOpt, taskEndTimeOpt, taskDescriptionOpt, taskStatusOpt, listOfTags);
}
}
|
package seedu.whatnow.model.task;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import seedu.whatnow.commons.exceptions.IllegalValueException;
//@@author A0139128A
public class TaskTime {
// public static final String TWENTY_FOUR_HOUR_FORMAT = "HHmm"; //E.g. 2359
public static final String TWELVE_HOUR_WITH_MINUTES_COLON_REGEX = "((\\d:\\d\\d)(am|pm))";
public static final String TWELVE_HOUR_WITH_MINUTES_COLON_FORMAT = "h:mma"; //E.g. 1:50 pm
public static final String TWELVE_HOUR_WITH_MINUTES_DOT_REGEX = "(\\d.\\d\\d)(am|pm)";
public static final String TWELVE_HOUR_WITH_MINUTES_DOT_FORMAT = "h.mma"; //E.g. 1.45 pm
public static final String TWELVE_HOUR_WITHOUT_MINUTES_REGEX = "([1]*[0-9]{1}+)(am|pm)";
// public static final String TWELVE_HOUR_WITHOUT_MINUTES_FORMAT = "ha"; //E.g. 2pm
// public static final String TWELVE_HOUR_WITHOUT_MINUTES_EXTEND_REGEX = "([1]{1}[0-2]{1})(am|pm)";
public static final String TWELVE_HOUR_WITHOUT_MINUTES_EXTEND_FORMAT = "hha";
public static final String DATE_NUM_SLASH_WITH_YEAR_FORMAT = "dd/MM/yyyy";
public static final String DATE_NUM_SLASH_WITH_YEAR_VALIDATION_REGEX = "([0-9]{2}+)/([0-9]{2}+)/([0-9]{4})";
public static final String DATE_NUM_SLASH_WITH_YEAR_SHORTENED_DAY_FORMAT = "d/MM/yyyy";
public static final String DATE_NUM_SLASH_WITH_YEAR_SHORTENED_DAY_VALIDATION_REGEX = "([1-9]{1}+)/([0-9]{2}+)/([0-9]{4})";
public static final String DATE_NUM_SLASH_WITH_YEAR_SHORTENED_MONTH_FORMAT = "dd/M/yyyy";
public static final String DATE_NUM_SLASH_WITH_YEAR_SHORTENED_MONTH_VALIDATION_REGEX = "([1-9]{2}+)/([1-9]{1}+)/([0-9]{4})";
public static final String DATE_NUM_SLASH_WITH_YEAR_SHORTENED_DAY_AND_MONTH_FORMAT = "d/M/yyyy";
public static final String DATE_NUM_SLASH_WITH_YEAR_SHORTENED_DAY_AND_MONTH_VALIDATION_REGEX = "([1-9]{1}+)/([1-9]{1}+)/([0-9]{4})";
public static final String DATE_NUM_SLASH_WITHOUT_YEAR_FORMAT = "dd/MM";
public static final String DATE_NUM_SLASH_WITHOUT_YEAR_VALIDATION_REGEX = "([1-9]{2}+)/([0-9]{2}+))";
public static final String DATE_NUM_SLASH_WITHOUT_YEAR_SHORTENED_DAY_FORMAT = "d/MM";
public static final String DATE_NUM_SLASH_WITHOUT_YEAR_SHORTENED_DAY_VALIDATION_REGEX = "([1-9]{1}+)/([0-9]{2}+)";
public static final String DATE_NUM_SLASH_WITHOUT_YEAR_SHORTENND_DAY_MONTH_FORMAT = "d/M";
public static final String DATE_NUM_SLASH_WITHOUT_YEAR_SHORTENED_DAY_MONTH_REGEX = "([1-9]{1}+)/([1-9]{1}+)";
public static final String DATE_AlPHA_WHITESPACE_WITH_YEAR_FORMAT = "dd MMMM yyyy ";
public static final String DATE_ALPHA_WHITESPACE_WITHOUT_YEAR_FORMAT = "dd MMMM";
public static final String DATE_NUM_REGEX_WITH_YEAR= "(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/((19|20)\\d\\d)";
public static ArrayList<String> ListOfDateRegex;
public static ArrayList<String> ListOfDateFormat;
public static ArrayList<String> ListOfTimeRegex;
public static ArrayList<String> ListOfTimeFormat;
public final String INVALID_TIME_MESSAGE = "Entered an invalid time format";
public final String INVALID_TIME_RANGE_MESSAGE = "Entered an invalid time range format";
public final String INVALID_DATE_MESSAGE = "Entered an invalid date format";
public final String INVALID_DATE_RANGE_MESSAGE = "Entered an invalid date range format";
private String time = null;
private String startTime = null;
private String endTime = null;
private String date = null;
private String startDate = null;
private String endDate = null;
public TaskTime(String time, String startTime, String endTime, String date, String startDate, String endDate) throws IllegalValueException{
ListOfDateRegex = new ArrayList<String>();
ListOfDateRegex.add(DATE_NUM_SLASH_WITH_YEAR_VALIDATION_REGEX); ListOfDateRegex.add(DATE_NUM_SLASH_WITH_YEAR_SHORTENED_DAY_VALIDATION_REGEX);
ListOfDateRegex.add(DATE_NUM_SLASH_WITH_YEAR_SHORTENED_MONTH_VALIDATION_REGEX); ListOfDateRegex.add(DATE_NUM_SLASH_WITH_YEAR_SHORTENED_DAY_AND_MONTH_VALIDATION_REGEX);
ListOfDateRegex.add(DATE_NUM_SLASH_WITHOUT_YEAR_VALIDATION_REGEX); ListOfDateRegex.add(DATE_NUM_SLASH_WITHOUT_YEAR_SHORTENED_DAY_VALIDATION_REGEX);
ListOfDateRegex.add(DATE_NUM_SLASH_WITHOUT_YEAR_SHORTENED_DAY_MONTH_REGEX);
ListOfDateFormat = new ArrayList<String>();
ListOfDateFormat.add(DATE_NUM_SLASH_WITH_YEAR_FORMAT); ListOfDateFormat.add(DATE_NUM_SLASH_WITH_YEAR_SHORTENED_DAY_FORMAT);
ListOfDateFormat.add(DATE_NUM_SLASH_WITH_YEAR_SHORTENED_MONTH_FORMAT); ListOfDateFormat.add(DATE_NUM_SLASH_WITH_YEAR_SHORTENED_DAY_AND_MONTH_FORMAT);
ListOfDateFormat.add(DATE_NUM_SLASH_WITHOUT_YEAR_FORMAT); ListOfDateFormat.add(DATE_NUM_SLASH_WITHOUT_YEAR_SHORTENED_DAY_FORMAT);
ListOfDateFormat.add(DATE_NUM_SLASH_WITHOUT_YEAR_SHORTENND_DAY_MONTH_FORMAT);
ListOfTimeRegex = new ArrayList<String>();
ListOfTimeRegex.add(TWELVE_HOUR_WITH_MINUTES_COLON_REGEX); ListOfTimeRegex.add(TWELVE_HOUR_WITH_MINUTES_DOT_REGEX);
ListOfTimeRegex.add(TWELVE_HOUR_WITHOUT_MINUTES_REGEX); //ListOfTimeRegex.add(TWELVE_HOUR_WITHOUT_MINUTES_EXTEND_REGEX);
ListOfTimeFormat = new ArrayList<String>();
ListOfTimeFormat.add(TWELVE_HOUR_WITH_MINUTES_COLON_FORMAT); ListOfTimeFormat.add(TWELVE_HOUR_WITH_MINUTES_DOT_FORMAT);
//ListOfTimeFormat.add(TWELVE_HOUR_WITHOUT_MINUTES_FORMAT);
ListOfTimeFormat.add(TWELVE_HOUR_WITHOUT_MINUTES_EXTEND_FORMAT);
if(!isValidDate(date)) {
throw new IllegalValueException(INVALID_DATE_MESSAGE);
}
if(!isValidDateRange(startDate, endDate)) {
throw new IllegalValueException(INVALID_DATE_RANGE_MESSAGE);
}
if(!isValidTime(time)) {
throw new IllegalValueException(INVALID_TIME_MESSAGE);
}
if(!isValidTimeRange(startTime, endTime)) {
throw new IllegalValueException(INVALID_TIME_RANGE_MESSAGE);
}
}
public String getFullString() {
return (date + " " + startDate + " " + endDate + " " + time + " " + startTime + " " + endTime);
}
/** returns time */
public String getTime() {
return this.time;
}
/** returns startTime */
public String getStartTime() {
return this.startTime;
}
/** returns endTime */
public String getEndTime() {
return this.endTime;
}
/** returns currentDate */
public String getDate() {
return this.date;
}
/** returns startDate */
public String getStartDate() {
return this.startDate;
}
/** returns endDate */
public String getEndDate() {
return this.endDate;
}
/**
* This function checks if the reqTime by the user is valid
* by finding the corresponding format and passes to the method
* isValidTimeSeq upon finding a match
* @param reqTime is the user inputTime
* @return true if the userInput time is valid, else false
*/
public boolean isValidTime(String reqTime) {
//i.e. not a deadline but a schedule
if(reqTime == null) {
return true;
}else {
for(int j=0 ; j < ListOfTimeRegex.size() ; j ++) {
if(reqTime.matches(ListOfTimeRegex.get(j))) {
return isValidTimeSeq(reqTime, ListOfTimeFormat.get(j));
}
}
return false;
}
}
/**
* Checks if given time given by the user is valid
* @param reqTime is the time input by the user
* @param format is the format that matches the reqTime's format
* @return true if the format is valid, else false
*/
public boolean isValidTimeSeq(String reqTime, String format) {
//First checks if it is indeed valid:
boolean currEarlierThanInput = false;
Date inputTime = null;
Date todayTime = null;
try {
String currentTime = new SimpleDateFormat(format).format(new Date());
DateFormat tf = new SimpleDateFormat(format);
tf.setLenient(false);
inputTime = tf.parse(reqTime);
todayTime = tf.parse(currentTime);
if(todayTime.before(inputTime)) {
currEarlierThanInput = true;
}
} catch(ParseException ex) {
ex.printStackTrace();
return false;
}
//Second check on whether this time is before the current Time
//This check if for e.g. input add "Sth" at 5 pm
//Attempts to put today's date, if current time is > 5pm, put it as tomorrow instead
if(startDate == null && endDate == null && date == null) {
//If currentTime is earlier than input time, puts today's date
if(currEarlierThanInput) {
DateFormat dateFormat = new SimpleDateFormat(DATE_NUM_SLASH_WITH_YEAR_FORMAT);
Calendar cal = Calendar.getInstance();
String taskDate = dateFormat.format(cal.getTime()); //Gets today's date
date = taskDate;
time = reqTime;
return true;
}
//CurrentTime is later than inputTime, puts tmr date instead
else {
DateFormat dateFormat = new SimpleDateFormat(DATE_NUM_SLASH_WITH_YEAR_FORMAT);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
date = dateFormat.format(cal.getTime());
time = reqTime;
return true;
}
}
else if(date != null) {
//checks for todayDate gets current time and compare with input time, returns false if invalid
if(date.toLowerCase().equals("today")) {
if(currEarlierThanInput){
DateFormat dateFormat = new SimpleDateFormat(DATE_NUM_SLASH_WITH_YEAR_FORMAT);
Calendar cal = Calendar.getInstance();
String taskDate = dateFormat.format(cal.getTime()); //Gets today's date
date = taskDate;
time = reqTime;
return true;
}
else
return false;
}
//Performs a normal check
else if(date.toLowerCase().equals("tomorrow")) {
DateFormat dateFormat = new SimpleDateFormat(DATE_NUM_SLASH_WITH_YEAR_FORMAT);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
date = dateFormat.format(cal.getTime());
time = reqTime;
return true;
}
}
//E.g. add "Sth" on 22/10/2016 to 23/10/2016 (date has been checked if its valid) at 8pm
//I.e. date is null, startDate is not null, endDate is not null
else {
time = reqTime;
return true;
}
return false;
}
/**
* This function checks if the givenTimeRange is valid by finding the corresponding
* regex and passes its corresponding format to a method isValidNumTime
* @param beforeTime is the startTime input by the user
* @param afterTime is the endTime input by the user
* @return true if the timeRangeIsValid, else false
*/
public boolean isValidTimeRange(String beforeTime, String afterTime) {
//First check for whether the given two times are valid
//Second check for whether the dates are present or not i.e.
//Third check for whether the beforeTime is indeed before the afterTime
if(beforeTime == null && afterTime == null && time != null) {
return true;
}
else {
for(int i =0; i < ListOfTimeRegex.size() && i < ListOfTimeFormat.size(); i ++) {
if(beforeTime.matches(ListOfTimeRegex.get(i)) && afterTime.matches(ListOfTimeRegex.get(i))) {
return isValidNumTime(beforeTime, afterTime, ListOfTimeFormat.get(i));
}
}
}
return false;
}
/**
* This function checks the validity of the time range and finds
* @param beforeTime is the user input starting time
* @param afterTime is the user input ending time
* @param format is the format that matches the format of the startTime
* @return true if valid timeFormat range, else return false
*/
public boolean isValidNumTime(String beforeTime, String afterTime, String format) {
//First check if two times are valid
boolean currEarlierThanInput = false;
boolean beforeEarlierThanAfter = false;
Date inputBeforeTime = null;
Date inputAfterTime = null;
Date todayTime = null;
try {
String currentTime = new SimpleDateFormat(format).format(new Date());
DateFormat tf = new SimpleDateFormat(format);
tf.setLenient(false);
inputBeforeTime = tf.parse(beforeTime);
inputAfterTime = tf.parse(afterTime);
todayTime = tf.parse(currentTime);
//The following checks if the user 2 inputTime is before the currentTime
if(inputBeforeTime.before(todayTime) && inputAfterTime.before(todayTime)) {
currEarlierThanInput = true;
}
//The following checks if the startTime is before endTime
if(inputBeforeTime.before(inputAfterTime)) {
beforeEarlierThanAfter = true;
}
} catch(ParseException ex) {
ex.printStackTrace();
return false;
}
//Checks if beforeTime is earlier than afterTime
if(beforeEarlierThanAfter) {
//This check if for e.g. input add "Sth" from 5pm to 7pm
//Attempts to put today's date, if current time is > 5pm, put it as tomorrow instead
if(startDate == null && endDate == null && date == null) {
//If currentTime is earlier than input time, puts today's date
if(!currEarlierThanInput) {
DateFormat dateFormat = new SimpleDateFormat(DATE_NUM_SLASH_WITH_YEAR_FORMAT);
Calendar cal = Calendar.getInstance();
String taskDate = dateFormat.format(cal.getTime()); //Gets today's date
date = taskDate;
startTime = beforeTime;
endTime = afterTime;
return true;
}
//CurrentTime is later than inputTime, puts tmr date instead
else {
DateFormat dateFormat = new SimpleDateFormat(DATE_NUM_SLASH_WITH_YEAR_FORMAT);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
date = dateFormat.format(cal.getTime());
startTime = beforeTime;
endTime = afterTime;
return true;
}
}
else if(date != null){
if(date.equals("today")) {
if(!currEarlierThanInput){
DateFormat dateFormat = new SimpleDateFormat(DATE_NUM_SLASH_WITH_YEAR_FORMAT);
Calendar cal = Calendar.getInstance();
String taskDate = dateFormat.format(cal.getTime()); //Gets today's date
date = taskDate;
startTime = beforeTime;
endTime = afterTime;
return true;
}
else
return false;
}
//Performs a normal check
else if(date.equals("tomorrow")) {
DateFormat dateFormat = new SimpleDateFormat(DATE_NUM_SLASH_WITH_YEAR_FORMAT);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
date = dateFormat.format(cal.getTime());
startTime = beforeTime;
endTime = afterTime;
return true;
}
//This date is Valid and is in the future
else {
startTime = beforeTime;
endTime = afterTime;
return true;
}
}
//Consists of a startDate and EndDate(That has been validated) along with a startTime and endTime
else {
startTime = beforeTime;
endTime = afterTime;
return true;
}
}
//Meaans time Range is invalid, however i have to check if a dateRange exists
else {
if(startDate != null && endDate != null) {
if(!startDate.equals(endDate)) {
startTime = beforeTime;
endTime = afterTime;
return true;
}
else {
return false;
}
}
return false;
}
}
/**
* Checks if a particular date is valid i.e. not before currentDate and is a valid sequence
* num is to be used to indicate what date im referring to i.e. 0 for variable date, 1 for variable startDate, 2 for variable endDate
* @return true if valid, else return false
*/
public boolean isValidDate(String reqDate) {
if(reqDate == null) {
date = null;
return true;
}
else if(reqDate.toLowerCase().equals("today")) {
date = "today";
return true;
}
else if(reqDate.toLowerCase().equals("tomorrow")) {
date = "tomorrow";
return true;
}
else {
for(int i = 0 ; i < ListOfDateFormat.size() && i < ListOfDateRegex.size(); i ++) {
if(reqDate.matches(ListOfDateRegex.get(i))) {
return isValidNumDate(reqDate, ListOfDateFormat.get(i));
}
}
return false;
}
}
/**
* This function checks whether the givenDate by the user is valid by placing
* it through different checks.
* @param reqDate is the userInput time
* @param format is the format that matches the user inputTime
* @return true if the time is valid, else false
*/
public boolean isValidNumDate(String reqDate, String format) {
//First check: whether if this date is of a valid format
Date tempDate = null;
try {
DateFormat df = new SimpleDateFormat(format);
df.setLenient(false);
tempDate = df.parse(reqDate);
} catch(ParseException ex) {
ex.printStackTrace();
return false;
}
//Second check : whether if this date is of the past
Calendar d = new GregorianCalendar();
d.set(Calendar.HOUR_OF_DAY, 23);
d.set(Calendar.MINUTE, 59);
d.set(Calendar.SECOND, 59);
tempDate = d.getTime();
Calendar c = new GregorianCalendar();
c.set(Calendar.HOUR_OF_DAY, 00);
c.set(Calendar.MINUTE, 00);
c.set(Calendar.SECOND, 00);
Date currDate = c.getTime();
if(currDate.compareTo(tempDate) > 0) {
return false;
}
return true;
//The following formats the date to become a dd/mm/yyyy format
/*
//E.g. 1/12/2017
if(format.equals(DATE_NUM_SLASH_WITH_YEAR_SHORTENED_DAY_FORMAT)) {
}
//E.g. 11/1/2017
else if(format.equals(DATE_NUM_SLASH_WITH_YEAR_SHORTENED_MONTH_FORMAT )) {
}
//E.g. 1/1/2017
else if(format.equals(DATE_NUM_SLASH_WITH_YEAR_SHORTENED_DAY_AND_MONTH_FORMAT)) {
}
//E.g. 12/12
else if(format.equals(DATE_NUM_SLASH_WITHOUT_YEAR_FORMAT)) {
Calendar now = Calendar.getInstance();
int yearInt = now.get(Calendar.YEAR);
String year = String.valueOf(yearInt);
reqDate.concat(year);
}
//E.g. 1/12
else if(format.equals(DATE_NUM_SLASH_WITHOUT_YEAR_SHORTENED_DAY_FORMAT)) {
}
//E.g. 1/1
else if(format.equals(DATE_NUM_SLASH_WITHOUT_YEAR_SHORTENND_DAY_MONTH_FORMAT)) {
}*/
}
/**
* Checks if a particular Date range is valid i.e. startDate is before endDate
* @return true if range is valid, false if range is invalid
*/
//Assume both beforeDate and afterDate is dd/mm/yyyy
public boolean isValidDateRange(String beforeDate, String afterDate) {
//Checks if the 2 dates are valid
//Checks if beforeDate is earlier than afterDate
if(beforeDate == null && afterDate == null) {
return true;
}
boolean validDateRange = false;
boolean sameDate = false;
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date beginDate = null;
Date finishDate = null;
try {
beginDate = sdf.parse(beforeDate);
finishDate = sdf.parse(afterDate);
if(beginDate.before(finishDate)) {
validDateRange = true;
}
if(beginDate.equals(finishDate)) {
sameDate = true;
}
} catch (ParseException e) {
return false;
}
if(!validDateRange && !sameDate) {
return false;
}
else {
startDate = beforeDate;
endDate = afterDate;
return true;
}
}
}
|
package storm.xlog;
import storm.kafka.*;
import backtype.storm.Config;
import backtype.storm.LocalCluster;
import backtype.storm.StormSubmitter;
import backtype.storm.generated.StormTopology;
import backtype.storm.spout.SchemeAsMultiScheme;
import backtype.storm.topology.BasicOutputCollector;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.TopologyBuilder;
import backtype.storm.topology.base.BaseBasicBolt;
import backtype.storm.topology.IRichBolt;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Tuple;
import backtype.storm.tuple.Values;
import backtype.storm.task.TopologyContext;
import backtype.storm.task.OutputCollector;
import backtype.storm.tuple.Tuple;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TimeZone;
import java.util.Locale;
import java.util.Date;
import java.util.Hashtable;
import java.util.HashMap;
import java.util.Map;
import java.util.Enumeration;
import java.text.ParseException;
import java.util.Vector;
import java.util.Properties;
import java.lang.Long.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import org.apache.commons.lang.StringUtils;
public class XlogKafkaSpoutTopology {
public static final Logger LOG = LoggerFactory.getLogger(XlogKafkaSpoutTopology.class);
public static class SplitSentence extends BaseBasicBolt {
private int thisTaskId = 0;
public void prepare(Map stormConf, TopologyContext context) {
thisTaskId = context.getThisTaskId();
}
public void execute(Tuple tuple, BasicOutputCollector collector) {
String line = tuple.getString(0);
String[] lineArr = StringUtils.split(line.substring(0, 20), " ");
//System.out.println(lineArr[0]);
collector.emit(new Values(lineArr[0], line));
}
public void cleanup() {
}
public void declareOutputFields(OutputFieldsDeclarer declarer) {
declarer.declare(new Fields("ip", "line"));
}
}
public static class XlogBolt extends BaseBasicBolt {
private long intervalTime = 60;
private long totalThreshold = 30;
private long scopeThreshold = 10;
private String topic = "";
private String mysqlUrl = "";
private String mysqlUser = "";
private String mysqlPassword = "";
private boolean isStatic = true;
private int start_datetime = 0;
private int start_mm = 0;
private int total = 0,statics = 0, dynamics = 0;
private int thisTaskId = 0;
Hashtable<String, Object> hashIp = new Hashtable<String, Object>(1000, 0.5F);
Hashtable<String, Object> hashIpUrl = new Hashtable<String, Object>(1000, 0.5F);
HashMap<String, Integer> ipWhitelist = new HashMap<String, Integer>();
public void prepare(Map stormConf, TopologyContext context) {
topic = (String) stormConf.get("xlog.kafka.topic.name");
totalThreshold = Long.parseLong((String) stormConf.get("insert.into.mysql.min.total"), 10);
scopeThreshold = Long.parseLong((String) stormConf.get("insert.into.mysql.max.scope"), 10);
intervalTime = Long.parseLong((String) stormConf.get("xlog.interval.time"), 10);
mysqlUrl = (String) stormConf.get("mysql.url");
mysqlUser = (String) stormConf.get("mysql.user");
mysqlPassword = (String) stormConf.get("mysql.password");
thisTaskId = context.getThisTaskId();
}
@Override
public void declareOutputFields(OutputFieldsDeclarer declarer) {
}
@Override
public void execute(Tuple tuple, BasicOutputCollector collector) {
String line = tuple.getString(1);
String regex = "([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3})\\s(.+)\\s\\-\\s\\[(.+)\\s\\+0800\\]\\s\"(.+)\\s(.+)\\s(.+)\"\\s(\\d+)\\s(\\d+)\\s\"(.+)\"\\s\"(.+)\"\\s\"(.+)\"\\s(\\d+\\.\\d+|\\d+|\\-)\\s(\\d+\\.\\d+|\\d+|\\-)";
String ip = "";
String host = "-";
String datetime = "";
String method = "";
String url = "";
String code = "";
String size = "";
int re_time = 0;
int mm = 0;
boolean inWhitelist = false;
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(line);
while (matcher.find()) {
ip = matcher.group(1);
host = matcher.group(2);
datetime = matcher.group(3);
method = matcher.group(4);
url = matcher.group(5);
code = matcher.group(7);
size = matcher.group(8);
total ++;
TimeZone.setDefault(TimeZone.getTimeZone("GMT+8:00"));
SimpleDateFormat sdf = new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss", Locale.US);
Date d;
try {
d = sdf.parse(datetime);
long l = d.getTime();
String str = String.valueOf(l);
re_time = Integer.parseInt(str.substring(0, 10));
} catch (ParseException e) {
e.printStackTrace();
}
String re_StrTime = null;
SimpleDateFormat sdf_1 = new SimpleDateFormat("yyyyMMddHHmm", Locale.CHINA);
SimpleDateFormat sdf_mm = new SimpleDateFormat("mm", Locale.CHINA);
long lcc_time = Long.valueOf(re_time);
re_StrTime = sdf_1.format(new Date(lcc_time * 1000L));
mm = Integer.parseInt(sdf_mm.format(new Date(lcc_time * 1000L)));
if ( start_datetime == 0) {
start_datetime = re_time;
start_mm = mm;
}
if (ip.equals('-')) {
continue;
}
inWhitelist = ipWhitelist.containsKey(ip);
if ( inWhitelist ) {
continue;
}
//hashIpUrl
boolean urlMapIsExist = hashIpUrl.containsKey(ip);
HashMap<String, Integer> mapUrl = null;
mapUrl = urlMapIsExist ? (HashMap<String, Integer>) hashIpUrl.get(ip) : new HashMap<String, Integer>();
Integer mapUrlSize = mapUrl.size();
if ( mapUrlSize >= scopeThreshold ) {
hashIpUrl.remove(ip);
ipWhitelist.put(ip, 1);
inWhitelist = true;
}
if (url.toLowerCase().matches(".+(\\.jpg|\\.png|\\.js|\\.gif|\\.css|\\.ico|\\.swf|\\.jpeg|\\.txt|\\.html|\\.htm){1}.*")) {
statics++;
isStatic = true;
} else {
dynamics++;
isStatic = false;
}
if ( !inWhitelist ) {
String newUrl = "";
if (isStatic) {
newUrl = url;
} else {
String[] urlArr = StringUtils.split(url,"/");
Integer count = urlArr.length;
if (count >= 3) {
newUrl = "/"+urlArr[0]+"/"+urlArr[1];
} else if (count <= 0) {
newUrl = "/";
} else {
//Integer indexof1 = url.indexOf('.');
Integer indexof2 = url.indexOf('?');
Integer indexof3 = url.indexOf('=');
if (indexof3 != -1 && indexof2 != -1) {
newUrl = url.substring(0, indexof3);
} else {
newUrl = urlArr[0];
}
}
}
mapUrl.put(newUrl, 1);
hashIpUrl.put(ip, mapUrl);
}
HashMap<String, Integer> map = null;
boolean ipMapIsExist = hashIp.containsKey(ip);
map = ipMapIsExist ? (HashMap<String, Integer>) hashIp.get(ip) : new HashMap<String, Integer>();
if (inWhitelist && ipMapIsExist) {
hashIp.remove(ip);
continue;
}
Integer codeFirst = Integer.parseInt(code.substring(0, 1));
String fieldName = "";
if ( ipMapIsExist ) {
map.put("total", map.get("total") + 1);
if ( isStatic ) {
map.put("statics", map.get("statics") + 1);
} else {
map.put("dynamics", map.get("dynamics") + 1);
}
if (method.equals("GET")) {
map.put("get", map.get("get") + 1);
} else if (method.equals("POST")) {
map.put("post", map.get("post") + 1);
} else if (method.equals("HEAD")) {
map.put("head", map.get("head") + 1);
} else {
map.put("other", map.get("other") + 1);
}
for(int c = 2; c<=5; c++){
fieldName = c + "xx";
if ( codeFirst == c ) {
map.put(fieldName, map.get(fieldName) + 1);
}
}
} else {
map.put("total", 1);
if ( isStatic ) {
map.put("statics", 1);
map.put("dynamics", 0);
} else {
map.put("statics", 0);
map.put("dynamics", 1);
}
map.put("get", 0);
map.put("post", 0);
map.put("head", 0);
map.put("other", 0);
if (method.equals("GET")) {
map.put("get", 1);
} else if (method.equals("POST")) {
map.put("post", 1);
} else if (method.equals("HEAD")) {
map.put("head", 1);
} else {
map.put("other", 1);
}
for(int c = 2; c<=5; c++){
fieldName = c + "xx";
if ( codeFirst == c ) {
map.put(fieldName, 1);
} else {
map.put(fieldName, 0);
}
}
}
if ( !inWhitelist && ipMapIsExist && mapUrlSize + 1 >= scopeThreshold) {
mapUrlSize = mapUrl.size();
if ( mapUrlSize >= scopeThreshold ) {
ipWhitelist.put(ip, 1);
hashIpUrl.remove(ip);
hashIp.remove(ip);
continue;
}
}
hashIp.put(ip, map);
}
if ( ( mm - start_mm > 0 && re_time - start_datetime > intervalTime ) || ( mm - start_mm < 0 && re_time - start_datetime > intervalTime ) ) {
System.out.println("TaskId: " +thisTaskId + " -> " + line);
System.out.println("TaskId: " +thisTaskId + " # topic -> " + topic + " totals -> "+ total +" # ip totals ->" + hashIp.size() + " # whitelist totals ->" + ipWhitelist.size());
String data = "";
ArrayList ipList = new ArrayList();
long totalIp = 0;
long valid = 0;
long scopeSize = 0;
for ( Iterator<String> it = hashIp.keySet().iterator(); it.hasNext(); ) {
String key = (String)it.next();
HashMap<String, Integer> value = (HashMap<String, Integer>) hashIp.get(key);
HashMap<String, Integer> hashUrl = (HashMap<String, Integer>) hashIpUrl.get(key);
totalIp = value.get("total");
scopeSize = hashUrl.size();
if ( totalIp > totalThreshold && scopeSize < scopeThreshold ) {
valid++;
ipList.add("'"+topic+"','"+ key +"','"+start_datetime+"','"+re_time+"','"+value.get("total")+"','"+value.get("statics")+"','"+value.get("dynamics")+"','"+value.get("2xx")+"','"+value.get("3xx")+"','"+value.get("4xx")+"','"+value.get("5xx")+"','"+value.get("get")+"','"+value.get("post")+"','"+value.get("head")+"','"+value.get("other")+"','"+scopeSize+"'");
}
value = null;
hashUrl = null;
}
data = StringUtils.join(ipList.toArray(), "), (");
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection(mysqlUrl, mysqlUser, mysqlPassword);
Statement stmt = conn.createStatement();//sql
if ( valid > 0) {
String sql = "INSERT INTO `ips` (`topic`,`ip` ,`time_start` ,`time_end` ,`total` ,`statics` ,`dynamics` ,`2xx` ,`3xx` ,`4xx` ,`5xx` ,`get` ,`post` ,`head` ,`other`, `scope`) VALUES (" + data + ");";
//System.out.println(sql);
stmt.execute(sql);
data = "";
sql = "";
}
conn.close();
} catch (Exception ex) {
System.out.println("Error : " + ex.toString());
}
total = 0;statics = 0;dynamics = 0;
hashIp = new Hashtable<String, Object>(1000, 0.5F);
hashIpUrl = new Hashtable<String, Object>(1000, 0.5F);
ipWhitelist = new HashMap<String, Integer>();
isStatic = true;
start_datetime = 0;
start_mm = 0;
}
}
}
private final BrokerHosts brokerHosts;
public XlogKafkaSpoutTopology(String kafkaZookeeper) {
brokerHosts = new ZkHosts(kafkaZookeeper);
}
public StormTopology buildTopology(String topic) {
SpoutConfig kafkaConfig = new SpoutConfig(brokerHosts, topic, "", "xlog_storm_"+topic);
kafkaConfig.scheme = new SchemeAsMultiScheme(new StringScheme());
TopologyBuilder builder = new TopologyBuilder();
builder.setSpout("KafkaSpout", new KafkaSpout(kafkaConfig)).setNumTasks(10);
builder.setBolt("SplitBolt", new SplitSentence()).setNumTasks(10).shuffleGrouping("KafkaSpout");
builder.setBolt("XlogBolt", new XlogBolt()).setNumTasks(10).fieldsGrouping("SplitBolt", new Fields("ip"));
return builder.createTopology();
}
public static void main(String[] args) throws Exception {
if ( args == null || args.length != 1 ) {
System.out.println("Usage:storm jar target/storm-xlog-***-jar-with-dependencies.jar storm.xlog.XlogKafkaSpoutTopology configure_file_path");
System.exit(0);
}
File file = new File(args[0]);
if( !file.exists() ) {
System.out.println("configure file " + args[0] + "do not exist!");
System.exit(0);
}
InputStream is = new FileInputStream(file);
Properties prop = new Properties();
prop.load(is);
Config config = new Config();
for (Object key : prop.keySet()) {
config.put((String) key, prop.get(key));
}
is.close();
String kafkaZk = (String) config.get("xlog.zookeeper.server");
String nimbusIp = (String) config.get("xlog.nimbus.host");
String topic = (String) config.get("xlog.kafka.topic.name");
String debug = (String) config.get("xlog.debug");
config.put(Config.TOPOLOGY_DEBUG, debug.toLowerCase().equals("true") ? true : false);
config.put(Config.TOPOLOGY_TRIDENT_BATCH_EMIT_INTERVAL_MILLIS, 50);
config.setNumWorkers(1);
config.setMaxTaskParallelism(10);
config.setMaxSpoutPending(10000);
config.put(Config.NIMBUS_HOST, nimbusIp);
config.put(Config.NIMBUS_THRIFT_PORT, 6627);
config.put(Config.STORM_ZOOKEEPER_PORT, 2181);
config.put(Config.STORM_ZOOKEEPER_SERVERS, Arrays.asList(kafkaZk));
XlogKafkaSpoutTopology XlogkafkaSpoutTopology = new XlogKafkaSpoutTopology(kafkaZk);
StormTopology stormTopology = XlogkafkaSpoutTopology.buildTopology(topic);
StormSubmitter.submitTopology(topic, config, stormTopology);
}
}
|
package tigase.server;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.logging.Logger;
import tigase.util.DNSResolver;
import static tigase.conf.Configurable.*;
/**
* Describe class MessageRouterConfig here.
*
*
* Created: Fri Jan 6 14:54:21 2006
*
* @author <a href="mailto:artur.hefczyc@tigase.org">Artur Hefczyc</a>
* @version $Rev$
*/
public class MessageRouterConfig {
private static final Logger log =
Logger.getLogger("tigase.server.MessageRouterConfig");
public static final String LOCAL_ADDRESSES_PROP_KEY = "hostnames";
public static String[] LOCAL_ADDRESSES_PROP_VALUE = {"localhost", "hostname"};
public static final String MSG_RECEIVERS_PROP_KEY =
"components/msg-receivers/";
public static final String MSG_RECEIVERS_NAMES_PROP_KEY =
MSG_RECEIVERS_PROP_KEY + "id-names";
public static final String DEF_SM_NAME = "sess-man";
public static final String DEF_C2S_NAME = "c2s";
public static final String DEF_S2S_NAME = "s2s";
public static final String DEF_EXT_COMP_NAME = "ext-comp";
public static final String DEF_SSEND_NAME = "ssend";
public static final String DEF_SRECV_NAME = "srecv";
public static final String DEF_BOSH_NAME = "bosh";
public static final String[] ALL_MSG_RECEIVERS_NAMES_PROP_VAL =
{ DEF_C2S_NAME, DEF_S2S_NAME, DEF_SM_NAME,
DEF_SSEND_NAME, DEF_SRECV_NAME, DEF_BOSH_NAME};
public static final String[] DEF_MSG_RECEIVERS_NAMES_PROP_VAL =
{ DEF_C2S_NAME, DEF_S2S_NAME, DEF_SM_NAME, DEF_BOSH_NAME };
public static final String[] SM_MSG_RECEIVERS_NAMES_PROP_VAL =
{ DEF_EXT_COMP_NAME, DEF_SM_NAME };
public static final String[] CS_MSG_RECEIVERS_NAMES_PROP_VAL =
{ DEF_C2S_NAME, DEF_S2S_NAME, DEF_EXT_COMP_NAME, DEF_BOSH_NAME };
public static final Map<String, String> MSG_RCV_CLASSES =
new LinkedHashMap<String, String>();
static {
MSG_RCV_CLASSES.put(DEF_C2S_NAME, C2S_COMP_CLASS_NAME);
MSG_RCV_CLASSES.put(DEF_S2S_NAME, S2S_COMP_CLASS_NAME);
MSG_RCV_CLASSES.put(DEF_EXT_COMP_NAME, EXT_COMP_CLASS_NAME);
MSG_RCV_CLASSES.put(DEF_SM_NAME, SM_COMP_CLASS_NAME);
MSG_RCV_CLASSES.put(DEF_SSEND_NAME, SSEND_COMP_CLASS_NAME);
MSG_RCV_CLASSES.put(DEF_SRECV_NAME, SRECV_COMP_CLASS_NAME);
MSG_RCV_CLASSES.put(DEF_BOSH_NAME, BOSH_COMP_CLASS_NAME);
}
public static final String REGISTRATOR_PROP_KEY = "components/registrators/";
public static final String REGISTRATOR_NAMES_PROP_KEY =
REGISTRATOR_PROP_KEY + "id-names";
public static final String[] REGISTRATOR_NAMES_PROP_VAL = { "stat-1" };
public static final String STAT_1_CLASS_PROP_KEY =
REGISTRATOR_PROP_KEY + "stat-1.class";
public static final String STAT_1_CLASS_PROP_VAL =
"tigase.stats.StatisticsCollector";
public static final String STAT_1_ACTIVE_PROP_KEY =
REGISTRATOR_PROP_KEY + "stat-1.active";
public static final boolean STAT_1_ACTIVE_PROP_VAL = true;
public static void getDefaults(Map<String, Object> defs,
Map<String, Object> params, String comp_name) {
String config_type = (String)params.get("config-type");
String[] rcv_names = DEF_MSG_RECEIVERS_NAMES_PROP_VAL;
Object par_names =
params.get(comp_name + "/" + MSG_RECEIVERS_NAMES_PROP_KEY);
if (par_names != null) {
rcv_names = (String[])par_names;
} else {
if (config_type.equals(GEN_CONFIG_ALL)) {
rcv_names = ALL_MSG_RECEIVERS_NAMES_PROP_VAL;
}
if (config_type.equals(GEN_CONFIG_SM)) {
rcv_names = SM_MSG_RECEIVERS_NAMES_PROP_VAL;
}
if (config_type.equals(GEN_CONFIG_CS)) {
rcv_names = CS_MSG_RECEIVERS_NAMES_PROP_VAL;
}
if (config_type.equals(GEN_CONFIG_COMP)) {
String c_name = (String)params.get(GEN_COMP_NAME);
String c_class = (String)params.get(GEN_COMP_CLASS);
rcv_names = new String[] {c_name};
defs.put(MSG_RECEIVERS_PROP_KEY + c_name + ".class", c_class);
defs.put(MSG_RECEIVERS_PROP_KEY + c_name + ".active", true);
}
}
Arrays.sort(rcv_names);
// Now init defaults for all external components:
for (String key: params.keySet()) {
if (key.startsWith(GEN_EXT_COMP)) {
String new_comp_name =
DEF_EXT_COMP_NAME + key.substring(GEN_EXT_COMP.length());
if (Arrays.binarySearch(rcv_names, new_comp_name) < 0) {
rcv_names = Arrays.copyOf(rcv_names, rcv_names.length+1);
rcv_names[rcv_names.length-1] = new_comp_name;
}
} // end of if (key.startsWith(GEN_EXT_COMP))
} // end of for ()
defs.put(MSG_RECEIVERS_NAMES_PROP_KEY, rcv_names);
for (String name: rcv_names) {
if (defs.get(MSG_RECEIVERS_PROP_KEY + name + ".class") == null) {
String def_class = MSG_RCV_CLASSES.get(name);
if (def_class == null) {
def_class = EXT_COMP_CLASS_NAME;
}
defs.put(MSG_RECEIVERS_PROP_KEY + name + ".class", def_class);
defs.put(MSG_RECEIVERS_PROP_KEY + name + ".active", true);
}
}
defs.put(REGISTRATOR_NAMES_PROP_KEY, REGISTRATOR_NAMES_PROP_VAL);
defs.put(STAT_1_CLASS_PROP_KEY, STAT_1_CLASS_PROP_VAL);
defs.put(STAT_1_ACTIVE_PROP_KEY, STAT_1_ACTIVE_PROP_VAL);
if (params.get(GEN_VIRT_HOSTS) != null) {
LOCAL_ADDRESSES_PROP_VALUE =
((String)params.get(GEN_VIRT_HOSTS)).split(",");
} else {
LOCAL_ADDRESSES_PROP_VALUE = DNSResolver.getDefHostNames();
}
defs.put(LOCAL_ADDRESSES_PROP_KEY, LOCAL_ADDRESSES_PROP_VALUE);
}
private Map<String, Object> props = null;
public MessageRouterConfig(Map<String, Object> props) {
this.props = props;
}
public String[] getRegistrNames() {
String[] names = (String[])props.get(REGISTRATOR_NAMES_PROP_KEY);
log.config(Arrays.toString(names));
ArrayList<String> al = new ArrayList<String>();
for (String name: names) {
if ((Boolean)props.get(REGISTRATOR_PROP_KEY + name + ".active")) {
al.add(name);
} // end of if ((Boolean)props.get())
} // end of for (String name: names)
return al.toArray(new String[al.size()]);
}
public String[] getMsgRcvNames() {
String[] names = (String[])props.get(MSG_RECEIVERS_NAMES_PROP_KEY);
log.config(Arrays.toString(names));
ArrayList<String> al = new ArrayList<String>();
for (String name: names) {
if (props.get(MSG_RECEIVERS_PROP_KEY + name + ".active") != null
&& (Boolean)props.get(MSG_RECEIVERS_PROP_KEY + name + ".active")) {
al.add(name);
}
} // end of for (String name: names)
return al.toArray(new String[al.size()]);
}
public ComponentRegistrator getRegistrInstance(String name) throws
ClassNotFoundException, InstantiationException, IllegalAccessException {
String cls_name = (String)props.get(REGISTRATOR_PROP_KEY + name + ".class");
// I changed location for the XMPPServiceCollector class
// to avoid problems with old configuration files let's detect it here
// and silently convert it to new package name:
if (cls_name.equals("tigase.server.XMPPServiceCollector")
|| cls_name.equals("tigase.disco.XMPPServiceCollector")) {
log.warning("This class is not used anymore. Correct your configuration please. Remove all references to class: XMPPServiceCollector.");
return null;
}
return (ComponentRegistrator)Class.forName(cls_name).newInstance();
}
public MessageReceiver getMsgRcvInstance(String name) throws
ClassNotFoundException, InstantiationException, IllegalAccessException {
String cls_name = (String)props.get(MSG_RECEIVERS_PROP_KEY + name + ".class");
return (MessageReceiver)Class.forName(cls_name).newInstance();
}
} // MessageRouterConfig
|
package transforms;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import ij.IJ;
import ij.ImagePlus;
import io.AffineImglib2IO;
import io.DfieldIoHelper;
import io.nii.NiftiIo;
import io.nii.Nifti_Writer;
import loci.formats.FormatException;
import mpicbg.models.AffineModel3D;
import mpicbg.models.IllDefinedDataPointsException;
import mpicbg.models.NotEnoughDataPointsException;
import mpicbg.models.Point;
import mpicbg.models.PointMatch;
import net.imglib2.Cursor;
import net.imglib2.Interval;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.RealPoint;
import net.imglib2.RealRandomAccess;
import net.imglib2.RealRandomAccessible;
import net.imglib2.img.Img;
import net.imglib2.img.display.imagej.ImageJFunctions;
import net.imglib2.img.imageplus.ImagePlusImg;
import net.imglib2.img.imageplus.ImagePlusImgFactory;
import net.imglib2.realtransform.AffineGet;
import net.imglib2.realtransform.AffineTransform3D;
import net.imglib2.realtransform.Scale3D;
import net.imglib2.realtransform.ants.ANTSDeformationField;
import net.imglib2.type.NativeType;
import net.imglib2.type.numeric.RealType;
import net.imglib2.type.numeric.real.FloatType;
import net.imglib2.util.Intervals;
import net.imglib2.util.Util;
import net.imglib2.view.IntervalView;
import net.imglib2.view.SubsampleIntervalView;
import net.imglib2.view.Views;
import net.imglib2.view.composite.Composite;
import net.imglib2.view.composite.CompositeIntervalView;
import net.imglib2.view.composite.GenericComposite;
import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;
@Command( version = "0.1.1-SNAPSHOT")
public class AffineFromDisplacement<T> implements Callable< Void >
{
public static final String FLAG_SKIP_WARP = "--skip-warp";
@Option( names = { "-i", "--input" }, required = true, description = "Input displacement field" )
private List< String > inputFiles = new ArrayList<>();
@Option( names = { "-o", "--out-suffix" }, required = false, description = "Output displacement field suffix" )
private String dfieldSuffix = "_noAffine.nrrd";
@Option( names = { "-a", "--affine-suffix" }, required = false, description = "Output displacement field suffix" )
private String affineSuffix = "_affine.txt";
@Option( names = { "-s", "--sample-step" }, required = false, description = "Sampling step" )
private int step = 4;
@Option( names = { "-q", "--num-threads" }, required = false, description = "Sampling step" )
private int nThreads = 1;
@Option( names = { "--do-warp" }, required = false, description = "Write displacementfield with affine part removed" )
private Boolean doWarp = true;
@Option( names = { "--filter" }, required = false, description = "Filter: ignore (0,0,0) vectors" )
private Boolean filter = true;
public AffineFromDisplacement() { }
@SuppressWarnings( "unchecked" )
public static void main( String[] args )
{
CommandLine.call( new AffineFromDisplacement(), args );
System.exit(0);
}
public Void call()
{
DfieldIoHelper dfieldIo = new DfieldIoHelper();
for( String dfieldPath : inputFiles )
{
// File inFile = new File( dfieldPath );
// System.out.println( inFile.getName() );
String outputPrefix = dfieldPath.substring( 0, dfieldPath.lastIndexOf( '.' ));
System.out.println( "out prefix: " + outputPrefix );
ANTSDeformationField dfield = null;
try
{
dfield = dfieldIo.readAsDeformationField( dfieldPath );
}
catch ( Exception e )
{
e.printStackTrace();
continue;
}
AffineTransform3D affine;
try
{
affine = estimateAffine( dfield.getImg(), dfield.getResolution(), step, true );
System.out.println( affine );
AffineImglib2IO.writeXfm( new File( outputPrefix + affineSuffix ), affine );
}
catch ( Exception e )
{
e.printStackTrace();
continue;
}
if( doWarp )
{
removeAffineComponentAndWrite(
new File( outputPrefix + dfieldSuffix),
affine, dfield.getImg(), Util.getTypeFromInterval( dfield.getImg() ),
dfield.getDefField(), dfield.getResolution(),
filter,
nThreads );
}
}
return null;
}
public static < T extends RealType< T > & NativeType< T > > void writeDfield(
final String outputFile, final RandomAccessibleInterval<T> dfieldIn,
final double[] outputResolution ) throws Exception
{
ImagePlusImgFactory< T > factory = new ImagePlusImgFactory<>( Util.getTypeFromInterval( dfieldIn ) );
ImagePlusImg< T, ? > dfieldraw = factory.create( dfieldIn );
RandomAccessibleInterval< T > dfield = DfieldIoHelper.vectorAxisPermute( dfieldraw, 3, 3 );
DfieldIoHelper dfieldIo = new DfieldIoHelper();
dfieldIo.spacing = outputResolution; // naughty
try
{
dfieldIo.write( dfield, outputFile );
}
catch ( Exception e )
{
e.printStackTrace();
}
}
public static void oldmain( String[] args ) throws NotEnoughDataPointsException, IllDefinedDataPointsException
{
int argIdx = 0;
boolean doWarp = true;
if( args[ argIdx ].equals( FLAG_SKIP_WARP ))
{
doWarp = false;
argIdx++;
}
String outPath = args[ argIdx++ ];
String filePath = args[ argIdx++ ];
int step = Integer.parseInt( args[ argIdx++ ] );
ImagePlus imp = null;
double[] resolution = new double[3];
Img< FloatType > displacement = null;
if( filePath.endsWith( "nii" ))
{
try
{
imp = NiftiIo.readNifti( new File( filePath ) );
} catch ( FormatException e )
{
e.printStackTrace();
} catch ( IOException e )
{
e.printStackTrace();
}
}
else
{
imp = IJ.openImage( filePath );
}
resolution[ 0 ] = imp.getCalibration().pixelWidth;
resolution[ 1 ] = imp.getCalibration().pixelHeight;
resolution[ 2 ] = imp.getCalibration().pixelDepth;
displacement = ImageJFunctions.convertFloat( imp );
if ( displacement == null )
{
System.err.println( "Failed to load displacement field" );
return;
}
System.out.println(
"DISPLACEMENT INTERVAL: " + Util.printInterval( displacement ) );
AffineTransform3D affine = estimateAffine( displacement, resolution, step, true );
System.out.println( affine );
try
{
AffineImglib2IO.writeXfm( new File( outPath + "_affine.txt" ), affine );
} catch ( IOException e )
{
e.printStackTrace();
}
if ( doWarp )
{
System.out.println( "removing affine part from warp" );
removeAffineComponentLegacy( displacement, affine, true );
System.out.println( "saving warp" );
// IJ.save( ImageJFunctions.wrap( displacement, "warp" ),
// outPath + "_warp.tif" );
Nifti_Writer.writeDisplacementField3d( imp, new File( outPath + "_warp.nii") );
}
}
/**
* Removes the affine part from a displacement field
* @param displacementField the displacement field
* @param affine the affine part
* @param filter if true, ignores vectors in the field equal to (0,0,0)
*/
public static <S extends RealType<S>, T extends RealType< T > & NativeType<T>> void removeAffineComponentAndWrite(
final File outFile,
final AffineTransform3D affine,
final Interval intervalIn,
final T t,
final RealRandomAccessible< S > displacementFieldIn,
final double[] outputResolution,
final boolean filter,
final int numThreads )
{
Interval intervalOut = DfieldIoHelper.dfieldIntervalVectorFirst3d( intervalIn );
Scale3D pixelToPhysical = new Scale3D( outputResolution );
ImagePlusImgFactory< T > factory = new ImagePlusImgFactory<>( t );
ImagePlusImg< T, ? > dfieldraw = factory.create( intervalOut );
try
{
RandomAccessibleInterval< T > dfield = DfieldIoHelper.vectorAxisPermute( dfieldraw, 3, 3 );
if( numThreads == 1 )
removeAffineComponent( affine, dfield, displacementFieldIn, pixelToPhysical, filter );
else
removeAffineComponent( affine, dfield, displacementFieldIn, pixelToPhysical, filter, numThreads );
DfieldIoHelper dfieldIo = new DfieldIoHelper();
dfieldIo.spacing = outputResolution; // naughty
dfieldIo.write( dfieldraw, outFile.getAbsolutePath() );
}
catch ( Exception e )
{
e.printStackTrace();
return;
}
}
/**
* Removes the affine part from a displacement field
*/
public static <S extends RealType<S>,T extends RealType< T >> void removeAffineComponent(
final AffineTransform3D affine,
final RandomAccessibleInterval< T > displacementFieldOut,
final RealRandomAccessible< S > displacementFieldInPhysical,
final AffineGet pixelToPhysical,
final boolean filter )
{
final int VECTOR_DIM = 3;
System.out.println("removing affine from dfield");
CompositeIntervalView< T, ? extends GenericComposite< T > > vectorField = Views.collapse( displacementFieldOut );
Cursor< ? extends GenericComposite< T > > c = Views.flatIterable( vectorField ).cursor();
RealRandomAccess< S > realRa = displacementFieldInPhysical.realRandomAccess();
RealPoint physPt = new RealPoint( 3 );
RealPoint affineResult = new RealPoint( 3 );
RealPoint physicalOutputPoint = new RealPoint( 3 );
RealPoint physicalDestinationPoint = new RealPoint( 3 );
while ( c.hasNext() )
{
GenericComposite< T > outputVector = c.next();
pixelToPhysical.apply( c, physPt );
for ( int i = 0; i < 3; i++ )
realRa.setPosition( physPt.getDoublePosition( i ), i );
realRa.setPosition( 0, VECTOR_DIM ); // first vector coordinate
if ( filter )
{
boolean allZeros = true;
for ( int i = 0; i < 3; i++ )
{
if( realRa.get().getRealFloat() != 0.0f )
{
allZeros = false;
break;
}
realRa.fwd( VECTOR_DIM );
}
if( allZeros )
continue;
}
// go to real space
pixelToPhysical.apply( c, physicalOutputPoint );
// what real coordinate does this tranformation go to
realRa.setPosition( 0, 3 ); // first vector coordinate
for ( int d = 0; d < 3; d++ )
{
physicalDestinationPoint.setPosition(
physicalOutputPoint.getDoublePosition( d ) + realRa.get().getRealDouble(),
d );
realRa.fwd( VECTOR_DIM );
}
// remove the affine part
affine.applyInverse( affineResult, physicalDestinationPoint );
// set the output
for ( int i = 0; i < 3; i++ )
outputVector.get( i ).setReal(
affineResult.getDoublePosition( i ) - physicalOutputPoint.getDoublePosition( i ) );
}
}
/**
* Removes the affine part from a displacement field
*/
public static <S extends RealType<S>,T extends RealType< T >> void removeAffineComponent(
final AffineTransform3D affine,
final RandomAccessibleInterval< T > displacementFieldOut,
final RealRandomAccessible< S > displacementFieldIn,
final AffineGet pixelToPhysical,
final boolean filter,
final int numThreads )
{
System.out.println("removing affine from dfield");
CompositeIntervalView< T, ? extends GenericComposite< T > > vectorField = Views.collapse( displacementFieldOut );
ExecutorService threadPool = Executors.newFixedThreadPool( numThreads );
LinkedList< Callable< Boolean > > jobs = new LinkedList< Callable< Boolean > >();
for ( int task = 0; task < numThreads; task++ )
{
final int index = task;
jobs.add( new Callable< Boolean >()
{
public Boolean call()
{
final RealPoint tmp1 = new RealPoint( 3 );
final RealPoint tmp2 = new RealPoint( 3 );
final RealPoint tmp3 = new RealPoint( 3 );
final Cursor< ? extends GenericComposite< T > > c = Views.flatIterable( vectorField ).cursor();
final RealRandomAccess< S > realRa = displacementFieldIn.realRandomAccess();
final AffineTransform3D affineCopy = affine.copy();
final AffineGet pix2PhysCopy = pixelToPhysical.copy();
c.jumpFwd( index );
while ( c.hasNext() )
{
c.jumpFwd( numThreads );
removeAffinePart( c, affineCopy,
realRa, pix2PhysCopy,
filter, tmp1, tmp2, tmp3 );
}
return true;
}
});
}
List< Future< Boolean > > futures;
try
{
futures = threadPool.invokeAll( jobs );
List< Boolean > results = new ArrayList< Boolean >();
for ( Future< Boolean > f : futures )
results.add( f.get() );
}
catch ( InterruptedException e )
{
e.printStackTrace();
}
catch ( ExecutionException e )
{
e.printStackTrace();
}
}
/**
* Subroutine for removing an affine froma a vector displacement field.
* Cursor must be set to the correct position before calling this method (the cursor position is not modified).
*
* @param c cursor holding displacement vector as a composite
* @param affine the affine to remove
* @param realRa original displacement
* @param pixelToPhysical transform from coordinate of
* @param filter ignore the zero vector?
* @param tmp1 temporary storage 1 (to reuse)
* @param tmp2 temporary storage 2 (to reuse)
*/
public static <T extends RealType<T>, S extends RealType<S>, V extends Composite<T>> void removeAffinePart(
final Cursor<V> c,
final AffineGet affine,
final RealRandomAccess< S > realRa,
final AffineGet pixelToPhysical,
final boolean filter,
final RealPoint tmp1,
final RealPoint tmp2,
final RealPoint tmp3 )
{
final int VECTOR_DIM = 3;
Composite< T > outputVector = c.get();
RealPoint physPt = tmp1;
pixelToPhysical.apply( c, physPt );
for ( int i = 0; i < 3; i++ )
realRa.setPosition( physPt.getDoublePosition( i ), i );
realRa.setPosition( 0, VECTOR_DIM ); // first vector coordinate
if ( filter )
{
boolean allZeros = true;
for ( int i = 0; i < 3; i++ )
{
if( realRa.get().getRealFloat() != 0.0f )
{
allZeros = false;
break;
}
realRa.fwd( VECTOR_DIM );
}
if( allZeros )
return;
}
// go to real space
RealPoint physicalOutputPoint = tmp1;
RealPoint physicalDestinationPoint = tmp2;
pixelToPhysical.apply( c, physicalOutputPoint );
// what real coordinate does this tranformation go to
realRa.setPosition( 0, 3 ); // first vector coordinate
for ( int d = 0; d < 3; d++ )
{
physicalDestinationPoint.setPosition(
physicalOutputPoint.getDoublePosition( d ) + realRa.get().getRealDouble(),
d );
realRa.fwd( VECTOR_DIM );
}
// remove the affine part
RealPoint affineResult = tmp3;
affine.applyInverse( affineResult, physicalDestinationPoint );
// set the output
for ( int i = 0; i < 3; i++ )
outputVector.get( i ).setReal(
affineResult.getDoublePosition( i ) - physicalOutputPoint.getDoublePosition( i ) );
}
/**
* Removes the affine part from a displacement field
* @param displacementField the displacement field
* @param affine the affine part
* @param filter if true, ignores vectors in the field equal to (0,0,0)
*/
public static <T extends RealType< T >> void removeAffineComponentLegacy(
RandomAccessibleInterval< T > displacementField,
AffineTransform3D affine,
boolean filter )
{
CompositeIntervalView< T, ? extends GenericComposite< T > > vectorField = Views
.collapse( displacementField );
Cursor< ? extends GenericComposite< T > > c = Views.flatIterable( vectorField )
.cursor();
RealPoint affineResult = new RealPoint( 3 );
RealPoint y = new RealPoint( 3 );
while ( c.hasNext() )
{
GenericComposite< T > vector = c.next();
if ( filter &&
vector.get( 0 ).getRealDouble() == 0 &&
vector.get( 1 ).getRealDouble() == 0 &&
vector.get( 2 ).getRealDouble() == 0 )
{
continue;
}
for ( int i = 0; i < 3; i++ )
y.setPosition( c.getDoublePosition( i ) + vector.get( i ).getRealDouble(), i );
affine.applyInverse( affineResult, y );
for ( int i = 0; i < 3; i++ )
vector.get( i ).setReal(
affineResult.getDoublePosition( i ) - c.getDoublePosition( i ) );
}
}
public static <T extends RealType< T >> void removeAffineComponentWRONG(
RandomAccessibleInterval< T > displacementField, AffineTransform3D affine,
boolean filter )
{
CompositeIntervalView< T, ? extends GenericComposite< T > > vectorField = Views
.collapse( displacementField );
Cursor< ? extends GenericComposite< T > > c = Views.flatIterable( vectorField )
.cursor();
RealPoint affineResult = new RealPoint( 3 );
while ( c.hasNext() )
{
GenericComposite< T > vector = c.next();
if ( filter &&
vector.get( 0 ).getRealDouble() == 0 &&
vector.get( 1 ).getRealDouble() == 0 &&
vector.get( 2 ).getRealDouble() == 0 )
{
continue;
}
affine.apply( c, affineResult );
for ( int i = 0; i < 2; i++ )
vector.get( i ).setReal(
c.getDoublePosition( i ) + vector.get( i ).getRealDouble()
- affineResult.getDoublePosition( i ) );
}
}
public static <T extends RealType< T >> AffineTransform3D estimateAffine(
final RandomAccessibleInterval< T > displacementField,
final double[] resolution,
int step, boolean filter )
throws NotEnoughDataPointsException, IllDefinedDataPointsException
{
assert resolution.length == displacementField.numDimensions() - 1;
final double[] resolutionAndStep = new double[ resolution.length ];
for( int d = 0; d < resolution.length; d++ )
{
resolutionAndStep[ d ] = step * resolution[ d ];
}
CompositeIntervalView< T, ? extends GenericComposite< T > > tmp = Views.collapse( displacementField );
System.out.println( "collapsed INTERVAL: " + Util.printInterval( tmp ));
SubsampleIntervalView< ? extends GenericComposite< T > > vectorField = Views.subsample( tmp, step );
System.out.println( "sub INTERVAL: " + Util.printInterval( vectorField ));
Cursor< ? extends GenericComposite< T > > c = Views.flatIterable( vectorField ).cursor();
int i = 0;
ArrayList<PointMatch> matches = new ArrayList<PointMatch>( (int)Intervals.numElements( vectorField ));
int numSkipped = 0;
while( c.hasNext())
{
GenericComposite< T > vector = c.next();
if( filter &&
vector.get( 0 ).getRealDouble() == 0 &&
vector.get( 1 ).getRealDouble() == 0 &&
vector.get( 2 ).getRealDouble() == 0 )
{
numSkipped++;
continue;
}
matches.add( new PointMatch(
new Point( new double[]{
resolutionAndStep[ 0 ] * c.getDoublePosition( 0 ),
resolutionAndStep[ 1 ] * c.getDoublePosition( 1 ),
resolutionAndStep[ 2 ] * c.getDoublePosition( 2 ),
}),
new Point( new double[]{
resolutionAndStep[ 0 ] * c.getDoublePosition( 0 ) + vector.get( 0 ).getRealDouble(),
resolutionAndStep[ 1 ] * c.getDoublePosition( 1 ) + vector.get( 1 ).getRealDouble(),
resolutionAndStep[ 2 ] * c.getDoublePosition( 2 ) + vector.get( 2 ).getRealDouble()
})
));
}
System.out.println( "skipped " + numSkipped + " points.");
System.out.println( "fitting affine with " + matches.size() + " point matches.");
AffineModel3D estimator = new AffineModel3D();
estimator.fit( matches );
AffineTransform3D affine = new AffineTransform3D();
affine.set( estimator.getMatrix( new double[ 12 ] ));
return affine;
}
public static <T extends RealType< T >> AffineTransform3D estimateAffineRaw(
RandomAccessibleInterval< T > displacementField )
throws NotEnoughDataPointsException, IllDefinedDataPointsException
{
// IntervalView< T > physicalSpace = Views.hyperSlice( displacementField, 3, 0 );
CompositeIntervalView< T, ? extends GenericComposite< T > > vectorField = Views.collapse( displacementField );
int N = 0;
Cursor< ? extends GenericComposite< T > > c = Views.flatIterable( vectorField ).cursor();
while( c.hasNext())
{
c.fwd();
N++;
}
c.reset();
int i = 0;
double[][] p = new double[ 3 ][ N ];
double[][] q = new double[ 3 ][ N ];
double[] w = new double[ N ];
while( c.hasNext())
{
GenericComposite< T > vector = c.next();
p[ 0 ][ i ] = c.getDoublePosition( 0 );
p[ 1 ][ i ] = c.getDoublePosition( 1 );
p[ 2 ][ i ] = c.getDoublePosition( 2 );
q[ 0 ][ i ] = c.getDoublePosition( 0 ) + vector.get( 0 ).getRealDouble();
q[ 1 ][ i ] = c.getDoublePosition( 1 ) + vector.get( 1 ).getRealDouble();
q[ 2 ][ i ] = c.getDoublePosition( 2 ) + vector.get( 2 ).getRealDouble();
}
Arrays.fill( w, 1.0 );
AffineModel3D estimator = new AffineModel3D();
estimator.fit( p, q, w );
AffineTransform3D affine = new AffineTransform3D();
affine.set( estimator.getMatrix( new double[12] ));
return affine;
}
}
|
package uk.gov.register.views;
import org.jvnet.hk2.annotations.Service;
import uk.gov.organisation.client.GovukOrganisation;
import uk.gov.organisation.client.GovukOrganisationClient;
import uk.gov.register.configuration.*;
import uk.gov.register.core.*;
import uk.gov.register.resources.Pagination;
import uk.gov.register.resources.RequestContext;
import uk.gov.register.thymeleaf.ThymeleafView;
import javax.inject.Inject;
import javax.inject.Provider;
import javax.ws.rs.BadRequestException;
import java.time.Instant;
import java.util.Collection;
import java.util.Map;
import java.util.Optional;
@Service
public class ViewFactory {
private final RequestContext requestContext;
private final PublicBodiesConfiguration publicBodiesConfiguration;
private final GovukOrganisationClient organisationClient;
private final Provider<RegisterMetadata> registerMetadata;
private final RegisterDomainConfiguration registerDomainConfiguration;
private final RegisterContentPages registerContentPages;
private final RegisterResolver registerResolver;
private final Provider<RegisterReadOnly> register;
private final Provider<RegisterTrackingConfiguration> registerTrackingConfiguration;
@Inject
public ViewFactory(RequestContext requestContext,
PublicBodiesConfiguration publicBodiesConfiguration,
GovukOrganisationClient organisationClient,
RegisterDomainConfiguration registerDomainConfiguration,
RegisterContentPagesConfiguration registerContentPagesConfiguration,
Provider<RegisterMetadata> registerMetadata,
Provider<RegisterTrackingConfiguration> registerTrackingConfiguration,
RegisterResolver registerResolver,
Provider<RegisterReadOnly> register) {
this.requestContext = requestContext;
this.publicBodiesConfiguration = publicBodiesConfiguration;
this.organisationClient = organisationClient;
this.registerDomainConfiguration = registerDomainConfiguration;
this.registerMetadata = registerMetadata;
this.registerContentPages = new RegisterContentPages(registerContentPagesConfiguration.getRegisterHistoryPageUrl());
this.registerTrackingConfiguration = registerTrackingConfiguration;
this.registerResolver = registerResolver;
this.register = register;
}
public ThymeleafView thymeleafView(String templateName) {
return new ThymeleafView(requestContext, templateName, registerTrackingConfiguration.get(), registerResolver, register.get());
}
public BadRequestExceptionView badRequestExceptionView(BadRequestException e) {
return new BadRequestExceptionView(requestContext, e, register.get(), registerTrackingConfiguration.get(), registerResolver);
}
public HomePageView homePageView(int totalRecords, int totalEntries, Optional<Instant> lastUpdated) {
return new HomePageView(
getRegistry(),
getBranding(),
requestContext,
totalRecords,
totalEntries,
lastUpdated,
register.get(),
registerContentPages,
registerTrackingConfiguration.get(),
registerResolver);
}
public DownloadPageView downloadPageView(Boolean enableDownloadResource) {
return new DownloadPageView(requestContext, register.get(), enableDownloadResource, registerTrackingConfiguration.get(), registerResolver);
}
public RegisterDetailView registerDetailView(int totalRecords, int totalEntries, Optional<Instant> lastUpdated) {
return new RegisterDetailView(totalRecords, totalEntries, lastUpdated, registerMetadata.get(), registerDomainConfiguration.getRegisterDomain());
}
public <T> AttributionView<T> getAttributionView(String templateName, T fieldValueMap) {
return new AttributionView<>(templateName, requestContext, getRegistry(), getBranding(), register.get(), registerTrackingConfiguration.get(), registerResolver, fieldValueMap);
}
public AttributionView<Map<String, FieldValue>> getItemView(Map<String, FieldValue> fieldValueMap) {
return getAttributionView("item.html", fieldValueMap);
}
public AttributionView<Entry> getEntryView(Entry entry) {
return getAttributionView("entry.html", entry);
}
public PaginatedView<EntryListView> getEntriesView(Collection<Entry> entries, Pagination pagination) {
return new PaginatedView<>("entries.html", requestContext, getRegistry(), getBranding(), register.get(), registerTrackingConfiguration.get(), registerResolver, pagination, new EntryListView(entries));
}
public PaginatedView<EntryListView> getRecordEntriesView(String recordKey, Collection<Entry> entries, Pagination pagination) {
return new PaginatedView<>("entries.html", requestContext, getRegistry(), getBranding(), register.get(), registerTrackingConfiguration.get(), registerResolver, pagination, new EntryListView(entries, recordKey));
}
public AttributionView<RecordView> getRecordView(RecordView record) {
return getAttributionView("record.html", record);
}
public PaginatedView<RecordsView> getRecordListView(Pagination pagination, RecordsView recordsView) {
return new PaginatedView<>("records.html", requestContext, getRegistry(), getBranding(), register.get(), registerTrackingConfiguration.get(), registerResolver, pagination,
recordsView);
}
private PublicBody getRegistry() {
return publicBodiesConfiguration.getPublicBody(registerMetadata.get().getRegistry());
}
private Optional<GovukOrganisation.Details> getBranding() {
Optional<GovukOrganisation> organisation = organisationClient.getOrganisation(registerMetadata.get().getRegistry());
return organisation.map(GovukOrganisation::getDetails);
}
}
|
package jburg;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
/**
* A State represents a vertex in the transition table.
* Vertices represent an equivalence class of input nodes,
* each of which has the same opcode/arity; an input node
* must match one of the pattern-matching productions in
* the state. The state may also be able to produce other
* nonterminals via nonterminal-to-nonterminal closures.
*
* The State class is Comparable so that it can be
* sorted on its state number.
*/
class State<Nonterminal, NodeType> implements Comparable<State<Nonterminal,NodeType>>
{
/**
* The state's number. This number is set
* by the production table when it places
* a state in its table of unique states.
*/
int number = -1;
/** "Typedef" a map of costs by nonterminal. */
class CostMap extends HashMap<Nonterminal,Long> {}
/** "Typedef" a map of Productions by Nonterminal. */
class ProductionMap extends HashMap<Nonterminal, Production<Nonterminal,NodeType>> {}
/** "Typedef" a map of Closures by Nonterminal. */
class ClosureMap extends HashMap<Nonterminal, Closure<Nonterminal>> {}
private CostMap costMap = new CostMap();
private ProductionMap productions = new ProductionMap();
private ClosureMap closures = new ClosureMap();
private final NodeType nodeType;
State(NodeType nodeType)
{
this.nodeType = nodeType;
}
void setProduction(Production<Nonterminal,NodeType> p, long cost)
{
assert(cost < getCost(p.target));
costMap.put(p.target, cost);
productions.put(p.target, p);
}
int size()
{
assert(productions.size() == costMap.size());
return productions.size();
}
boolean empty()
{
assert(productions.isEmpty() == costMap.isEmpty());
return productions.isEmpty();
}
long getCost(Nonterminal nt)
{
if (costMap.containsKey(nt)) {
return costMap.get(nt);
} else if (closures.containsKey(nt)) {
Closure<Nonterminal> closure = closures.get(nt);
long closedCost = closure.ownCost + getCost(closure.source);
assert closedCost < Integer.MAX_VALUE;
return closedCost;
} else {
return Integer.MAX_VALUE;
}
}
/**
* Add a closure to the closure map if it's the best alternative seen so far.
* @return true if the closure is added to the map.
*/
boolean addClosure(Closure<Nonterminal> closure)
{
// The cost of a closure is its own cost,
// plus the cost of producing its antecedent.
long closureCost = closure.ownCost + getCost(closure.source);
if (closureCost < this.getCost(closure.target)) {
closures.put(closure.target, closure);
return true;
} else {
return false;
}
}
@Override
public String toString()
{
StringBuilder buffer = new StringBuilder();
buffer.append("State ");
buffer.append(String.valueOf(number));
if (productions.size() > 0) {
buffer.append("( patterns(");
boolean didFirst = false;
for (Nonterminal nt: productions.keySet()) {
Production p = productions.get(nt);
if (didFirst) {
buffer.append(",");
} else {
didFirst = true;
}
buffer.append(String.format("%s=%s", nt, p));
}
buffer.append(")");
if (closures.size() > 0) {
buffer.append(closures);
}
buffer.append(")");
}
return buffer.toString();
}
/**
* Define a state's hash code in terms of its cost map's hash code.
* @return this state's cost map's hashCode()
*/
@Override
public int hashCode()
{
return nodeType.hashCode() * 31 + costMap.hashCode();
}
/**
* Two states are equal if their cost maps are equal.
* @param o the object to compare against.
* @return unclosed.costMap(o.costMap) if o is a State,
* false otherwise.
*/
@Override
@SuppressWarnings({"unchecked"})
public boolean equals(Object o)
{
if (o instanceof State) {
State<Nonterminal,NodeType> s = (State<Nonterminal,NodeType>)o;
return this.nodeType.equals(s.nodeType) && this.costMap.equals(s.costMap);
} else {
return false;
}
}
/**
* States are comparable on their state number;
* this is a convenience so that the state table,
* which is stored in hashed order, can be emitted
* in state number order.
*/
@Override
public int compareTo(State<Nonterminal,NodeType> other)
{
assert this.number != -1 && other.number != -1;
return this.number - other.number;
}
}
|
package de.echox.hacklace.pix0lat0r.gui;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import de.echox.hacklace.pix0lat0r.core.App;
public class GUI {
private Display display;
private Shell shell;
private App controller;
public void initialize(App controller) {
this.controller = controller;
display = new Display ();
shell = new Shell (display);
initializeMenu();
initializeAnimator();
shell.setLayout (new RowLayout ());
shell.pack();
shell.open ();
while (!shell.isDisposed()) {
if (!display.readAndDispatch ()) display.sleep ();
}
display.dispose ();
}
private void initializeAnimator() {
// controls
Button left = new Button (shell, SWT.PUSH);
left.setText(" < ");
left.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
System.out.println("OK");
}
});
Label label = new Label(shell, SWT.VERTICAL);
label.setText("1/1");
Button right = new Button (shell, SWT.PUSH);
right.setText(" > ");
right.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
System.out.println("OK");
}
});
// drawer
Drawer drawer = new Drawer(shell, 0);
}
private void initializeMenu() {
Menu bar = new Menu (shell, SWT.BAR);
shell.setMenuBar (bar);
MenuItem fileItem = new MenuItem (bar, SWT.CASCADE);
fileItem.setText ("File");
Menu submenu = new Menu (shell, SWT.DROP_DOWN);
fileItem.setMenu (submenu);
MenuItem item = new MenuItem (submenu, SWT.PUSH);
item.addListener (SWT.Selection, new Listener () {
public void handleEvent (Event e) {
controller.quit();
}
});
item.setText ("Quit");
MenuItem settings = new MenuItem(bar,SWT.PUSH);
settings.setText("Settings");
}
}
|
package de.jtem.halfedge.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import de.jtem.halfedge.Edge;
import de.jtem.halfedge.Face;
import de.jtem.halfedge.HalfEdgeDataStructure;
import de.jtem.halfedge.Vertex;
/**
* Class providing static utility methods for half-edge data structures.
*
* @author Boris Springborn
*/
/**
* @author springb
*
*/
public final class HalfEdgeUtils {
// Don't instatiate.
private HalfEdgeUtils() {}
/**
* Test whether the half-edge data structure represents a valid surface.
*
* Checks whether the following conditions are satisfied.<br>
* <br>
* <b>1.</b> The edge list is not empty.<br>
* <br>
* For all edges {@code e} in the edge list: <br>
* <br>
* <b>2.</b> Neither {@link Edge#getNextEdge() e.getNextEdge()}, nor {@link Edge#getPreviousEdge() e.getPreviousEdge()},
* nor {@link Edge#getOppositeEdge() e.getOppositeEdge()} returns {@code null}.<br>
* <b>3.</b> {@link Edge#getTargetVertex() e.getTargetVertex()} does not return {@code null}.<br>
* <b>4.</b> {@link Edge#getLeftFace() e.getLeftFace()} and {@link Edge#getRightFace() e.getRightFace()} do not <i>both</i> return {@code null}. <br>
* <b>5.</b> {@link Edge#getLeftFace() getLeftFace()} returns the same face for {@code e} and {@code e.}{@link Edge#getNextEdge() getNextEdge()}.<br>
* <b>6.</b> {@link Edge#getTargetVertex() getTargetVertex()} returns the same vertex for {@code e} and
* {@code e.}{@link Edge#getNextEdge() getNextEdge().}{@link Edge#getOppositeEdge() getOppositeEdge()}.<br>
* <br>
* For all faces {@code f} in the face list: <br>
* <br>
* <b>7.</b> There is at least one edge {@code e} in the edge list that has {@code f} as left face. That is, there are no isolated faces.<br>
* <b>8.</b> If you repeatedly perform {@code e = e.}{@link Edge#getNextEdge() getNextEdge()}, you can reach all edges with {@code f} as left face.<br>
* <br>
* For all vertices {@code v} in the vertex list:<br>
* <br>
* <b>9.</b> There is at least one edge {@code e} in the edge list that has {@code v} as target vertex. That is, there are no isolated vertices.<br>
* <b>10.</b> If you repeatedly perform {@code e = e.}{@link Edge#getNextEdge() getNextEdge().}{@link Edge#getOppositeEdge() getOppositeEdge()},
* you can reach all edges with {@code v} as target vertex. <br>
* <b>11.</b> Among all edges {@code e} with {@code v} as target vertex, there is at most one for which {@link Edge#getLeftFace() e.getLeftFace()} returns {@code null}.
* <br>
* <br>
* Together with the invariants that are maintained by the classes in this package, this guarantees that the half-edge data structure encodes a cell
* decomposition of a surface.
*
* @return {@code true} if the half-edge data structure represents a valid surface, {@code false} otherwise
*/
static public boolean isValidSurface(HalfEdgeDataStructure<?,?,?> heds) {
return isValidSurface(heds, false);
}
/**
* Test whether the half-edge data structure represents a valid surface and, optionally, give a reason if it fails the test.
* If the parameter is {@code false}, this method behaves exatly as {@link #isValidSurface(HalfEdgeDataStructure)}. If the parameter is {@code true},
* and the half-edge data structure fails to represent a valid surface, the method outputs a brief explanation to {@link System#err}.
* This feature is intended for debugging.
* @param printReasonForFailureToSystemErr {@code true} if you want output to {@link System#err}.
* @return {@code true} if the half-edge data structure represents a valid surface, {@code false} otherwise
*/
static public boolean isValidSurface(HalfEdgeDataStructure<?,?,?> heds, boolean printReasonForFailureToSystemErr) {
// must have at least one edge
if (heds.getEdges().isEmpty()) {
if (printReasonForFailureToSystemErr) System.err.println("getEdges().isEmpty == true");
return false;
}
// check for null references
for (Edge<?,?,?> e : heds.getEdges()) {
if (e.getNextEdge() == null) {
if (printReasonForFailureToSystemErr) System.err.println("getNextEdge() returns null for edge " + e.getIndex());
return false;
}
if (e.getPreviousEdge() == null) {
if (printReasonForFailureToSystemErr) System.err.println("getPreviousEdge() returns null for edge " + e.getIndex());
return false;
}
if (e.getOppositeEdge() == null) {
if (printReasonForFailureToSystemErr) System.err.println("getOppositeEdge() returns null for edge " + e.getIndex());
return false;
}
if (e.getTargetVertex() == null) {
if (printReasonForFailureToSystemErr) System.err.println("getTargetVertex() returns null for edge " + e.getIndex());
return false;
}
// either left face or right face may be null but not both
if (e.getLeftFace() == null && e.getRightFace() == null) {
if (printReasonForFailureToSystemErr) System.err.println("Left face and right face are null for edge " + e.getIndex());
return false;
}
}
// Check if edges in a cycle have same left face and edges in a cocycle have same target vertex
for (Edge<?,?,?> e : heds.getEdges()) {
if (e.getLeftFace() != e.getNextEdge().getLeftFace()) {
if (printReasonForFailureToSystemErr) System.err.println("e.getLeftFace() != e.getNextEdge().getLeftFace() for edge " + e.getIndex());
return false;
}
if (e.getTargetVertex() != e.getNextEdge().getOppositeEdge().getTargetVertex()) {
if (printReasonForFailureToSystemErr) System.err.println("e.getTargetVertex() != e.getNextEdge().getOppositeEdge().getTargetVertex() for edge " + e.getIndex());
return false;
}
}
// check if every face has a boundary edge
for (Face<?,?,?> f : heds.getFaces()) {
if (f.getBoundaryEdge() == null) {
if (printReasonForFailureToSystemErr) System.err.println("Face " + f.getIndex() + " has no boundary edge.");
return false;
}
}
// check if every vertex has an incoming edge
for (Vertex<?,?,?> v : heds.getVertices()) {
if (v.getIncomingEdge() == null) {
if (printReasonForFailureToSystemErr) System.err.println("Vertex " + v.getIndex() + " has no incoming edge.");
}
}
// check if each face corresponds to a unique edge cycle,
// each vertex corresponds to a unique edge cocycle,
// and that there is at most one edge in a vertex cocyle with left face == null
int ne = heds.numEdges();
int nf = heds.numFaces();
int nv = heds.numVertices();
assert (nv > 0 && ne > 0 && nf > 0);
boolean[] vertexMark = new boolean[nv];
boolean[] edgeMark = new boolean[ne];
boolean[] faceMark = new boolean[nf];
assert (false == (edgeMark[0])); // false should be the default value
for (Edge<?,?,?> e : heds.getEdges()) {
if (edgeMark[e.getIndex()]) {
// the cycle of this edge has already been treated
continue;
}
Face<?,?,?> f = e.getLeftFace();
if (f != null) {
// has this edge's left face already occurred in another cycle?
if (faceMark[f.getIndex()]) {
if (printReasonForFailureToSystemErr) System.err.println("Face " + f.getIndex() + " is contained in more than one edge cycle. (Found out while looking at " + e + ")");
return false;
}
// mark the left face
faceMark[f.getIndex()] = true;
}
// mark all edges in the edge cycle
edgeMark[e.getIndex()] = true;
for (Edge<?,?,?> e1 = e.getNextEdge(); e1 != e; e1 = e1.getNextEdge()) {
// System.err.println(e1);
edgeMark[e1.getIndex()] = true;
}
}
edgeMark = new boolean[ne]; // initialize to false again
assert (false == (edgeMark[0])); // false should be the default value
for (Edge<?,?,?> e : heds.getEdges()) {
if (edgeMark[e.getIndex()]) {
// the cycle of this edge has already been treated
continue;
}
Vertex<?,?,?> v = e.getTargetVertex();
// has this edge's target vertex already occurred in another cycle?
if (vertexMark[v.getIndex()]) {
if (printReasonForFailureToSystemErr) System.err.println("Vertex " + v.getIndex() + " is contained in more than one edge cocycle.");
return false;
}
// mark the left face
vertexMark[v.getIndex()] = true;
// mark all edges in the edge cocycle and check whether there's more than one with left face == null.
edgeMark[e.getIndex()] = true;
boolean leftFaceNull = e.getLeftFace() == null;
for (Edge<?,?,?> e1 = e.getNextEdge().getOppositeEdge(); e1 != e; e1 = e1.getNextEdge().getOppositeEdge()) {
// System.err.println(e1);
edgeMark[e1.getIndex()] = true;
if (e1.getLeftFace() == null) {
if (leftFaceNull) {
if (printReasonForFailureToSystemErr) System.err.println("There is more than one edge with target vertex " + v.getIndex() + " and left face null.");
return false;
}
leftFaceNull = true;
}
}
}
// passed all tests
return true;
}
/**
* Returns a list containing all vertices that are
* target vertices of the boundary of the given face
* @see {@link HalfEdgeUtils#boundaryEdges(Face)}
* @param <V>
* @param <E>
* @param <F>
* @param face the face
* @return
*/
public static <
V extends Vertex<V, E, F>,
E extends Edge<V, E, F>,
F extends Face<V, E, F>
> List<V> boundaryVertices(F face) {
Collection<E> b = boundaryEdges(face);
LinkedList<V> vList = new LinkedList<V>();
for (E e : b) {
vList.add(e.getTargetVertex());
}
return vList;
}
/**
* Return a list of the edges which have a given face as left face.
* <p>
* This method expects that if there is at least one such edge {@code e}, then all such edges, and only those, can be reached by repeatedly
* executing {@code e = e.}{@link de.jtem.halfedge.Edge#getNextEdge() getNextEdge()}, and that in the process
* {@code e} never becomes {@code null}.
* <p>
* The returned list contains the boundary edges in the correct cyclic order.
*
* @param <E> the edge type
* @param <F> the face type
* @param face the face
* @return the list of boundary edges in the correct cyclic order
*/
static public <E extends Edge<?,E,F>, F extends Face<?,E,F>> List<E> boundaryEdges(F face) {
final E e0 = face.getBoundaryEdge();
if (e0 == null) {
return Collections.emptyList();
}
LinkedList<E> result = new LinkedList<E>();
E e = e0;
do {
if (face != e.getLeftFace()) {
throw new RuntimeException("Edge " + e + " does not have face " + face + " as left face, " +
"although it is the next edge of an edge which does.");
}
result.add(e);
e = e.getNextEdge();
if (e == null) {
throw new RuntimeException("Some edge has null as next edge.");
}
} while (e != e0);
return result;
}
/**
* Returns a collection containing all edges of {@code heds} with left face equal to null.
* @param <E> the edge type
* @param heds the surface
* @return the collection of boundary edges
*/
static public <E extends Edge<?,E,?>> Collection<E> boundaryEdges(HalfEdgeDataStructure<?,E,?> heds) {
Collection <E>result = new ArrayList<E>();
for (E e : heds.getEdges()) {
if (e.getLeftFace() == null) {
result.add(e);
}
}
return result;
}
/**
* Returns a list containing lists for all boundary components
* of {@code hds} with left face equal to null.
* @param <E> the edge type
* @param hds the surface
* @return the collection of boundary components
* @see boundaryEdges
*/
static public <E extends Edge<?,E,?>> List<List<E>> boundaryComponents(HalfEdgeDataStructure<?,E,?> hds) {
List<List<E>> result = new ArrayList<List<E>>();
Set<E> b = new HashSet<E>(boundaryEdges(hds));
while (!b.isEmpty()) {
List<E> c = new LinkedList<E>();
E first = b.iterator().next();
E e = first;
do {
assert b.contains(e);
c.add(e);
b.remove(e);
e = e.getNextEdge();
} while (e != first);
result.add(c);
}
return result;
}
/**
* Returns a collection of all boundary vertices of {@code surf}. Assumes that {@code surf} represents a valid surface.
* @param <V> the vertex type
* @param <E> the edge type
* @param surf
* @return collection of boundary vertices
*/
static public <V extends Vertex<V,E,?>, E extends Edge<V,E,?>> Collection<V> boundaryVertices(HalfEdgeDataStructure<V,E,?> surf) {
Collection<V> result = new ArrayList<V>();
for (E e : surf.getEdges()) {
if (e.getLeftFace() == null) {
result.add(e.getTargetVertex());
}
}
return result;
}
/**
* Return a list of the edges which have a given vertex as target vertex.
* <p>
* This method expects that if there is one such edge {@code e}, then all such edges, and only those, can be reached by repeatedly
* executing {@code e = e.}{@link de.jtem.halfedge.Edge#getNextEdge() getNextEdge()}{@code .}{@link de.jtem.halfedge.Edge#getOppositeEdge() getOppositeEdge()},
* and that in the process {@code e} never becomes {@code null}.
* <p>
* The returned list contains the incoming edges in clockwise order.
*
* @param <E> the edge type
* @param <V> the vertex type
* @param vertex the vertex
* @return the list of incoming edges, in clockwise order
*/
static public <E extends Edge<V,E,?>, V extends Vertex<V,E,?>> List<E> incomingEdges(V vertex){
final E e0 = vertex.getIncomingEdge();
if (e0 == null) {
return Collections.emptyList();
}
LinkedList<E> result = new LinkedList<E>();
E e = e0;
do {
if (vertex != e.getTargetVertex()) {
throw new RuntimeException("Edge " + e + " does not have vertex " + vertex + " as target vertex, " +
"although it is the opposite of the next edge of an edge which does.");
}
result.add(e);
e = e.getNextEdge();
if (e == null) {
throw new RuntimeException("Some edge has null as next edge.");
}
e = e.getOppositeEdge();
if (e == null) {
throw new RuntimeException("Some edge has null as opposite edge.");
}
} while (e != e0);
return result;
}
/**
* Return a list of those vertices that are connected to a given {@code vertex} by an edge.
* <p>
* The {@code i}th element of in this list is simply<br>
* {@code vertex.}{@link #incomingEdges(Vertex) getIncomingEdges(vertex)}{@code .get(i).}{@link de.jtem.halfedge.Edge#getStartVertex() getStartVertex() }.<br>
* Thus, the preconditions of {@link #incomingEdges(Vertex)} apply.
* <p>
* The list contains the neighboring vertices in clockwise order, and it may contain the same vertex multiple times.
* (It may also contain {@code null}s.)
*
* @param <E> the edge type
* @param <V> the vertex type
* @param vertex the list of neighboring vertices.
* @return the list of neighbor vertices, in clockwise order
*/
static public <E extends Edge<V,E,?>, V extends Vertex<V,E,?>> List<V> neighboringVertices(V vertex) {
List<E> incoming = incomingEdges(vertex);
LinkedList<V> result = new LinkedList<V>();
for (E e : incoming) {
result.add(e.getStartVertex());
}
return result;
}
/**
* Return a list of faces that are incident with a given vertex.
* <p>
* Uses {@link #incomingEdges(Vertex)}, so the preconditions explained there apply.
* <p>
* The returned list contains the incident faces in clockwise order. It does not contain {@code null},
* even if the vertex is on the boundary.
* @param <V> the vertex type
* @param <E> the edge type
* @param <F> the face type
* @param vertex the vertex
* @return the incident faces in clockwise order
*/
static public <V extends Vertex<V,E,F>, E extends Edge<V,E,F>, F extends Face<V,E,F>> List<F> facesIncidentWithVertex(V vertex) {
List<E> incoming = incomingEdges(vertex);
List<F> result = new LinkedList<F>();
for (E e : incoming) {
F f = e.getLeftFace();
if (f != null) {
result.add(f);
}
}
return result;
}
/**
* Test if a given vertex is on the boundary.
* <p>
* Uses {@link #incomingEdges(Vertex)}, so the preconditions explained there apply.
*
* @param vertex
* @return {@code true} if there is an incoming edge with {@code null} as {@linkplain de.jtem.halfedge.Edge#getLeftFace() left face}, otherwise {@code false}.
*/
static public <V extends Vertex<V,E,?>,E extends Edge<V,E,?>> boolean isBoundaryVertex(V vertex) {
List<E> incoming = incomingEdges(vertex);
for (E e : incoming) {
if (e.getLeftFace() == null) {
return true;
}
}
return false;
}
/**
* Test if a given edge is on the boundary.
*
* @param e
* @return {@code true} if either e.getLeftFace() == null or e.getRightFace() == null.
*/
static public <E extends Edge<?, E, ?>> boolean isBoundaryEdge(E e) {
return e.getLeftFace() == null || e.getRightFace() == null;
}
/**
* Test if a given face is an inerior face (that is, not on the boundary).
* <p>
* Uses {@link #boundaryEdges(Face)}, so the preconditions explained there apply.
* @param <E> the edge type
* @param <F> the face type
* @param face the face
* @return {@code false} if there is a boundary edge with {@code null} as {@linkplain de.jtem.halfedge.Edge#getRightFace() right face}, otherwise {@code true}
*/
static public <F extends Face<?,E,F>, E extends Edge<?,E,F>> boolean isInteriorFace(F face){
for (E e : boundaryEdges(face))
if (e.getRightFace() == null) {
return false;
}
return true;
}
/**
* Test if a given edge is an interior edge (that is, not on the boundary).
* @param e the edge
* @return {@code e.getLeftFace() != null && e.getRightFace() != null}
*/
static public boolean isInteriorEdge(Edge<?,?,?> e){
return e.getLeftFace() != null && e.getRightFace() != null;
}
/**
* Insert a new face into an edge cycle with no left face.
* <p>
* An edge cycle is a cycle of edges obtained by repeatedly applying {@link de.jtem.halfedge.Edge#getNextEdge()}.
* This method expects that one does not encounter {@code null} when doing so, and that all edges in the cycle
* have {@code null} as left face.
*
* @param <V> the vertex type
* @param <E> the edge type
* @param <F> the face type
* @param edge an edge of the edge cycle
* @return the new face
* @throws RuntimeException if it is called with {@code null} as parameter, of if {@link de.jtem.halfedge.Edge#getNextEdge()}
* returns {@code null} for some edge in the edge cycle, or if {@link de.jtem.halfedge.Edge#getLeftFace} is not {@code null} for some
* edge in the cycle.
*/
static public <V extends Vertex<V,E,F>,E extends Edge<V,E,F>, F extends Face<V,E,F>> F fillHole(E edge) throws RuntimeException {
// System.err.println("fillHole(" + edge + ")");
List<E> edgeList = new ArrayList<E>();
E e = edge;
do {
if (e == null) {
throw new RuntimeException("Method must not be called with null as parameter.");
}
if (e.getLeftFace() != null) {
throw new RuntimeException(edge + " has a non-null left face. Null expected.");
}
edgeList.add(e);
e = e.getNextEdge();
} while (e != edge);
F f = edge.getHalfEdgeDataStructure().addNewFace();
// System.err.print("\tgluing " + f + " to ");
for (E ee : edgeList) {
// System.err.print(ee + " ");
ee.setLeftFace(f);
}
// System.err.println();
return f;
}
/**
* Fill all holes by adding faces.
* <p>
* Simply calls {@link #fillHole(Edge)} on edges with no left face until all edges have a left face.
* Hence, the preconditions described there apply.
*
* @param heds
*/
static public <V extends Vertex<V,E,F>,
E extends Edge<V,E,F>,
F extends Face<V,E,F>> void fillAllHoles(HalfEdgeDataStructure<V,E,F> heds) {
for (E e : heds.getEdges()) {
if (e.getLeftFace() == null) {
fillHole(e);
}
}
}
/**
* Add a new n-gon.
* <p>
* Increases the number of faces by 1, the number of edges by 2*n, and the number of vertices by n.
* @param <V> the vertex type
* @param <E> the edge type
* @param <F> the face type
* @param heds the half-edge data structure
* @param n the number of vertices
* @return the new face
*/
static public <V extends Vertex<V,E,F>,E extends Edge<V,E,F>, F extends Face<V,E,F>> F addNGon(HalfEdgeDataStructure<V,E,F> heds, int n) {
List<E> edges = heds.addNewEdges(n);
List<E> oppositeEdges = heds.addNewEdges(n);
List<V> vertices = heds.addNewVertices(n);
F face = heds.addNewFace();
for (int i = 0; i < n; i++) {
int iPlus1 = (i + 1) % n;
E eI = edges.get(i);
E eIPlus1 = edges.get(iPlus1);
E eOppI = oppositeEdges.get(i);
E eOppIPlus1 = oppositeEdges.get(iPlus1);
V vI = vertices.get(i);
eI.linkOppositeEdge(eOppI);
eI.linkNextEdge(eIPlus1);
eOppI.linkPreviousEdge(eOppIPlus1);
eI.setLeftFace(face);
eI.setTargetVertex(vI);
eOppIPlus1.setTargetVertex(vI);
}
return face;
}
/**
* Find an edge with given start and target vertices.
* <p>
* Uses {@link #incomingEdges(Vertex)}, so the preconditions explained there apply.
* @param <V> the vertex type
* @param <E> the edge type
* @param startVertex the start vertex
* @param targetVertex the target vertex
* @return an edge with those vertices as start and target vertices, or {@code null} if no such edge exists.
*/
static public <V extends Vertex<V,E,?>,E extends Edge<V,E,?>> E findEdgeBetweenVertices(V startVertex, V targetVertex) {
for (E e : incomingEdges(targetVertex)) {
if (startVertex == e.getStartVertex()) {
return e;
}
}
return null;
}
/**
* Find an edge with given left and right faces.
* <p>
* Uses {@link #boundaryEdges(Face)}, so the preconditions explained there apply.
* @param <E> the edge type
* @param <F> the face type
* @param leftFace the left face
* @param rightFace the right face
* @return an edge with those faces as left and right face, or {@code null} if no such edge exists.
*/
static public <E extends Edge<?,E,F>, F extends Face<?,E,F>> E findEdgeBetweenFaces(F leftFace, F rightFace) {
for (E e : boundaryEdges(leftFace)) {
if (rightFace == e.getRightFace()) {
return e;
}
}
return null;
}
/**
* Construct a new face by giving its vertices in cyclic order.
* <p>
* This method assumes:<br>
* <ul>
* <li>At least three non-null vertices are passed as parameters.</li>
* <li>They belong to the {@link de.jtem.halfedge.HalfEdgeDataStructure HalfEdgeDataStructure} {@code heds}.</li>
* <li>Except for isolated vertices and missing faces, {@code heds} is a valid surface or empty. More precisely: If all vertices {@code v} with
* {@code v.}{@link de.jtem.halfedge.Vertex#getIncomingEdge() getIncomingEdge()}{@code == null}
* were removed from {@code heds}, and after executing {@link #fillAllHoles(HalfEdgeDataStructure) fillAllHoles(heds)}, {@code heds} would be empty or a
* {@linkplain de.jtem.halfedge.HalfEdgeDataStructure#isValidSurface() valid surface}.</li>
* <li>There are no loops or double edges in {@code heds}. More precisely: If {@code v0} and {@code v1} are vertices of {@code heds}
* (where {@code v0 == v1} is allowed) then there is at most one {@link de.jtem.halfedge.Edge Edge} with start vertex {@code v0}
* and target vertex {@code v1}.</li>
* <li>Adding a face with the given vertices will result in a {@link de.jtem.halfedge.HalfEdgeDataStructure HalfEdgeDataStructure}
* without loops or double edges, which is again valid surface except for isolated vertices and missing faces. </li>
* </ul>
* <p>
* Failure of this method is not atomic: If it throws an exception, the half-edge data structure may be left in some intermediate state.
* @param <V> the vertex type
* @param <E> the edge type
* @param <F> the face type
* @param heds the half-edge data structure
* @param v the vertices
* @return an edge with the new face as left face
* @throws RuntimeException in some cases when something goes wrong. Of course, this should not happen if the above preconditions are fulfilled.
*/
static public <V extends Vertex<V,E,F>, E extends Edge<V,E,F>, F extends Face<V,E,F>>
E constructFaceByVertices(HalfEdgeDataStructure<V,E,F> heds, Vertex<?,?,?>... v) throws RuntimeException {
// System.err.print("constructFaceByVertices(");
// for (int i = 0; i < v.length; i ++) {
// System.err.print(v[i] + " ");
// System.err.println(")");
if (heds == null) {
throw new RuntimeException("Null may not be passed as HalfEdgeDataStructure argument.");
}
if (v.length < 3) {
throw new RuntimeException("At least three vertices must be passed as arguments.");
}
// if (v[0] == null) {
// throw new RuntimeException("Null elements are not allowed as vertex arguments.");
// HalfEdgeDataStructure<V,E,F> heds = v[0].getHalfEdgeDataStructure();
for (int i = 0; i < v.length; i++) {
if (v[i] == null) {
throw new RuntimeException("Null elements are not allowed in the vertex argument list.");
}
if (v[i].getHalfEdgeDataStructure() != heds) {
throw new RuntimeException(v[i] + " doesn't belong to " + heds + ".");
}
}
Class<V> vClass = heds.getVertexClass();
int numOldEdges = heds.numEdges();
List<E> edgeCycle = new ArrayList<E>();
for (int i = 0; i < v.length; i++) {
E e = findEdgeBetweenVertices(vClass.cast(v[i]), vClass.cast(v[(i+1) % v.length]));
if (e == null) {
// make a new pair of half-edges
// System.err.println("\tCreating edge pair from " + v[i] + " to " + v[(i+1) % v.length]);
e = heds.addNewEdge();
E eOpp = heds.addNewEdge();
e.linkOppositeEdge(eOpp);
} else {
if (e.getOppositeEdge() == null) {
throw new RuntimeException(e + " has no opposite edge.");
}
if (e.getLeftFace() != null) {
throw new RuntimeException("There already is an edge from " + e.getStartVertex() + " to " + e.getTargetVertex()
+ " with " + e.getLeftFace() + " as left face.");
}
}
edgeCycle.add(e);
}
int n = edgeCycle.size();
for (int i0 = 0; i0 < n; i0++) {
int i1 = (i0 + 1) % n;
E e0 = edgeCycle.get(i0);
E e1 = edgeCycle.get(i1);
// V v0 = v[i0];
V v1 = vClass.cast(v[i1]);
if (e0.getIndex() >= numOldEdges) {
if (e1.getIndex() >= numOldEdges) {
// e0 and e1 are new
e0.linkNextEdge(e1);
e1.getOppositeEdge().linkNextEdge(e0.getOppositeEdge());
e0.setTargetVertex(v1);
e1.getOppositeEdge().setTargetVertex(v1);
} else {
// e0 is new, e1 is old
E oldPrevEdge = e1.getPreviousEdge();
e0.linkNextEdge(e1);
oldPrevEdge.linkNextEdge(e0.getOppositeEdge());
e0.setTargetVertex(v1);
}
} else {
if (e1.getIndex() >= numOldEdges) {
// e0 is old, e1 is new
E oldNextEdge = e0.getNextEdge();
e0.linkNextEdge(e1);
e1.getOppositeEdge().linkNextEdge(oldNextEdge);
e1.getOppositeEdge().setTargetVertex(v1);
} // else e0 and e1 are old: nothing to do
}
}
fillHole(edgeCycle.get(0));
return edgeCycle.get(0);
}
static public <V extends Vertex<V,E,F>, E extends Edge<V,E,F>, F extends Face<V,E,F>> E addTetrahedron(HalfEdgeDataStructure<V,E,F> heds) {
V v0 = heds.addNewVertex();
V v1 = heds.addNewVertex();
V v2 = heds.addNewVertex();
V v3 = heds.addNewVertex();
E eResult = constructFaceByVertices(heds, v0, v1, v2);
constructFaceByVertices(heds, v1, v0, v3);
constructFaceByVertices(heds, v2, v1, v3);
constructFaceByVertices(heds, v0, v2, v3);
return eResult;
}
static public <V extends Vertex<V,E,F>, E extends Edge<V,E,F>, F extends Face<V,E,F>> E addCube(HalfEdgeDataStructure<V,E,F> heds) {
V v0 = heds.addNewVertex();
V v1 = heds.addNewVertex();
V v2 = heds.addNewVertex();
V v3 = heds.addNewVertex();
V v4 = heds.addNewVertex();
V v5 = heds.addNewVertex();
V v6 = heds.addNewVertex();
V v7 = heds.addNewVertex();
E eResult = constructFaceByVertices(heds, v0, v1, v2, v3);
constructFaceByVertices(heds, v0, v4, v5, v1);
constructFaceByVertices(heds, v1, v5, v6, v2);
constructFaceByVertices(heds, v2, v6, v7, v3);
constructFaceByVertices(heds, v3, v7, v4, v0);
constructFaceByVertices(heds, v7, v6, v5, v4);
return eResult;
}
static public <V extends Vertex<V,E,F>, E extends Edge<V,E,F>, F extends Face<V,E,F>> E addOctahedron(HalfEdgeDataStructure<V,E,F> heds) {
V v0 = heds.addNewVertex();
V v1 = heds.addNewVertex();
V v2 = heds.addNewVertex();
V v3 = heds.addNewVertex();
V v4 = heds.addNewVertex();
V v5 = heds.addNewVertex();
E eResult = constructFaceByVertices(heds, v0, v1, v2);
constructFaceByVertices(heds, v0, v2, v3);
constructFaceByVertices(heds, v0, v3, v4);
constructFaceByVertices(heds, v0, v4, v1);
constructFaceByVertices(heds, v2, v1, v5);
constructFaceByVertices(heds, v3, v2, v5);
constructFaceByVertices(heds, v4, v3, v5);
constructFaceByVertices(heds, v1, v4, v5);
return eResult;
}
static public <V extends Vertex<V,E,F>, E extends Edge<V,E,F>, F extends Face<V,E,F>> E addDodecahedron(HalfEdgeDataStructure<V,E,F> heds) {
V v0 = heds.addNewVertex();
V v1 = heds.addNewVertex();
V v2 = heds.addNewVertex();
V v3 = heds.addNewVertex();
V v4 = heds.addNewVertex();
V v5 = heds.addNewVertex();
V v6 = heds.addNewVertex();
V v7 = heds.addNewVertex();
V v8 = heds.addNewVertex();
V v9 = heds.addNewVertex();
V v10 = heds.addNewVertex();
V v11 = heds.addNewVertex();
V v12 = heds.addNewVertex();
V v13 = heds.addNewVertex();
V v14 = heds.addNewVertex();
V v15 = heds.addNewVertex();
V v16 = heds.addNewVertex();
V v17 = heds.addNewVertex();
V v18 = heds.addNewVertex();
V v19 = heds.addNewVertex();
E eResult = constructFaceByVertices(heds, v0, v1, v2, v3, v4);
constructFaceByVertices(heds, v0, v5, v10, v6, v1);
constructFaceByVertices(heds, v1, v6, v11, v7, v2);
constructFaceByVertices(heds, v2, v7, v12, v8, v3);
constructFaceByVertices(heds, v3, v8, v13, v9, v4);
constructFaceByVertices(heds, v4, v9, v14, v5, v0);
constructFaceByVertices(heds, v14, v15, v16, v10, v5);
constructFaceByVertices(heds, v10, v16, v17, v11, v6);
constructFaceByVertices(heds, v11, v17, v18, v12, v7);
constructFaceByVertices(heds, v12, v18, v19, v13, v8);
constructFaceByVertices(heds, v13, v19, v15, v14, v9);
constructFaceByVertices(heds, v19, v18, v17, v16, v15);
return eResult;
}
static public <V extends Vertex<V,E,F>, E extends Edge<V,E,F>, F extends Face<V,E,F>> E addIcosahedron(HalfEdgeDataStructure<V,E,F> heds) {
V v0 = heds.addNewVertex();
V v1 = heds.addNewVertex();
V v2 = heds.addNewVertex();
V v3 = heds.addNewVertex();
V v4 = heds.addNewVertex();
V v5 = heds.addNewVertex();
V v6 = heds.addNewVertex();
V v7 = heds.addNewVertex();
V v8 = heds.addNewVertex();
V v9 = heds.addNewVertex();
V v10 = heds.addNewVertex();
V v11 = heds.addNewVertex();
E eResult = constructFaceByVertices(heds, v0, v1, v2);
constructFaceByVertices(heds, v0, v2, v3);
constructFaceByVertices(heds, v0, v3, v4);
constructFaceByVertices(heds, v0, v4, v5);
constructFaceByVertices(heds, v0, v5, v1);
constructFaceByVertices(heds, v2, v1, v7);
constructFaceByVertices(heds, v3, v2, v6);
constructFaceByVertices(heds, v4, v3, v10);
constructFaceByVertices(heds, v5, v4, v9);
constructFaceByVertices(heds, v1, v5, v8);
constructFaceByVertices(heds, v1, v8, v7);
constructFaceByVertices(heds, v2, v7, v6);
constructFaceByVertices(heds, v3, v6, v10);
constructFaceByVertices(heds, v4, v10, v9);
constructFaceByVertices(heds, v5, v9, v8);
constructFaceByVertices(heds, v7, v8, v11);
constructFaceByVertices(heds, v6, v7, v11);
constructFaceByVertices(heds, v10, v6, v11);
constructFaceByVertices(heds, v9, v10, v11);
constructFaceByVertices(heds, v8, v9, v11);
return eResult;
}
/**
* Calculates the genus of the 2-manifold represented
* by the given HalfedgeDataDtructure by evaluating
* X = hds.numVertices() - hds.numEdges() / 2 + hds.numFaces()
* r = number of boundary components
* g = (2 - X - r) / 2
* @param hds a 2-manifold
* @return g
*/
public static int getGenus(HalfEdgeDataStructure<?, ?, ?> hds) {
int r = boundaryComponents(hds).size();
int X = hds.numVertices() - hds.numEdges() / 2 + hds.numFaces();
return (2 - X - r) / 2;
}
/**
* Returns true if the neighborhood of this vertex is homeomorphic
* either to R2 or to a half-space
* @param v the vertex
* @return
*/
public static <
V extends Vertex<V,E,F>,
E extends Edge<V,E,F>,
F extends Face<V,E,F>
> boolean isManifoldVertex(V v) {
int bc = 0;
for (E e : incomingEdges(v)) {
if (e.getLeftFace() == null) {
bc++;
}
}
return bc <= 1;
}
/**
* Inserts the nodes of src into dst
* @param src
* @param dst
* @return The vertex offset of the new vertices in dst
*/
public static <
V extends Vertex<V,E,F>,
E extends Edge<V,E,F>,
F extends Face<V,E,F>,
HDSSRC extends HalfEdgeDataStructure<V, E, F>,
VV extends Vertex<VV,EE,FF>,
EE extends Edge<VV,EE,FF>,
FF extends Face<VV,EE,FF>,
HDSDST extends HalfEdgeDataStructure<VV, EE, FF>
> int copy(HDSSRC src, HDSDST dst) {
Set<E> srcEdges = new HashSet<E>(src.getEdges());
int vOffset = dst.numVertices();
int eOffset = dst.numEdges();
int fOffset = dst.numFaces();
dst.addNewVertices(src.numVertices());
dst.addNewEdges(src.numEdges());
dst.addNewFaces(src.numFaces());
for (E e : srcEdges) {
E eNext = e.getNextEdge();
E eOpp = e.getOppositeEdge();
F f = e.getLeftFace();
V v = e.getTargetVertex();
EE ee = dst.getEdge(eOffset + e.getIndex());
ee.setIsPositive(e.isPositive());
if (eNext != null) {
ee.linkNextEdge(dst.getEdge(eOffset + eNext.getIndex()));
}
if (eOpp != null) {
ee.linkOppositeEdge(dst.getEdge(eOffset + eOpp.getIndex()));
}
if (f != null) {
ee.setLeftFace(dst.getFace(fOffset + f.getIndex()));
}
if (v != null) {
ee.setTargetVertex(dst.getVertex(vOffset + v.getIndex()));
}
}
return vOffset;
}
}
|
package nachos.threads;
import java.util.LinkedList;
import java.util.Iterator;
import nachos.ag.BoatGrader;
import nachos.machine.*; // for Lib.assertTrue()
public class Boat
{
static BoatGrader bg;
// define two location
static final int Oahu = 0;
static final int Molokai = 1;
static int boatLocation = Oahu; // where is the boat
static int cntPassengers = 0;
static Lock boatLock = new Lock(); // boat holds a lock
static Condition2 waitingOnOahu = new Condition2(boatLock);
static Condition2 waitingOnMolokai = new Condition2(boatLock);
static Condition2 waitingOnBoatFull = new Condition2(boatLock);
static int OahuChildren = 0;
static int OahuAdults = 0;
static int MolokaiChildren = 0;
static int MolokaiAdults = 0;
static Communicator reporter = new Communicator();
public static void selfTest()
{
BoatGrader b = new BoatGrader();
System.out.println("\n***Testing Boats with VARs***");
// begin(0, 2, b);
// Var1: just one child
// expected result: OK
// begin(0, 1, b);
// Var2: two child
// expected result: OK
// begin(0, 2, b);
// Var3: three child
// expected result: OK
// begin(0, 3, b);
// Var4: one adult
// expected result: Failed
// begin(1, 0, b);
// Var5: one adult, one child
// expected result: Failed
// begin(1, 1, b);
// Var6: one adult, two child
// expected result: OK
// begin(1, 2, b);
// Var7: one adult, three child
// expected result: OK
// begin(1, 3, b);
// Var8: two adult, two child
// expected result: OK
// begin(2, 2, b);
// Var9: two adult, two child
// expected result: OK
// begin(3, 2, b);
// Var10: lots of adult, two child
// expected result: OK
// begin(10, 2, b);
// Var11: lots of adult, lots of child
// expected result: OK
// begin(10, 20, b);
// Var12: stress testing
// expected result: OK
begin(100, 50, b);
/*
begin(2, 2, b);
begin(3, 2, b);
begin(4, 2, b);
begin(1, 3, b);
begin(2, 3, b);
begin(3, 3, b);
begin(4, 3, b);
*/
// begin(1, 2, b);
// begin(3, 3, b);
}
public static void begin( int adults, int children, BoatGrader b)
{
// Store the externally generated autograder in a class
// variable to be accessible by children.
bg = b;
// Initialize counters
OahuChildren = children;
OahuAdults = adults;
MolokaiChildren = 0;
MolokaiAdults = 0;
// Instantiate global variables here
// Create threads here. See section 3.4 of the Nachos for Java
// Walkthrough linked from the projects page.
Runnable r_child = new Runnable() {
public void run() {
int location = Oahu; // thread local varialbe, indicate where person is
ChildItinerary(location);
};
};
Runnable r_adult = new Runnable() {
public void run() {
int location = Oahu; // thread local varialbe, indicate where person is
AdultItinerary(location);
};
};
for (int i = 0; i < children; i++) {
KThread t = new KThread(r_child);
t.setName("Boat Thread - Child -
t.fork();
}
for (int i = 0; i < adults; i++) {
KThread t = new KThread(r_adult);
t.setName("Boat Thread - Adult -
t.fork();
}
while(true)
{
int recv = reporter.listen();
System.out.println("***** Receive " + recv);
if (recv == children + adults)
{
break;
}
}
}
static void ChildItinerary(int location)
{
System.out.println("***** ChildItinerary, place: " + location);
boatLock.acquire();
while (true) {
// below block is to cheat Java compiler, otherwise the code doesn't compile
if (location == 12345678)
{
// unreachable path
Lib.assertTrue(false);
break; // ploace a break to cheat JAVA compiler
}
if (location == Oahu)
{
// wait until boat's arrival and available seat on boat
// if only one child left in Oahu, adults go first
while (boatLocation != Oahu || cntPassengers >= 2
|| (OahuAdults > 0 && OahuChildren == 1) )
{
waitingOnOahu.sleep();
}
waitingOnOahu.wakeAll();
// if no adult and only one child left in Oahu, the child row to Molokai directly
if (OahuAdults == 0 && OahuChildren == 1)
{
OahuChildren
bg.ChildRowToMolokai();
boatLocation = Molokai;
location = Molokai;
MolokaiChildren++;
// clear passenger number after arrival
cntPassengers = 0;
// collate the number of people in Molokai
reporter.speak(MolokaiChildren+MolokaiAdults);
// child arrives in Molokai, to wake up one person in Molokai
// at this point, all the persons should be on Molokai
// waitingOnMolokai.wakeAll();
// current child is sleeping in Molokai
waitingOnMolokai.sleep();
}
else if (OahuChildren > 1) // send children to Molokai first
{
// book the seat on boat
cntPassengers++;
// two children on boat, the second child rides to Molokai
if (cntPassengers == 2)
{
// notify the fisrt guy to row to Molokai
waitingOnBoatFull.wake();
waitingOnBoatFull.sleep();
// then ride myself to Molokai
OahuChildren
bg.ChildRideToMolokai();
// all the children get off boat, decrease passenger number
cntPassengers = cntPassengers - 2;
// note, now boat arrives on Molokai
boatLocation = Molokai;
location = Molokai;
MolokaiChildren++;
reporter.speak(MolokaiChildren+MolokaiAdults);
// two children arrive in Molokai, wake up one child in Molokai
waitingOnMolokai.wakeAll();
// current child is sleeping
waitingOnMolokai.sleep();
}
// the first passenger(pilot) rows to Molokai
else if (cntPassengers == 1)
{
// only one child on boat, wait for next child(passenger) coming
waitingOnBoatFull.sleep();
OahuChildren
bg.ChildRowToMolokai();
location = Molokai;
MolokaiChildren++;
// notify another passenger on baord to leave
waitingOnBoatFull.wake();
// current child is sleeping
waitingOnMolokai.sleep();
}
} // if OahuChildren > 1
}
else if (location == Molokai)
{
Lib.assertTrue(MolokaiChildren > 0);
while (boatLocation != Molokai)
{
waitingOnMolokai.sleep();
}
// note, just need one child pilot back to Oahu
MolokaiChildren
bg.ChildRowToOahu();
boatLocation = Oahu;
location = Oahu;
OahuChildren++;
waitingOnOahu.wakeAll();
waitingOnOahu.sleep();
}
} // while (true)
boatLock.release();
}
static void AdultItinerary(int location)
{
boatLock.acquire();
while (true)
{
if (location == Oahu)
{
// child first, then send adults to Molokai
// but leave one child in Oahu
while (cntPassengers > 0
|| OahuChildren > 1 || boatLocation != Oahu)
{
waitingOnOahu.sleep();
}
bg.AdultRowToMolokai();
OahuAdults
boatLocation = Molokai;
MolokaiAdults++;
location = Molokai;
reporter.speak(MolokaiChildren+MolokaiAdults);
Lib.assertTrue(MolokaiChildren > 0);
// adult arrive in Molokai, wake up one child in Molokai
waitingOnMolokai.wakeAll();
// current adult is sleeping
waitingOnMolokai.sleep();
}
else if (location == Molokai)
{
waitingOnMolokai.sleep();
}
else
{
// unreachable path
Lib.assertTrue(false);
break; // ploace a break to cheat JAVA compiler
}
}
boatLock.release();
}
static void SampleItinerary()
{
// Please note that this isn't a valid solution (you can't fit
// all of them on the boat). Please also note that you may not
// have a single thread calculate a solution and then just play
// it back at the autograder -- you will be caught.
System.out.println("\n ***Everyone piles on the boat and goes to Molokai***");
bg.AdultRowToMolokai();
bg.ChildRideToMolokai();
bg.AdultRideToMolokai();
bg.ChildRideToMolokai();
}
}
|
package org.commcare.utils;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import android.webkit.MimeTypeMap;
import org.commcare.core.network.AuthenticationInterceptor;
import org.commcare.network.CommcareRequestGenerator;
import org.commcare.network.EncryptedFileBody;
import org.commcare.tasks.DataSubmissionListener;
import org.commcare.util.LogTypes;
import org.commcare.xml.CommCareElementParser;
import org.javarosa.core.io.StreamsUtil;
import org.javarosa.core.io.StreamsUtil.InputIOException;
import org.javarosa.core.model.User;
import org.javarosa.core.services.Logger;
import org.javarosa.xml.ElementParser;
import org.javarosa.xml.util.InvalidStructureException;
import org.javarosa.xml.util.UnfullfilledRequirementsException;
import org.kxml2.io.KXmlParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.UnknownHostException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Response;
public class FormUploadUtil {
private static final String TAG = FormUploadUtil.class.getSimpleName();
/**
* 15 MB size limit
*/
public static final long MAX_BYTES = (15 * 1048576) - 1024;
private static final String[] SUPPORTED_FILE_EXTS =
{".xml", ".jpg", "jpeg", ".3gpp", ".3gp", ".3ga", ".3g2", ".mp3",
".wav", ".amr", ".mp4", ".3gp2", ".mpg4", ".mpeg4",
".m4v", ".mpg", ".mpeg", ".qcp", ".ogg"};
public static Cipher getDecryptCipher(SecretKeySpec key) {
Cipher cipher;
try {
cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, key);
return cipher;
//TODO: Something smart here;
} catch (NoSuchAlgorithmException |
NoSuchPaddingException | InvalidKeyException e) {
e.printStackTrace();
}
return null;
}
/**
* Send unencrypted data to the server without user facing progress
* reporting.
*
* @param submissionNumber For progress reporting
* @param folder All supported files in this folder will be
* attached to the submission
* @param url Submission server url
* @param user Used to build the http post
* @return Submission status code
* @throws FileNotFoundException Is raised if xml file isn't found on the
* file-system
*/
public static FormUploadResult sendInstance(int submissionNumber, File folder,
String url, User user)
throws FileNotFoundException {
return sendInstance(submissionNumber, folder, null, url, null, user);
}
/**
* Send data to the server, encrypting xml files and reporting progress
* along the way.
*
* @param submissionNumber For progress reporting
* @param folder All supported files in this folder will be
* attached to the submission
* @param key For encrypting xml files
* @param url Submission server url
* @param listener Used to report progress to the calling task
* @param user Used to build the http post
* @return Submission status code
* @throws FileNotFoundException Is raised if xml file isn't found on the
* file-system
*/
public static FormUploadResult sendInstance(int submissionNumber, File folder,
SecretKeySpec key, String url,
AsyncTask listener, User user)
throws FileNotFoundException {
boolean hasListener = false;
DataSubmissionListener myListener = null;
if (listener instanceof DataSubmissionListener) {
hasListener = true;
myListener = (DataSubmissionListener)listener;
}
File[] files = folder.listFiles();
if (files == null) {
// make sure external storage is available to begin with.
String state = Environment.getExternalStorageState();
if (!Environment.MEDIA_MOUNTED.equals(state)) {
// If so, just bail as if the user had logged out.
throw new SessionUnavailableException("External Storage Removed");
} else {
throw new FileNotFoundException("No directory found at: " +
folder.getAbsoluteFile());
}
}
// If we're listening, figure out how much (roughly) we have to send
long bytes = estimateUploadBytes(files);
if (hasListener) {
myListener.startSubmission(submissionNumber, bytes);
}
if (files.length == 0) {
Log.e(TAG, "no files to upload");
listener.cancel(true);
throw new FileNotFoundException("Folder at path " + folder.getAbsolutePath() + " had no files.");
}
List<MultipartBody.Part> parts = new ArrayList<>();
if (!buildMultipartEntity(parts, key, files)) {
return FormUploadResult.RECORD_FAILURE;
}
CommcareRequestGenerator generator = new CommcareRequestGenerator(user);
return submitEntity(parts, url, generator);
}
/**
* Submit multipart entity with plenty of logging
*
* @return submission status of multipart entity post
*/
private static FormUploadResult submitEntity(List<MultipartBody.Part> parts, String url,
CommcareRequestGenerator generator) {
Response<ResponseBody> response;
try {
response = generator.postMultipart(url, parts);
} catch (InputIOException ioe) {
// This implies that there was a problem with the _source_ of the
// transmission, not the processing or receiving end.
Logger.log(LogTypes.TYPE_ERROR_STORAGE,
"Internal error reading form record during submission: " +
ioe.getWrapped().getMessage());
return FormUploadResult.RECORD_FAILURE;
} catch (UnknownHostException e) {
e.printStackTrace();
Logger.log(LogTypes.TYPE_WARNING_NETWORK,
"Client network issues during submission: " + e.getMessage());
return FormUploadResult.TRANSPORT_FAILURE;
} catch (AuthenticationInterceptor.PlainTextPasswordException e) {
e.printStackTrace();
Logger.log(LogTypes.TYPE_ERROR_CONFIG_STRUCTURE,
"Encountered PlainTextPasswordException while submission: Sending password over HTTP");
return FormUploadResult.AUTH_OVER_HTTP;
} catch (IOException | IllegalStateException e) {
Logger.exception("Error reading form during submission: " + e.getMessage(), e);
return FormUploadResult.TRANSPORT_FAILURE;
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
if (response.body() != null) {
InputStream responseStream = response.body().byteStream();
StreamsUtil.writeFromInputToOutputNew(responseStream, bos);
}
} catch (IllegalStateException | IOException e) {
e.printStackTrace();
}
String responseString = new String(bos.toByteArray());
int responseCode = response.code();
logResponse(responseCode, responseString);
if (responseCode >= 200 && responseCode < 300) {
return FormUploadResult.FULL_SUCCESS;
} else if (responseCode == 401) {
return FormUploadResult.AUTH_FAILURE;
} else if (responseCode == 422) {
return handleProcessingFailure(response.errorBody().byteStream());
} else {
return FormUploadResult.FAILURE;
}
}
private static FormUploadResult handleProcessingFailure(InputStream responseStream) {
FormUploadResult result = FormUploadResult.PROCESSING_FAILURE;
try {
result.setProcessingFailureReason(parseProcessingFailureResponse(responseStream));
} catch (IOException | InvalidStructureException | XmlPullParserException |
UnfullfilledRequirementsException e) {
// If we can't parse out the failure reason then we won't quarantine this form, because
// we won't have any clear info about what happened
result = FormUploadResult.FAILURE;
Logger.exception(e);
e.printStackTrace();
}
return result;
}
private static void logResponse(int responseCode, String responseString) {
String responseCodeMessage = "Response code to form submission attempt was: " + responseCode;
Log.e(TAG, responseCodeMessage);
Log.d(TAG, responseString);
if (!(responseCode >= 200 && responseCode < 300)) {
Logger.log(LogTypes.TYPE_WARNING_NETWORK, responseCodeMessage);
Logger.log(LogTypes.TYPE_FORM_SUBMISSION, responseCodeMessage);
Logger.log(LogTypes.TYPE_FORM_SUBMISSION,
"Response string to failed form submission attempt was: " + responseString);
}
}
/**
* Validate the content body of the XML submission file.
*
* TODO: this should really be the responsibility of the form record, not
* of the submission process, persay.
*
* NOTE: this is a shallow validation (everything should be more or else
* constant time). Throws an exception if the file is gone because that's
* a common issue that gets caught to check if storage got removed
*
* @param f xml file to check
* @return false if the file is empty; otherwise true
* @throws FileNotFoundException file in question isn't found on the
* file-system
*/
private static boolean validateSubmissionFile(File f)
throws FileNotFoundException {
if (!f.exists()) {
throw new FileNotFoundException("Submission file: " +
f.getAbsolutePath());
}
// Gotta check f exists here since f.length returns 0 if the file isn't
// there for some reason.
if (f.length() == 0 && f.exists()) {
Logger.log(LogTypes.TYPE_ERROR_STORAGE,
"Submission body has no content at: " + f.getAbsolutePath());
return false;
}
return true;
}
/**
* @return The aggregated size in bytes the files of supported extension
* type.
*/
private static long estimateUploadBytes(File[] files) {
long bytes = 0;
for (File file : files) {
// Make sure we'll be sending it
if (!isSupportedMultimediaFile(file.getName())) {
continue;
}
bytes += file.length();
Log.d(TAG, "Added file: " + file.getName() +
". Bytes to send: " + bytes);
}
return bytes;
}
/**
* Add files of supported type to the multipart entity, encrypting xml
* files.
*
* @param parts Add files to this
* @param key Used to encrypt xml files
* @param files The files to be added to the entity,
* @return false if invalid xml files are found; otherwise true.
* @throws FileNotFoundException Is raised when an xml doesn't exist on the
* file-system
*/
private static boolean buildMultipartEntity(List<MultipartBody.Part> parts,
SecretKeySpec key,
File[] files)
throws FileNotFoundException {
int numAttachmentsInInstanceFolder = 0;
int numAttachmentsSuccessfullyAdded = 0;
for (File f : files) {
if (f.getName().endsWith(".xml")) {
if (key != null) {
if (!validateSubmissionFile(f)) {
return false;
}
parts.add(createEncryptedFilePart("xml_submission_file", f, "text/xml", key));
} else {
parts.add(createFilePart("xml_submission_file", f, "text/xml"));
}
} else {
String contentType = getFileContentType(f);
if (contentType != null) {
numAttachmentsInInstanceFolder++;
numAttachmentsSuccessfullyAdded += addPartToEntity(parts, f, contentType);
} else if (isSupportedMultimediaFile(f.getName())) {
numAttachmentsInInstanceFolder++;
numAttachmentsSuccessfullyAdded += addPartToEntity(parts, f, "application/octet-stream");
} else {
Logger.log(LogTypes.TYPE_FORM_SUBMISSION,
"Could not add unsupported file type to submission entity: " + f.getName());
}
}
}
Logger.log(LogTypes.TYPE_FORM_SUBMISSION, "Attempted to add "
+ numAttachmentsInInstanceFolder + " attachments to submission entity");
Logger.log(LogTypes.TYPE_FORM_SUBMISSION, "Successfully added "
+ numAttachmentsSuccessfullyAdded + " attachments to submission entity");
return true;
}
private static int addPartToEntity(List<MultipartBody.Part> parts, File f, String contentType) {
if (f.length() <= MAX_BYTES) {
parts.add(createFilePart(f.getName(), f, contentType));
return 1;
} else {
Logger.log(LogTypes.TYPE_FORM_SUBMISSION,
"Failed to add attachment to submission entity (too large): " + f.getName());
return 0;
}
}
private static String getFileContentType(File f) {
if (f.getName().endsWith(".xml")) {
return "text/xml";
} else if (f.getName().endsWith(".jpg")) {
return "image/jpeg";
} else if (f.getName().endsWith(".3gpp")) {
return "audio/3gpp";
} else if (f.getName().endsWith(".3gp")) {
return "video/3gpp";
}
return null;
}
private static MultipartBody.Part createFilePart(String partName, File file, String contentType) {
// create RequestBody instance from file
RequestBody requestFile = RequestBody.create(
MediaType.parse(contentType),
file);
// MultipartBody.Part is used to send also the actual file name
return MultipartBody.Part.createFormData(partName, file.getName(), requestFile);
}
public static MultipartBody.Part createEncryptedFilePart(String partName, File file, String contentType, SecretKeySpec key) {
// create RequestBody instance from file
RequestBody requestFile = new EncryptedFileBody(
MediaType.parse(contentType),
file,
FormUploadUtil.getDecryptCipher(key));
// MultipartBody.Part is used to send also the actual file name
return MultipartBody.Part.createFormData(partName, file.getName(), requestFile);
}
/**
* @return Is the filename's extension in the hard-coded list of supported
* files or have a media mimetype?
*/
public static boolean isSupportedMultimediaFile(String filename) {
for (String ext : SUPPORTED_FILE_EXTS) {
if (filename.endsWith(ext)) {
return true;
}
}
return isAudioVisualMimeType(filename);
}
/**
* Use the file's extension to determine if it has an audio,
* video, or image mimetype.
*
* @return true if the file has an audio, image, or video mimetype
*/
private static boolean isAudioVisualMimeType(String filename) {
MimeTypeMap mtm = MimeTypeMap.getSingleton();
String[] filenameSegments = filename.split("\\.");
if (filenameSegments.length > 1) {
// use the file extension to determine the mimetype
String ext = filenameSegments[filenameSegments.length - 1];
String mimeType = mtm.getMimeTypeFromExtension(ext);
return (mimeType != null) &&
(mimeType.startsWith("audio") ||
mimeType.startsWith("image") ||
mimeType.startsWith("video"));
}
return false;
}
public static String parseProcessingFailureResponse(InputStream responseStream)
throws IOException, InvalidStructureException, UnfullfilledRequirementsException,
XmlPullParserException {
KXmlParser baseParser = ElementParser.instantiateParser(responseStream);
ElementParser<String> responseParser = new ElementParser<String>(baseParser) {
@Override
public String parse() throws InvalidStructureException, IOException,
XmlPullParserException, UnfullfilledRequirementsException {
checkNode("OpenRosaResponse");
nextTag("message");
String natureOfResponse = parser.getAttributeValue(null, "nature");
if ("processing_failure".equals(natureOfResponse)) {
return parser.nextText();
} else {
throw new UnfullfilledRequirementsException(
"<message> for 422 response did not contain expected content",
CommCareElementParser.SEVERITY_UNKOWN);
}
}
};
return responseParser.parse();
}
}
|
package org.commcare.views;
import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Point;
import android.os.Build;
import android.support.v4.util.Pair;
import android.support.v4.widget.Space;
import android.support.v7.widget.GridLayout;
import android.text.Spannable;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;
import org.commcare.dalvik.R;
import org.commcare.models.AsyncEntity;
import org.commcare.models.Entity;
import org.commcare.suite.model.Detail;
import org.commcare.util.GridCoordinate;
import org.commcare.util.GridStyle;
import org.commcare.utils.CachingAsyncImageLoader;
import org.commcare.utils.MarkupUtil;
import org.commcare.utils.MediaUtil;
import org.commcare.views.media.AudioButton;
import org.commcare.views.media.ViewId;
import org.javarosa.core.services.Logger;
import org.javarosa.xpath.XPathUnhandledException;
import java.util.Arrays;
/**
* This class defines an individual panel within an advanced case list.
* Each panel is defined by a Detail and an Entity
* Significant axis of configuration are NUMBER_ROWS, NUMBER_COLUMNS, AND CELL_HEIGHT_DIVISOR defined below
*
* @author wspride
*/
public class EntityViewTile extends GridLayout {
private String[] searchTerms;
// All of the views that are being shown in this tile, one for each field of the entity's detail
private View[] mFieldViews;
private boolean mFuzzySearchEnabled = false;
private boolean mIsAsynchronous = false;
// load the screen-size-dependent font sizes
private final float SMALL_FONT = getResources().getDimension(R.dimen.font_size_small);
private final float MEDIUM_FONT = getResources().getDimension(R.dimen.font_size_medium);
private final float LARGE_FONT = getResources().getDimension(R.dimen.font_size_large);
private final float XLARGE_FONT = getResources().getDimension(R.dimen.font_size_xlarge);
private final float DENSITY = getResources().getDisplayMetrics().density;
private final int DEFAULT_TILE_PADDING_HORIZONTAL =
(int)getResources().getDimension(R.dimen.row_padding_horizontal);
private final int DEFAULT_TILE_PADDING_VERTICAL =
(int)getResources().getDimension(R.dimen.row_padding_vertical);
// Constants used to calibrate how many tiles should be shown on a screen at once -- This is
// saying that we expect a device with a density of 160 dpi and a height of 4 inches to look
// good in portrait mode with 4 tiles of 6 rows each being displayed at once.
private static final double DEFAULT_SCREEN_HEIGHT_IN_INCHES = 4.0;
private static final int DEFAULT_SCREEN_DENSITY = DisplayMetrics.DENSITY_MEDIUM;
private static final double DEFAULT_NUM_TILES_PER_SCREEN_PORTRAIT = 4;
private static final int DEFAULT_NUMBER_ROWS_PER_GRID = 6;
private static final double LANDSCAPE_TO_PORTRAIT_RATIO = .75;
// this is fixed for all tiles
private static final int NUMBER_COLUMNS_PER_GRID = 12;
private final int numRowsPerTile;
private final int numTilesPerRow;
private double cellWidth;
private double cellHeight;
private final CachingAsyncImageLoader mImageLoader;
private final boolean beingDisplayedInAwesomeMode;
public static EntityViewTile createTileForIndividualDisplay(Context context, Detail detail,
Entity entity) {
return new EntityViewTile(context, detail, entity, new String[0],
new CachingAsyncImageLoader(context), false, false);
}
public static EntityViewTile createTileForEntitySelectDisplay(Context context, Detail detail,
Entity entity,
String[] searchTerms,
CachingAsyncImageLoader loader,
boolean fuzzySearchEnabled,
boolean inAwesomeMode) {
return new EntityViewTile(context, detail, entity, searchTerms, loader,
fuzzySearchEnabled, inAwesomeMode);
}
private EntityViewTile(Context context, Detail detail, Entity entity, String[] searchTerms,
CachingAsyncImageLoader loader, boolean fuzzySearchEnabled,
boolean inAwesomeMode) {
super(context);
this.searchTerms = searchTerms;
this.mIsAsynchronous = entity instanceof AsyncEntity;
this.mImageLoader = loader;
this.mFuzzySearchEnabled = fuzzySearchEnabled;
this.numRowsPerTile = getMaxRows(detail);
this.numTilesPerRow = detail.getNumEntitiesToDisplayPerRow();
this.beingDisplayedInAwesomeMode = inAwesomeMode;
setEssentialGridLayoutValues();
setCellWidthAndHeight(context, detail);
addFieldViews(context, detail, entity);
}
/**
* @return the maximum height of the grid view for the given detail
*/
private static int getMaxRows(Detail detail) {
GridCoordinate[] coordinates = detail.getGridCoordinates();
int currentMaxHeight = 0;
for (GridCoordinate coordinate : coordinates) {
int yCoordinate = coordinate.getY();
int height = coordinate.getHeight();
int maxHeight = yCoordinate + height;
if (maxHeight > currentMaxHeight) {
currentMaxHeight = maxHeight;
}
}
return currentMaxHeight;
}
private void setEssentialGridLayoutValues() {
setColumnCount(NUMBER_COLUMNS_PER_GRID);
setRowCount(numRowsPerTile);
setPaddingIfNotInGridView();
}
private void setCellWidthAndHeight(Context context, Detail detail) {
Pair<Integer, Integer> tileWidthAndHeight = computeTileWidthAndHeight(context);
cellWidth = tileWidthAndHeight.first / (double)NUMBER_COLUMNS_PER_GRID;
if (detail.useUniformUnitsInCaseTile()) {
cellHeight = cellWidth;
} else {
cellHeight = tileWidthAndHeight.second / (double)numRowsPerTile;
}
}
/**
* Compute what the width and height of a single tile should be, based upon the available
* screen space, how many columns there should be, and how many rows we want to show at a time.
* Round up to the nearest integer since the GridView's width and height will ultimately be
* computed indirectly from these values, and those values need to be integers, and we don't
* want to end up cutting things off
*/
private Pair<Integer, Integer> computeTileWidthAndHeight(Context context) {
double screenWidth, screenHeight;
Display display = ((Activity)context).getWindowManager().getDefaultDisplay();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
Point size = new Point();
display.getSize(size);
screenWidth = size.x;
screenHeight = size.y;
} else {
screenWidth = display.getWidth();
screenHeight = display.getHeight();
}
if (!tileBeingShownInGridView()) {
// If we added padding, subtract that space since we can't use it
screenWidth = screenWidth - DEFAULT_TILE_PADDING_HORIZONTAL * 2;
}
int tileHeight;
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
if (beingDisplayedInAwesomeMode) {
// if in awesome mode, split available width in half
screenWidth = screenWidth / 2;
}
tileHeight = (int)Math.ceil(screenHeight / computeNumTilesPerScreen(false, screenHeight));
} else {
tileHeight = (int)Math.ceil(screenHeight / computeNumTilesPerScreen(true, screenHeight));
}
int tileWidth = (int)Math.ceil(screenWidth / numTilesPerRow);
return new Pair<>(tileWidth, tileHeight);
}
/**
* @return - The number of tiles that should be displayed on a single screen on this device,
* calibrated against our default values based upon both the screen density and the screen
* height in inches
*/
private double computeNumTilesPerScreen(boolean inPortrait, double screenHeightInPixels) {
double numTilesPerScreenPortrait = DEFAULT_NUM_TILES_PER_SCREEN_PORTRAIT *
(DEFAULT_NUMBER_ROWS_PER_GRID / (float)numRowsPerTile);
double baseNumberOfTiles;
if (inPortrait) {
baseNumberOfTiles = numTilesPerScreenPortrait;
} else {
baseNumberOfTiles = numTilesPerScreenPortrait * LANDSCAPE_TO_PORTRAIT_RATIO;
}
int screenDensity = getResources().getDisplayMetrics().densityDpi;
return (baseNumberOfTiles + getAdditionalTilesBasedOnScreenDensity(screenDensity))
* getScreenHeightMultiplier(screenDensity, screenHeightInPixels);
}
private static double getAdditionalTilesBasedOnScreenDensity(int screenDensity) {
// For every additional 160dpi from the default density, show one more tile on the screen
int defaultDensityDpi = DEFAULT_SCREEN_DENSITY;
return (screenDensity - defaultDensityDpi) / 160;
}
private static double getScreenHeightMultiplier(int screenDensity, double screenHeightInPixels) {
double screenHeightInInches = screenHeightInPixels / screenDensity;
return screenHeightInInches / DEFAULT_SCREEN_HEIGHT_IN_INCHES;
}
/**
* Add Spaces to this GridLayout to strictly enforce that Grid columns and rows stay the width/height we want
* Android GridLayout tries to be very "smart" about moving entries placed arbitrarily within the grid so that
* they look "ordered" even though this often ends up looking not how we want it. It will only make these adjustments
* to rows/columns that end up empty or near empty, so we solve this by adding spaces to every row and column.
* We just add a space of width cellWidth and height 1 to every column of the first row, and likewise a sapce of height
* cellHeight and width 1 to every row of the first column. These are then written on top of if need be.
*/
private void addBuffers(Context context) {
for (int i = 0; i < numRowsPerTile; i++) {
Spec rowSpec = GridLayout.spec(i);
Spec colSpec = GridLayout.spec(0);
GridLayout.LayoutParams mGridParams = new GridLayout.LayoutParams(rowSpec, colSpec);
mGridParams.width = 1;
mGridParams.height = (int)cellHeight;
Space mSpace = new Space(context);
mSpace.setLayoutParams(mGridParams);
this.addView(mSpace, mGridParams);
}
for (int i = 0; i < NUMBER_COLUMNS_PER_GRID; i++) {
Spec rowSpec = GridLayout.spec(0);
Spec colSpec = GridLayout.spec(i);
GridLayout.LayoutParams mGridParams = new GridLayout.LayoutParams(rowSpec, colSpec);
mGridParams.width = (int)cellWidth;
mGridParams.height = 1;
Space mSpace = new Space(context);
mSpace.setLayoutParams(mGridParams);
this.addView(mSpace, mGridParams);
}
}
/**
* Add the view for each field in the detail
*
* @param detail - the Detail describing how to display each entry
* @param entity - the Entity describing the actual data of each entry
*/
public void addFieldViews(Context context, Detail detail, Entity entity) {
this.removeAllViews();
addBuffers(context); // add spacers to enforce regularized column and row size
GridCoordinate[] coordinatesOfEachField = detail.getGridCoordinates();
String[] typesOfEachField = detail.getTemplateForms();
GridStyle[] stylesOfEachField = detail.getGridStyles();
Log.v("TempForms", "Template: " + Arrays.toString(typesOfEachField) +
" | Coords: " + Arrays.toString(coordinatesOfEachField) +
" | Styles: " + Arrays.toString(stylesOfEachField));
setPaddingIfNotInGridView();
if (tileBeingShownInGridView()) {
// Fake dividers between each square in the grid view by using contrasting
// background colors for the grid view as a whole and each element in the grid view
setBackgroundColor(Color.WHITE);
}
mFieldViews = new View[coordinatesOfEachField.length];
for (int i = 0; i < mFieldViews.length; i++) {
addFieldView(context, typesOfEachField[i], stylesOfEachField[i],
coordinatesOfEachField[i], entity.getFieldString(i), entity.getSortField(i), i);
}
}
private void addFieldView(Context context, String form,
GridStyle style, GridCoordinate coordinateData, String fieldString,
String sortField, int index) {
if (coordinatesInvalid(coordinateData)) {
return;
}
ViewId uniqueId = new ViewId(coordinateData.getX(), coordinateData.getY(), false);
GridLayout.LayoutParams gridParams = getLayoutParamsForField(coordinateData);
View view = getView(context, style, form, fieldString, uniqueId, sortField,
gridParams.width, gridParams.height);
if (!(view instanceof ImageView)) {
gridParams.height = LayoutParams.WRAP_CONTENT;
}
view.setLayoutParams(gridParams);
mFieldViews[index] = view;
this.addView(view, gridParams);
}
private GridLayout.LayoutParams getLayoutParamsForField(GridCoordinate coordinateData) {
Spec columnSpec = GridLayout.spec(coordinateData.getX(), coordinateData.getWidth());
Spec rowSpec = GridLayout.spec(coordinateData.getY(), coordinateData.getHeight());
GridLayout.LayoutParams gridParams = new GridLayout.LayoutParams(rowSpec, columnSpec);
gridParams.width = (int)Math.ceil(cellWidth * coordinateData.getWidth());
gridParams.height = (int)Math.ceil(cellHeight * coordinateData.getHeight());
return gridParams;
}
private boolean coordinatesInvalid(GridCoordinate coordinate) {
if (coordinate.getX() + coordinate.getWidth() > NUMBER_COLUMNS_PER_GRID ||
coordinate.getY() + coordinate.getHeight() > numRowsPerTile) {
Logger.log("e", "Grid entry dimensions exceed allotted sizes");
throw new XPathUnhandledException("grid coordinates out of bounds: " +
coordinate.getX() + " " + coordinate.getWidth() + ", " +
coordinate.getY() + " " + coordinate.getHeight());
}
return (coordinate.getX() < 0 || coordinate.getY() < 0);
}
/**
* Get the correct View for this particular activity.
*
* @param fieldForm either "image", "audio", or default text. Describes how this XPath result should be displayed.
* @param rowData The actual data to display, either an XPath to media or a String to display.
*/
private View getView(Context context, GridStyle style, String fieldForm, String rowData,
ViewId uniqueId, String searchField, int maxWidth, int maxHeight) {
// How the text should be aligned horizontally - left, center, or right
String horzAlign = style.getHorzAlign();
// How the text should be aligned vertically - top, center, or bottom
String vertAlign = style.getVertAlign();
View retVal;
switch (fieldForm) {
case EntityView.FORM_IMAGE:
retVal = new ImageView(context);
setScaleType((ImageView)retVal, horzAlign);
// make the image's padding proportional to its size
retVal.setPadding(maxWidth / 6, maxHeight / 6, maxWidth / 6, maxHeight / 6);
if (rowData != null && !rowData.equals("")) {
if (mImageLoader != null) {
mImageLoader.display(rowData, ((ImageView)retVal), R.drawable.info_bubble,
maxWidth, maxHeight);
} else {
Bitmap b = MediaUtil.inflateDisplayImage(getContext(), rowData,
maxWidth, maxHeight, true);
((ImageView)retVal).setImageBitmap(b);
}
}
break;
case EntityView.FORM_AUDIO:
if (rowData != null && rowData.length() > 0) {
retVal = new AudioButton(context, rowData, uniqueId, true);
} else {
retVal = new AudioButton(context, rowData, uniqueId, false);
}
break;
default:
retVal = new TextView(context);
//the html spanner currently does weird stuff like converts "a a" into "a a"
//so we've gotta mirror that for the search text. Booooo. I dunno if there's any
//other other side effects (newlines? nbsp?)
String htmlIfiedSearchField = searchField == null ? null : MarkupUtil.getSpannable(searchField).toString();
String cssid = style.getCssID();
if (cssid != null && !cssid.equals("none")) {
// user defined a style we want to use
Spannable mSpannable = MarkupUtil.getCustomSpannable(cssid, rowData);
EntityView.highlightSearches(searchTerms, mSpannable, htmlIfiedSearchField, mFuzzySearchEnabled, mIsAsynchronous);
((TextView)retVal).setText(mSpannable);
} else {
// just process inline markup
Spannable mSpannable = MarkupUtil.returnCSS(rowData);
EntityView.highlightSearches(searchTerms, mSpannable, htmlIfiedSearchField, mFuzzySearchEnabled, mIsAsynchronous);
((TextView)retVal).setText(mSpannable);
}
int gravity = 0;
// handle horizontal alignments
switch (horzAlign) {
case "center":
gravity |= Gravity.CENTER_HORIZONTAL;
break;
case "left":
gravity |= Gravity.LEFT;
break;
case "right":
gravity |= Gravity.RIGHT;
break;
}
// handle vertical alignment
switch (vertAlign) {
case "center":
gravity |= Gravity.CENTER_VERTICAL;
break;
case "top":
gravity |= Gravity.TOP;
break;
case "bottom":
gravity |= Gravity.BOTTOM;
break;
}
if (gravity != 0) {
((TextView)retVal).setGravity(gravity);
}
// handle text resizing
switch (style.getFontSize()) {
case "large":
((TextView)retVal).setTextSize(LARGE_FONT / DENSITY);
break;
case "small":
((TextView)retVal).setTextSize(SMALL_FONT / DENSITY);
break;
case "medium":
((TextView)retVal).setTextSize(MEDIUM_FONT / DENSITY);
break;
case "xlarge":
((TextView)retVal).setTextSize(XLARGE_FONT / DENSITY);
break;
}
}
return retVal;
}
private static void setScaleType(ImageView imageView, String horizontalAlignment) {
switch (horizontalAlignment) {
case "center":
imageView.setScaleType(ScaleType.CENTER_INSIDE);
break;
case "left":
imageView.setScaleType(ScaleType.FIT_START);
break;
case "right":
imageView.setScaleType(ScaleType.FIT_END);
break;
}
}
public void setSearchTerms(String[] currentSearchTerms) {
this.searchTerms = currentSearchTerms;
}
public void setTextColor(int color) {
for (View rowView : mFieldViews) {
if (rowView instanceof TextView) {
((TextView)rowView).setTextColor(color);
}
}
}
public void setTitleTextColor(int color) {
for (View rowView : mFieldViews) {
if (rowView instanceof TextView) {
((TextView)rowView).setTextColor(color);
return;
}
}
}
private boolean tileBeingShownInGridView() {
return numTilesPerRow > 1;
}
private void setPaddingIfNotInGridView() {
if (!tileBeingShownInGridView()) {
setPadding(DEFAULT_TILE_PADDING_HORIZONTAL, DEFAULT_TILE_PADDING_VERTICAL,
DEFAULT_TILE_PADDING_HORIZONTAL, DEFAULT_TILE_PADDING_VERTICAL);
}
}
}
|
package dr.app.beauti.options;
import dr.evolution.alignment.Alignment;
/**
* @author Andrew Rambaut
* @author Alexei Drummond
*/
public class DataPartition {
public DataPartition(String name, String fileName, Alignment alignment) {
this(name, fileName, alignment, -1, -1);
}
public DataPartition(String name, String fileName, Alignment alignment, int fromSite, int toSite) {
this.name = name;
this.fileName = fileName;
this.alignment = alignment;
this.coding = false;
this.fromSite = fromSite;
this.toSite = toSite;
// Patterns patterns = new Patterns(alignment);
// DistanceMatrix distances = new JukesCantorDistanceMatrix(patterns);
// meanDistance = distances.getMeanDistance();
meanDistance = 0.0;
}
public double getMeanDistance() {
return meanDistance;
}
public String getFileName() {
return fileName;
}
public Alignment getAlignment() {
return alignment;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setPartitionModel(PartitionModel model) {
this.model = model;
}
public PartitionModel getPartitionModel() {
return model;
}
public boolean isCoding() {
return coding;
}
public void setCoding(boolean coding) {
this.coding = coding;
}
public int getFromSite() {
return fromSite;
}
public int getToSite() {
return toSite;
}
public int getSiteCount() {
int from = getFromSite();
if (from < 1) {
from = 1;
}
int to = getToSite();
if (to < 1) {
to = alignment.getSiteCount();
}
return to - from + 1;
}
public String toString() {
return getName();
}
private final String fileName;
private final Alignment alignment;
private final double meanDistance;
private String name;
private boolean coding;
private int fromSite;
private int toSite;
private PartitionModel model;
}
|
package dr.evomodelxml.tree;
import dr.evolution.tree.NodeRef;
import dr.evolution.tree.Tree;
import dr.evolution.util.Date;
import dr.evolution.util.Taxon;
import dr.evolution.util.TimeScale;
import dr.evomodel.tree.TreeModel;
import dr.inference.model.Parameter;
import dr.inference.model.ParameterParser;
import dr.xml.*;
import java.util.logging.Logger;
/**
* @author Alexei Drummond
*/
public class TreeModelParser extends AbstractXMLObjectParser {
public static final String ROOT_HEIGHT = "rootHeight";
public static final String LEAF_HEIGHT = "leafHeight";
public static final String LEAF_TRAIT = "leafTrait";
public static final String NODE_HEIGHTS = "nodeHeights";
public static final String NODE_RATES = "nodeRates";
public static final String NODE_TRAITS = "nodeTraits";
public static final String MULTIVARIATE_TRAIT = "traitDimension";
public static final String INITIAL_VALUE = "initialValue";
public static final String ROOT_NODE = "rootNode";
public static final String INTERNAL_NODES = "internalNodes";
public static final String LEAF_NODES = "leafNodes";
public static final String FIRE_TREE_EVENTS = "fireTreeEvents";
public static final String TAXON = "taxon";
public static final String NAME = "name";
public TreeModelParser() {
rules = new XMLSyntaxRule[]{
new ElementRule(Tree.class),
new ElementRule(ROOT_HEIGHT, Parameter.class, "A parameter definition with id only (cannot be a reference!)", false),
new ElementRule(NODE_HEIGHTS,
new XMLSyntaxRule[]{
AttributeRule.newBooleanRule(ROOT_NODE, true, "If true the root height is included in the parameter"),
AttributeRule.newBooleanRule(INTERNAL_NODES, true, "If true the internal node heights (minus the root) are included in the parameter"),
new ElementRule(Parameter.class, "A parameter definition with id only (cannot be a reference!)")
}, 1, Integer.MAX_VALUE),
new ElementRule(LEAF_HEIGHT,
new XMLSyntaxRule[]{
AttributeRule.newStringRule(TAXON, false, "The name of the taxon for the leaf"),
new ElementRule(Parameter.class, "A parameter definition with id only (cannot be a reference!)")
}, 0, Integer.MAX_VALUE),
new ElementRule(NODE_TRAITS,
new XMLSyntaxRule[]{
AttributeRule.newStringRule(NAME, false, "The name of the trait attribute in the taxa"),
AttributeRule.newBooleanRule(ROOT_NODE, true, "If true the root trait is included in the parameter"),
AttributeRule.newBooleanRule(INTERNAL_NODES, true, "If true the internal node traits (minus the root) are included in the parameter"),
AttributeRule.newBooleanRule(LEAF_NODES, true, "If true the leaf node traits are included in the parameter"),
AttributeRule.newIntegerRule(MULTIVARIATE_TRAIT, true, "The number of dimensions (if multivariate)"),
AttributeRule.newDoubleRule(INITIAL_VALUE, true, "The initial value(s)"),
AttributeRule.newBooleanRule(FIRE_TREE_EVENTS, true, "Whether to fire tree events if the traits change"),
new ElementRule(Parameter.class, "A parameter definition with id only (cannot be a reference!)")
}, 0, Integer.MAX_VALUE),
new ElementRule(NODE_RATES,
new XMLSyntaxRule[]{
AttributeRule.newBooleanRule(ROOT_NODE, true, "If true the root rate is included in the parameter"),
AttributeRule.newBooleanRule(INTERNAL_NODES, true, "If true the internal node rate (minus the root) are included in the parameter"),
AttributeRule.newBooleanRule(LEAF_NODES, true, "If true the leaf node rate are included in the parameter"),
AttributeRule.newDoubleRule(INITIAL_VALUE, true, "The initial value(s)"),
new ElementRule(Parameter.class, "A parameter definition with id only (cannot be a reference!)")
}, 0, Integer.MAX_VALUE),
new ElementRule(LEAF_TRAIT,
new XMLSyntaxRule[]{
AttributeRule.newStringRule(TAXON, false, "The name of the taxon for the leaf"),
AttributeRule.newStringRule(NAME, false, "The name of the trait attribute in the taxa"),
new ElementRule(Parameter.class, "A parameter definition with id only (cannot be a reference!)")
}, 0, Integer.MAX_VALUE)
};
}
public String getParserName() {
return TreeModel.TREE_MODEL;
}
/**
* @return a tree object based on the XML element it was passed.
*/
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
Tree tree = (Tree) xo.getChild(Tree.class);
TreeModel treeModel = new TreeModel(xo.getId(), tree);
Logger.getLogger("dr.evomodel").info("Creating the tree model, '" + xo.getId() + "'");
for (int i = 0; i < xo.getChildCount(); i++) {
if (xo.getChild(i) instanceof XMLObject) {
XMLObject cxo = (XMLObject) xo.getChild(i);
if (cxo.getName().equals(ROOT_HEIGHT)) {
ParameterParser.replaceParameter(cxo, treeModel.getRootHeightParameter());
} else if (cxo.getName().equals(LEAF_HEIGHT)) {
String taxonName;
if (cxo.hasAttribute(TAXON)) {
taxonName = cxo.getStringAttribute(TAXON);
} else {
throw new XMLParseException("taxa element missing from leafHeight element in treeModel element");
}
int index = treeModel.getTaxonIndex(taxonName);
if (index == -1) {
throw new XMLParseException("taxon " + taxonName + " not found for leafHeight element in treeModel element");
}
NodeRef node = treeModel.getExternalNode(index);
Parameter newParameter = treeModel.getLeafHeightParameter(node);
ParameterParser.replaceParameter(cxo, newParameter);
Taxon taxon = treeModel.getTaxon(index);
Date date = taxon.getDate();
if (date != null) {
double precision = date.getPrecision();
if (precision > 0.0) {
// taxon date not specified to exact value so add appropriate bounds
double upper = Taxon.getHeightFromDate(date);
double lower = Taxon.getHeightFromDate(date);
if (date.isBackwards()) {
upper += precision;
} else {
lower -= precision;
}
// set the bounds for the given precision
newParameter.addBounds(new Parameter.DefaultBounds(upper, lower, 1));
// set the initial value to be mid-point
newParameter.setParameterValue(0, (upper + lower) / 2);
}
}
} else if (cxo.getName().equals(NODE_HEIGHTS)) {
boolean rootNode = cxo.getAttribute(ROOT_NODE, false);
boolean internalNodes = cxo.getAttribute(INTERNAL_NODES, false);
boolean leafNodes = cxo.getAttribute(LEAF_NODES, false);
if (!rootNode && !internalNodes && !leafNodes) {
throw new XMLParseException("one or more of root, internal or leaf nodes must be selected for the nodeHeights element");
}
ParameterParser.replaceParameter(cxo, treeModel.createNodeHeightsParameter(rootNode, internalNodes, leafNodes));
} else if (cxo.getName().equals(NODE_RATES)) {
boolean rootNode = cxo.getAttribute(ROOT_NODE, false);
boolean internalNodes = cxo.getAttribute(INTERNAL_NODES, false);
boolean leafNodes = cxo.getAttribute(LEAF_NODES, false);
double[] initialValues = null;
if (cxo.hasAttribute(INITIAL_VALUE)) {
initialValues = cxo.getDoubleArrayAttribute(INITIAL_VALUE);
}
if (!rootNode && !internalNodes && !leafNodes) {
throw new XMLParseException("one or more of root, internal or leaf nodes must be selected for the nodeRates element");
}
ParameterParser.replaceParameter(cxo, treeModel.createNodeRatesParameter(initialValues, rootNode, internalNodes, leafNodes));
} else if (cxo.getName().equals(NODE_TRAITS)) {
boolean rootNode = cxo.getAttribute(ROOT_NODE, false);
boolean internalNodes = cxo.getAttribute(INTERNAL_NODES, false);
boolean leafNodes = cxo.getAttribute(LEAF_NODES, false);
boolean fireTreeEvents = cxo.getAttribute(FIRE_TREE_EVENTS, false);
String name = cxo.getAttribute(NAME, "trait");
int dim = cxo.getAttribute(MULTIVARIATE_TRAIT, 1);
double[] initialValues = null;
if (cxo.hasAttribute(INITIAL_VALUE)) {
initialValues = cxo.getDoubleArrayAttribute(INITIAL_VALUE);
}
if (!rootNode && !internalNodes && !leafNodes) {
throw new XMLParseException("one or more of root, internal or leaf nodes must be selected for the nodeTraits element");
}
ParameterParser.replaceParameter(cxo, treeModel.createNodeTraitsParameter(name, dim, initialValues, rootNode, internalNodes, leafNodes, fireTreeEvents));
} else if (cxo.getName().equals(LEAF_TRAIT)) {
String name = cxo.getAttribute(NAME, "trait");
String taxonName;
if (cxo.hasAttribute(TAXON)) {
taxonName = cxo.getStringAttribute(TAXON);
} else {
throw new XMLParseException("taxa element missing from leafTrait element in treeModel element");
}
int index = treeModel.getTaxonIndex(taxonName);
if (index == -1) {
throw new XMLParseException("taxon '" + taxonName + "' not found for leafTrait element in treeModel element");
}
NodeRef node = treeModel.getExternalNode(index);
Parameter parameter = treeModel.getNodeTraitParameter(node, name);
if (parameter == null)
throw new XMLParseException("trait '" + name + "' not found for leafTrait (taxon, " + taxonName + ") element in treeModel element");
ParameterParser.replaceParameter(cxo, parameter);
} else {
throw new XMLParseException("illegal child element in " + getParserName() + ": " + cxo.getName());
}
} else if (xo.getChild(i) instanceof Tree) {
// do nothing - already handled
} else {
throw new XMLParseException("illegal child element in " + getParserName() + ": " + xo.getChildName(i) + " " + xo.getChild(i));
}
}
// AR this is doubling up the number of bounds on each node.
// treeModel.setupHeightBounds();
//System.err.println("done constructing treeModel");
Logger.getLogger("dr.evomodel").info(" initial tree topology = " + Tree.Utils.uniqueNewick(treeModel, treeModel.getRoot()));
Logger.getLogger("dr.evomodel").info(" tree height = " + treeModel.getNodeHeight(treeModel.getRoot()));
return treeModel;
}
|
package edu.iu.grid.oim.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import com.divrep.DivRep;
import com.divrep.DivRepEvent;
import edu.iu.grid.oim.lib.Authorization;
import edu.iu.grid.oim.model.UserContext;
import edu.iu.grid.oim.model.db.ContactModel;
import edu.iu.grid.oim.model.db.record.ContactRecord;
import edu.iu.grid.oim.view.BootMenuView;
import edu.iu.grid.oim.view.BootPage;
import edu.iu.grid.oim.view.ContactAssociationView;
import edu.iu.grid.oim.view.GenericView;
import edu.iu.grid.oim.view.HtmlView;
import edu.iu.grid.oim.view.IView;
import edu.iu.grid.oim.view.LinkView;
import edu.iu.grid.oim.view.SideContentView;
public class HomeServlet extends ServletBase {
private static final long serialVersionUID = 1L;
static Logger log = Logger.getLogger(HomeServlet.class);
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
UserContext context = new UserContext(request);
//Authorization auth = context.getAuthorization();
BootMenuView menuview = new BootMenuView(context, "home");
BootPage page = new BootPage(context, menuview, new Content(context), createSideView(context));
page.addExCSS("home.css");
GenericView header = new GenericView();
header.add(new HtmlView("<h1>OSG Information Management System</h1>"));
header.add(new HtmlView("<p class=\"lead\">Defines the topology used by various OSG services based on the <a target=\"_blank\" href=\"http://osg-docdb.opensciencegrid.org/cgi-bin/ShowDocument?docid=18\">OSG Blueprint Document</a></p>"));
page.setPageHeader(header);
page.render(response.getWriter());
}
class Content implements IView {
UserContext context;
public Content(UserContext context) {
this.context = context;
}
@Override
public void render(PrintWriter out) {
//out.write("<div>");
Authorization auth = context.getAuthorization();
if(auth.isUser()) {
try {
ContactRecord user = auth.getContact();
Confirmation conf = new Confirmation(user.id, context);
conf.render(out);
} catch (SQLException e) {
log.error(e);
}
//show entities that this user is associated
try {
ContactAssociationView caview = new ContactAssociationView(context, auth.getContact().id);
caview.showNewButtons(true);
caview.render(out);
} catch (SQLException e) {
log.error(e);
}
} else {
//guest view
out.write("<div class=\"row-fluid\">");
out.write("<div class=\"span4 hotlink\" onclick=\"document.location='topology';\">");
out.write("<h2>Topology</h2>");
out.write("<p>Defines resource hierarchy</p>");
out.write("<img src=\"images/topology.png\">");
out.write("</div>");
out.write("<div class=\"span4 hotlink\" onclick=\"document.location='vo';\">");
out.write("<h2>Virtual Organization</h2>");
out.write("<p>Defines access for group of users</p>");
out.write("<img src=\"images/voicon.png\">");
out.write("</div>");
out.write("<div class=\"span4 hotlink\" onclick=\"document.location='sc';\">");
out.write("<h2>Support Centers</h2>");
out.write("<p>Defines who supports virtual organization</p>");
out.write("<img src=\"images/scicon.png\">");
out.write("</div>");
out.write("</div>");
}
//out.write("</div>");
}
}
private SideContentView createSideView(UserContext context)
{
SideContentView contentview = new SideContentView();
Authorization auth = context.getAuthorization();
if(auth.isUnregistered()) {
contentview.add(new HtmlView("<div class=\"alert alert-info\"><p>Your certificate is not yet registered with OIM.</p><p><a class=\"btn btn-info\" href=\"register\">Register</a></p></div>"));
} else if(auth.isDisabled()) {
contentview.add(new HtmlView("<div class=\"alert alert-danger\"><p>Your contact or DN is disabled. Please contact GOC for more information.</p><a class=\"btn btn-danger\" href=\"https://ticket.grid.iu.edu\">Contact GOC</a></p></div>"));
} else if(!auth.isUser()) {
String text = "<p>OIM requires an X509 certificate issued by an <a target=\"_blank\" href='http://software.grid.iu.edu/cadist/'>OSG-approved Certifying Authority (CA)</a> to authenticate.</p>"+
"<p><a class=\"btn btn-info\" href=\"/oim/certificaterequestuser\">Request New Certificate</a></p>"+
"If you already have a certificate installed on your browser, please login.</p><p><a class=\"btn btn-info\" href=\""+context.getSecureUrl()+"\">Login</a></p>";
contentview.add(new HtmlView("<div class=\"alert alert-info\"><p>"+text+"</p></div>"));
}
contentview.add(new HtmlView("<h2>Documentations</h2>"));
contentview.add(new LinkView("https://twiki.grid.iu.edu/twiki/bin/view/Operations/OIMTermDefinition", "OIM Definitions", true));
contentview.add(new LinkView("https://twiki.grid.iu.edu/twiki/bin/view/Operations/OIMRegistrationInstructions", "Registration", true));
contentview.add(new LinkView("https://twiki.grid.iu.edu/twiki/bin/view/Operations/OIMMaintTool", "Resource Downtime", true));
if(auth.isUser()) {
contentview.addContactLegend();
}
return contentview;
}
@SuppressWarnings("serial")
class Confirmation extends DivRep
{
final ContactRecord crec;
final ContactModel cmodel;
final UserContext context;
public Confirmation(Integer contact_id, UserContext _context) throws SQLException {
super(_context.getPageRoot());
cmodel = new ContactModel(_context);
crec = (ContactRecord) cmodel.get(contact_id);//.clone();
context = _context;
}
protected void onEvent(DivRepEvent e) {
// TODO Auto-generated method stub
}
public void render(PrintWriter out) {
if(crec.isConfirmationExpired()) {
out.write("<div id=\""+getNodeID()+"\">");
out.write("<h2>Content Confirmation</h2>");
out.write("<p class=\"divrep_round divrep_elementerror\">You have not recently confirmed that your information in OIM is current</p>");
out.write("<p>The last time you confirmed your profile information was "+crec.confirmed.toString()+"</p>");
out.write("<p>Please go to the ");
out.write("<a href=\"profileedit\">My Profile</a>");
out.write(" page to check your profile information</p>");
out.write("</div>");
}
}
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package erp.mod.trn.view;
import erp.data.SDataConstants;
import erp.mcfg.data.SDataParamsErp;
import erp.mod.SModConsts;
import erp.mod.SModSysConsts;
import java.util.ArrayList;
import sa.lib.SLibTimeUtils;
import sa.lib.SLibUtils;
import sa.lib.db.SDbConsts;
import sa.lib.grid.SGridColumnView;
import sa.lib.grid.SGridConsts;
import sa.lib.grid.SGridFilterDateCutOff;
import sa.lib.grid.SGridPaneSettings;
import sa.lib.grid.SGridPaneView;
import sa.lib.gui.SGuiClient;
import sa.lib.gui.SGuiConsts;
import sa.lib.gui.SGuiDate;
/**
*
* @author Sergio Flores
*/
public class SViewInventoryCost extends SGridPaneView {
private SGridFilterDateCutOff moFilterDateCutOff;
public SViewInventoryCost(SGuiClient client, int subtype, String title) {
super(client, SGridConsts.GRID_PANE_VIEW, SModConsts.TRNX_STK_COST, subtype, title, null);
initComponentsCustom();
}
private void initComponentsCustom() {
setRowButtonsEnabled(false, false, false, false, false);
moFilterDateCutOff = new SGridFilterDateCutOff(miClient, this);
moFilterDateCutOff.initFilter(new SGuiDate(SGuiConsts.GUI_DATE_DATE, SLibTimeUtils.getEndOfYear(miClient.getSession().getCurrentDate()).getTime()));
getPanelCommandsSys(SGuiConsts.PANEL_CENTER).add(moFilterDateCutOff);
}
@Override
public void prepareSqlQuery() {
String sql = "";
Object filter = null;
moPaneSettings = new SGridPaneSettings(2);
filter = (SGuiDate) moFiltersMap.get(SGridConsts.FILTER_DATE).getValue();
if (filter != null) {
sql += (sql.isEmpty() ? "" : "AND ") + "s.id_year = " + SLibTimeUtils.digestYear((SGuiDate) filter)[0] + " AND " +
"s.dt <= '" + SLibUtils.DbmsDateFormatDate.format((SGuiDate) filter) + "' ";
}
switch (mnGridSubtype) {
case SModConsts.CFGU_COB_ENT:
msSql = "SELECT "
+ "s.id_cob AS " + SDbConsts.FIELD_ID + "1, "
+ "s.id_wh AS " + SDbConsts.FIELD_ID + "2, "
+ "ent.code AS " + SDbConsts.FIELD_CODE + ", "
+ "ent.ent AS " + SDbConsts.FIELD_NAME + ", "
+ "bpb.code, "
+ "bpb.bpb, "
+ "SUM(s.debit) AS _dbt, "
+ "SUM(s.credit) AS _cdt, "
+ "SUM(s.debit - s.credit) AS _cst "
+ "FROM " + SModConsts.TablesMap.get(SModConsts.TRN_STK) + " AS s "
+ "INNER JOIN " + SModConsts.TablesMap.get(SModConsts.BPSU_BPB) + " AS bpb ON s.id_cob = bpb.id_bpb "
+ "INNER JOIN " + SModConsts.TablesMap.get(SModConsts.CFGU_COB_ENT) + " AS ent ON s.id_cob = ent.id_cob AND s.id_wh = ent.id_ent "
+ "WHERE s.b_del = 0 AND " + sql + " "
+ "GROUP BY s.id_cob, s.id_wh "
+ "HAVING _cst <> 0 "
+ "ORDER BY bpb.bpb, bpb.code, ent.ent, ent.code, s.id_cob, s.id_wh ";
break;
case SModConsts.ITMU_ITEM:
msSql = "SELECT "
+ "s.id_item AS " + SDbConsts.FIELD_ID + "1, "
+ "s.id_unit AS " + SDbConsts.FIELD_ID + "2, "
+ "i.item_key AS " + SDbConsts.FIELD_CODE + ", "
+ "i.item AS " + SDbConsts.FIELD_NAME + ", "
+ "u.symbol, "
+ "u.unit, "
+ "SUM(s.mov_in) AS _mov_in, "
+ "SUM(s.mov_out) AS _mov_out, "
+ "SUM(s.mov_in - s.mov_out) AS _stk, "
+ "SUM(s.debit) AS _dbt, "
+ "SUM(s.credit) AS _cdt, "
+ "SUM(s.debit - s.credit) AS _cst "
+ "FROM " + SModConsts.TablesMap.get(SModConsts.TRN_STK) + " AS s "
+ "INNER JOIN " + SModConsts.TablesMap.get(SModConsts.ITMU_ITEM) + " AS i ON s.id_item = i.id_item "
+ "INNER JOIN " + SModConsts.TablesMap.get(SModConsts.ITMU_UNIT) + " AS u ON s.id_unit = u.id_unit "
+ "WHERE s.b_del = 0 AND " + sql + " "
+ "GROUP BY s.id_item, s.id_unit "
+ "HAVING _stk <> 0 OR _cst <> 0 "
+ "ORDER BY "
+ (((SDataParamsErp) miClient.getSession().getConfigSystem()).getFkSortingItemTypeId() == SModSysConsts.CFGS_TP_SORT_KEY_NAME ? "i.item, i.item_key, " : "i.item_key, i.item, ")
+ "s.id_item, u.symbol, s.id_unit ";
break;
default:
}
}
@Override
public ArrayList<SGridColumnView> createGridColumns() {
SGridColumnView column = null;
ArrayList<SGridColumnView> columns = new ArrayList<SGridColumnView>();
switch (mnGridSubtype) {
case SModConsts.CFGU_COB_ENT:
columns.add(new SGridColumnView(SGridConsts.COL_TYPE_TEXT_NAME_CAT_S, "bpb.bpb", SGridConsts.COL_TITLE_NAME + " sucursal empresa"));
columns.add(new SGridColumnView(SGridConsts.COL_TYPE_TEXT_CODE_CAT, "bpb.code", SGridConsts.COL_TITLE_CODE + " sucursal empresa"));
columns.add(new SGridColumnView(SGridConsts.COL_TYPE_TEXT_NAME_CAT_M, SDbConsts.FIELD_NAME, SGridConsts.COL_TITLE_NAME + " almacén"));
columns.add(new SGridColumnView(SGridConsts.COL_TYPE_TEXT_CODE_CAT, SDbConsts.FIELD_CODE, SGridConsts.COL_TITLE_CODE + " almacén"));
break;
case SModConsts.ITMU_ITEM:
if (((SDataParamsErp) miClient.getSession().getConfigSystem()).getFkSortingItemTypeId() == SModSysConsts.CFGS_TP_SORT_KEY_NAME) {
columns.add(new SGridColumnView(SGridConsts.COL_TYPE_TEXT_NAME_ITM_L, SDbConsts.FIELD_NAME, SGridConsts.COL_TITLE_NAME + " ítem"));
columns.add(new SGridColumnView(SGridConsts.COL_TYPE_TEXT_CODE_ITM, SDbConsts.FIELD_CODE, SGridConsts.COL_TITLE_CODE + " ítem"));
}
else {
columns.add(new SGridColumnView(SGridConsts.COL_TYPE_TEXT_CODE_ITM, SDbConsts.FIELD_CODE, SGridConsts.COL_TITLE_CODE + " ítem"));
columns.add(new SGridColumnView(SGridConsts.COL_TYPE_TEXT_NAME_ITM_L, SDbConsts.FIELD_NAME, SGridConsts.COL_TITLE_NAME + " ítem"));
}
columns.add(new SGridColumnView(SGridConsts.COL_TYPE_DEC_QTY, "_mov_in", "Entradas"));
columns.add(new SGridColumnView(SGridConsts.COL_TYPE_DEC_QTY, "_mov_out", "Salidas"));
columns.add(new SGridColumnView(SGridConsts.COL_TYPE_DEC_QTY, "_stk", "Existencias"));
columns.add(new SGridColumnView(SGridConsts.COL_TYPE_TEXT_CODE_UNT, "u.symbol", "Unidad"));
break;
default:
}
column = new SGridColumnView(SGridConsts.COL_TYPE_DEC_AMT, "_dbt", "Cargos $");
column.setSumApplying(true);
columns.add(column);
column = new SGridColumnView(SGridConsts.COL_TYPE_DEC_AMT, "_cdt", "Abonos $");
column.setSumApplying(true);
columns.add(column);
column = new SGridColumnView(SGridConsts.COL_TYPE_DEC_AMT, "_cst", "Saldo $");
column.setSumApplying(true);
columns.add(column);
return columns;
}
@Override
public void defineSuscriptions() {
moSuscriptionsSet.add(mnGridType);
moSuscriptionsSet.add(SModConsts.TRN_INV_VAL);
moSuscriptionsSet.add(SModConsts.TRNX_STK_DIOG_TP);
moSuscriptionsSet.add(SDataConstants.ITMU_ITEM);
moSuscriptionsSet.add(SDataConstants.ITMU_UNIT);
moSuscriptionsSet.add(SDataConstants.TRN_LOT);
moSuscriptionsSet.add(SDataConstants.TRN_DIOG);
moSuscriptionsSet.add(SDataConstants.TRN_STK);
moSuscriptionsSet.add(SDataConstants.TRN_STK_CFG);
moSuscriptionsSet.add(SDataConstants.TRNX_DPS_SUPPLY_PEND);
moSuscriptionsSet.add(SDataConstants.TRNX_DPS_SUPPLY_PEND_ETY);
moSuscriptionsSet.add(SDataConstants.TRNX_DPS_RETURN_PEND);
moSuscriptionsSet.add(SDataConstants.TRNX_DPS_RETURN_PEND_ETY);
}
}
|
package com.tavultesoft.kmea;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.PorterDuff.Mode;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import androidx.appcompat.app.AppCompatActivity;
import com.tavultesoft.kmea.util.FileUtils;
import com.tavultesoft.kmea.KMManager;
import com.tavultesoft.kmea.KMManager.Tier;
import com.tavultesoft.kmea.util.KMPLink;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.tavultesoft.kmea.util.KMPLink.KMP_PRODUCTION_HOST;
import static com.tavultesoft.kmea.util.KMPLink.KMP_STAGING_HOST;
public class KMPBrowserActivity extends AppCompatActivity {
private static final String TAG = "KMPBrowserActivity";
// URL for keyboard search web page presented to user when they add a keyboard in the app.
private static final String KMP_SEARCH_KEYBOARDS_FORMATSTR = "https://%s/go/android/%s/download-keyboards%s";
private static final String KMP_SEARCH_KEYBOARDS_LANGUAGES = "/languages/%s";
// Patterns for determining if a link should be opened in external browser
// 1. Host isn't keyman.com (production/staging)
// 2. Host is keyman.com but not /keyboards/
private static final String INTERNAL_KEYBOARDS_LINK_FORMATSTR = "^http(s)?://(%s|%s)/keyboards(\\/)?(.+)?$";
private static final String keyboardPatternFormatStr = String.format(INTERNAL_KEYBOARDS_LINK_FORMATSTR,
KMPLink.KMP_PRODUCTION_HOST,
KMPLink.KMP_STAGING_HOST);
private static final Pattern keyboardPattern = Pattern.compile(keyboardPatternFormatStr);
private WebView webView;
private boolean isLoading = false;
private boolean didFinishLoading = false;
@SuppressLint({"SetJavaScriptEnabled", "InflateParams"})
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Context context = this;
setContentView(R.layout.activity_kmp_browser);
webView = (WebView) findViewById(R.id.kmpBrowserWebView);
webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setSupportZoom(true);
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
}
});
webView.setWebViewClient(new WebViewClient() {
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
didFinishLoading = true;
isLoading = false;
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
String lowerURL = url.toLowerCase();
if (lowerURL.equals("about:blank")) {
return true; // never load a blank page, e.g. when the component initializes
}
if (KMPLink.isKeymanInstallLink(url)) {
Uri downloadURI = KMPLink.getKeyboardDownloadLink(url);
// Create intent with keyboard download link for KMAPro main activity to handle
Intent intent = new Intent(Intent.ACTION_VIEW, downloadURI);
startActivityForResult(intent, 1);
// Finish activity
finish();
} else if (!isKeymanKeyboardsLink(url)) {
Uri uri = Uri.parse(url);
// All links that aren't internal Keyman keyboard links open in user's browser
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
return true;
}
if (lowerURL.startsWith("keyman:")) {
// Warn for unsupported keyman schemes
Log.d(TAG, "Scheme for " + url + " not handled");
return true;
}
// Display URL
return false;
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
isLoading = true;
didFinishLoading = false;
}
@Override
public void onPageFinished(WebView view, String url) {
didFinishLoading = true;
isLoading = false;
}
});
// Tier determines the keyboard search host
String host = KMPLink.getHost();
// If language ID is provided, include it in the keyboard search
String languageID = getIntent().getStringExtra("languageCode");
String languageStr = (languageID != null) ? String.format(KMP_SEARCH_KEYBOARDS_LANGUAGES, languageID) : "";
String appMajorVersion = KMManager.getMajorVersion();
String kmpSearchUrl = String.format(KMP_SEARCH_KEYBOARDS_FORMATSTR, host, appMajorVersion, languageStr);
webView.loadUrl(kmpSearchUrl);
}
@Override
protected void onResume() {
super.onResume();
if (webView != null) {
webView.reload();
}
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (webView != null) {
if (resultCode == RESULT_OK && data != null) {
String url = data.getStringExtra("url");
if (url != null)
webView.loadUrl(url);
}
}
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
}
@Override
public void onBackPressed() {
if (webView != null && webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
finish();
}
}
/**
* Check if a URL is a valid internal Keyman keyboard link
* @param url String of the URL to parse
* @return boolean
*/
public boolean isKeymanKeyboardsLink(String url) {
boolean status = false;
if (url == null || url.isEmpty()) {
return status;
}
Matcher matcher = keyboardPattern.matcher(url);
if (matcher.matches()) {
status = true;
}
return status;
}
}
|
package org.appcelerator.titanium.util;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.appcelerator.kroll.common.Log;
import android.graphics.Color;
import android.os.Build;
/**
* This class contain utility methods that converts a String color, like "red", into its corresponding RGB/RGBA representation.
*/
public class TiColorHelper
{
static Pattern shortHexPattern = Pattern.compile("#([0-9a-f])([0-9a-f])([0-9a-f])([0-9a-f]?)");
static Pattern rgbPattern = Pattern.compile("rgb\\(\\s*([0-9]{1,3})\\s*,\\s*([0-9]{1,3})\\s*,\\s*([0-9]{1,3})\\s*\\)");
static Pattern argbPattern = Pattern.compile("rgba\\(\\s*([0-9]{1,3})\\s*,\\s*([0-9]{1,3})\\s*,\\s*([0-9]{1,3})\\s*,\\s*([0-9]{1,3}[^\\.\\)])\\s*\\)");
static Pattern rgbaPattern = Pattern.compile("rgba\\(\\s*([0-9]{1,3})\\s*,\\s*([0-9]{1,3})\\s*,\\s*([0-9]{1,3})\\s*,\\s*(\\d\\.\\d)\\s*\\)");
static Pattern floatsPattern = Pattern.compile("rgba\\(\\s*(\\d\\.\\d)\\s*,\\s*(\\d\\.\\d)\\s*,\\s*(\\d\\.\\d)\\s*,\\s*(\\d\\.\\d)\\s*\\)");
private static final String TAG = "TiColorHelper";
private static HashMap<String, Integer> colorTable;
private static List<String> alphaMissingColors = Arrays.asList(new String[] {"aqua", "fuchsia", "lime", "maroon", "navy", "olive", "purple", "silver", "teal"});
/**
* Convert string representations of colors, like "red" into the corresponding RGB/RGBA representation.
* @param value the color value to convert. For example, "red".
* @return the RGB/RGBA representation (int) of the color.
*/
public static int parseColor(String value) {
int color = Color.TRANSPARENT;
if (value != null) {
String lowval = value.trim().toLowerCase();
Matcher m = null;
if ((m = shortHexPattern.matcher(lowval)).matches()) {
StringBuilder sb = new StringBuilder();
sb.append("
for(int i = 1; i <= m.groupCount(); i++) {
String s = m.group(i);
sb.append(s).append(s);
}
String newColor = sb.toString();
color = Color.parseColor(newColor);
} else if ((m = rgbPattern.matcher(lowval)).matches()) {
color = Color.rgb(
Integer.valueOf(m.group(1)),
Integer.valueOf(m.group(2)),
Integer.valueOf(m.group(3))
);
} else if ((m = argbPattern.matcher(lowval)).matches()) {
color = Color.argb(
Integer.valueOf(m.group(4)),
Integer.valueOf(m.group(1)),
Integer.valueOf(m.group(2)),
Integer.valueOf(m.group(3))
);
} else if ((m = rgbaPattern.matcher(lowval)).matches()) {
color = Color.argb(
Math.round(Float.valueOf(m.group(4))*255f),
Integer.valueOf(m.group(1)),
Integer.valueOf(m.group(2)),
Integer.valueOf(m.group(3))
);
} else if ((m = floatsPattern.matcher(lowval)).matches()) {
color = Color.argb(
Math.round(Float.valueOf(m.group(4))*255f),
Math.round(Float.valueOf(m.group(1))*255f),
Math.round(Float.valueOf(m.group(2))*255f),
Math.round(Float.valueOf(m.group(3))*255f)
);
} else {
try {
// In 4.3, Google introduced some new string color constants and they forgot to
// add the alpha bits to them! This is a temporary workaround
// until they fix it. I've created a Google ticket for this:
if (Build.VERSION.SDK_INT > 17 && alphaMissingColors.contains(lowval)) {
color = Color.parseColor(lowval) | 0xFF000000;
} else {
color = Color.parseColor(lowval);
}
} catch (IllegalArgumentException e) {
if (colorTable == null) {
buildColorTable();
}
if (colorTable.containsKey(lowval)) {
color = colorTable.get(lowval);
} else {
Log.w(TAG, "Unknown color: " + value);
}
}
}
}
return color;
}
private static void buildColorTable() {
synchronized(TiColorHelper.class) {
colorTable = new HashMap<String, Integer>(20);
colorTable.put("black", Color.BLACK);
colorTable.put("red", Color.RED);
colorTable.put("purple", Color.rgb(0x80, 0, 0x80));
colorTable.put("orange", Color.rgb(0xff, 0x80, 0));
colorTable.put("gray", Color.GRAY);
colorTable.put("darkgray", Color.DKGRAY);
colorTable.put("lightgray", Color.LTGRAY);
colorTable.put("cyan", Color.CYAN);
colorTable.put("magenta",Color.MAGENTA);
colorTable.put("transparent", Color.TRANSPARENT);
colorTable.put("aqua", Color.rgb(0, 0xff, 0xff));
colorTable.put("fuchsia", Color.rgb(0xff, 0, 0xff));
colorTable.put("lime", Color.rgb(0, 0xff, 0));
colorTable.put("maroon", Color.rgb(0x88,0 ,0x88));
colorTable.put("pink", Color.rgb(0xff,0xc0, 0xcb));
colorTable.put("navy", Color.rgb(0, 0, 0x80));
colorTable.put("silver", Color.rgb(0xc0, 0xc0, 0xc0));
colorTable.put("olive", Color.rgb(0x80, 0x80, 0));
colorTable.put("teal", Color.rgb(0x0, 0x80, 0x80));
colorTable.put("brown", Color.rgb(0x99, 0x66, 0x33));
}
}
}
|
package finalir.DataStructure;
import java.util.*;
public class InvertedIndex {
private Map<String, Map<Integer, DocumentTermEntry>> _index = new HashMap<>();
private Map<Integer, Document> _docs = new HashMap<>();
public Document AddDoc(String name,int length){
Document d = new Document(name,length);
_docs.put(d.getId(),d);
return d;
}
public Document GetDoc(int id){
return _docs.get(id);
}
public InvertedIndex AddTerm(String term, Document doc, int position, TermType type) {
if (_index.containsKey(term) == false) {
Map<Integer, DocumentTermEntry> e = new HashMap<>();
e.put(doc.getId(), new DocumentTermEntry(doc,term).Add(position, type));
_index.put(term, e);
}
else {
Map<Integer, DocumentTermEntry> e =_index.get(term);
if(e.containsKey(doc.getId()) == false)
e.put(doc.getId(), new DocumentTermEntry(doc,term).Add(position, type));
else
e.get(doc.getId()).Add(position, type);
}
return this;
}
public int getDF(String term){
return _index.get(term).size();
}
public int getTF(String term, Document doc) {
return _index.get(term).get(doc.getId()).getLength(); // .getFrequency() ??
}
public int getSiqmaTF(String term) {
int sum = 0;
for (DocumentTermEntry d : _index.get(term).values())
sum += d.getLength(); // .getFrequency() ??
return sum;
}
public int getAllDocumentsCount(){
return _docs.size();
}
public double getAvaregeDocumentLength(){
if(getAllDocumentsCount() == 0)
return 0;
double sum = 0;
for (Document d : _docs.values())
sum += d.getLength();
return sum / getAllDocumentsCount();
}
public int GetMaxTF(Document doc){
return _docs.get(doc.getId()).getMaxTF();
}
public Collection<DocumentTermEntry> searchFor(String term){
return _index.get(term).values();
}
}
|
package flounder.networking;
import flounder.framework.*;
import flounder.logger.*;
import flounder.networking.packets.*;
import flounder.profiling.*;
/**
* A module used for handling networking, servers, clients, and packets.
*/
public class FlounderNetwork extends Module {
private static final FlounderNetwork INSTANCE = new FlounderNetwork();
public static final String PROFILE_TAB_NAME = "Network";
public static final int DEFAULT_PORT = 2266;
private Server socketServer;
private Client socketClient;
private String username;
private int port;
private boolean setup;
/**
* Creates a new network manager.
*/
public FlounderNetwork() {
super(ModuleUpdate.UPDATE_POST, PROFILE_TAB_NAME, FlounderLogger.class);
}
@Override
public void init() {
if (!setup) {
this.port = DEFAULT_PORT;
this.setup = true;
}
// this.username = "USERNAME" + ((int) (Math.random() * 10000));
}
@Override
public void update() {
}
@Override
public void profile() {
FlounderProfiler.add(PROFILE_TAB_NAME, "Username", username);
FlounderProfiler.add(PROFILE_TAB_NAME, "Port", port);
}
/**
* Starts the server.
*/
public static void startServer(int port) {
FlounderLogger.log("Starting server!");
INSTANCE.socketServer = new Server(port);
INSTANCE.socketServer.start();
}
/**
* Starts the client.
*/
public static void startClient(String username, String ipAddress, int port) {
INSTANCE.username = username;
FlounderLogger.log("Starting Client!");
INSTANCE.socketClient = new Client(ipAddress, port); // Default ip: "localhost"
INSTANCE.socketClient.start();
PacketLogin loginPacket = new PacketLogin(INSTANCE.username);
loginPacket.writeData(INSTANCE.socketClient);
}
/**
* Closes the server.
*/
public static void closeServer() {
if (INSTANCE.socketServer != null) {
FlounderLogger.log("Closing server!");
new PacketDisconnect("server").writeData(INSTANCE.socketServer);
INSTANCE.socketServer.dispose();
INSTANCE.socketServer = null;
}
}
/**
* Closes the client.
*/
public static void closeClient() {
if (INSTANCE.socketClient != null) {
FlounderLogger.log("Closing client!");
new PacketDisconnect(INSTANCE.username).writeData(INSTANCE.socketClient);
INSTANCE.socketClient.dispose();
INSTANCE.socketClient = null;
}
}
/**
* Gets the server currently running from this engine.
*
* @return The server running from this server.
*/
public static Server getSocketServer() {
return INSTANCE.socketServer;
}
/**
* Gets the client currently running.
*
* @return The client running.
*/
public static Client getSocketClient() {
return INSTANCE.socketClient;
}
public static String getUsername() {
return INSTANCE.username;
}
public static int getPort() {
return INSTANCE.port;
}
@Override
public Module getInstance() {
return INSTANCE;
}
@Override
public void dispose() {
closeServer();
closeClient();
}
}
|
package foam.core;
import foam.dao.pg.IndexedPreparedStatement;
import foam.nanos.logger.Logger;
import java.lang.UnsupportedOperationException;
import java.util.ArrayList;
import java.util.List;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public abstract class AbstractArrayPropertyInfo
extends AbstractPropertyInfo
{
@Override
public void setFromString(Object obj, String value) {
System.out.println("return String: " + value);
if ( value == null ) {
this.set(obj, null);
return;
}
java.util.List<String> list = new java.util.LinkedList<String>();
StringBuilder sb = new StringBuilder();
char prev = '$';
int length = value.length();
char[] cs = value.toCharArray();
for ( int i = 0 ; i < cs.length ; i++ ) {
if ( cs[i] == '\\' ) {
if ( prev == '\\' ) {
sb.append("\\");
prev = '$';
} else {
prev = '\\';
}
} else if ( cs[i] == ',' ) {
if ( prev == '\\' ) {
sb.append(',');
} else {
list.add(sb.toString());
sb.setLength(0);
}
prev = '$';
} else {
sb.append(cs[i]);
prev = cs[i];
}
}
list.add(sb.toString());
int resultSize = list.size();
System.out.println("list size: " + list.size());
String[] result = new String[resultSize];
//add support for other array types
this.set(obj, list.subList(0, resultSize).toArray(result));
}
public abstract String of();
// NESTED ARRAY
@Override
public Object fromXML(X x, XMLStreamReader reader) {
List objList = new ArrayList();
String startTag = reader.getLocalName();
try {
int eventType;
while ( reader.hasNext() ) {
eventType = reader.next();
switch ( eventType ) {
case XMLStreamConstants.START_ELEMENT:
if ( reader.getLocalName().equals("value") ) {
// TODO: TYPE CASTING FOR PROPER CONVERSION. NEED FURTHER SUPPORT FOR PRIMITIVE TYPES
throw new UnsupportedOperationException("Primitive typed array XML reading is not supported yet");
}
break;
case XMLStreamConstants.END_ELEMENT:
if ( reader.getLocalName() == startTag ) { return objList.toArray(); }
}
}
} catch (XMLStreamException ex) {
Logger logger = (Logger) x.get("logger");
logger.error("Premature end of XML file");
}
return objList.toArray();
}
@Override
public void toXML (FObject obj, Document doc, Element objElement) {
if ( this.f(obj) == null ) return;
Element prop = doc.createElement(this.getName());
objElement.appendChild(prop);
Object[] nestObj = (Object[]) this.f(obj);
for ( int k = 0; k < nestObj.length; k++ ) {
Element nestedProp = doc.createElement("value");
nestedProp.appendChild(doc.createTextNode(nestObj[k].toString()));
prop.appendChild(nestedProp);
}
}
@Override
public void setStatementValue(IndexedPreparedStatement stmt, FObject o) throws java.sql.SQLException {
Object obj = this.get(o);
if ( obj == null ) {
stmt.setObject(null);
return;
}
Object[] os = (Object[]) obj;
java.lang.StringBuilder sb = new java.lang.StringBuilder();
int length = os.length;
if ( length == 0 ) {
stmt.setObject(null);
return;
}
for ( int i = 0 ; i < length ; i++ ) {
if ( os[i] == null )
sb.append("");
else {
sb.append(os[i].toString().replace("\\","\\\\").replace(",","\\,"));
}
if ( i < length - 1 ) {
sb.append(",");
}
}
stmt.setObject(sb.toString());
}
@Override
public void setFromResultSet(java.sql.ResultSet resultSet, int index, FObject o) throws java.sql.SQLException{
String value = (String) resultSet.getObject(index);
setFromString(o, value);
}
}
|
package foam.lib.json;
import foam.lib.parse.*;
public class IdentifierStartParser extends ProxyParser {
public IdentifierStartParser() {
super(new Alt(Range.create('A', 'Z'), Range.create('a', 'z'), Literal.create("_"), Literal.create("$")));
}
}
|
package mondrian.util;
import mondrian.olap.Util;
import java.util.*;
import junit.framework.TestCase;
/**
* Test case for {@link ObjectPool}.
*
* @version $Id$
* @author Richard Emberson
*/
public class ObjectPoolTest extends TestCase {
public ObjectPoolTest() {
super();
}
public ObjectPoolTest(String name) {
super(name);
}
static class KeyValue {
long key;
Object value;
KeyValue(long key, Object value) {
this.key = key;
this.value = value;
}
public int hashCode() {
return (int)(key ^ (key >>> 32));
}
public boolean equals(Object o) {
return (o instanceof KeyValue)
? (((KeyValue) o).key == this.key)
: false;
}
public String toString() {
return value.toString();
}
}
public void testString() throws Exception {
// for reasons unknown this fails with java4
if (Util.PreJdk15) {
return;
}
ObjectPool<String> strings = new ObjectPool<String>();
int nos = 100000;
String[] ss1 = genStringsArray(nos);
for (int i = 0; i < nos; i++) {
strings.add(ss1[i]);
}
assertEquals("size not equal", nos, strings.size());
// second array of strings, same as the first but different objects
String[] ss2 = genStringsArray(nos);
for (int i = 0; i < nos; i++) {
String s = strings.add(ss2[i]);
assertEquals("string not equal: " +s, s, ss2[i]);
// REVIEW jvs 16-Jan-2008: This failed for me when
// I ran with a 1GB JVM heap size on JDK 1.5, probably
// because of interning (I tried changing genStringsList to add a
// gratuitous String constructor call, but that did not help). If
// there's a reason this test is on strings explicitly, then
// this needs to stay disabled; if the datatype can be changed
// to something which doesn't have any magic interning, then
// it can be re-enabled. This probably explains the
// Util.PreJdk15 "unknown reasons" above.
/*
assertFalse("same object", (s == ss2[i]));
*/
}
strings.clear();
assertEquals("size not equal", 0, strings.size());
nos = 25;
ss1 = genStringsArray(nos);
for (int i = 0; i < nos; i++) {
strings.add(ss1[i]);
}
assertEquals("size not equal", nos, strings.size());
List<String> l = genStringsList(nos);
Iterator<String> it = strings.iterator();
while (it.hasNext()) {
String s = it.next();
l.remove(s);
}
assertTrue("list not empty", l.isEmpty());
}
public void testKeyValue() throws Exception {
ObjectPool<KeyValue> op = new ObjectPool<KeyValue>();
int nos = 100000;
KeyValue[] kv1 = genKeyValueArray(nos);
for (int i = 0; i < nos; i++) {
op.add(kv1[i]);
}
assertEquals("size not equal", nos, op.size());
// second array of KeyValues, same as the first but different objects
KeyValue[] kv2 = genKeyValueArray(nos);
for (int i = 0; i < nos; i++) {
KeyValue kv = op.add(kv2[i]);
assertEquals("KeyValue not equal: " +kv, kv, kv2[i]);
assertFalse("same object", (kv == kv2[i]));
}
op.clear();
assertEquals("size not equal", 0, op.size());
nos = 25;
kv1 = genKeyValueArray(nos);
for (int i = 0; i < nos; i++) {
op.add(kv1[i]);
}
assertEquals("size not equal", nos, op.size());
List<KeyValue> l = genKeyValueList(nos);
Iterator<KeyValue> it = op.iterator();
while (it.hasNext()) {
KeyValue kv = it.next();
l.remove(kv);
}
assertTrue("list not empty", l.isEmpty());
}
/**
* Tests ObjectPools containing large numbers of integer and string keys,
* and makes sure they return the same results as HashSet. Optionally
* measures performance.
*/
public void testLarge() {
// Some typical results (2.4 GHz Intel dual-core).
// Key type: Integer String
// Implementation: ObjectPool HashSet ObjectPool HashSet
// With density=0.01, 298,477 distinct entries, 7,068 hits
// 300,000 adds 221 ms 252 ms 293 ms 1013 ms
// 700,000 gets 164 ms 148 ms 224 ms 746 ms
// With density=0.5, 236,022 distinct entries, 275,117 hits
// 300,000 adds 175 ms 250 ms 116 ms 596 ms
// 700,000 gets 147 ms 176 ms 190 ms 757 ms
// With density=0.999, 189,850 distinct entries, 442,618 hits
// 300,000 adds 128 ms 185 ms 99 ms 614 ms
// 700,000 gets 133 ms 184 ms 130 ms 830 ms
checkLargeMulti(300000, 0.01, 700000, 298477, 7068);
checkLargeMulti(300000, 0.5, 700000, 236022, 275117);
checkLargeMulti(300000, 0.999, 700000, 189850, 442618);
}
private void checkLargeMulti(
int entryCount,
double density,
int retrieveCount,
int expectedDistinct,
int expectedHits)
{
checkLarge(
true, true, entryCount, density, retrieveCount,
expectedDistinct, expectedHits);
checkLarge(
false, true, entryCount, density, retrieveCount,
expectedDistinct, expectedHits);
checkLarge(
false, true, entryCount, density, retrieveCount,
expectedDistinct, expectedHits);
checkLarge(
false, false, entryCount, density, retrieveCount,
expectedDistinct, expectedHits);
}
private void checkLarge(
boolean usePool,
boolean intKey,
int entryCount,
double density,
int retrieveCount,
int expectedDistinct,
int expectedHits)
{
final boolean print = false;
final long t1 = System.currentTimeMillis();
assert density > 0 && density <= 1;
int space = (int) (entryCount / density);
ObjectPool<Object> objectPool = new ObjectPool<Object>();
HashSet<Object> set = new HashSet<Object>();
Random random = new Random(1234);
int distinctCount = 0;
final String longString =
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyy";
for (int i = 0; i < entryCount; i++) {
final Object key = intKey
? random.nextInt(space)
: longString + random.nextInt(space);
if (usePool) {
if (objectPool.add(key) != null) {
++distinctCount;
}
} else {
if (set.add(key)) {
++distinctCount;
}
}
}
final long t2 = System.currentTimeMillis();
int hitCount = 0;
for (int i = 0; i < retrieveCount; i++) {
final Object key = intKey
? random.nextInt(space)
: longString + random.nextInt(space);
if (usePool) {
if (objectPool.contains(key)) {
++hitCount;
}
} else {
if (set.contains(key)) {
++hitCount;
}
}
}
final long t3 = System.currentTimeMillis();
if (usePool) {
// todo: assertEquals(expectedDistinct, objectPool.size());
distinctCount = objectPool.size();
} else {
assertEquals(expectedDistinct, set.size());
}
if (print) {
System.out.println(
"Using " + (usePool ? "ObjectPool" : "HashSet")
+ ", density=" + density
+ ", " + distinctCount + " distinct entries, "
+ hitCount + " hits");
System.out.println(
entryCount + " adds took " + (t2 - t1) + " milliseconds");
System.out.println(
retrieveCount + " gets took " + (t3 - t2) + " milliseconds");
}
assertEquals(expectedDistinct, distinctCount);
assertEquals(expectedHits, hitCount);
}
// helpers
private static String[] genStringsArray(int nos) {
List l = genStringsList(nos);
return (String[]) l.toArray(new String[l.size()]);
}
private static List<String> genStringsList(int nos) {
List<String> l = new ArrayList<String>(nos);
for (int i = 0; i < nos; i++) {
l.add(Integer.valueOf(i).toString());
}
return l;
}
private static KeyValue[] genKeyValueArray(int nos) {
List<KeyValue> l = genKeyValueList(nos);
return (KeyValue[]) l.toArray(new KeyValue[l.size()]);
}
private static List<KeyValue> genKeyValueList(int nos) {
List<KeyValue> l = new ArrayList<KeyValue>(nos);
for (int i = 0; i < nos; i++) {
l.add(new KeyValue((long)i, Integer.valueOf(i)));
}
return l;
}
}
// End ObjectPoolTest.java
|
package org.voltdb.iv2;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Queue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.voltcore.logging.VoltLogger;
import org.voltcore.messaging.HostMessenger;
import org.voltcore.messaging.TransactionInfoBaseMessage;
import org.voltcore.messaging.VoltMessage;
import org.voltcore.utils.CoreUtils;
import org.voltdb.ClientResponseImpl;
import org.voltdb.CommandLog;
import org.voltdb.CommandLog.DurabilityListener;
import org.voltdb.PartitionDRGateway;
import org.voltdb.SnapshotCompletionInterest;
import org.voltdb.SnapshotCompletionMonitor;
import org.voltdb.SystemProcedureCatalog;
import org.voltdb.VoltDB;
import org.voltdb.VoltTable;
import org.voltdb.client.ClientResponse;
import org.voltdb.dtxn.TransactionState;
import org.voltdb.iv2.SiteTasker.SiteTaskerRunnable;
import org.voltdb.messaging.BorrowTaskMessage;
import org.voltdb.messaging.CompleteTransactionMessage;
import org.voltdb.messaging.DumpMessage;
import org.voltdb.messaging.FragmentResponseMessage;
import org.voltdb.messaging.FragmentTaskMessage;
import org.voltdb.messaging.InitiateResponseMessage;
import org.voltdb.messaging.Iv2InitiateTaskMessage;
import org.voltdb.messaging.Iv2LogFaultMessage;
import org.voltdb.messaging.MultiPartitionParticipantMessage;
import com.google_voltpatches.common.primitives.Ints;
import com.google_voltpatches.common.primitives.Longs;
import com.google_voltpatches.common.util.concurrent.ListenableFuture;
public class SpScheduler extends Scheduler implements SnapshotCompletionInterest
{
static final VoltLogger tmLog = new VoltLogger("TM");
static class DuplicateCounterKey implements Comparable<DuplicateCounterKey>
{
private final long m_txnId;
private final long m_spHandle;
transient final int m_hash;
DuplicateCounterKey(long txnId, long spHandle)
{
m_txnId = txnId;
m_spHandle = spHandle;
m_hash = (37 * (int)(m_txnId ^ (m_txnId >>> 32))) +
((int)(m_spHandle ^ (m_spHandle >>> 32)));
}
@Override
public boolean equals(Object o)
{
if (this == o) {
return true;
}
if (o == null || !(getClass().isInstance(o))) {
return false;
}
DuplicateCounterKey other = (DuplicateCounterKey)o;
return (m_txnId == other.m_txnId && m_spHandle == other.m_spHandle);
}
// Only care about comparing TXN ID part for sorting in updateReplicas
@Override
public int compareTo(DuplicateCounterKey o)
{
if (m_txnId < o.m_txnId) {
return -1;
} else if (m_txnId > o.m_txnId) {
return 1;
} else {
if (m_spHandle < o.m_spHandle) {
return -1;
}
else if (m_spHandle > o.m_spHandle) {
return 1;
}
else {
return 0;
}
}
}
@Override
public int hashCode()
{
return m_hash;
}
@Override
public String toString()
{
return "<" + m_txnId + ", " + m_spHandle + ">";
}
};
List<Long> m_replicaHSIds = new ArrayList<Long>();
long m_sendToHSIds[] = new long[0];
private final TransactionTaskQueue m_pendingTasks;
private final Map<Long, TransactionState> m_outstandingTxns =
new HashMap<Long, TransactionState>();
private final Map<DuplicateCounterKey, DuplicateCounter> m_duplicateCounters =
new HashMap<DuplicateCounterKey, DuplicateCounter>();
// MP fragment tasks or completion tasks pending durability
private final Map<Long, Queue<TransactionTask>> m_mpsPendingDurability =
new HashMap<Long, Queue<TransactionTask>>();
private CommandLog m_cl;
private PartitionDRGateway m_drGateway = new PartitionDRGateway();
private final SnapshotCompletionMonitor m_snapMonitor;
// Need to track when command log replay is complete (even if not performed) so that
// we know when we can start writing viable replay sets to the fault log.
boolean m_replayComplete = false;
private final DurabilityListener m_durabilityListener;
//Generator of pre-IV2ish timestamp based unique IDs
private final UniqueIdGenerator m_uniqueIdGenerator;
// the current not-needed-any-more point of the repair log.
long m_repairLogTruncationHandle = Long.MIN_VALUE;
SpScheduler(int partitionId, SiteTaskerQueue taskQueue, SnapshotCompletionMonitor snapMonitor)
{
super(partitionId, taskQueue);
m_pendingTasks = new TransactionTaskQueue(m_tasks,getCurrentTxnId());
m_snapMonitor = snapMonitor;
m_durabilityListener = new DurabilityListener() {
@Override
public void onDurability(final ArrayList<Object> durableThings) {
final SiteTaskerRunnable r = new SiteTasker.SiteTaskerRunnable() {
@Override
void run() {
synchronized (m_lock) {
for (Object o : durableThings) {
m_pendingTasks.offer((TransactionTask)o);
// Make sure all queued tasks for this MP txn are released
if (!((TransactionTask) o).getTransactionState().isSinglePartition()) {
offerPendingMPTasks(((TransactionTask) o).getTxnId());
}
}
}
}
};
if (InitiatorMailbox.SCHEDULE_IN_SITE_THREAD) {
m_tasks.offer(r);
} else {
r.run();
}
}
};
m_uniqueIdGenerator = new UniqueIdGenerator(partitionId, 0);
}
@Override
public void setLeaderState(boolean isLeader)
{
super.setLeaderState(isLeader);
m_snapMonitor.addInterest(this);
}
@Override
public void setMaxSeenTxnId(long maxSeenTxnId)
{
super.setMaxSeenTxnId(maxSeenTxnId);
writeIv2ViableReplayEntry();
}
public void setDRGateway(PartitionDRGateway gateway)
{
m_drGateway = gateway;
if (m_drGateway != null) {
// Schedules to be fired every 5ms
VoltDB.instance().schedulePriorityWork(new Runnable() {
@Override
public void run() {
// Send a DR task to the site
m_tasks.offer(new DRTask(m_drGateway));
}
}, 0, 5, TimeUnit.MILLISECONDS);
}
}
@Override
public void shutdown()
{
m_tasks.offer(m_nullTask);
}
// This is going to run in the BabySitter's thread. This and deliver are synchronized by
// virtue of both being called on InitiatorMailbox and not directly called.
// (That is, InitiatorMailbox's API, used by BabySitter, is synchronized on the same
// lock deliver() is synchronized on.)
@Override
public void updateReplicas(List<Long> replicas, Map<Integer, Long> partitionMasters)
{
// First - correct the official replica set.
m_replicaHSIds = replicas;
// Update the list of remote replicas that we'll need to send to
List<Long> sendToHSIds = new ArrayList<Long>(m_replicaHSIds);
sendToHSIds.remove(m_mailbox.getHSId());
m_sendToHSIds = Longs.toArray(sendToHSIds);
// Cleanup duplicate counters and collect DONE counters
// in this list for further processing.
List<DuplicateCounterKey> doneCounters = new LinkedList<DuplicateCounterKey>();
for (Entry<DuplicateCounterKey, DuplicateCounter> entry : m_duplicateCounters.entrySet()) {
DuplicateCounter counter = entry.getValue();
int result = counter.updateReplicas(m_replicaHSIds);
if (result == DuplicateCounter.DONE) {
doneCounters.add(entry.getKey());
}
}
// Maintain the CI invariant that responses arrive in txnid order.
Collections.sort(doneCounters);
for (DuplicateCounterKey key : doneCounters) {
DuplicateCounter counter = m_duplicateCounters.remove(key);
VoltMessage resp = counter.getLastResponse();
if (resp != null) {
// MPI is tracking deps per partition HSID. We need to make
// sure we write ours into the message getting sent to the MPI
if (resp instanceof FragmentResponseMessage) {
FragmentResponseMessage fresp = (FragmentResponseMessage)resp;
fresp.setExecutorSiteId(m_mailbox.getHSId());
}
m_mailbox.send(counter.m_destinationId, resp);
}
else {
hostLog.warn("TXN " + counter.getTxnId() + " lost all replicas and " +
"had no responses. This should be impossible?");
}
}
writeIv2ViableReplayEntry();
}
/**
* Poll the replay sequencer and process the messages until it returns null
*/
private void deliverReadyTxns() {
// First, pull all the sequenced messages, if any.
VoltMessage m = m_replaySequencer.poll();
while(m != null) {
deliver(m);
m = m_replaySequencer.poll();
}
// Then, try to pull all the drainable messages, if any.
m = m_replaySequencer.drain();
while (m != null) {
if (m instanceof Iv2InitiateTaskMessage) {
// Send IGNORED response for all SPs
Iv2InitiateTaskMessage task = (Iv2InitiateTaskMessage) m;
final InitiateResponseMessage response = new InitiateResponseMessage(task);
response.setResults(new ClientResponseImpl(ClientResponse.UNEXPECTED_FAILURE,
new VoltTable[0],
ClientResponseImpl.IGNORED_TRANSACTION));
m_mailbox.send(response.getInitiatorHSId(), response);
}
m = m_replaySequencer.drain();
}
}
/**
* Sequence the message for replay if it's for CL or DR.
*
* @param message
* @return true if the message can be delivered directly to the scheduler,
* false if the message is queued
*/
@Override
public boolean sequenceForReplay(VoltMessage message)
{
boolean canDeliver = false;
long sequenceWithTxnId = Long.MIN_VALUE;
boolean commandLog = (message instanceof TransactionInfoBaseMessage &&
(((TransactionInfoBaseMessage)message).isForReplay()));
boolean dr = ((message instanceof TransactionInfoBaseMessage &&
((TransactionInfoBaseMessage)message).isForDR()));
boolean sentinel = message instanceof MultiPartitionParticipantMessage;
boolean replay = commandLog || sentinel || dr;
boolean sequenceForReplay = m_isLeader && replay;
assert(!(commandLog && dr));
if (commandLog || sentinel) {
sequenceWithTxnId = ((TransactionInfoBaseMessage)message).getTxnId();
}
else if (dr) {
sequenceWithTxnId = ((TransactionInfoBaseMessage)message).getOriginalTxnId();
}
if (sequenceForReplay) {
InitiateResponseMessage dupe = m_replaySequencer.dedupe(sequenceWithTxnId,
(TransactionInfoBaseMessage) message);
if (dupe != null) {
// Duplicate initiate task message, send response
m_mailbox.send(dupe.getInitiatorHSId(), dupe);
}
else if (!m_replaySequencer.offer(sequenceWithTxnId, (TransactionInfoBaseMessage) message)) {
canDeliver = true;
}
else {
deliverReadyTxns();
}
// If it's a DR sentinel, send an acknowledgement
if (sentinel && !commandLog) {
MultiPartitionParticipantMessage mppm = (MultiPartitionParticipantMessage) message;
final InitiateResponseMessage response = new InitiateResponseMessage(mppm);
ClientResponseImpl clientResponse =
new ClientResponseImpl(ClientResponseImpl.UNEXPECTED_FAILURE,
new VoltTable[0], ClientResponseImpl.IGNORED_TRANSACTION);
response.setResults(clientResponse);
m_mailbox.send(response.getInitiatorHSId(), response);
}
}
else {
if (replay) {
// Update last seen and last polled txnId for replicas
m_replaySequencer.updateLastSeenTxnId(sequenceWithTxnId,
(TransactionInfoBaseMessage) message);
m_replaySequencer.updateLastPolledTxnId(sequenceWithTxnId,
(TransactionInfoBaseMessage) message);
}
canDeliver = true;
}
return canDeliver;
}
// SpInitiators will see every message type. The Responses currently come
// from local work, but will come from replicas when replication is
// implemented
@Override
public void deliver(VoltMessage message)
{
if (message instanceof Iv2InitiateTaskMessage) {
handleIv2InitiateTaskMessage((Iv2InitiateTaskMessage)message);
}
else if (message instanceof InitiateResponseMessage) {
handleInitiateResponseMessage((InitiateResponseMessage)message);
}
else if (message instanceof FragmentTaskMessage) {
handleFragmentTaskMessage((FragmentTaskMessage)message);
}
else if (message instanceof FragmentResponseMessage) {
handleFragmentResponseMessage((FragmentResponseMessage)message);
}
else if (message instanceof CompleteTransactionMessage) {
handleCompleteTransactionMessage((CompleteTransactionMessage)message);
}
else if (message instanceof BorrowTaskMessage) {
handleBorrowTaskMessage((BorrowTaskMessage)message);
}
else if (message instanceof Iv2LogFaultMessage) {
handleIv2LogFaultMessage((Iv2LogFaultMessage)message);
}
else if (message instanceof DumpMessage) {
handleDumpMessage();
}
else {
throw new RuntimeException("UNKNOWN MESSAGE TYPE, BOOM!");
}
}
private long getMaxTaskedSpHandle() {
return m_pendingTasks.getMaxTaskedSpHandle();
}
// SpScheduler expects to see InitiateTaskMessages corresponding to single-partition
// procedures only.
public void handleIv2InitiateTaskMessage(Iv2InitiateTaskMessage message)
{
if (!message.isSinglePartition()) {
throw new RuntimeException("SpScheduler.handleIv2InitiateTaskMessage " +
"should never receive multi-partition initiations.");
}
final String procedureName = message.getStoredProcedureName();
long newSpHandle;
long uniqueId = Long.MIN_VALUE;
Iv2InitiateTaskMessage msg = message;
if (m_isLeader || message.isReadOnly()) {
/*
* A short circuit read is a read where the client interface is local to
* this node. The CI will let a replica perform a read in this case and
* it does looser tracking of client handles since it can't be
* partitioned from the local replica.
*/
if (!m_isLeader &&
CoreUtils.getHostIdFromHSId(msg.getInitiatorHSId()) !=
CoreUtils.getHostIdFromHSId(m_mailbox.getHSId())) {
VoltDB.crashLocalVoltDB("Only allowed to do short circuit reads locally", true, null);
}
/*
* If this is for CL replay or DR, update the unique ID generator
*/
if (message.isForReplay()) {
uniqueId = message.getUniqueId();
try {
m_uniqueIdGenerator.updateMostRecentlyGeneratedUniqueId(uniqueId);
}
catch (Exception e) {
hostLog.fatal(e.getMessage());
hostLog.fatal("Invocation: " + message);
VoltDB.crashLocalVoltDB(e.getMessage(), true, e);
}
} else if (message.isForDR()) {
uniqueId = message.getStoredProcedureInvocation().getOriginalUniqueId();
// @LoadSinglepartitionTable does not have a valid uid
if (UniqueIdGenerator.getPartitionIdFromUniqueId(uniqueId) == m_partitionId) {
m_uniqueIdGenerator.updateMostRecentlyGeneratedUniqueId(uniqueId);
}
}
/*
* If this is CL replay use the txnid from the CL and also
* update the txnid to match the one from the CL
*/
if (message.isForReplay()) {
newSpHandle = message.getTxnId();
setMaxSeenTxnId(newSpHandle);
} else if (m_isLeader && !message.isReadOnly()) {
TxnEgo ego = advanceTxnEgo();
newSpHandle = ego.getTxnId();
uniqueId = m_uniqueIdGenerator.getNextUniqueId();
} else {
/*
* The short circuit read case. Since we are not a master
* we can't create new transaction IDs, so reuse the last seen
* txnid. For a timestamp, might as well give a reasonable one
* for a read heavy workload so time isn't bursty.
*/
uniqueId = UniqueIdGenerator.makeIdFromComponents(
Math.max(System.currentTimeMillis(), m_uniqueIdGenerator.lastUsedTime),
0,
m_uniqueIdGenerator.partitionId);
//Don't think it wise to make a new one for a short circuit read
newSpHandle = getMaxTaskedSpHandle();
}
// Need to set the SP handle on the received message
// Need to copy this or the other local sites handling
// the same initiate task message will overwrite each
// other's memory -- the message isn't copied on delivery
// to other local mailboxes.
msg = new Iv2InitiateTaskMessage(
message.getInitiatorHSId(),
message.getCoordinatorHSId(),
m_repairLogTruncationHandle,
message.getTxnId(),
message.getUniqueId(),
message.isReadOnly(),
message.isSinglePartition(),
message.getStoredProcedureInvocation(),
message.getClientInterfaceHandle(),
message.getConnectionId(),
message.isForReplay());
msg.setSpHandle(newSpHandle);
// Also, if this is a vanilla single-part procedure, make the TXNID
// be the SpHandle (for now)
// Only system procedures are every-site, so we'll check through the SystemProcedureCatalog
if (SystemProcedureCatalog.listing.get(procedureName) == null ||
!SystemProcedureCatalog.listing.get(procedureName).getEverysite()) {
msg.setTxnId(newSpHandle);
msg.setUniqueId(uniqueId);
}
//Don't replicate reads, this really assumes that DML validation
//is going to be integrated soonish
if (m_isLeader && !msg.isReadOnly() && m_sendToHSIds.length > 0) {
Iv2InitiateTaskMessage replmsg =
new Iv2InitiateTaskMessage(m_mailbox.getHSId(),
m_mailbox.getHSId(),
m_repairLogTruncationHandle,
msg.getTxnId(),
msg.getUniqueId(),
msg.isReadOnly(),
msg.isSinglePartition(),
msg.getStoredProcedureInvocation(),
msg.getClientInterfaceHandle(),
msg.getConnectionId(),
msg.isForReplay());
// Update the handle in the copy since the constructor doesn't set it
replmsg.setSpHandle(newSpHandle);
m_mailbox.send(m_sendToHSIds, replmsg);
DuplicateCounter counter = new DuplicateCounter(
msg.getInitiatorHSId(),
msg.getTxnId(), m_replicaHSIds, msg.getStoredProcedureName());
m_duplicateCounters.put(new DuplicateCounterKey(msg.getTxnId(), newSpHandle), counter);
}
}
else {
setMaxSeenTxnId(msg.getSpHandle());
newSpHandle = msg.getSpHandle();
uniqueId = msg.getUniqueId();
}
Iv2Trace.logIv2InitiateTaskMessage(message, m_mailbox.getHSId(), msg.getTxnId(), newSpHandle);
doLocalInitiateOffer(msg);
return;
}
/**
* Do the work necessary to turn the Iv2InitiateTaskMessage into a
* TransactionTask which can be queued to the TransactionTaskQueue.
* This is reused by both the normal message handling path and the repair
* path, and assumes that the caller has dealt with or ensured that the
* necessary ID, SpHandles, and replication issues are resolved.
*/
private void doLocalInitiateOffer(Iv2InitiateTaskMessage msg)
{
final String procedureName = msg.getStoredProcedureName();
final SpProcedureTask task =
new SpProcedureTask(m_mailbox, procedureName, m_pendingTasks, msg, m_drGateway);
if (!msg.isReadOnly()) {
ListenableFuture<Object> durabilityBackpressureFuture =
m_cl.log(msg, msg.getSpHandle(), null, m_durabilityListener, task);
//Durability future is always null for sync command logging
//the transaction will be delivered again by the CL for execution once durable
//Async command logging has to offer the task immediately with a Future for backpressure
if (durabilityBackpressureFuture != null) {
m_pendingTasks.offer(task.setDurabilityBackpressureFuture(durabilityBackpressureFuture));
}
} else {
m_pendingTasks.offer(task);
}
}
@Override
public void handleMessageRepair(List<Long> needsRepair, VoltMessage message)
{
if (message instanceof Iv2InitiateTaskMessage) {
handleIv2InitiateTaskMessageRepair(needsRepair, (Iv2InitiateTaskMessage)message);
}
else if (message instanceof FragmentTaskMessage) {
handleFragmentTaskMessageRepair(needsRepair, (FragmentTaskMessage)message);
}
else if (message instanceof CompleteTransactionMessage) {
// It should be safe to just send CompleteTransactionMessages to everyone.
handleCompleteTransactionMessage((CompleteTransactionMessage)message);
}
else {
throw new RuntimeException("SpScheduler.handleMessageRepair received unexpected message type: " +
message);
}
}
private void handleIv2InitiateTaskMessageRepair(List<Long> needsRepair, Iv2InitiateTaskMessage message)
{
if (!message.isSinglePartition()) {
throw new RuntimeException("SpScheduler.handleIv2InitiateTaskMessageRepair " +
"should never receive multi-partition initiations.");
}
// set up duplicate counter. expect exactly the responses corresponding
// to needsRepair. These may, or may not, include the local site.
// We currently send the final response into the ether, since we don't
// have the original ClientInterface HSID stored. It would be more
// useful to have the original ClienInterface HSId somewhere handy.
List<Long> expectedHSIds = new ArrayList<Long>(needsRepair);
DuplicateCounter counter = new DuplicateCounter(
HostMessenger.VALHALLA,
message.getTxnId(), expectedHSIds, message.getStoredProcedureName());
m_duplicateCounters.put(new DuplicateCounterKey(message.getTxnId(), message.getSpHandle()), counter);
m_uniqueIdGenerator.updateMostRecentlyGeneratedUniqueId(message.getUniqueId());
// is local repair necessary?
if (needsRepair.contains(m_mailbox.getHSId())) {
needsRepair.remove(m_mailbox.getHSId());
// make a copy because handleIv2 non-repair case does?
Iv2InitiateTaskMessage localWork =
new Iv2InitiateTaskMessage(message.getInitiatorHSId(),
message.getCoordinatorHSId(), message);
doLocalInitiateOffer(localWork);
}
// is remote repair necessary?
if (!needsRepair.isEmpty()) {
Iv2InitiateTaskMessage replmsg =
new Iv2InitiateTaskMessage(m_mailbox.getHSId(), m_mailbox.getHSId(), message);
m_mailbox.send(com.google_voltpatches.common.primitives.Longs.toArray(needsRepair), replmsg);
}
}
private void handleFragmentTaskMessageRepair(List<Long> needsRepair, FragmentTaskMessage message)
{
// set up duplicate counter. expect exactly the responses corresponding
// to needsRepair. These may, or may not, include the local site.
List<Long> expectedHSIds = new ArrayList<Long>(needsRepair);
DuplicateCounter counter = new DuplicateCounter(
message.getCoordinatorHSId(), // Assume that the MPI's HSID hasn't changed
message.getTxnId(), expectedHSIds, "MP_DETERMINISM_ERROR");
m_duplicateCounters.put(new DuplicateCounterKey(message.getTxnId(), message.getSpHandle()), counter);
// is local repair necessary?
if (needsRepair.contains(m_mailbox.getHSId())) {
// Sanity check that we really need repair.
if (m_outstandingTxns.get(message.getTxnId()) != null) {
hostLog.warn("SPI repair attempted to repair a fragment which it has already seen. " +
"This shouldn't be possible.");
// Not sure what to do in this event. Crash for now
throw new RuntimeException("Attempted to repair with a fragment we've already seen.");
}
needsRepair.remove(m_mailbox.getHSId());
// make a copy because handleIv2 non-repair case does?
FragmentTaskMessage localWork =
new FragmentTaskMessage(message.getInitiatorHSId(),
message.getCoordinatorHSId(), message);
doLocalFragmentOffer(localWork);
}
// is remote repair necessary?
if (!needsRepair.isEmpty()) {
FragmentTaskMessage replmsg =
new FragmentTaskMessage(m_mailbox.getHSId(), m_mailbox.getHSId(), message);
m_mailbox.send(com.google_voltpatches.common.primitives.Longs.toArray(needsRepair), replmsg);
}
}
// Pass a response through the duplicate counters.
public void handleInitiateResponseMessage(InitiateResponseMessage message)
{
// All single-partition reads are short-circuit reads and will have no duplicate counter.
// SpScheduler will only see InitiateResponseMessages for SP transactions, so if it's
// read-only here, it's short-circuited. Avoid all the lookup below. Also, don't update
// the truncation handle, since it won't have meaning for anyone.
if (message.isReadOnly()) {
// the initiatorHSId is the ClientInterface mailbox. Yeah. I know.
m_mailbox.send(message.getInitiatorHSId(), message);
return;
}
final long spHandle = message.getSpHandle();
final DuplicateCounterKey dcKey = new DuplicateCounterKey(message.getTxnId(), spHandle);
DuplicateCounter counter = m_duplicateCounters.get(dcKey);
if (counter != null) {
int result = counter.offer(message);
if (result == DuplicateCounter.DONE) {
m_duplicateCounters.remove(dcKey);
m_repairLogTruncationHandle = spHandle;
m_mailbox.send(counter.m_destinationId, counter.getLastResponse());
}
else if (result == DuplicateCounter.MISMATCH) {
VoltDB.crashGlobalVoltDB("HASH MISMATCH: replicas produced different results.", true, null);
}
}
else {
// the initiatorHSId is the ClientInterface mailbox. Yeah. I know.
m_repairLogTruncationHandle = spHandle;
m_mailbox.send(message.getInitiatorHSId(), message);
}
}
// BorrowTaskMessages encapsulate a FragmentTaskMessage along with
// input dependency tables. The MPI issues borrows to a local site
// to perform replicated reads or aggregation fragment work.
private void handleBorrowTaskMessage(BorrowTaskMessage message) {
// borrows do not advance the sp handle. The handle would
// move backwards anyway once the next message is received
// from the SP leader.
long newSpHandle = getMaxTaskedSpHandle();
Iv2Trace.logFragmentTaskMessage(message.getFragmentTaskMessage(),
m_mailbox.getHSId(), newSpHandle, true);
TransactionState txn = m_outstandingTxns.get(message.getTxnId());
if (txn == null) {
// If the borrow is the first fragment for a transaction, run it as
// a single partition fragment; Must not engage/pause this
// site on a MP transaction before the SP instructs to do so.
// Do not track the borrow task as outstanding - it completes
// immediately and is not a valid transaction state for
// full MP participation (it claims everything can run as SP).
txn = new BorrowTransactionState(newSpHandle, message);
}
if (message.getFragmentTaskMessage().isSysProcTask()) {
final SysprocFragmentTask task =
new SysprocFragmentTask(m_mailbox, (ParticipantTransactionState)txn,
m_pendingTasks, message.getFragmentTaskMessage(),
message.getInputDepMap());
m_pendingTasks.offer(task);
}
else {
final FragmentTask task =
new FragmentTask(m_mailbox, (ParticipantTransactionState)txn,
m_pendingTasks, message.getFragmentTaskMessage(),
message.getInputDepMap());
m_pendingTasks.offer(task);
}
}
// SpSchedulers will see FragmentTaskMessage for:
// - The scatter fragment(s) of a multi-part transaction (normal or sysproc)
// - Borrow tasks to do the local fragment work if this partition is the
// buddy of the MPI. Borrow tasks may include input dependency tables for
// aggregation fragments, or not, if it's a replicated table read.
// For multi-batch MP transactions, we'll need to look up the transaction state
// that gets created when the first batch arrives.
// During command log replay a new SP handle is going to be generated, but it really
// doesn't matter, it isn't going to be used for anything.
void handleFragmentTaskMessage(FragmentTaskMessage message)
{
FragmentTaskMessage msg = message;
long newSpHandle;
if (m_isLeader) {
// Quick hack to make progress...we need to copy the FragmentTaskMessage
// before we start mucking with its state (SPHANDLE). We need to revisit
// all the messaging mess at some point.
msg = new FragmentTaskMessage(message.getInitiatorHSId(),
message.getCoordinatorHSId(), message);
//Not going to use the timestamp from the new Ego because the multi-part timestamp is what should be used
if (!message.isReadOnly()) {
TxnEgo ego = advanceTxnEgo();
newSpHandle = ego.getTxnId();
} else {
newSpHandle = getMaxTaskedSpHandle();
}
msg.setSpHandle(newSpHandle);
if (msg.getInitiateTask() != null) {
msg.getInitiateTask().setSpHandle(newSpHandle);//set the handle
//Trigger reserialization so the new handle is used
msg.setStateForDurability(msg.getInitiateTask(), msg.getInvolvedPartitions());
}
/*
* If there a replicas to send it to, forward it!
* Unless... it's read only AND not a sysproc. Read only sysprocs may expect to be sent
* everywhere.
* In that case don't propagate it to avoid a determinism check and extra messaging overhead
*/
if (m_sendToHSIds.length > 0 && (!msg.isReadOnly() || msg.isSysProcTask())) {
FragmentTaskMessage replmsg =
new FragmentTaskMessage(m_mailbox.getHSId(),
m_mailbox.getHSId(), msg);
m_mailbox.send(m_sendToHSIds,
replmsg);
DuplicateCounter counter;
/*
* Non-determinism should be impossible to happen with MP fragments.
* if you see "MP_DETERMINISM_ERROR" as procedure name in the crash logs
* something has horribly gone wrong.
*/
if (message.getFragmentTaskType() != FragmentTaskMessage.SYS_PROC_PER_SITE) {
counter = new DuplicateCounter(
msg.getCoordinatorHSId(),
msg.getTxnId(), m_replicaHSIds, "MP_DETERMINISM_ERROR");
}
else {
counter = new SysProcDuplicateCounter(
msg.getCoordinatorHSId(),
msg.getTxnId(), m_replicaHSIds, "MP_DETERMINISM_ERROR");
}
m_duplicateCounters.put(new DuplicateCounterKey(msg.getTxnId(), newSpHandle), counter);
}
}
else {
newSpHandle = msg.getSpHandle();
setMaxSeenTxnId(newSpHandle);
}
Iv2Trace.logFragmentTaskMessage(message, m_mailbox.getHSId(), newSpHandle, false);
doLocalFragmentOffer(msg);
}
/**
* Do the work necessary to turn the FragmentTaskMessage into a
* TransactionTask which can be queued to the TransactionTaskQueue.
* This is reused by both the normal message handling path and the repair
* path, and assumes that the caller has dealt with or ensured that the
* necessary ID, SpHandles, and replication issues are resolved.
*/
private void doLocalFragmentOffer(FragmentTaskMessage msg)
{
TransactionState txn = m_outstandingTxns.get(msg.getTxnId());
boolean logThis = false;
// bit of a hack...we will probably not want to create and
// offer FragmentTasks for txn ids that don't match if we have
// something in progress already
if (txn == null) {
txn = new ParticipantTransactionState(msg.getSpHandle(), msg);
m_outstandingTxns.put(msg.getTxnId(), txn);
// Only want to send things to the command log if it satisfies this predicate
// AND we've never seen anything for this transaction before. We can't
// actually log until we create a TransactionTask, though, so just keep track
// of whether it needs to be done.
logThis = (msg.getInitiateTask() != null && !msg.getInitiateTask().isReadOnly());
}
// Check to see if this is the final task for this txn, and if so, if we can close it out early
// Right now, this just means read-only.
// NOTE: this overlaps slightly with CompleteTransactionMessage handling completion. It's so tiny
// that for now, meh, but if this scope grows then it should get refactored out
if (msg.isFinalTask() && txn.isReadOnly()) {
m_outstandingTxns.remove(msg.getTxnId());
}
TransactionTask task;
if (msg.isSysProcTask()) {
task =
new SysprocFragmentTask(m_mailbox, (ParticipantTransactionState)txn,
m_pendingTasks, msg, null);
}
else {
task =
new FragmentTask(m_mailbox, (ParticipantTransactionState)txn,
m_pendingTasks, msg, null);
}
if (logThis) {
ListenableFuture<Object> durabilityBackpressureFuture =
m_cl.log(msg.getInitiateTask(), msg.getSpHandle(), Ints.toArray(msg.getInvolvedPartitions()),
m_durabilityListener, task);
//Durability future is always null for sync command logging
//the transaction will be delivered again by the CL for execution once durable
//Async command logging has to offer the task immediately with a Future for backpressure
if (durabilityBackpressureFuture != null) {
m_pendingTasks.offer(task.setDurabilityBackpressureFuture(durabilityBackpressureFuture));
} else {
/* Getting here means that the task is the first fragment of an MP txn and
* synchronous command logging is on, so create a backlog for future tasks of
* this MP arrived before it's marked durable.
*
* This is important for synchronous command logging and MP txn restart. Without
* this, a restarted MP txn may not be gated by logging of the first fragment.
*/
assert !m_mpsPendingDurability.containsKey(task.getTxnId());
m_mpsPendingDurability.put(task.getTxnId(), new ArrayDeque<TransactionTask>());
}
} else {
queueOrOfferMPTask(task);
}
}
/**
* Offer all fragment tasks and complete transaction tasks queued for durability for the given
* MP transaction, and remove the entry from the pending map so that future ones won't be
* queued.
*
* @param txnId The MP transaction ID.
*/
private void offerPendingMPTasks(long txnId)
{
Queue<TransactionTask> pendingTasks = m_mpsPendingDurability.get(txnId);
if (pendingTasks != null) {
for (TransactionTask task : pendingTasks) {
m_pendingTasks.offer(task);
}
m_mpsPendingDurability.remove(txnId);
}
}
/**
* Check if the MP task has to be queued because the first fragment is still being logged
* synchronously to the command log. If not, offer it to the transaction task queue.
*
* @param task A fragment task or a complete transaction task
*/
private void queueOrOfferMPTask(TransactionTask task)
{
// The pending map will only have an entry for the transaction if the first fragment is
// still pending durability.
Queue<TransactionTask> pendingTasks = m_mpsPendingDurability.get(task.getTxnId());
if (pendingTasks != null) {
pendingTasks.offer(task);
} else {
m_pendingTasks.offer(task);
}
}
// Eventually, the master for a partition set will need to be able to dedupe
// FragmentResponses from its replicas.
public void handleFragmentResponseMessage(FragmentResponseMessage message)
{
// Send the message to the duplicate counter, if any
DuplicateCounter counter =
m_duplicateCounters.get(new DuplicateCounterKey(message.getTxnId(), message.getSpHandle()));
if (counter != null) {
int result = counter.offer(message);
if (result == DuplicateCounter.DONE) {
m_duplicateCounters.remove(new DuplicateCounterKey(message.getTxnId(), message.getSpHandle()));
m_repairLogTruncationHandle = message.getSpHandle();
FragmentResponseMessage resp = (FragmentResponseMessage)counter.getLastResponse();
// MPI is tracking deps per partition HSID. We need to make
// sure we write ours into the message getting sent to the MPI
resp.setExecutorSiteId(m_mailbox.getHSId());
m_mailbox.send(counter.m_destinationId, resp);
}
else if (result == DuplicateCounter.MISMATCH) {
VoltDB.crashGlobalVoltDB("HASH MISMATCH running multi-part procedure.", true, null);
}
// doing duplicate suppresion: all done.
return;
}
m_mailbox.send(message.getDestinationSiteId(), message);
}
public void handleCompleteTransactionMessage(CompleteTransactionMessage message)
{
CompleteTransactionMessage msg = message;
if (m_isLeader) {
msg = new CompleteTransactionMessage(message);
// Set the spHandle so that on repair the new master will set the max seen spHandle
// correctly
if (!msg.isForReplay()) advanceTxnEgo();
msg.setSpHandle(getCurrentTxnId());
if (m_sendToHSIds.length > 0) {
m_mailbox.send(m_sendToHSIds, msg);
}
} else {
setMaxSeenTxnId(msg.getSpHandle());
}
TransactionState txn = m_outstandingTxns.get(msg.getTxnId());
// We can currently receive CompleteTransactionMessages for multipart procedures
// which only use the buddy site (replicated table read). Ignore them for
// now, fix that later.
if (txn != null)
{
Iv2Trace.logCompleteTransactionMessage(msg, m_mailbox.getHSId());
final CompleteTransactionTask task =
new CompleteTransactionTask(txn, m_pendingTasks, msg, m_drGateway);
queueOrOfferMPTask(task);
// If this is a restart, then we need to leave the transaction state around
if (!msg.isRestart()) {
m_outstandingTxns.remove(msg.getTxnId());
}
}
}
public void handleIv2LogFaultMessage(Iv2LogFaultMessage message)
{
// Should only receive these messages at replicas, call the internal log write with
// the provided SP handle
writeIv2ViableReplayEntryInternal(message.getSpHandle());
setMaxSeenTxnId(message.getSpHandle());
}
public void handleDumpMessage()
{
String who = CoreUtils.hsIdToString(m_mailbox.getHSId());
hostLog.warn("State dump for site: " + who);
hostLog.warn("" + who + ": partition: " + m_partitionId + ", isLeader: " + m_isLeader);
if (m_isLeader) {
hostLog.warn("" + who + ": replicas: " + CoreUtils.hsIdCollectionToString(m_replicaHSIds));
if (m_sendToHSIds.length > 0) {
m_mailbox.send(m_sendToHSIds, new DumpMessage());
}
}
hostLog.warn("" + who + ": most recent SP handle: " + getCurrentTxnId() + " " +
TxnEgo.txnIdToString(getCurrentTxnId()));
hostLog.warn("" + who + ": outstanding txns: " + m_outstandingTxns.keySet() + " " +
TxnEgo.txnIdCollectionToString(m_outstandingTxns.keySet()));
hostLog.warn("" + who + ": TransactionTaskQueue: " + m_pendingTasks.toString());
if (m_duplicateCounters.size() > 0) {
hostLog.warn("" + who + ": duplicate counters: ");
for (Entry<DuplicateCounterKey, DuplicateCounter> e : m_duplicateCounters.entrySet()) {
hostLog.warn("\t" + who + ": " + e.getKey().toString() + ": " + e.getValue().toString());
}
}
}
@Override
public void setCommandLog(CommandLog cl) {
m_cl = cl;
}
@Override
public void enableWritingIv2FaultLog()
{
m_replayComplete = true;
writeIv2ViableReplayEntry();
}
/**
* If appropriate, cause the initiator to write the viable replay set to the command log
* Use when it's unclear whether the caller is the leader or a replica; the right thing will happen.
*/
void writeIv2ViableReplayEntry()
{
if (m_replayComplete) {
if (m_isLeader) {
// write the viable set locally
long faultSpHandle = advanceTxnEgo().getTxnId();
writeIv2ViableReplayEntryInternal(faultSpHandle);
// Generate Iv2LogFault message and send it to replicas
Iv2LogFaultMessage faultMsg = new Iv2LogFaultMessage(faultSpHandle);
m_mailbox.send(m_sendToHSIds,
faultMsg);
}
}
}
/**
* Write the viable replay set to the command log with the provided SP Handle
*/
void writeIv2ViableReplayEntryInternal(long spHandle)
{
if (m_replayComplete) {
m_cl.logIv2Fault(m_mailbox.getHSId(), new HashSet<Long>(m_replicaHSIds), m_partitionId,
spHandle);
}
}
@Override
public CountDownLatch snapshotCompleted(SnapshotCompletionEvent event)
{
if (event.truncationSnapshot && event.didSucceed) {
synchronized(m_lock) {
writeIv2ViableReplayEntry();
}
}
return new CountDownLatch(0);
}
@Override
public void dump()
{
m_replaySequencer.dump(m_mailbox.getHSId());
tmLog.info(String.format("%s: %s", CoreUtils.hsIdToString(m_mailbox.getHSId()), m_pendingTasks));
}
}
|
package org.voltdb.utils;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.TimeZone;
import java.util.concurrent.LinkedBlockingQueue;
import org.supercsv.io.CsvListReader;
import org.supercsv.io.ICsvListReader;
import org.supercsv.prefs.CsvPreference;
import org.supercsv_voltpatches.tokenizer.Tokenizer;
import org.voltcore.logging.VoltLogger;
import org.voltdb.CLIConfig;
import org.voltdb.client.AutoReconnectListener;
import org.voltdb.client.Client;
import org.voltdb.client.ClientConfig;
import org.voltdb.client.ClientFactory;
import org.voltdb.client.ClientImpl;
import org.voltdb.client.ClientResponse;
/**
* CSVLoader is a simple utility to load data from a CSV formatted file to a table.
*
* This utility processes partitioned data efficiently and creates as many partition processors.
* For partitioned data each processor calls
* @LoadSinglepartitionTable
*
* For multi-partitioned data it uses a single processor which call
* @LoadMultipartitionTable
*
* The maxerror indicates maximum number of errors it can tolerate.
* Its a threshold but since processors are processing in parallel we may process rows beyond
* maxerror and additional errors may occur. Only first maxerror indicated errors will be reported.
*
*/
public class CSVLoader implements BulkLoaderErrorHandler {
/**
* Path of invalid row file that will be created.
*/
static String pathInvalidrowfile = "";
/**
* report file name
*/
static String pathReportfile = "csvloaderReport.log";
/**
* log file name
*/
static String pathLogfile = "csvloaderLog.log";
private static final VoltLogger m_log = new VoltLogger("CSVLOADER");
private static CSVConfig config = null;
private static long start = 0;
private static boolean standin = false;
private static BufferedWriter out_invaliderowfile;
private static BufferedWriter out_logfile;
private static BufferedWriter out_reportfile;
private static CsvPreference csvPreference = null;
/**
* default CSV separator
*/
public static final char DEFAULT_SEPARATOR = ',';
/**
* default quote char
*/
public static final char DEFAULT_QUOTE_CHARACTER = '\"';
/**
* default escape char
*/
public static final char DEFAULT_ESCAPE_CHARACTER = '\\';
/**
* Are we using strict quotes
*/
public static final boolean DEFAULT_STRICT_QUOTES = false;
/**
* Number of lines to skip in CSV
*/
public static final int DEFAULT_SKIP_LINES = 0;
/**
* Allow whitespace?
*/
public static final boolean DEFAULT_NO_WHITESPACE = false;
/**
* Size limit for each column.
*/
public static final long DEFAULT_COLUMN_LIMIT_SIZE = 16777216;
/**
* Using upsert instead of insert
*/
public static final boolean DEFAULT_UPSERT_MODE = false;
/**
* First line is column name?
*/
public static final boolean DEFAULT_HEADER = false;
/**
* Stop when all connections are lost?
*/
public static final boolean DEFAULT_STOP_ON_DISCONNECT = false;
/**
* Used for testing only.
*/
public static boolean testMode = false;
private class ErrorInfoItem {
public long lineNumber;
public String[] errorInfo;
ErrorInfoItem(long line, String[] info) {
lineNumber = line;
errorInfo = info;
}
}
private static final int ERROR_INFO_QUEUE_SIZE = Integer.getInteger("ERROR_INFO_QUEUE_SIZE", 500);
//Errors we keep track only upto maxerrors
private final LinkedBlockingQueue<ErrorInfoItem> m_errorInfo = new LinkedBlockingQueue<ErrorInfoItem>(ERROR_INFO_QUEUE_SIZE);
private volatile long m_errorCount = 0;
private class ErrorInfoFlushProcessor extends Thread {
@Override
public void run() {
while (true) {
try {
ErrorInfoItem currItem;
currItem = m_errorInfo.take();
if (currItem.lineNumber == -1) {
return;
}
if (currItem.errorInfo.length != 2) {
System.out.println("internal error, information is not enough");
}
out_invaliderowfile.write(currItem.errorInfo[0] + "\n");
String message = "Invalid input on line " + currItem.lineNumber + ". " + currItem.errorInfo[1];
m_log.error(message);
out_logfile.write(message + "\n Content: " + currItem.errorInfo[0] + "\n");
m_errorCount++;
} catch (FileNotFoundException e) {
m_log.error("CSV report directory '" + config.reportdir
+ "' does not exist.");
} catch (Exception x) {
m_log.error(x.getMessage());
}
}
}
}
private ErrorInfoFlushProcessor m_errorinfoProcessor = null;
public void launchErrorFlushProcessor() {
m_errorinfoProcessor = new ErrorInfoFlushProcessor();
m_errorinfoProcessor.start();
}
public void waitForErrorFlushComplete() throws InterruptedException {
//Put an empty ErrorInfoItem
ErrorInfoItem emptyErrorInfo = new ErrorInfoItem(-1, null);
if (!m_errorInfo.offer(emptyErrorInfo)) {
m_errorInfo.put(emptyErrorInfo);
}
if (m_errorinfoProcessor != null) {
m_errorinfoProcessor.join();
}
}
@Override
public boolean handleError(RowWithMetaData metaData, ClientResponse response, String error) {
synchronized (m_errorInfo) {
//Don't collect more than we want to report.
if (m_errorCount + m_errorInfo.size() >= config.maxerrors) {
return true;
}
String rawLine;
if (metaData.rawLine == null) {
rawLine = "Unknown line content";
} else {
rawLine = metaData.rawLine.toString();
}
String infoStr = (response != null) ? response.getStatusString() : error;
String[] info = {rawLine, infoStr};
ErrorInfoItem newErrorInfo = new ErrorInfoItem(metaData.lineNumber, info);
try {
if (!m_errorInfo.offer(newErrorInfo)) {
m_errorInfo.put(newErrorInfo);
}
} catch (InterruptedException e) {
}
if (response != null) {
byte status = response.getStatus();
if (status != ClientResponse.USER_ABORT && status != ClientResponse.GRACEFUL_FAILURE) {
System.out.println("Fatal Response from server for: " + response.getStatusString()
+ " for: " + rawLine);
System.exit(1);
}
}
return false;
}
}
@Override
public boolean hasReachedErrorLimit()
{
return m_errorCount + m_errorInfo.size() >= config.maxerrors;
}
/**
* Configuration options.
*/
public static class CSVConfig extends CLIConfig {
@Option(shortOpt = "f", desc = "location of CSV input file")
String file = "";
@Option(shortOpt = "p", desc = "procedure name to insert the data into the database")
String procedure = "";
@Option(desc = "maximum rows to be read from the CSV file")
int limitrows = Integer.MAX_VALUE;
@Option(shortOpt = "r", desc = "directory path for report files")
String reportdir = System.getProperty("user.dir");
@Option(shortOpt = "m", desc = "maximum errors allowed")
int maxerrors = 100;
@Option(desc = "different ways to handle blank items: {error|null|empty} (default: null)")
String blank = "null";
@Option(desc = "delimiter to use for separating entries")
char separator = DEFAULT_SEPARATOR;
@Option(desc = "character to use for quoted elements (default: \")")
char quotechar = DEFAULT_QUOTE_CHARACTER;
@Option(desc = "character to use for escaping a separator or quote (default: \\)")
char escape = DEFAULT_ESCAPE_CHARACTER;
@Option(desc = "require all input values to be enclosed in quotation marks", hasArg = false)
boolean strictquotes = DEFAULT_STRICT_QUOTES;
@Option(desc = "number of lines to skip before inserting rows into the database")
long skip = DEFAULT_SKIP_LINES;
@Option(desc = "do not allow whitespace between values and separators", hasArg = false)
boolean nowhitespace = DEFAULT_NO_WHITESPACE;
@Option(desc = "max size of a quoted column in bytes(default: 16777216 = 16MB)")
long columnsizelimit = DEFAULT_COLUMN_LIMIT_SIZE;
@Option(shortOpt = "s", desc = "list of servers to connect to (default: localhost)")
String servers = "localhost";
@Option(desc = "username when connecting to the servers")
String user = "";
@Option(desc = "password to use when connecting to servers")
String password = "";
@Option(desc = "port to use when connecting to database (default: 21212)")
int port = Client.VOLTDB_SERVER_PORT;
@Option(shortOpt = "z", desc = "timezone for interpreting date and time strings")
String timezone = "";
@Option(shortOpt = "n", desc = "Custom null string, overrides all other Null pattern matching")
String customNullString = "";
// add a charset flag as "c"
@Option(shortOpt = "c", desc = "character set , default system character set")
String charset = "utf-8";
@Option(desc = "Disables the quote character. All characters between delimiters, including quote characters, are included in the input.",
hasArg = false)
boolean noquotechar = false;
@Option(desc = "Enable SSL, Optionally provide configuration file.")
String ssl = "";
@Option(desc = "Enable Kerberos and use provided JAAS login configuration entry key.")
String kerberos = "";
/**
* Batch size for processing batched operations.
*/
@Option(desc = "Batch Size for processing.")
public int batch = 200;
@Option(desc = "First line of csv file is column name.", hasArg = false)
boolean header = DEFAULT_HEADER;
/**
* Table name to insert CSV data into.
*/
@AdditionalArgs(desc = "insert the data into database by TABLENAME.insert procedure by default")
public String table = "";
// This is set to true when -p option us used.
boolean useSuppliedProcedure = false;
@Option(desc = "Use upsert instead of insert", hasArg = false)
boolean update = DEFAULT_UPSERT_MODE;
@Option(desc = "Stop when all connections are lost", hasArg = false)
boolean stopondisconnect = DEFAULT_STOP_ON_DISCONNECT;
/**
* Validate command line options.
*/
@Override
public void validate() {
if (header && !procedure.equals("")) {
exitWithMessageAndUsage("--header and --procedure options are mutually exclusive.");
}
if (maxerrors < 0) {
exitWithMessageAndUsage("abortfailurecount must be >=0");
}
if (procedure.equals("") && table.equals("")) {
exitWithMessageAndUsage("procedure name or a table name required");
}
if (!procedure.equals("") && !table.equals("")) {
exitWithMessageAndUsage("Only a procedure name or a table name required, pass only one please");
}
if (skip < 0) {
exitWithMessageAndUsage("skipline must be >= 0");
}
if (port < 0) {
exitWithMessageAndUsage("port number must be >= 0");
}
if (batch < 0) {
exitWithMessageAndUsage("batch size number must be >= 0");
}
if(!customNullString.isEmpty() && !blank.equals("error")){
blank = "empty";
}
if (!blank.equalsIgnoreCase("error") &&
!blank.equalsIgnoreCase("null") &&
!blank.equalsIgnoreCase("empty")) {
exitWithMessageAndUsage("blank configuration specified must be one of {error|null|empty}");
}
if ((procedure != null) && (procedure.trim().length() > 0)) {
useSuppliedProcedure = true;
}
if ((useSuppliedProcedure) && (update)){
update = false;
exitWithMessageAndUsage("update is not applicable when stored procedure specified");
}
if(!timezone.equals("")){
boolean isValidTimezone = false;
for (String tzId : TimeZone.getAvailableIDs()) {
if(tzId.equals(timezone)) {
TimeZone.setDefault(TimeZone.getTimeZone(timezone));
isValidTimezone = true;
break;
}
}
if(!isValidTimezone){
exitWithMessageAndUsage("specified timezone \"" + timezone + "\" is invalid");
}
}
}
/**
* Usage
*/
@Override
public void printUsage() {
System.out
.println("Usage: csvloader [args] tablename");
System.out
.println(" csvloader [args] -p procedurename");
super.printUsage();
}
}
/**
* csvloader main. (main is directly used by tests as well be sure to reset statics that you need to start over)
*
* @param args
* @throws IOException
* @throws InterruptedException
*
*/
public static void main(String[] args) throws IOException,
InterruptedException {
start = System.currentTimeMillis();
long insertTimeStart = start;
long insertTimeEnd;
final CSVConfig cfg = new CSVConfig();
cfg.parse(CSVLoader.class.getName(), args);
config = cfg;
if (config.noquotechar) {
config.quotechar = '\u0000';
}
configuration();
final Tokenizer tokenizer;
ICsvListReader listReader = null;
try {
if (CSVLoader.standin) {
tokenizer = new Tokenizer(new BufferedReader(new InputStreamReader(System.in)), csvPreference,
config.strictquotes, config.escape, config.columnsizelimit,
config.skip, config.header);
listReader = new CsvListReader(tokenizer, csvPreference);
} else {
FileInputStream fis = new FileInputStream(config.file);
InputStreamReader isr = new InputStreamReader(fis, config.charset);
tokenizer = new Tokenizer(isr,
csvPreference,
config.strictquotes,
config.escape,
config.columnsizelimit,
config.skip,
config.header);
listReader = new CsvListReader(tokenizer, csvPreference);
}
} catch (FileNotFoundException e) {
m_log.error("CSV file '" + config.file + "' could not be found.");
System.exit(-1);
}
// Split server list
final String[] serverlist = config.servers.split(",");
// If we need to prompt the user for a password, do so.
config.password = CLIConfig.readPasswordIfNeeded(config.user, config.password, "Enter password: ");
// Create connection
final ClientConfig c_config;
AutoReconnectListener listener = new AutoReconnectListener();
if (config.stopondisconnect) {
c_config = new ClientConfig(config.user, config.password, null);
c_config.setReconnectOnConnectionLoss(false);
} else {
c_config = new ClientConfig(config.user, config.password, listener);
c_config.setReconnectOnConnectionLoss(true);
}
if (config.ssl != null && !config.ssl.trim().isEmpty()) {
c_config.setTrustStoreConfigFromPropertyFile(config.ssl);
c_config.enableSSL();
}
if (!config.kerberos.trim().isEmpty()) {
c_config.enableKerberosAuthentication(config.kerberos);
}
c_config.setProcedureCallTimeout(0); // Set procedure all to infinite
Client csvClient = null;
try {
csvClient = CSVLoader.getClient(c_config, serverlist, config.port);
} catch (Exception e) {
m_log.error("Error connecting to the servers: "
+ config.servers);
System.exit(-1);
}
assert (csvClient != null);
try {
long readerTime;
long insertCount;
long ackCount;
long rowsQueued;
final CSVLoader errHandler = new CSVLoader();
final CSVDataLoader dataLoader;
errHandler.launchErrorFlushProcessor();
if (config.useSuppliedProcedure) {
dataLoader = new CSVTupleDataLoader((ClientImpl) csvClient, config.procedure, errHandler);
} else {
dataLoader = new CSVBulkDataLoader((ClientImpl) csvClient, config.table, config.batch, config.update, errHandler);
}
if (!config.stopondisconnect) {
listener.setLoader(dataLoader);
}
CSVFileReader.initializeReader(cfg, csvClient, listReader);
CSVFileReader csvReader = new CSVFileReader(dataLoader, errHandler);
Thread readerThread = new Thread(csvReader);
readerThread.setName("CSVFileReader");
readerThread.setDaemon(true);
//Wait for reader to finish.
readerThread.start();
readerThread.join();
insertTimeEnd = System.currentTimeMillis();
csvClient.close();
errHandler.waitForErrorFlushComplete();
readerTime = (csvReader.m_parsingTime) / 1000000;
insertCount = dataLoader.getProcessedRows();
ackCount = insertCount - dataLoader.getFailedRows();
rowsQueued = CSVFileReader.m_totalRowCount.get();
//Close the reader.
try {
listReader.close();
} catch (Exception ex) {
m_log.error("Error closing reader: " + ex);
} finally {
m_log.debug("Rows Queued by Reader: " + rowsQueued);
}
if (errHandler.hasReachedErrorLimit()) {
m_log.warn("The number of failed rows exceeds the configured maximum failed rows: "
+ config.maxerrors);
}
m_log.debug("Parsing CSV file took " + readerTime + " milliseconds.");
m_log.debug("Inserting Data took " + ((insertTimeEnd - insertTimeStart) - readerTime) + " milliseconds.");
m_log.info("Read " + insertCount + " rows from file and successfully inserted "
+ ackCount + " rows (final)");
errHandler.produceFiles(ackCount, insertCount);
close_cleanup();
//In test junit mode we let it continue for reuse
if (!CSVLoader.testMode) {
System.exit(errHandler.m_errorInfo.isEmpty() ? 0 : -1);
}
} catch (Exception ex) {
m_log.error("Exception Happened while loading CSV data: " + ex);
System.exit(1);
}
}
private static void configuration() {
csvPreference = new CsvPreference.Builder(config.quotechar, config.separator, "\n").build();
if (config.file.equals("")) {
standin = true;
}
String insertProcedure;
if (!config.table.equals("")) {
insertProcedure = config.table.toUpperCase() + ".insert";
} else {
insertProcedure = config.procedure;
}
if (!config.reportdir.endsWith("/")) {
config.reportdir += "/";
}
try {
File dir = new File(config.reportdir);
if (!dir.exists()) {
dir.mkdirs();
}
} catch (Exception x) {
m_log.error(x.getMessage(), x);
System.exit(-1);
}
insertProcedure = insertProcedure.replaceAll("\\.", "_");
pathInvalidrowfile = config.reportdir + "csvloader_" + insertProcedure + "_"
+ "invalidrows.csv";
pathLogfile = config.reportdir + "csvloader_" + insertProcedure + "_"
+ "log.log";
pathReportfile = config.reportdir + "csvloader_" + insertProcedure + "_"
+ "report.log";
try {
out_invaliderowfile = new BufferedWriter(new FileWriter(
pathInvalidrowfile));
out_logfile = new BufferedWriter(new FileWriter(pathLogfile));
out_reportfile = new BufferedWriter(new FileWriter(pathReportfile));
} catch (IOException e) {
m_log.error(e.getMessage());
System.exit(-1);
}
}
/**
* Get connection to servers in cluster.
*
* @param config
* @param servers
* @param port
* @return
* @throws Exception
*/
public static Client getClient(ClientConfig config, String[] servers,
int port) throws Exception {
config.setTopologyChangeAware(true); // Set client to be topology-aware
final Client client = ClientFactory.createClient(config);
for (String server : servers) {
// Try connecting servers one by one until we have a success
try {
client.createConnection(server.trim(), port);
break;
} catch(IOException e) {
// Only swallow the exceptions from Java network or connection problems
// Unresolved hostname exceptions will be thrown
}
}
if (client.getConnectedHostList().isEmpty()) {
throw new Exception("Unable to connect to any servers.");
}
return client;
}
private void produceFiles(long ackCount, long insertCount) {
long latency = System.currentTimeMillis() - start;
m_log.info("Elapsed time: " + latency / 1000F
+ " seconds");
try {
// Get elapsed time in seconds
float elapsedTimeSec = latency / 1000F;
out_reportfile.write("CSVLoader elaspsed: " + elapsedTimeSec + " seconds\n");
long trueSkip;
long totolLineCnt;
long totalRowCnt;
if (config.useSuppliedProcedure) {
totolLineCnt = CSVFileReader.m_totalLineCount.get();
totalRowCnt = CSVFileReader.m_totalRowCount.get();
} else {
totolLineCnt = CSVFileReader.m_totalLineCount.get();
totalRowCnt = CSVFileReader.m_totalRowCount.get();
}
//get the actual number of lines skipped
if (config.skip < totolLineCnt) {
trueSkip = config.skip;
} else {
trueSkip = totolLineCnt;
}
out_reportfile.write("Number of input lines skipped: "
+ trueSkip + "\n");
out_reportfile.write("Number of lines read from input: "
+ (totolLineCnt - trueSkip) + "\n");
if (config.limitrows == -1) {
out_reportfile.write("Input stopped after "
+ totalRowCnt + " rows read" + "\n");
}
out_reportfile.write("Number of rows discovered: "
+ totolLineCnt + "\n");
out_reportfile.write("Number of rows successfully inserted: "
+ ackCount + "\n");
// if prompted msg changed, change it also for test case
out_reportfile.write("Number of rows that could not be inserted: "
+ m_errorCount + "\n");
out_reportfile.write("CSVLoader rate: " + insertCount
/ elapsedTimeSec + " row/s\n");
m_log.info("Invalid row file: " + pathInvalidrowfile);
m_log.info("Log file: " + pathLogfile);
m_log.info("Report file: " + pathReportfile);
out_invaliderowfile.flush();
out_logfile.flush();
out_reportfile.flush();
} catch (FileNotFoundException e) {
m_log.error("CSV report directory '" + config.reportdir
+ "' does not exist.");
} catch (Exception x) {
m_log.error(x.getMessage());
}
}
private static void close_cleanup() throws IOException,
InterruptedException {
out_invaliderowfile.close();
out_logfile.close();
out_reportfile.close();
}
}
|
package gov.nih.nci.nautilus.test;
import gov.nih.nci.nautilus.criteria.*;
import gov.nih.nci.nautilus.data.PatientData;
import gov.nih.nci.nautilus.de.*;
import gov.nih.nci.nautilus.de.AgeAtDiagnosisDE.UpperAgeLimit;
import gov.nih.nci.nautilus.query.*;
import gov.nih.nci.nautilus.queryprocessing.ge.GeneExpr;
import gov.nih.nci.nautilus.queryprocessing.ge.GeneExpr.GeneExprSingle;
import gov.nih.nci.nautilus.resultset.DimensionalViewContainer;
import gov.nih.nci.nautilus.resultset.ResultSet;
import gov.nih.nci.nautilus.resultset.Resultant;
import gov.nih.nci.nautilus.resultset.ResultsContainer;
import gov.nih.nci.nautilus.resultset.ResultsetProcessor;
import gov.nih.nci.nautilus.resultset.gene.GeneExprSingleViewResultsContainer;
import gov.nih.nci.nautilus.resultset.gene.GeneResultset;
import gov.nih.nci.nautilus.resultset.gene.ReporterResultset;
import gov.nih.nci.nautilus.resultset.gene.SampleFoldChangeValuesResultset;
import gov.nih.nci.nautilus.resultset.gene.ViewByGroupResultset;
import gov.nih.nci.nautilus.view.GroupType;
import gov.nih.nci.nautilus.view.ViewFactory;
import gov.nih.nci.nautilus.view.ViewType;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
public class QueryTest extends TestCase {
private static final DecimalFormat resultFormat = new DecimalFormat("0.00");
DiseaseOrGradeCriteria diseaseCrit;
FoldChangeCriteria foldCrit;
CopyNumberCriteria copyNumberCrit;
GeneIDCriteria geneIDCrit;
GeneOntologyCriteria ontologyCrit;
PathwayCriteria pathwayCrit;
RegionCriteria regionCrit;
CloneOrProbeIDCriteria cloneCrit;
CloneOrProbeIDCriteria probeCrit;
ArrayPlatformCriteria allPlatformCrit;
ArrayPlatformCriteria affyOligoPlatformCrit;
ArrayPlatformCriteria cdnaPlatformCrit;
SNPCriteria snpCrit;
SurvivalCriteria survivalCrit;
AgeCriteria ageCriteria;
GenderCriteria genderCrit;
protected void setUp() throws Exception {
buildDiseaseTypeCrit();
buildSurvivalCrit();
buildAgeCrit();
buildGenderCrit();
buildRegionCrit();
buildPlatformCrit();
buildCloneCrit();
buildProbeCrit();
buildFoldChangeCrit();
buildGeneIDCrit();
buildOntologyCrit();
buildPathwayCrit();
buildSNPCrit();
buildCopyChangeCrit();
}
public static class GeneExpression extends QueryTest {
public void testGeneExprQuery() {
GeneExpressionQuery q = (GeneExpressionQuery) QueryManager.createQuery(QueryType.GENE_EXPR_QUERY_TYPE);
q.setQueryName("Test Gene Query");
q.setAssociatedView(ViewFactory.newView(ViewType.GENE_SINGLE_SAMPLE_VIEW));
//q.setGeneIDCrit(geneIDCrit);
q.setGeneOntologyCrit(ontologyCrit);
q.setRegionCrit(regionCrit);
q.setPathwayCrit(pathwayCrit);
//q.setGeneOntologyCrit(ontologyCrit);
//q.setRegionCrit(regionCrit);
//q.setPathwayCrit(pathwayCrit);
q.setArrayPlatformCrit(allPlatformCrit);
//q.setPlatCriteria(affyOligoPlatformCrit);
//q.setPlatCriteria(cdnaPlatformCrit);
//q.setCloneOrProbeIDCrit(cloneCrit);
//q.setCloneProbeCrit(probeCrit);
//q.setDiseaseOrGradeCrit(diseaseCrit);
q.setFoldChgCrit(foldCrit);
try {
CompoundQuery myCompoundQuery = new CompoundQuery(q);
ResultSet[] geneExprObjects = QueryManager.executeQuery(myCompoundQuery);
System.out.println("NUMBER OF RECORDS: " + geneExprObjects.length);
print(geneExprObjects);
if (geneExprObjects.length > 0)
testResultset(geneExprObjects);
} catch(Throwable t ) {
t.printStackTrace();
}
}
private void print(ResultSet[] geneExprObjects) {
int count = 0;
HashSet probeIDS = new HashSet();
HashSet cloneIDs = new HashSet();
for (int i = 0; i < geneExprObjects.length; i++) {
ResultSet obj = geneExprObjects[i];
GeneExpr exprObj = null;
if (obj instanceof GeneExpr.GeneExprGroup) {
exprObj = (GeneExpr.GeneExprGroup) obj;
}
else if (obj instanceof GeneExpr.GeneExprSingle) {
exprObj = (GeneExpr.GeneExprSingle) obj;
}
if (exprObj.getProbesetId() != null) {
System.out.println("Disease: "+ exprObj.getDiseaseType());
System.out.println("ProbesetID: " + exprObj.getProbesetId() + " :Exp Value: "
+ exprObj.getExpressionRatio() + " GeneSymbol: " + exprObj.getGeneSymbol() );
probeIDS.add(exprObj.getProbesetId());
}
if ( exprObj.getCloneId() != null) {
System.out.println("CloneID: " + exprObj.getCloneId()+ " :Exp Value: "
+ exprObj.getExpressionRatio() + " GeneSymbol: " + exprObj.getGeneSymbol());
cloneIDs.add(exprObj.getCloneId() );
}
++count;
}
System.out.println("Total Number Of Samples: " + count);
StringBuffer p = new StringBuffer();
for (Iterator iterator = probeIDS.iterator(); iterator.hasNext();) {
Long aLong = (Long) iterator.next();
p.append(aLong.toString() + ",");
}
System.out.println("Total Probes: " + probeIDS.size());
System.out.println(p.toString());
StringBuffer c = new StringBuffer();
for (Iterator iterator = cloneIDs.iterator(); iterator.hasNext();) {
Long aLong = (Long) iterator.next();
c.append(aLong.toString() + ",");
}
System.out.println("Total clones: " + cloneIDs.size());
System.out.println(c.toString());
return ;
}
public void testResultset(ResultSet[] geneExprObjects){
assertNotNull(geneExprObjects);
assertTrue(geneExprObjects.length > 0);
ResultsContainer resultsContainer = ResultsetProcessor.handleGeneExprSingleView(new Resultant(),(GeneExprSingle[]) geneExprObjects, GroupType.DISEASE_TYPE_GROUP);
if (resultsContainer instanceof DimensionalViewContainer){
DimensionalViewContainer dimensionalViewContainer = (DimensionalViewContainer) resultsContainer;
GeneExprSingleViewResultsContainer geneViewContainer = dimensionalViewContainer.getGeneExprSingleViewContainer();
Collection genes = geneViewContainer.getGeneResultsets();
Collection labels = geneViewContainer.getGroupsLabels();
Collection sampleIds = null;
StringBuffer header = new StringBuffer();
StringBuffer sampleNames = new StringBuffer();
StringBuffer stringBuffer = new StringBuffer();
header.append("Gene\tReporter\t");
sampleNames.append("Name\tName\t\tType\t");
for (Iterator labelIterator = labels.iterator(); labelIterator.hasNext();) {
String label = (String) labelIterator.next();
header.append("Disease: "+label);
sampleIds = geneViewContainer.getBiospecimenLabels(label);
for (Iterator sampleIdIterator = sampleIds.iterator(); sampleIdIterator.hasNext();) {
sampleNames.append(sampleIdIterator.next()+"\t");
header.append("\t");
}
}
//System.out.println("Gene Count: "+genes.size());
System.out.println(header.toString());
System.out.println(sampleNames.toString());
for (Iterator geneIterator = genes.iterator(); geneIterator.hasNext();) {
GeneResultset geneResultset = (GeneResultset)geneIterator.next();
Collection reporters = geneResultset.getReporterResultsets();
//System.out.println("Repoter Count: "+reporters.size());
for (Iterator reporterIterator = reporters.iterator(); reporterIterator.hasNext();) {
ReporterResultset reporterResultset = (ReporterResultset)reporterIterator.next();
Collection groupTypes = reporterResultset.getGroupByResultsets();
//System.out.println("Group Count: "+groupTypes.size());
for (Iterator groupIterator = groupTypes.iterator(); groupIterator.hasNext();) {
ViewByGroupResultset groupResultset = (ViewByGroupResultset)groupIterator.next();
String label = groupResultset.getType().getValue().toString();
sampleIds = geneViewContainer.getBiospecimenLabels(label);
// Collection biospecimens = groupResultset.getBioSpecimenResultsets();
// System.out.println("Biospecimen Count: "+biospecimens.size());
// for (Iterator biospecimenIterator = biospecimens.iterator(); biospecimenIterator.hasNext();) {
// BioSpecimenResultset biospecimenResultset = (BioSpecimenResultset)biospecimenIterator.next();
stringBuffer = new StringBuffer();
stringBuffer.append(geneResultset.getGeneSymbol().getValueObject().toString()+"\t"+
reporterResultset.getReporter().getValue().toString()+"\t\t");
//"| GroupType : "+groupResultset.getType().getValue().toString()+"\t");
for (Iterator sampleIdIterator = sampleIds.iterator(); sampleIdIterator.hasNext();) {
String sampleId = (String) sampleIdIterator.next();
SampleFoldChangeValuesResultset samplesResultset = (SampleFoldChangeValuesResultset) groupResultset.getBioSpecimenResultset(sampleId);
if(samplesResultset != null){
Double ratio = (Double)samplesResultset.getFoldChangeRatioValue().getValue();
stringBuffer.append(resultFormat.format(ratio)+"\t");
}
}
System.out.println(stringBuffer.toString());
}
}
}
}
}
}
public static class CGH extends QueryTest {
public void testCGHExprQuery() {
ComparativeGenomicQuery q = (ComparativeGenomicQuery) QueryManager.createQuery(QueryType.CGH_QUERY_TYPE);
q.setQueryName("Test CGH Query");
//q.setAssociatedView(ViewFactory.newView(ViewType.GENE_SINGLE_SAMPLE_VIEW));
//q.setAssociatedView(ViewFactory.newView(ViewType.GENE_GROUP_SAMPLE_VIEW));
//q.setGeneIDCrit(geneIDCrit);
//q.setGeneOntologyCrit(ontologyCrit);
//q.setRegionCrit(regionCrit);
//q.setPathwayCrit(pathwayCrit);
AssayPlatformCriteria crit = new AssayPlatformCriteria();
crit.setAssayPlatformDE(new AssayPlatformDE(Constants.AFFY_100K_SNP_ARRAY));
q.setAssayPlatformCrit(crit);
//q.setRegionCrit(regionCrit);
//q.setSNPCrit(snpCrit);
q.setGeneIDCrit(geneIDCrit);
q.setDiseaseOrGradeCrit(diseaseCrit);
q.setCopyNumberCrit(copyNumberCrit);
try {
ResultSet[] cghObjects = QueryManager.executeQuery(q);
//print(geneExprObjects);
//testResultset(geneExprObjects);
} catch(Throwable t ) {
t.printStackTrace();
}
}
}
public static class Clinical extends QueryTest {
public void testClinicalQuery() {
ClinicalDataQuery q = (ClinicalDataQuery) QueryManager.createQuery(QueryType.CLINICAL_DATA_QUERY_TYPE);
q.setQueryName("Test Clinical Query");
//q.setSurvivalCrit(survivalCrit);
q.setGenderCrit(genderCrit);
//q.setAgeCrit(ageCriteria);
q.setDiseaseOrGradeCrit(diseaseCrit);
try {
ResultSet[] patientDataObjects = QueryManager.executeQuery(q);
print(patientDataObjects);
//testResultset(geneExprObjects);
} catch(Throwable t ) {
t.printStackTrace();
}
}
/**
* @param cghObjects
*/
private void print(ResultSet[] patientDataObjects) {
for(int i =0; i < patientDataObjects.length ;i++){
PatientData patientData = (PatientData)patientDataObjects[i];
System.out.println( patientData.getSampleId()+
"\t"+patientData.getGender()+
"\t"+patientData.getDiseaseType()+
"\t"+patientData.getSurvivalLengthRange()+
"\t"+patientData.getAgeGroup());
}
}
}
public static Test suite() {
TestSuite suit = new TestSuite();
//suit.addTest(new TestSuite(GeneExpression.class));
//suit.addTest(new TestSuite(CGH.class));
suit.addTest(new TestSuite(Clinical.class));
return suit;
}
public static void main (String[] args) {
junit.textui.TestRunner.run(suite());
}
private void buildGeneIDCrit() {
ArrayList inputIDs = new ArrayList();
inputIDs.add(0, "10050");
inputIDs.add(1, "10056");
//inputIDs.add(0, "220988"); // Locus Link for hnRNPA3
//inputIDs.add(0, "BF195526"); // accession numbers for hnRNPA3 gene are AW080932, AA527502, AA528233
// inputIDs.add(0, "hnRNPA3");
// GeneIdentifierDE.GeneSymbol gs = new GeneIdentifierDE.GeneSymbol("CTNND2");
// inputIDs.add(gs);
GeneIdentifierDE llObj1 =
new GeneIdentifierDE.LocusLink((String)inputIDs.get(0));
GeneIdentifierDE llObj2 =
new GeneIdentifierDE.LocusLink((String)inputIDs.get(1));
GeneIdentifierDE.GeneSymbol gs = new GeneIdentifierDE.GeneSymbol("VEGF");
inputIDs.add(gs);
// GeneIdentifierDE geIDObj =
// new GeneIdentifierDE.LocusLink((String)inputIDs.get(0));
// GeneIdentifierDE geIDObj =
// new GeneIdentifierDE.GenBankAccessionNumber((String)inputIDs.get(0));
//GeneIdentifierDE geIDObj =
// new GeneIdentifierDE.GeneSymbol((String)inputIDs.get(0));
ArrayList geneIDentifiers = new ArrayList();
geneIDentifiers.add(gs);
//geneIDentifiers.add(llObj2);
geneIDCrit = new GeneIDCriteria();
geneIDCrit.setGeneIdentifiers(geneIDentifiers);
}
private void buildRegionCrit() {
regionCrit = new RegionCriteria();
// cytoband and start & end positions are mutually exclusive
regionCrit.setCytoband(new CytobandDE("p21.32"));
//regionCrit.setStart(new BasePairPositionDE.StartPosition(new Integer(6900000)));
// regionCrit.setEnd(new BasePairPositionDE.EndPosition(new Integer(8800000)));
// Chromosome Number is mandatory
regionCrit.setChromNumber(new ChromosomeNumberDE(new String("6")));
}
private void buildOntologyCrit() {
ontologyCrit = new GeneOntologyCriteria();
//ontologyCrit.setGOIdentifier(new GeneOntologyDE("GO:0016021"));
ontologyCrit.setGOIdentifier(new GeneOntologyDE("GO:0005634"));
}
private void buildSNPCrit() {
ArrayList inputIDs = new ArrayList();
// build DBSNPs
SNPIdentifierDE.DBSNP snp1 = new SNPIdentifierDE.DBSNP("rs1396904");
SNPIdentifierDE.DBSNP snp2 = new SNPIdentifierDE.DBSNP("rs10489139");
SNPIdentifierDE.DBSNP snp3 = new SNPIdentifierDE.DBSNP("rs4475768");
SNPIdentifierDE.DBSNP snp4 = new SNPIdentifierDE.DBSNP("rs10492941");
SNPIdentifierDE.DBSNP snp5 = new SNPIdentifierDE.DBSNP("rs966366");
// build SNPProbesets
/*SNPIdentifierDE.SNPProbeSet snp1 = new SNPIdentifierDE.SNPProbeSet ("SNP_A-1676650");
SNPIdentifierDE.SNPProbeSet snp2 = new SNPIdentifierDE.SNPProbeSet ("SNP_A-1748913");
SNPIdentifierDE.SNPProbeSet snp3 = new SNPIdentifierDE.SNPProbeSet ("SNP_A-1667950");
SNPIdentifierDE.SNPProbeSet snp4 = new SNPIdentifierDE.SNPProbeSet ("SNP_A-1642581");
SNPIdentifierDE.SNPProbeSet snp5 = new SNPIdentifierDE.SNPProbeSet ("SNP_A-1657367");
*/
inputIDs.add(snp1 ); inputIDs.add(snp2); inputIDs.add(snp3);
inputIDs.add(snp4); inputIDs.add(snp5);
snpCrit = new SNPCriteria();
snpCrit.setSNPIdentifiers(inputIDs);
}
private void buildPathwayCrit() {
pathwayCrit = new PathwayCriteria();
PathwayDE obj1 = new PathwayDE("AcetaminophenPathway");
PathwayDE obj2 = new PathwayDE("41bbPathway");
Collection pathways = new ArrayList();
pathways.add(obj1); pathways.add(obj2);
pathwayCrit.setPathwayNames(pathways);
}
private void buildPlatformCrit() {
allPlatformCrit = new ArrayPlatformCriteria(new ArrayPlatformDE(Constants.ALL_PLATFROM));
affyOligoPlatformCrit = new ArrayPlatformCriteria(new ArrayPlatformDE(Constants.AFFY_OLIGO_PLATFORM));
cdnaPlatformCrit = new ArrayPlatformCriteria(new ArrayPlatformDE(Constants.CDNA_ARRAY_PLATFORM));
}
private void buildDiseaseTypeCrit() {
diseaseCrit = new DiseaseOrGradeCriteria();
diseaseCrit.setDisease(new DiseaseNameDE("OLIG"));
}
private void buildSurvivalCrit() {
survivalCrit = new SurvivalCriteria();
survivalCrit.setLowerSurvivalRange(
new SurvivalDE.LowerSurvivalRange(new Integer("20")));
survivalCrit.setUpperSurvivalRange(
new SurvivalDE.UpperSurvivalRange(new Integer("40")));
}
private void buildAgeCrit() {
ageCriteria = new AgeCriteria();
ageCriteria.setLowerAgeLimit(
new AgeAtDiagnosisDE.LowerAgeLimit(new Integer("00")));
ageCriteria.setUpperAgeLimit(
new UpperAgeLimit(new Integer("40")));
}
private void buildGenderCrit(){
genderCrit = new GenderCriteria();
genderCrit.setGenderDE(new GenderDE("M"));
}
private void buildProbeCrit() {
probeCrit = new CloneOrProbeIDCriteria();
//probeCrit.setCloneIdentifier(new CloneIdentifierDE.ProbesetID("204655_at"));
// probeCrit.setCloneIdentifier(new CloneIdentifierDE.ProbesetID("243387_at"));
probeCrit.setCloneIdentifier(new CloneIdentifierDE.ProbesetID("210354_at"));
}
private void buildCloneCrit() {
cloneCrit = new CloneOrProbeIDCriteria();
//cloneCrit.setCloneIdentifier(new CloneIdentifierDE.BACClone("IMAGE:755299"));
//cloneCrit.setCloneIdentifier(new CloneIdentifierDE.BACClone("IMAGE:1287390"));
//cloneCrit.setCloneIdentifier(new CloneIdentifierDE.BACClone("IMAGE:2709102"));
//cloneCrit.setCloneIdentifier(new CloneIdentifierDE.BACClone("IMAGE:3303708"));
cloneCrit.setCloneIdentifier(new CloneIdentifierDE.IMAGEClone("1579639"));
}
private void buildFoldChangeCrit() {
Float upRegExpected = new Float(2.0);
Float downRegExpected = new Float(0.8);
ExprFoldChangeDE.UpRegulation upRegObj = new ExprFoldChangeDE.UpRegulation(upRegExpected );
ExprFoldChangeDE.DownRegulation downRegObj = new ExprFoldChangeDE.DownRegulation(downRegExpected );
ExprFoldChangeDE.UnChangedRegulationUpperLimit upUnChangedObj = new ExprFoldChangeDE.UnChangedRegulationUpperLimit(upRegExpected );
ExprFoldChangeDE.UnChangedRegulationDownLimit downUnChangedRegObj = new ExprFoldChangeDE.UnChangedRegulationDownLimit(downRegExpected );
foldCrit = new FoldChangeCriteria();
Collection objs = new ArrayList(4);
//objs.add(upRegObj);
//objs.add(downRegObj);
objs.add(upRegObj); //objs.add(downUnChangedRegObj);
foldCrit.setFoldChangeObjects(objs);
}
private void buildCopyChangeCrit() {
Float amplification = new Float(2.0);
Float deletion = new Float(0.8);
CopyNumberDE.Amplification ampObj = new CopyNumberDE.Amplification(amplification );
CopyNumberDE.Deletion deletionObj = new CopyNumberDE.Deletion(deletion);
CopyNumberDE.UnChangedCopyNumberUpperLimit upCopyNumberObj = new CopyNumberDE.UnChangedCopyNumberUpperLimit(amplification);
CopyNumberDE.UnChangedCopyNumberDownLimit downCopyNumberObj = new CopyNumberDE.UnChangedCopyNumberDownLimit(deletion);
copyNumberCrit = new CopyNumberCriteria();
Collection objs = new ArrayList(4);
objs.add(ampObj);
//objs.add(deletionObj);
//objs.add(upCopyNumberObj); objs.add(downCopyNumberObj);
copyNumberCrit.setCopyNumbers(objs);
}
}
|
package gr.phaistosnetworks.tank;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* TankClient implementation for java.
*/
public class TankClient {
/**
* Constructor for the TankClient object.
* Upon initialization TankClient will attempt to connect to server.
* Upon success, it will check for ping response from server.
* If it's unsuccesful an error will be logged, and it will retry indefinately.
*/
public TankClient(String tankHost, int tankPort) {
this.tankHost = tankHost;
this.tankPort = tankPort;
clientReqId = 0;
log = Logger.getLogger("tankClient");
try {
clientId = ByteManipulator.getStr8("JC01");
} catch (TankException | UnsupportedEncodingException te) {
log.severe("Cannot generate default clientID str8. " + te.getMessage());
System.exit(1);
}
try {
while (true) {
try {
client = new Socket(tankHost, tankPort);
} catch (IOException ioe) {
log.severe(ioe.getMessage());
log.log(Level.FINEST, "ERROR opening socket", ioe);
Thread.sleep(TankClient.RETRY_INTERVAL);
continue;
}
//client.setSoTimeout(1000);
client.setTcpNoDelay(true);
client.setKeepAlive(true);
client.setReuseAddress(true);
log.config("Connected to " + client.getRemoteSocketAddress());
log.config(" + recv buffer size: " + client.getReceiveBufferSize());
log.config(" + send buffer size: " + client.getSendBufferSize());
log.config(" + timeout: " + client.getSoTimeout());
log.config(" + soLinger: " + client.getSoLinger());
log.config(" + nodelay: " + client.getTcpNoDelay());
log.config(" + keepalive: " + client.getKeepAlive());
log.config(" + oobinline: " + client.getOOBInline());
log.config(" + reuseAddress: " + client.getReuseAddress());
bis = new BufferedInputStream(client.getInputStream());
socketOutputStream = client.getOutputStream();
break;
}
while (true) {
if (!getPing(bis)) {
log.severe("ERROR: No Ping Received");
} else {
log.fine("PING OK");
break;
}
}
} catch (IOException | InterruptedException ioe) {
log.log(Level.SEVERE, "ERROR opening Streams", ioe);
System.exit(1);
}
}
/**
* get a valid ping response from server.
*
* @param bis BufferedInputStream to read from
* @return true if valid ping response is received.
*/
private boolean getPing(BufferedInputStream bis) {
try {
int av = bis.available();
if (av == 0) {
return false;
}
byte readByte = (byte)bis.read();
if (readByte != PING_REQ) {
return false;
}
// payload size:u32 is 0 for ping
bis.skip(U32);
} catch (IOException ioe) {
log.log(Level.SEVERE, "ERROR getting ping", ioe);
return false;
}
return true;
}
/**
* tries to get data from the network socket.
* It will loop and retry if there's no data.
* If the data is incomplete, i.e. available less than payload,
* then it will loop and append until payload size is reached.
*/
private List<TankResponse> poll(short requestType, TankRequest request) throws TankException {
ByteManipulator input = new ByteManipulator(null);
int remainder = 0;
int toRead = 0;
while (true) {
int av = 0;
try {
av = bis.available();
} catch (IOException ioe) {
log.log(Level.SEVERE, "Unable to read from socket", ioe);
}
log.finest("bytes available: " + av);
if (av == 0) {
try {
Thread.sleep(TankClient.RETRY_INTERVAL);
} catch (InterruptedException ie) {
log.warning("Cmon, lemme get some sleep ! " + ie.getCause());
} finally {
continue;
}
}
if (remainder >= 0) {
toRead = av;
} else {
toRead = remainder;
}
byte [] ba = new byte[toRead];
try {
bis.read(ba, 0, toRead);
} catch (IOException ioe) {
log.log(Level.SEVERE, "Unable to read from socket", ioe);
}
if (remainder > 0) {
input.append(ba);
} else {
input = new ByteManipulator(ba);
}
byte resp = (byte)input.deSerialize(U8);
long payloadSize = input.deSerialize(U32);
if (resp != requestType) {
log.severe("Bad Response type. Expected " + requestType + ", got " + resp);
throw new TankException("Bad Response type. Expected " + requestType + ", got " + resp);
}
if (payloadSize > input.getRemainingLength()) {
log.finer("Received packet incomplete ");
remainder = (int)(payloadSize - input.getRemainingLength());
input.resetOffset();
continue;
} else {
remainder = 0;
}
log.fine("resp: " + resp);
log.fine("payload size: " + payloadSize);
if (requestType == CONSUME_REQ) {
return processConsumeResponse(input, request);
} else if (requestType == PUBLISH_REQ) {
return getPubResponse(input, request);
}
for (Handler h : log.getHandlers()) {
h.flush();
}
break;
}
return new ArrayList<TankResponse>();
}
/**
* Send consume request to broker.
*/
public List<TankResponse> consume(TankRequest request) throws TankException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
log.fine("Issuing consume with " + request.getTopicsCount() + " topics");
try {
baos.write((byte)CONSUME_REQ);
baos.write(ByteManipulator.serialize(0, U32));
//clientVersion not implemented
baos.write(ByteManipulator.serialize(0L, U16));
baos.write(ByteManipulator.serialize(clientReqId++, U32));
baos.write(clientId);
baos.write(ByteManipulator.serialize(maxWait, U64));
baos.write(ByteManipulator.serialize(minBytes, U32));
baos.write(ByteManipulator.serialize(request.getTopicsCount(), U8));
baos.write(request.serialize());
} catch (IOException ioe) {
log.log(Level.SEVERE, "ERROR creating consume request", ioe);
System.exit(1);
}
byte [] req = baos.toByteArray();
byte [] rsize = (ByteManipulator.serialize(req.length - 5, U32));
log.fine("consume request size is " + req.length);
for (int i = 0; i < U32; i++) {
req[i + 1] = rsize[i];
}
try {
socketOutputStream.write(req);
} catch (IOException ioe) {
log.log(Level.SEVERE, "ERROR writing publish request to socket", ioe);
System.exit(1);
}
return poll(CONSUME_REQ, request);
}
/**
* Processes a response from tank server after we issue a publish request.
*
* @param input a ByteManipulator object containing the data received from server.
*/
private List<TankResponse> getConsumeResponse(ByteManipulator input, TankRequest request) {
List<TankResponse> response = processConsumeResponse(input, request);
return response;
}
/**
* Processes the headers of the input received from tank server.
*
* @param input the ByteManipulator object that contains the bytes received from server.
* @param topics the request topics. Used to crosscheck between request and response.
*/
private List<TankResponse> processConsumeResponse(ByteManipulator input, TankRequest request) {
ArrayList<Chunk> chunkList = new ArrayList<Chunk>();
ArrayList<TankResponse> response = new ArrayList<TankResponse>();
// Headers
long headerSize = input.deSerialize(U32);
long requestId = input.deSerialize(U32);
long totalTopics = input.deSerialize(U8);
log.fine("header size: " + headerSize);
log.fine("reqid: " + requestId);
log.fine(String.format("topics count: %d", totalTopics));
for (int t = 0; t < totalTopics; t++) {
String topic = input.getStr8();
long totalPartitions = input.deSerialize(U8);
log.fine("topic name: " + topic);
log.fine("Total Partitions: " + totalPartitions);
int partition = (int)input.deSerialize(U16);
if (partition == U16_MAX) {
log.warning("Topic " + topic + " Not Found ");
continue;
} else {
// Partitions
for (int p = 0; p < totalPartitions; p++) {
if (p != 0) {
partition = (int)input.deSerialize(U16);
}
byte errorOrFlags = (byte)input.deSerialize(U8);
log.fine("Partition : " + partition);
log.fine(String.format("ErrorOrFlags : %x", errorOrFlags));
if ((errorOrFlags & U8_MAX) == U8_MAX) {
log.warning("Unknown Partition");
continue;
}
long baseAbsSeqNum = 0L;
if ((errorOrFlags & U8_MAX) != 0xFE) {
baseAbsSeqNum = input.deSerialize(U64);
log.fine("Base Abs Seq Num : " + baseAbsSeqNum);
}
long highWaterMark = input.deSerialize(U64);
long chunkLength = input.deSerialize(U32);
log.fine("High Watermark : " + highWaterMark);
log.fine("Chunk Length : " + chunkLength);
if (errorOrFlags == 0x1) {
long firstAvailSeqNum = input.deSerialize(U64);
long requestedSeqNum = request.getSequenceNum(topic, p);
log.warning(
"Sequence "
+ requestedSeqNum
+ " out of bounds. Range: "
+ firstAvailSeqNum + " - " + highWaterMark);
TankResponse blankResponse = new TankResponse(topic, partition, errorOrFlags);
blankResponse.setHighWaterMark(highWaterMark);
blankResponse.setFirstAvailSeqNum(firstAvailSeqNum);
blankResponse.setRequestSeqNum(requestedSeqNum);
/*
if (requestedSeqNum < firstAvailSeqNum) {
blankResponse.setRequestSeqNum(firstAvailSeqNum);
} else {
blankResponse.setRequestSeqNum(highWaterMark);
}
*/
response.add(blankResponse);
continue;
}
chunkList.add(
new Chunk(topic, partition, errorOrFlags, baseAbsSeqNum, highWaterMark, chunkLength));
}
}
}
return processChunks(requestId, input, request, chunkList, response);
}
/**
* Processes the chunks of the input received from tank server.
*
* @param input the ByteManipulator object that contains the bytes received from server.
* @param topics the request topics. Used to crosscheck between request and response.
* @param chunkList the chunkList as read from headers.
*/
private List<TankResponse> processChunks(
long requestId,
ByteManipulator input,
TankRequest request,
ArrayList<Chunk> chunkList,
ArrayList<TankResponse> response) {
for (Chunk c : chunkList) {
long bundleLength = 0;
long requestedSeqNum = request.getSequenceNum(c.topic, c.partition);
log.fine("Chunk for " + c.topic + ":" + c.partition + " @" + requestedSeqNum + " with baseSeqNum: " + c.baseAbsSeqNum);
TankResponse topicPartition = new TankResponse(c.topic, c.partition, c.errorOrFlags);
topicPartition.setRequestSeqNum(requestedSeqNum);
if (c.length == 0) {
response.add(topicPartition);
continue;
}
long firstMessageNum = c.baseAbsSeqNum;
long remainingChunkBytes = c.length;
input.flushOffset();
while (remainingChunkBytes > 0) {
log.fine("Remaining Length: " + input.getRemainingLength());
try {
bundleLength = input.getVarInt();
} catch (ArrayIndexOutOfBoundsException aioobe) {
log.info("Bundle length varint incomplete");
break;
}
log.fine("Bundle length : " + bundleLength);
if (bundleLength > topicPartition.getFetchSize()) {
topicPartition.setFetchSize(bundleLength);
}
if (bundleLength > input.getRemainingLength()) {
log.fine("Bundle Incomplete (remaining bytes: " + input.getRemainingLength() + ")");
break;
}
if (bundleLength > remainingChunkBytes) {
log.fine("Bundle Incomplete (remaining chunk bytes: " + remainingChunkBytes + ")");
} else {
remainingChunkBytes -= bundleLength;
}
remainingChunkBytes -= input.getOffset();
input.flushOffset();
byte flags = (byte)input.deSerialize(U8);
// See TANK tank_encoding.md for flags
long messageCount = (flags >> 2) & 0xF;
long compressed = flags & 0x3;
long sparse = (flags >> 6) & 0xF;
log.finer("Bundle compressed : " + compressed);
log.finer("Bundle SPARSE : " + sparse);
if (messageCount == 0) {
messageCount = input.getVarInt();
}
log.finer("Messages in set : " + messageCount);
long lastMessageNum = 0L;
if (sparse == 1) {
firstMessageNum = input.deSerialize(U64);
log.finer("First message: " + firstMessageNum);
if (messageCount > 1) {
lastMessageNum = input.getVarInt() + 1 + firstMessageNum;
log.finer("Last message: " + lastMessageNum);
}
}
ByteManipulator chunkMsgs;
if (compressed == 1) {
log.finer("Snappy uncompression");
try {
chunkMsgs = new ByteManipulator(
input.snappyUncompress(
bundleLength - input.getOffset()));
} catch (IOException ioe) {
log.log(Level.SEVERE, "ERROR uncompressing", ioe);
return response;
}
} else {
chunkMsgs = input;
}
long timestamp = 0L;
long prevSeqNum = firstMessageNum;
long curSeqNum = firstMessageNum;
for (int i = 0; i < messageCount; i++) {
log.finer("
flags = (byte)chunkMsgs.deSerialize(U8);
log.finer(String.format("flags : %d", flags));
if (sparse == 1) {
if (i == 0) {
//do nothing. curSeqNum is already set.
} else if ((flags & SEQ_NUM_PREV_PLUS_ONE) != 0) {
log.fine("SEQ_NUM_PREV_PLUS_ONE");
curSeqNum = prevSeqNum + 1;
} else if (i != (messageCount - 1)) {
curSeqNum = (chunkMsgs.getVarInt() + 1 + prevSeqNum);
} else {
curSeqNum = lastMessageNum;
}
log.finer("sparse msg: " + i + " seq num: " + curSeqNum);
prevSeqNum = curSeqNum;
}
log.finer("cur seq num: " + curSeqNum);
if ((flags & USE_LAST_SPECIFIED_TS) == 0) {
timestamp = chunkMsgs.deSerialize(U64);
log.finer("New Timestamp : " + timestamp);
} else {
log.finer("Using last Timestamp : " + timestamp);
}
String key = new String();
if ((flags & HAVE_KEY) != 0) {
key = chunkMsgs.getStr8();
log.finer("We have a key and it is : " + key);
}
long contentLength = chunkMsgs.getVarInt();
log.finer("Content Length: " + contentLength);
byte [] message = chunkMsgs.getNextBytes((int)contentLength);
log.finest(new String(message));
// Don't save the message if it has a sequence number lower than we requested.
if (curSeqNum >= requestedSeqNum) {
topicPartition.addMessage(new TankMessage(curSeqNum, timestamp, key.getBytes(), message));
}
curSeqNum++;
firstMessageNum++;
}
}
response.add(topicPartition);
}
return response;
}
/**
* Send publish request to broker.
*/
public List<TankResponse> publish(TankRequest request) throws TankException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
log.info("Issuing publish with " + request.getTopicsCount() + " topics");
try {
baos.write((byte)PUBLISH_REQ);
baos.write(ByteManipulator.serialize(0, U32));
//clientVersion not implemented
baos.write(ByteManipulator.serialize(0L, U16));
baos.write(ByteManipulator.serialize(clientReqId++, U32));
baos.write(clientId);
//requestAcks not implemented
baos.write(ByteManipulator.serialize(0L, U8));
//ackTimeout not implemented
baos.write(ByteManipulator.serialize(0L, U32));
baos.write(ByteManipulator.serialize(request.getTopicsCount(), U8));
baos.write(request.serialize());
} catch (IOException ioe) {
log.log(Level.SEVERE, "ERROR creating publish request", ioe);
System.exit(1);
}
byte [] req = baos.toByteArray();
byte [] rsize = (ByteManipulator.serialize(req.length - 5, U32));
log.fine("Publish request size is " + req.length);
for (int i = 0; i < U32; i++) {
req[i + 1] = rsize[i];
}
try {
socketOutputStream.write(req);
} catch (IOException ioe) {
log.log(Level.SEVERE, "ERROR writing publish request to socket", ioe);
System.exit(1);
}
return poll(PUBLISH_REQ, request);
}
/**
* Processes a response from tank server after we issue a publish request.
*
* @param input a ByteManipulator object containing the data received from server.
*/
private List<TankResponse> getPubResponse(ByteManipulator input, TankRequest tr) {
ArrayList<TankResponse> response = new ArrayList<TankResponse>();
log.fine("Getting response for Request id: " + input.deSerialize(U32));
long error = 0L;
String noTopic = new String();
for (SimpleEntry<String, Long> tuple : tr.getTopicPartitions()) {
log.fine("Processing response for " + tuple.getKey() + ":" + tuple.getValue());
if (tuple.getKey().equals(noTopic)) {
//No such topic. No errors encoded for further partitions
} else {
error = input.deSerialize(U8);
}
if (error == ERROR_NO_SUCH_TOPIC) {
noTopic = tuple.getKey();
}
response.add(
new TankResponse(
tuple.getKey(),
tuple.getValue(),
error));
}
return response;
}
/**
* see tank_protocol.md for chunk details.
*/
private class Chunk {
/**
* constructor.
*
* @param eof errorOrFlags
* @param basn base absolute sequence number.
* @param hwm high water mark
*/
public Chunk(String topic, int partition, byte eof, long basn, long hwm, long length) {
this.topic = topic;
this.partition = partition;
this.errorOrFlags = eof;
this.baseAbsSeqNum = basn;
this.highWaterMark = hwm;
this.length = length;
}
private String topic;
private long partition;
private byte errorOrFlags;
private long highWaterMark;
private long length;
private long baseAbsSeqNum;
}
/**
* See TANK tank_protocol.md for maxWait semantics.
*
* @return the maxWait to wait for (ms) (default 5s)
*/
public long getFetchRespMaxWaitMs() {
return maxWait;
}
/**
* See TANK tank_protocol.md for maxWait semantics.
*
* @param maxWaitMs the maxWait to wait for (ms)
*/
public void setFetchRespMaxWait(long maxWaitMs) {
this.maxWait = maxWaitMs;
}
/**
* See TANK tank_protocol.md for minBytes semantics.
*
* @return the minBytes to wait for (default 20k)
*/
public long getFetchRespMinBytes() {
return minBytes;
}
/**
* See TANK tank_protocol.md for minBytes semantics.
*
* @param byteCount the minBytes to wait for
*/
public void setFetchRespMinBytes(long byteCount) {
this.minBytes = byteCount;
}
/**
* Set the client identification string (optional) for requests.
* See tank_protocol.md for details
*
* @param clientId the client id (max 255 chars)
*/
public void setClientId(String clientId) {
try {
this.clientId = ByteManipulator.getStr8(clientId);
} catch (TankException | UnsupportedEncodingException te) {
log.warning("Unable to set requested clientId. Ignoring." + te.getMessage());
}
}
private String tankHost;
private int tankPort;
private int reqSeqNum;
private Socket client;
private BufferedInputStream bis;
private OutputStream socketOutputStream;
private Logger log;
private int clientReqId;
private long maxWait = 5000L;
private long minBytes = 0L;
private byte [] clientId;
public static final long U64_MAX = -1L;
public static final int U16_MAX = 65535;
public static final int U8_MAX = 255;
public static final int U4_MAX = 15;
public static final byte HAVE_KEY = 1;
public static final byte USE_LAST_SPECIFIED_TS = 2;
public static final byte SEQ_NUM_PREV_PLUS_ONE = 4;
private static final long RETRY_INTERVAL = 50;
public static final short PUBLISH_REQ = 1;
public static final short CONSUME_REQ = 2;
private static final short PING_REQ = 3;
public static final byte U8 = 1;
public static final byte U16 = 2;
public static final byte U32 = 4;
public static final byte U64 = 8;
public static final long ERROR_NO_SUCH_TOPIC = 255;
public static final long ERROR_NO_SUCH_PARTITION = 1;
public static final long ERROR_INVALID_SEQNUM = 2;
public static final long ERROR_OUT_OF_BOUNDS = 1;
public static final long COMPRESS_MIN_SIZE = 1024;
}
|
package logic;
/**
* binary tree class
*
* @author Rico
*
*/
public class BinaryTree {
private Node root;
public Boolean addNode(String data) {
// creates a new node
Node newNode = new Node(data);
// without a root node this will become root
if (root == null) {
root = newNode;
return true;
} else {
// sets root as starting point for traversing the tree
Node focusNode = root;
// future partent for new node
Node parent;
while (true) {
// start at top with root
parent = focusNode;
// check whether new node goes on left or right side
if (data.compareTo(focusNode.getData()) < 0) {
focusNode = focusNode.getLeftChild();
// if left child has no children
if (focusNode == null) {
// places new node on the left
parent.setLeftChild(newNode);
return true;
}
} else if (data.compareTo(focusNode.getData()) > 0) {
// puts node on right side
focusNode = focusNode.getRightChild();
// if right child has no children
if (focusNode == null) {
// place new ndoe on the right
parent.setRightChild(newNode);
return true;
}
// check if a duplicate node is being added
} else {
if (data.compareTo(focusNode.getData()) == 0) {
System.out.println("add: no duplicate nodes allowed");
return false;
}
}
}
}
}
/**
* delete method for nodes
*
* @param data
* the node that the user wants to delete
* @return returns true if deletion was successful and false if it was not
*/
public boolean deleteNode(String data) {
Node focusNode = root;
Node parent = root;
boolean isItLeftChild = true;
if (root != null) {
while (focusNode.getData().compareTo(data) != 0) {
parent = focusNode;
if (data.compareTo(focusNode.getData()) < 0) {
isItLeftChild = true;
focusNode = focusNode.getLeftChild();
} else if (data.compareTo(focusNode.getData()) > 0) {
isItLeftChild = false;
focusNode = focusNode.getRightChild();
}
if (focusNode == null) {
return false;
}
}
if (focusNode.getLeftChild() == null && focusNode.getRightChild() == null) {
if (focusNode == root) {
root = null;
} else if (isItLeftChild) {
parent.setLeftChild(null);
} else {
parent.setRightChild(null);
}
} else if (focusNode.getRightChild() == null) {
if (focusNode == root) {
root = focusNode.getLeftChild();
} else if (isItLeftChild) {
parent.setLeftChild(focusNode.getLeftChild());
} else {
parent.setRightChild(focusNode.getLeftChild());
}
} else if (focusNode.getLeftChild() == null) {
if (focusNode == root) {
root = focusNode.getRightChild();
} else if (isItLeftChild) {
parent.setLeftChild(focusNode.getRightChild());
} else {
parent.setRightChild(focusNode.getLeftChild());
}
} else {
Node replacement = getReplacementNode(focusNode);
if (focusNode == root) {
root = replacement;
} else if (isItLeftChild) {
parent.setLeftChild(replacement);
} else {
parent.setRightChild(replacement);
}
replacement.setLeftChild(focusNode.getLeftChild());
}
return true;
}
System.out.println("delete: node not found");
return false;
}
public Node findNode(String data) {
// starts at top of the tree
Node focusNode = root;
while (focusNode.getData().compareTo(data) != 0) {
if (data.compareTo(focusNode.getData()) < 0) {
focusNode = focusNode.getLeftChild();
} else if (data.compareTo(focusNode.getData()) > 0) {
focusNode = focusNode.getRightChild();
}
// if node is not found
if (focusNode == null) {
return null;
}
}
return focusNode;
}
public Node getRootNode() {
return root;
}
public void preorderTraverseTree(Node focusNode) {
if (focusNode != null) {
System.out.println(focusNode);
preorderTraverseTree(focusNode.getLeftChild());
preorderTraverseTree(focusNode.getRightChild());
}
}
private Node getReplacementNode(Node replacedNode) {
Node replacementParent = replacedNode;
Node replacement = replacedNode;
Node focusNode = replacedNode.getRightChild();
while (focusNode != null) {
replacementParent = replacement;
replacement = focusNode;
focusNode = focusNode.getLeftChild();
}
if (replacement != replacedNode.getRightChild()) {
replacementParent.setLeftChild(replacement.getRightChild());
replacement.setRightChild(replacedNode.getRightChild());
}
return replacement;
}
}
|
package hello;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.SQLException;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
/**
* Class that interacts with the database
* @author Zach Panzarino
* @version 1.0.0
*/
public class Worker {
private static final Logger log = Logger.getLogger(Worker.class.getName());
Connection conn;
Statement stmt;
/**
* Creates a new Worker with a database connection
* @param url The database URL
* @param username The database username
* @param password The database password
*/
public Worker(String url, String username, String password){
try {
conn = DriverManager.getConnection(url, username, password);
} catch (SQLException ex) {
BasicConfigurator.configure();
log.info("SQLException: " + ex.getMessage());
log.info("SQLState: " + ex.getSQLState());
log.info("VendorError: " + ex.getErrorCode());
}
}
/**
* Execute an SQL statement with database
* @param statement The SQL statement to be executed
* @return Results of executed query
*/
public ResultSet executeQuery(String statement){
try {
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(statement);
return rs;
} catch (SQLException ex) {
BasicConfigurator.configure();
log.info("SQLException: " + ex.getMessage());
log.info("SQLState: " + ex.getSQLState());
log.info("VendorError: " + ex.getErrorCode());
return null;
}
}
/**
* Execute an SQL statement with database (INSERT, UPDATE, DELETE only)
* @param statement The SQL statement to be executed
* @return Results of executed query
*/
public int executeUpdate(String statement){
try {
stmt = conn.createStatement();
int rs = stmt.executeUpdate(statement);
stmt.close();
return rs;
} catch (SQLException ex) {
BasicConfigurator.configure();
log.info("SQLException: " + ex.getMessage());
log.info("SQLState: " + ex.getSQLState());
log.info("VendorError: " + ex.getErrorCode());
return -1;
}
}
/**
* Close the database connection
*/
public void close(){
try {
stmt.close();
conn.close();
} catch (SQLException ex) {
BasicConfigurator.configure();
log.info("SQLException: " + ex.getMessage());
log.info("SQLState: " + ex.getSQLState());
log.info("VendorError: " + ex.getErrorCode());
}
}
}
|
// This file is part of OpenTSDB.
// This program is free software: you can redistribute it and/or modify it
// option) any later version. This program is distributed in the hope that it
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
package net.opentsdb.core;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.opentsdb.utils.DateTime;
/**
* Parameters and state to query the underlying storage system for
* timeseries data points. When setting up a query, use the setter methods to
* store user information such as the start time and list of queries. After
* setting the proper values, call the {@link #validateAndSetQuery} method to
* validate the request. If required information is missing or cannot be parsed
* it will throw an exception. If validation passes, use {@link #buildQueries}
* to compile the query into {@link Query} objects for processing.
* <b>Note:</b> If using POJO deserialization, make sure to avoid setting the
* {@code start_time} and {@code end_time} fields.
* @since 2.0
*/
public final class TSQuery {
/** User given start date/time, could be relative or absolute */
private String start;
/** User given end date/time, could be relative, absolute or empty */
private String end;
/** User's timezone used for converting absolute human readable dates */
private String timezone;
/** Options for serializers, graphs, etc */
private HashMap<String, ArrayList<String>> options;
/**
* Whether or not to include padding, i.e. data to either side of the start/
* end dates
*/
private boolean padding;
/** Whether or not to suppress annotation output */
private boolean no_annotations;
/** Whether or not to scan for global annotations in the same time range */
private boolean with_global_annotations;
/** Whether or not to show TSUIDs when returning data */
private boolean show_tsuids;
/** A list of parsed sub queries, must have one or more to fetch data */
private ArrayList<TSSubQuery> queries;
/** The parsed start time value
* <b>Do not set directly</b> */
private long start_time;
/** The parsed end time value
* <b>Do not set directly</b> */
private long end_time;
/** Whether or not the user wasn't millisecond resolution */
private boolean ms_resolution;
/**
* Default constructor necessary for POJO de/serialization
*/
public TSQuery() {
}
public void validateAndSetQuery() {
if (start == null || start.isEmpty()) {
throw new IllegalArgumentException("Missing start time");
}
start_time = DateTime.parseDateTimeString(start, timezone);
if (end != null && !end.isEmpty()) {
end_time = DateTime.parseDateTimeString(end, timezone);
} else {
end_time = System.currentTimeMillis();
}
if (end_time <= start_time) {
throw new IllegalArgumentException(
"End time [" + end_time + "] must be greater than the start time ["
+ start_time +"]");
}
if (queries == null || queries.isEmpty()) {
throw new IllegalArgumentException("Missing queries");
}
// validate queries
for (TSSubQuery sub : queries) {
sub.validateAndSetQuery();
}
}
/**
* Compiles the TSQuery into an array of Query objects for execution.
* If the user has not set a down sampler explicitly, and they don't want
* millisecond resolution, then we set the down sampler to 1 second to handle
* situations where storage may have multiple data points per second.
* @param tsdb The tsdb to use for {@link newQuery}
* @return An array of queries
*/
public Query[] buildQueries(final TSDB tsdb) {
final Query[] queries = new Query[this.queries.size()];
int i = 0;
for (TSSubQuery sub : this.queries) {
final Query query = tsdb.newQuery();
query.setStartTime(start_time);
query.setEndTime(end_time);
if (sub.downsampler() != null) {
query.downsample(sub.downsampleInterval(), sub.downsampler());
} else if (!ms_resolution) {
// we *may* have multiple millisecond data points in the set so we have
// to downsample. use the sub query's aggregator
query.downsample(1000, sub.aggregator());
}
if (sub.getTsuids() != null && !sub.getTsuids().isEmpty()) {
if (sub.getRateOptions() != null) {
query.setTimeSeries(sub.getTsuids(), sub.aggregator(), sub.getRate(),
sub.getRateOptions());
} else {
query.setTimeSeries(sub.getTsuids(), sub.aggregator(), sub.getRate());
}
} else if (sub.getRateOptions() != null) {
query.setTimeSeries(sub.getMetric(), sub.getTags(), sub.aggregator(),
sub.getRate(), sub.getRateOptions());
} else {
query.setTimeSeries(sub.getMetric(), sub.getTags(), sub.aggregator(),
sub.getRate());
}
queries[i] = query;
i++;
}
return queries;
}
public String toString() {
final StringBuilder buf = new StringBuilder();
buf.append("TSQuery(start_time=")
.append(start)
.append(", end_time=")
.append(end)
.append(", subQueries[");
if (queries != null && !queries.isEmpty()) {
int counter = 0;
for (TSSubQuery sub : queries) {
if (counter > 0) {
buf.append(", ");
}
buf.append(sub);
counter++;
}
}
buf.append("] padding=")
.append(padding)
.append(", no_annotations=")
.append(no_annotations)
.append(", with_global_annotations=")
.append(with_global_annotations)
.append(", show_tsuids=")
.append(show_tsuids)
.append(", ms_resolution=")
.append(ms_resolution)
.append(", options=[");
if (options != null && !options.isEmpty()) {
int counter = 0;
for (Map.Entry<String, ArrayList<String>> entry : options.entrySet()) {
if (counter > 0) {
buf.append(", ");
}
buf.append(entry.getKey())
.append("=[");
final ArrayList<String> values = entry.getValue();
for (int i = 0; i < values.size(); i++) {
if (i > 0) {
buf.append(", ");
}
buf.append(values.get(i));
}
}
}
buf.append("])");
return buf.toString();
}
/** @return the parsed start time for all queries */
public long startTime() {
return this.start_time;
}
/** @return the parsed end time for all queries */
public long endTime() {
return this.end_time;
}
/** @return the user given, raw start time */
public String getStart() {
return start;
}
/** @return the user given, raw end time */
public String getEnd() {
return end;
}
/** @return the user supplied timezone */
public String getTimezone() {
return timezone;
}
/** @return a map of serializer options */
public Map<String, ArrayList<String>> getOptions() {
return options;
}
/** @return whether or not the user wants padding */
public boolean getPadding() {
return padding;
}
/** @return whether or not to supress annotatino output */
public boolean getNoAnnotations() {
return no_annotations;
}
/** @return whether or not to load global annotations for the time range */
public boolean getGlobalAnnotations() {
return with_global_annotations;
}
/** @return whether or not to display TSUIDs with the results */
public boolean getShowTSUIDs() {
return show_tsuids;
}
/** @return the list of sub queries */
public List<TSSubQuery> getQueries() {
return queries;
}
/** @return whether or not the requestor wants millisecond resolution */
public boolean getMsResolution() {
return ms_resolution;
}
/**
* Sets the start time for further parsing. This can be an absolute or
* relative value. See {@link DateTime#parseDateTimeString} for details.
* @param a start time from the user
*/
public void setStart(String start) {
this.start = start;
}
/**
* Optionally sets the end time for all queries. If not set, the current
* system time will be used. This can be an absolute or relative value. See
* {@link DateTime#parseDateTimeString} for details.
* @param an end time from the user
*/
public void setEnd(String end) {
this.end = end;
}
/** @param timezone an optional timezone for date parsing */
public void setTimezone(String timezone) {
this.timezone = timezone;
}
/** @param options a map of options to pass on to the serializer */
public void setOptions(HashMap<String, ArrayList<String>> options) {
this.options = options;
}
/** @param padding whether or not the query should include padding */
public void setPadding(boolean padding) {
this.padding = padding;
}
/** @param no_annotations whether or not to suppress annotation output */
public void setNoAnnotations(boolean no_annotations) {
this.no_annotations = no_annotations;
}
/** @param with_global whether or not to load global annotations */
public void setGlobalAnnotations(boolean with_global) {
with_global_annotations = with_global;
}
/** @param show_tsuids whether or not to show TSUIDs in output */
public void setShowTSUIDs(boolean show_tsuids) {
this.show_tsuids = show_tsuids;
}
/** @param queries a list of {@link TSSubQuery} objects to store*/
public void setQueries(ArrayList<TSSubQuery> queries) {
this.queries = queries;
}
/** @param ms_resolution whether or not the user wants millisecond resolution */
public void setMsResolution(boolean ms_resolution) {
this.ms_resolution = ms_resolution;
}
}
|
package outbackcdx;
import static java.nio.charset.StandardCharsets.US_ASCII;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.function.Predicate;
import org.rocksdb.ColumnFamilyHandle;
import org.rocksdb.RocksDB;
import org.rocksdb.RocksDBException;
import org.rocksdb.RocksIterator;
import org.rocksdb.TransactionLogIterator;
import org.rocksdb.WriteBatch;
import org.rocksdb.WriteOptions;
import static java.lang.System.out;
/**
* Wraps RocksDB with a higher-level query interface.
*/
public class Index {
final String name;
final RocksDB db;
final ColumnFamilyHandle defaultCF;
final ColumnFamilyHandle aliasCF;
final AccessControl accessControl;
public Index(String name, RocksDB db, ColumnFamilyHandle defaultCF, ColumnFamilyHandle aliasCF, AccessControl accessControl) {
this.name = name;
this.db = db;
this.defaultCF = defaultCF;
this.aliasCF = aliasCF;
this.accessControl = accessControl;
}
public void flushWal() throws RocksDBException{
this.db.flushWal(true);
}
public TransactionLogIterator getUpdatesSince(long sequenceNumber) {
out.println(String.format("looking for updates since %s", sequenceNumber));
try {
TransactionLogIterator logReader = db.getUpdatesSince(sequenceNumber);
return logReader;
} catch (RocksDBException e) {
throw new RuntimeException(e);
}
}
/**
* Returns all captures that match the given prefix.
*/
public Iterable<Capture> prefixQuery(String surtPrefix, Predicate<Capture> filter) {
return () -> filteredCaptures(Capture.encodeKey(surtPrefix, 0), record -> record.urlkey.startsWith(surtPrefix), filter, false);
}
public Iterable<Capture> prefixQueryAP(String surtPrefix, String accessPoint) {
if (accessPoint != null && accessControl != null) {
return prefixQuery(surtPrefix, accessControl.filter(accessPoint, new Date()));
} else {
return prefixQuery(surtPrefix, null);
}
}
/**
* Returns all captures with keys in the given range.
*/
public Iterable<Capture> rangeQuery(String startSurt, String endSurt, Predicate<Capture> filter) {
return () -> filteredCaptures(Capture.encodeKey(startSurt, 0), record -> record.urlkey.compareTo(endSurt) < 0, filter, false);
}
/**
* Returns all captures for the given url.
*/
public Iterable<Capture> query(String surt, Predicate<Capture> filter) {
String urlkey = resolveAlias(surt);
byte[] key = Capture.encodeKey(urlkey, 0);
return () -> filteredCaptures(key, record -> record.urlkey.equals(urlkey), filter, false);
}
/**
* Returns all captures for the given url.
*/
public Iterable<Capture> queryAP(String surt, String accessPoint) {
if (accessPoint != null && accessControl != null) {
return query(surt, accessControl.filter(accessPoint, new Date()));
} else {
return query(surt, null);
}
}
/**
* Returns all captures for the given url in reverse order.
*/
public Iterable<Capture> reverseQuery(String surt, Predicate<Capture> filter) {
String urlkey = resolveAlias(surt);
byte[] key = Capture.encodeKey(urlkey, 99999999999999L);
return () -> filteredCaptures(key, record -> record.urlkey.equals(urlkey), filter, true);
}
/**
* Returns all captures for the given url ordered by distance from the given timestamp.
*/
public Iterable<Capture> closestQuery(String surt, long targetTimestamp, Predicate<Capture> filter) {
String urlkey = resolveAlias(surt);
byte[] key = Capture.encodeKey(urlkey, targetTimestamp);
Predicate<Capture> scope = record -> record.urlkey.equals(urlkey);
return () -> new ClosestTimestampIterator(targetTimestamp,
filteredCaptures(key, scope, filter, false),
filteredCaptures(key, scope, filter, true));
}
public Iterable<Capture> execute(Query query) {
Predicate<Capture> filter = query.filter;
if (query.accessPoint != null && accessControl != null) {
filter = filter.and(accessControl.filter(query.accessPoint, new Date()));
}
String surt = UrlCanonicalizer.surtCanonicalize(query.url);
switch (query.matchType) {
case EXACT:
switch (query.sort) {
case DEFAULT:
return query(surt, filter);
case CLOSEST:
return closestQuery(UrlCanonicalizer.surtCanonicalize(query.url), Long.parseLong(query.closest), filter);
case REVERSE:
return reverseQuery(UrlCanonicalizer.surtCanonicalize(query.url), filter);
}
case PREFIX:
if (query.url.endsWith("/") && !surt.endsWith("/")) {
surt += "/";
}
return prefixQuery(surt, filter);
case HOST:
return prefixQuery(hostFromSurt(surt) + ")/", filter);
case DOMAIN:
String host = hostFromSurt(surt);
return rangeQuery(host, host + "-", filter);
case RANGE:
return rangeQuery(surt, "~", filter);
default:
throw new IllegalArgumentException("unknown matchType: " + query.matchType);
}
}
/**
* "org,example)/foo/bar" => "org,example"
*/
static String hostFromSurt(String surtPrefix) {
int i = surtPrefix.indexOf(")/");
return i < 0 ? surtPrefix : surtPrefix.substring(0, i);
}
/**
* Combines a forward iterator and backward iterator into order-by closest
* distance to timestamp iterator.
*/
static class ClosestTimestampIterator implements Iterator<Capture> {
final long targetMillis;
final Iterator<Capture> forwardIterator;
final Iterator<Capture> backwardIterator;
Capture nextForward = null;
Capture nextBackward = null;
ClosestTimestampIterator(long targetTimestamp, Iterator<Capture> forwardIterator, Iterator<Capture> backwardIterator) {
this.targetMillis = Capture.parseTimestamp(targetTimestamp).getTime();
this.forwardIterator = forwardIterator;
this.backwardIterator = backwardIterator;
}
@Override
public boolean hasNext() {
return nextForward != null || nextBackward != null || forwardIterator.hasNext() || backwardIterator.hasNext();
}
@Override
public Capture next() {
if (nextForward == null && forwardIterator.hasNext()) {
nextForward = forwardIterator.next();
}
if (nextBackward == null && backwardIterator.hasNext()) {
nextBackward = backwardIterator.next();
}
// if one or the other iterator is exhausted pick from its rival
if (nextForward == null) {
if (nextBackward == null) {
throw new NoSuchElementException();
}
return pickBackward();
} else if (nextBackward == null) {
return pickForward();
}
// both are still active so pick the closest
long forwardDistance = nextForward.date().getTime() - targetMillis;
long backwardDistance = targetMillis - nextBackward.date().getTime();
if (forwardDistance <= backwardDistance) {
return pickForward();
} else {
return pickBackward();
}
}
private Capture pickBackward() {
Capture result = nextBackward;
nextBackward = null;
return result;
}
private Capture pickForward() {
Capture result = nextForward;
nextForward = null;
return result;
}
}
/**
* Perform a query without first resolving aliases.
*/
private Iterable<Capture> rawQuery(String key, Predicate<Capture> filter, boolean reverse) {
return () -> filteredCaptures(Capture.encodeKey(key, 0), record -> record.urlkey.equals(key), filter, reverse);
}
/**
* Returns all captures starting from the given key.
*/
Iterable<Capture> capturesAfter(String start) {
return () -> filteredCaptures(Capture.encodeKey(start, 0), record -> true, null, false);
}
public String resolveAlias(String surt) {
try {
byte[] resolved = db.get(aliasCF, surt.getBytes(StandardCharsets.US_ASCII));
if (resolved != null) {
return new String(resolved, StandardCharsets.US_ASCII);
} else {
return surt;
}
} catch (RocksDBException e) {
throw new RuntimeException(e);
}
}
private Iterator<Capture> filteredCaptures(byte[] key, Predicate<Capture> scope, Predicate<Capture> filter, boolean reverse) {
Iterator<Capture> captures = new Records<>(db, defaultCF, key, Capture::new, scope, reverse);
if (filter != null) {
captures = new FilteringIterator<>(captures, filter);
}
return captures;
}
public Iterable<Alias> listAliases(String start) {
byte[] key = start.getBytes(US_ASCII);
return () -> new Records<>(db, aliasCF, key, Alias::new, (alias) -> true, false);
}
public long estimatedRecordCount() {
try {
return db.getLongProperty("rocksdb.estimate-num-keys");
} catch (RocksDBException e) {
throw new RuntimeException(e);
}
}
private interface RecordConstructor<T> {
public T construct(byte[] key, byte[] value);
}
/**
* Iterates capture records in RocksDb, starting from queryUrl and continuing until scope returns false.
*/
private static class Records<T> implements Iterator<T> {
private final RocksIterator it;
private final Predicate<T> scope;
private final RecordConstructor<T> constructor;
private final boolean reverse;
private T record = null;
private boolean exhausted = false;
@Override
protected void finalize() throws Throwable {
it.close();
super.finalize();
}
public Records(RocksDB db, ColumnFamilyHandle columnFamilyHandle, byte[] startKey, RecordConstructor<T> constructor, Predicate<T> scope, boolean reverse) {
final RocksIterator it = db.newIterator(columnFamilyHandle);
it.seek(startKey);
if (reverse) {
if (it.isValid()) {
it.prev();
} else {
it.seekToLast();
}
}
this.constructor = constructor;
this.scope = scope;
this.it = it;
this.reverse = reverse;
}
public boolean hasNext() {
if (exhausted) {
return false;
}
if (record == null && it.isValid()) {
record = constructor.construct(it.key(), it.value());
}
if (record == null || !scope.test(record)) {
record = null;
exhausted = true;
it.close();
return false;
}
return true;
}
public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
T record = this.record;
this.record = null;
if (reverse) {
it.prev();
} else {
it.next();
}
return record;
}
}
/**
* Wraps another iterator and only returns elements that match the given predicate.
*/
private static class FilteringIterator<T> implements Iterator<T> {
private final Iterator<T> iterator;
private final Predicate<T> predicate;
private T next;
private boolean holdingNext = false;
public FilteringIterator(Iterator<T> iterator, Predicate<T> predicate) {
this.iterator = iterator;
this.predicate = predicate;
}
@Override
public boolean hasNext() {
while (!holdingNext && iterator.hasNext()) {
T candidate = iterator.next();
if (predicate.test(candidate)) {
next = candidate;
holdingNext = true;
}
}
return holdingNext;
}
@Override
public T next() {
if (hasNext()) {
T result = next;
holdingNext = false;
next = null;
return result;
} else {
throw new NoSuchElementException();
}
}
}
public Batch beginUpdate() {
return new Batch();
}
public void commitBatch(WriteBatch writeBatch) throws RocksDBException {
try (WriteOptions options = new WriteOptions()) {
options.setSync(true);
db.write(options, writeBatch);
}
}
public class Batch implements AutoCloseable {
private WriteBatch dbBatch = new WriteBatch();
private final Map<String, String> newAliases = new HashMap<>();
private Batch() {
}
/**
* Add a new capture to the index. Existing captures with the same urlkey and timestamp will be overwritten.
* @throws IOException
*/
public void putCapture(Capture capture) throws IOException {
String resolved = newAliases.get(capture.urlkey);
if (resolved != null) {
capture.urlkey = resolved;
} else {
capture.urlkey = resolveAlias(capture.urlkey);
}
try {
dbBatch.put(capture.encodeKey(), capture.encodeValue());
} catch (RocksDBException e) {
throw new IOException(e);
}
}
/**
* Deletes a capture from the index. Does not actually check if the capture exists.
* @throws IOException
*/
void deleteCapture(Capture capture) throws IOException {
capture.urlkey = resolveAlias(capture.urlkey);
try {
dbBatch.remove(capture.encodeKey());
} catch (RocksDBException e) {
throw new IOException(e);
}
}
/**
* Adds a new alias to the index. Updates existing captures affected by the new alias.
* @throws IOException
*/
public void putAlias(String aliasSurt, String targetSurt) throws IOException {
if (aliasSurt.equals(targetSurt)) {
return; // a self-referential alias is equivalent to no alias so don't bother storing it
}
try {
dbBatch.put(aliasCF, aliasSurt.getBytes(US_ASCII), targetSurt.getBytes(US_ASCII));
} catch (RocksDBException e) {
throw new IOException(e);
}
newAliases.put(aliasSurt, targetSurt);
updateExistingRecordsWithNewAlias(dbBatch, aliasSurt, targetSurt);
}
public void commit() throws IOException {
try {
commitBatch(dbBatch);
} catch (RocksDBException e) {
throw new RuntimeException(e);
}
/*
* Most of the time this will do nothing as we've already updated existing captures in putAlias, but there's
* a data race as another batch could have inserted some captures in bewtween putAlias() and commit().
*
* Rather than serializing updates let's just do a second pass after committing to catch any captures that
* were added in the meantime.
*/
updateExistingRecordsWithNewAliases();
}
private void updateExistingRecordsWithNewAliases() throws IOException {
try (WriteBatch wb = new WriteBatch()) {
for (Map.Entry<String, String> entry : newAliases.entrySet()) {
updateExistingRecordsWithNewAlias(wb, entry.getKey(), entry.getValue());
}
try {
commitBatch(wb);
} catch (RocksDBException e) {
throw new RuntimeException(e);
}
}
}
private void updateExistingRecordsWithNewAlias(WriteBatch wb, String aliasSurt, String targetSurt) throws IOException {
for (Capture capture : rawQuery(aliasSurt, null, false)) {
try {
wb.remove(capture.encodeKey());
} catch (RocksDBException e) {
throw new IOException(e);
}
capture.urlkey = targetSurt;
try {
wb.put(capture.encodeKey(), capture.encodeValue());
} catch (RocksDBException e) {
throw new IOException(e);
}
}
}
@Override
public void close() {
dbBatch.close();
}
}
}
|
package common;
import server.SimpleMessageBox;
import javax.naming.AuthenticationException;
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface AccessProvider extends Remote {
public Object getAccess(String login, String passwordHash)
throws RemoteException, AuthenticationException;
}
|
package example;
//-*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
//@homepage@
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
public final class MainPanel extends JPanel {
private final JTextArea textArea = new JTextArea("aaaaaaaaaaaaaaaaa\nbbbbb\nccc");
private final JCheckBox hidingCaretCheck = new JCheckBox("Hide Caret");
private final JCheckBox hidingHighlighterCheck = new JCheckBox("Hide Highlighter");
private final JCheckBox editableCheck = new JCheckBox("Editable", true);
private final JCheckBox focusableCheck = new JCheckBox("Focusable", true);
public MainPanel() {
super(new BorderLayout());
Caret hidingCaret = new DefaultCaret() {
@Override public boolean isVisible() {
return false;
}
};
Caret defaultCaret = textArea.getCaret();
Highlighter defaultHighlighter = textArea.getHighlighter();
hidingCaretCheck.addActionListener(e -> textArea.setCaret(((JCheckBox) e.getSource()).isSelected() ? hidingCaret : defaultCaret));
hidingHighlighterCheck.addActionListener(e -> textArea.setHighlighter(((JCheckBox) e.getSource()).isSelected() ? null : defaultHighlighter));
editableCheck.addActionListener(e -> textArea.setEditable(((JCheckBox) e.getSource()).isSelected()));
focusableCheck.addActionListener(e -> textArea.setFocusable(((JCheckBox) e.getSource()).isSelected()));
JPanel p1 = new JPanel();
p1.add(hidingCaretCheck);
p1.add(hidingHighlighterCheck);
JPanel p2 = new JPanel();
p2.add(editableCheck);
p2.add(focusableCheck);
JPanel p = new JPanel(new BorderLayout(0, 0));
p.add(p1, BorderLayout.NORTH);
p.add(p2, BorderLayout.SOUTH);
add(p, BorderLayout.NORTH);
add(new JScrollPane(textArea));
add(new JTextField(), BorderLayout.SOUTH);
setPreferredSize(new Dimension(320, 240));
}
public static void main(String... args) {
EventQueue.invokeLater(new Runnable() {
@Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException
| IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
|
package LogMaintainence;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import serverclient.MainStart;
public class ChatLogging implements Runnable
{
private JSONObject mainObject;
private File path;
private File jsonFilePath;
private String fileName;
private String myId = MainStart.myID;
private int totalUsers;
private String userId;
private String userName;
private BlockingQueue<String> bq;
public ChatLogging(String userId, String userName, BlockingQueue<String> bq)
{
this.userId = userId;
this.userName = userName;
this.fileName = userId+".json";
this.bq = bq;
}
@SuppressWarnings("unchecked")
public void run()
{
path = new File(System.getProperty("user.dir"));
jsonFilePath = new File(path,fileName);
if(!jsonFilePath.exists())
{
mainObject = new JSONObject();
mainObject.put("totalUsers", totalUsers);
mainObject.put("groupId", userId);
mainObject.put("groupName", userName);
mainObject.put("lineCount", 0l);
JSONArray groupUsers = new JSONArray();
groupUsers.add(userId);
//groupUsers.add("rajat");
//groupUsers.add("shasuck");
//groupUsers.add("baid");
mainObject.put("users", groupUsers);
JSONArray chatArray = new JSONArray();
JSONObject sessionObject = new JSONObject();
sessionObject.put("1", chatArray);
mainObject.put("session", sessionObject);
mainObject.put("lastUpdatedSession", 1l);
}
else//if file exists
{
JSONParser parser = new JSONParser();
Object obj = null;
try
{
obj = parser.parse(new FileReader(fileName));
}
catch (IOException | ParseException e2)
{
e2.printStackTrace();
}
mainObject = (JSONObject)obj;
}
boolean on = true;
while(on)
{
String qElement=null;
String detailsArray[] = null;
for(int i=0;i<15;i++)
{
try {
qElement = bq.poll(1000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
if( qElement!=null && !qElement.isEmpty())
{
if(!qElement.equals("CLOSE"))
{
detailsArray = qElement.split("\\|");//details[0]=userId [1]=userName [2]=timeStamp [3]=messageText
if(detailsArray.length>4)
{
for(int j=4;j<detailsArray.length;j++)//Concatenating message with pipes into one place
detailsArray[3]+="|"+detailsArray[j];
}
logCreate(detailsArray[0], detailsArray[1], detailsArray[3], detailsArray[2]);
}
else
{
on=false;
break;
}
}
}
writeLogToFile();
}
}
@SuppressWarnings("unchecked")
public void logCreate(String userId, String userName, String userMessage, String timeStamp)
{
//System.out.println("Main object in logCreate :"+mainObject);
long lastSessionValue = (long)mainObject.get("lastUpdatedSession");
JSONObject sessionObject = (JSONObject) mainObject.get("session");
long lineCount = (long)mainObject.get("lineCount");
lineCount++;
boolean sessionchange = false;
if(lineCount%5 == 0)
{
lastSessionValue++;
sessionchange = true;
}
JSONObject messageObject = new JSONObject();
messageObject.put("timeStamp", timeStamp);
messageObject.put("userName", userName);
messageObject.put("messageText", userMessage);
messageObject.put("userId", userId);
JSONArray chatArray;
if(!sessionchange)
{
System.out.println("Last session value" + lastSessionValue);
chatArray = (JSONArray) sessionObject.get(""+lastSessionValue);
}
else
chatArray = new JSONArray();
chatArray.add(messageObject);
sessionObject.put(""+lastSessionValue, chatArray);
mainObject.put("lineCount", lineCount);
mainObject.put("lastUpdatedSession", lastSessionValue);
}
public void writeLogToFile()
{
//System.out.println("Main object writelogtofile :"+mainObject);
try
{
//Write Code to write the main object to file
jsonFilePath.createNewFile();
//System.out.println(jsonFilePath);
FileWriter jsonFileWriter = new FileWriter(jsonFilePath);
jsonFileWriter.write(mainObject.toJSONString());
jsonFileWriter.flush();
jsonFileWriter.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void clearLog(String userId)
{
File path = new File(System.getProperty("user.dir"));
File jsonFilePath = new File(path,""+userId+".json");
String fileName = userId+".json";
if(jsonFilePath.exists())
{
try
{
if(jsonFilePath.delete())
System.out.println("file "+fileName+" is deleted\n");
else
System.out.println("delete failed\n");
}
catch (Exception e)
{
e.printStackTrace();
}
}
else
{
System.out.println("file doesnt exist!\n");
}
}
}
|
public class DecisionFactory {
public DecisionFactory(){
};
//only send two arguements here for now
private String[] packageStrings (String...strings) {
return strings;
}
/*
* Here are the different Decisions you can make
* Format is like this:
* method to create decision
* interface that the decision class uses
*/
public Decision vaccination (District d) {
//2 decisions
String descString = "It's flu season, and many of the people in your district are unvaccinated. Will you spend funds for a free vaccination program?";
String[] decisionDescString = packageStrings (
"Allocate $50,000 to fund the vaccination program.",
"The funds will be better used elsewhere.");
String[] outcomeDescString = packageStrings (
"The vaccination program is a success! There are no deaths from the flu this year.",
"This season's flu is especially bad. People die. You bring shame and dishonor to your family.");
return new Decision(new DVaccination(), Category.Population, descString, 2, decisionDescString, outcomeDescString, d);
}
class DVaccination implements Behavior {
//reduce money, change nothing else
public void AcceptDecision(District d) {
d.updateBudget(d.getBudget() - 50000);
}
//decrease population
public void IgnoreDecision(District d) {
d.updatePop(d.getPop() * 0.95);
}
}
public Decision road (District d) {
//2 decisions
String descString = "Many of the roads in your district are out of repair, and your office has been receiving complaints from the citizenry. Will you allocate funds to repair the roads?";
String[] decisionDescString = packageStrings (
"Roads are important. Allocate $200,000 to start the repairs",
"The roads are fine. At least near your house.");
String[] outcomeDescString = packageStrings (
"You've allocated funds to improve the roads around town. In a few months, the town's roads will be nice and shiny, but in the meantime the citizens have to deal with increased traffic and the noise of jackhammers.",
"The roads are not repaired. They continue to fall into disrepair, making the citizens unhappy. A few traffic accidents also occur.");
return new Decision(new DBuildRoads(), Category.Infrastructure, descString, 2, decisionDescString, outcomeDescString, d);
}
class DBuildRoads implements Behavior {
//reduce money
//TODO reduce approval
public void AcceptDecision(District d) {
d.updateBudget(d.getBudget() - 200000);
}
//increase death rate
public void IgnoreDecision(District d) {
d.updateDeath(d.getDeath() + d.getPop() * 0.01);
}
}
public Decision kill (District d) {
//2 decisions
String descString = "A mysterious man approaches you. He asks, 'Would you like to kill everyone in your district?' What do you say?";
String[] decisionDescString = packageStrings (
"hell ya",
"hell naw");
String[] outcomeDescString = packageStrings (
"Congratulations! You've killed everyone in your district. Are you proud of yourself?",
"Uh, congrats. You didn't kill your entire town.");
return new Decision(new DKILL(), Category.Population, descString, 2, decisionDescString, outcomeDescString, d);
}
class DKILL implements Behavior {
//kill everyone
public void AcceptDecision(District d) {
d.updatePop(0);
}
//do nothing
public void IgnoreDecision(District d) {
}
}
public Decision foodInspection (District d) {
//2 decisions
String descString = "The food inspection department is running over budget.";
String[] decisionDescString = packageStrings (
"Give them $200,000 of extra funding.",
"Let them find their own sources for money.");
String[] outcomeDescString = packageStrings (
"The food inspection department continues to request more money. Eventually someone notices that their balances don't add up, but no one is able to find out where the money went or who is responsible.",
"The food inspection department undergoes restructuring. People are laid off, and inspections stop for the forseeable future.");
return new Decision(new DFoodInspection(), Category.Commerce, descString, 2, decisionDescString, outcomeDescString, d);
}
class DFoodInspection implements Behavior {
//Spend money
//[TODO] Lower population satisfaction
public void AcceptDecision(District d) {
d.updateBudget(d.getBudget() - 200000);
}
//Increase death rate slightly
//[TODO] Lower population satisfaction
public void IgnoreDecision(District d) {
d.updateDeath(d.getDeath() + d.getPop() * 0.001);
}
}
public Decision schoolTalk (District d) {
//2 decisions
String descString = "The local high school invites you to give a presentation about your role in the government to their current students.";
String[] decisionDescString = packageStrings (
"Accept. You like talking about yourself.",
"Decline. They're high school students. You don't like high school students.");
String[] outcomeDescString = packageStrings (
"Your speech is generally successful. The local newspaper covers the event, and your approval goes up.",
"Eh, the kids probably didn't want to listen to you anyways.");
return new Decision(new DSchoolTalk(), Category.Population, descString, 2, decisionDescString, outcomeDescString, d);
}
class DSchoolTalk implements Behavior {
//[TODO] Approval rating goes up
public void AcceptDecision(District d) {
}
//nothing happens
public void IgnoreDecision(District d) {
}
}
public Decision merchantInvestigation (District d) {
//2 decisions
String descString = "You are approached by a wealthy businessman, one of the most influential in the district. 'I'm under investigation for municipal tax evasion,' he mutters, eyes darting around the room. 'Help me out, and I'll make it worth your while'.";
String[] decisionDescString = packageStrings (
"Accept.",
"Decline.");
String[] outcomeDescString = packageStrings (
"The charges against the businessman are dropped. Everyone knows something suspicious went on, but no one has solid proof you helped. But the rumors start anyways.",
"The businessman, obviously flustered by your refusal, hems and haws for a few minutes before leaving. The courts slap him with a heavy fine.");
return new Decision(new DMerchantInvestigation(), Category.Personal, descString, 2, decisionDescString, outcomeDescString, d);
}
class DMerchantInvestigation implements Behavior {
//Receive money
//[TODO] Decrease approval
public void AcceptDecision(District d) {
d.updateBudget(d.getBudget() + 1000000);
}
//receive money
public void IgnoreDecision(District d) {
d.updateBudget(d.getBudget() + 100000);
}
}
public Decision amazonTax (District d) {
//2 decisions
String descString = "Some members of your cabinet want to collect sales tax from online retailers that ship to your region.";
String[] decisionDescString = packageStrings (
"Tax them. They get free shipping anyways.",
"Don't tax them. You don't want to pay sales tax on that new washing machine you're buying.");
String[] outcomeDescString = packageStrings (
"The tax passes. Revenue increases.",
"Your washing machine arrives. Free shipping, no sales tax. How nice.");
return new Decision(new DAmazonTax(), Category.Commerce, descString, 2, decisionDescString, outcomeDescString, d);
}
class DAmazonTax implements Behavior {
//Get money
//[TODO] Lower approval
public void AcceptDecision(District d) {
d.updateBudget(d.getBudget() + 500000);
}
//Nothing happens
public void IgnoreDecision(District d) {
}
}
//template
/*
public Decision ["NAMEOFDECISION"] (District d) {
//2 decisions
String descString = "[DESCRIPTION]";
String[] decisionDescString = packageStrings (
"[OPTION1]",
"[OPTION2");
String[] outcomeDescString = packageStrings (
"[OUTCOME1]",
"[OUTCOME2]");
return new Decision(new ["INTERFACE"](), Category.["CATEGORY"], descString, 2, decisionDescString, outcomeDescString, d);
}
class ["INTERFACE"] implements Behavior {
//[DOCUMENTATION]
public void AcceptDecision(District d) {
}
//[DOCUMENTATION]
public void IgnoreDecision(District d) {
}
}
*/
}
|
import java.util.*;
public class Babel
{
public Babel (boolean debug)
{
_debug = debug;
}
public void translate (Vector<Food> foods)
{
Vector<String> mapped = new Vector<String>();
for (int i = 0; i < foods.size(); i++)
{
Food toCheck = foods.elementAt(i);
Vector<String> ingredients = toCheck.getIngredients();
for (int j = 0; j < ingredients.size(); j++)
{
String ingredient = ingredients.elementAt(j);
for (int k = 0; k < foods.size(); k++)
{
Food compare = foods.elementAt(k);
if (!toCheck.equals(compare))
{
if (compare.getIngredients().contains(ingredient))
{
if (_debug)
System.out.println("Ingredient "+ingredient+" found in\n"+compare);
// now check where this is also used
if (mapped.contains(ingredient))
System.out.println("Already added "+ingredient);
else
mapped.add(ingredient);
}
}
}
}
}
System.out.println("Mapped "+mapped.size());
for (int i = 0; i < mapped.size(); i++)
{
System.out.println("Mapped: "+mapped.elementAt(i));
}
}
private boolean _debug;
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package appgraphs;
import java.util.List;
/**
*
* @author Rflpz
*/
public class Grafo {
//Atributos
List<Nodo> listos=null;
char[] nodos; //Nodo identifier
int distanciaRutaMasCorta = Integer.MAX_VALUE; //Distancia de la ruta mas corta
String rutaMasCorta; //Ruta mas corta encontrada
int[][] grafo; //Matriz de las distancias
//Constructor
Grafo(String serieNodos) {
nodos = serieNodos.toCharArray();
grafo = new int[nodos.length][nodos.length];
}
//Agregar ruta
public void agregarRuta(char origen, char destino, int distancia) {
int n1 = posicionNodo(origen);
int n2 = posicionNodo(destino);
grafo[n1][n2]=distancia;
grafo[n2][n1]=distancia;
}
//Crear la posicion del nodo
private int posicionNodo(char nodo) {
for(int i=0; i < nodos.length; i++) {
if(nodos[i] == nodo)
return i;
}
return -1;
}
}
|
package shadow.build.closure;
import com.google.javascript.jscomp.*;
import com.google.javascript.jscomp.Compiler;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.TokenStream;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class PropertyCollector implements NodeTraversal.Callback, CompilerPass {
private final AbstractCompiler compiler;
public final Map<String, Set<String>> properties = new HashMap<>();
public PropertyCollector(AbstractCompiler compiler) {
this.compiler = compiler;
}
@Override
public boolean shouldTraverse(NodeTraversal t, Node node, Node parent) {
// don't traverse into .json files
return !node.isScript() || !t.getSourceName().endsWith(".json");
}
public final static Set<String> ignoredProps = new HashSet<>();
static {
ignoredProps.add("exports");
ignoredProps.add("module");
ignoredProps.add("prototype");
}
private void addProperty(NodeTraversal t, String property) {
if (!property.equals("exports") && !property.equals("module") && TokenStream.isJSIdentifier(property)) {
String sourceName = t.getSourceName();
Set<String> x = properties.get(sourceName);
if (x == null) {
x = new HashSet<>();
properties.put(sourceName, x);
}
x.add(property);
}
}
@Override
public void visit(NodeTraversal t, Node node, Node parent) {
// exports.foo = 1;
// function Foo() {}
// Foo.prototype.bar = 1;
// exports.Foo = Foo;
// find every property assign
// extract property name
// use as :externs in :advanced mode build using JS deps
// profit?
// FIXME: bad idea? probably way too many names we don't actually need to preserve
if (node.isAssign()) {
Node getProp = node.getFirstChild();
// only collect assignments to props
// thing.x = 1;
// not
// var x = 1;
// var x; x = 1;
if (getProp.isGetProp()) {
Node name = getProp.getLastChild();
if (!name.isString()) {
System.out.println("==== assign without string");
System.out.println(node.toStringTree());
System.out.println("====");
} else {
String property = name.getString();
addProperty(t, property);
}
} else {
// FIXME: other cases I'm missing?
// System.out.println(node.toStringTree());
}
} else if (node.isObjectLit()) {
for (int i = 0; i < node.getChildCount(); i++) {
Node keyNode = node.getChildAtIndex(i);
if (keyNode.isStringKey() || keyNode.isGetterDef() || keyNode.isSetterDef()) {
addProperty(t, keyNode.getString());
} else {
System.out.println("==== object-lit without string key");
System.out.println(node.toStringTree());
}
}
} else if (NodeUtil.isCallTo(node,"Object.defineProperty")) {
Node property = node.getChildAtIndex(2);
if (property.isString()) {
addProperty(t, property.getString());
}
}
}
public void process(Node externs, Node root) {
NodeTraversal.traverse(compiler, root, this);
}
public static Node process(Compiler cc, SourceFile srcFile) {
JsAst ast = new JsAst(srcFile);
Node node = ast.getAstRoot(cc);
JsAst.ParseResult result = (JsAst.ParseResult) node.getProp(Node.PARSE_RESULTS);
PropertyCollector pass = new PropertyCollector(cc);
NodeTraversal.traverse(cc, node, pass);
System.out.println(pass.properties);
return node;
}
public static void main(String... args) {
Compiler cc = new Compiler();
CompilerOptions co = new CompilerOptions();
co.setLanguageIn(CompilerOptions.LanguageMode.ECMASCRIPT_2017);
co.setPrettyPrint(true);
cc.initOptions(co);
// SourceFile srcFile = SourceFile.fromFile("node_modules/@firebase/util/dist/cjs/src/crypt.js");
SourceFile srcFile = SourceFile.fromFile("tmp/alex.js");
// SourceFile srcFile = SourceFile.fromCode("test.json", "exports.foo = 1;");
cc.toSource(process(cc, srcFile));
}
}
|
package me.ryanhamshire.ExtraHardMode;
import me.ryanhamshire.ExtraHardMode.command.Commander;
import me.ryanhamshire.ExtraHardMode.config.RootConfig;
import me.ryanhamshire.ExtraHardMode.config.messages.MessageConfig;
import me.ryanhamshire.ExtraHardMode.event.BlockEventHandler;
import me.ryanhamshire.ExtraHardMode.event.EntityEventHandler;
import me.ryanhamshire.ExtraHardMode.event.PlayerEventHandler;
import me.ryanhamshire.ExtraHardMode.module.BlockModule;
import me.ryanhamshire.ExtraHardMode.module.DataStoreModule;
import me.ryanhamshire.ExtraHardMode.module.DataStoreModule.PlayerData;
import me.ryanhamshire.ExtraHardMode.module.EntityModule;
import me.ryanhamshire.ExtraHardMode.module.UtilityModule;
import me.ryanhamshire.ExtraHardMode.service.IModule;
import me.ryanhamshire.ExtraHardMode.task.MoreMonstersTask;
import org.bukkit.entity.Player;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
/**
* Main plugin class.
*/
public class ExtraHardMode extends JavaPlugin
{
/**
* Plugin tag.
*/
public static final String TAG = "[EHM]";
/**
* Registered modules.
*/
private final Map<Class<? extends IModule>, IModule> modules = new HashMap<Class<? extends IModule>, IModule>();
/**
* for computing random chance
*/
private final Random randomNumberGenerator = new Random();
/**
* initializes well... everything
*/
@Override
public void onEnable()
{
// Register modules
registerModule(RootConfig.class, new RootConfig(this));
registerModule(MessageConfig.class, new MessageConfig(this));
registerModule(DataStoreModule.class, new DataStoreModule(this));
registerModule(EntityModule.class, new EntityModule(this));
registerModule(BlockModule.class, new BlockModule(this));
registerModule(UtilityModule.class, new UtilityModule(this));
//Register command
getCommand("ehm").setExecutor(new Commander(this));
// register for events
PluginManager pluginManager = this.getServer().getPluginManager();
// player events
PlayerEventHandler playerEventHandler = new PlayerEventHandler(this);
pluginManager.registerEvents(playerEventHandler, this);
// block events
BlockEventHandler blockEventHandler = new BlockEventHandler(this);
pluginManager.registerEvents(blockEventHandler, this);
// entity events
EntityEventHandler entityEventHandler = new EntityEventHandler(this);
pluginManager.registerEvents(entityEventHandler, this);
// FEATURE: monsters spawn in the light under a configurable Y level
MoreMonstersTask task = new MoreMonstersTask(this);
// TODO Once this feature is fleshed out make it customizable
this.getServer().getScheduler().scheduleSyncRepeatingTask(this, task, 800L, 800L);
}
/**
* Sends a message to a player. Attempts to not spam the player with
* messages.
*
* @param player - Target player.
* @param message - Message to send.
*/
public void sendMessage(Player player, String message)
{
if (player == null)
{
getLogger().warning("Could not send the following message: " + message);
}
else
{
// FEATURE: don't spam messages
PlayerData playerData = getModuleForClass(DataStoreModule.class).getPlayerData(player.getName());
long now = Calendar.getInstance().getTimeInMillis();
if (!message.equals(playerData.lastMessageSent) || now - playerData.lastMessageTimestamp > 30000)
{
player.sendMessage(message);
playerData.lastMessageSent = message;
playerData.lastMessageTimestamp = now;
}
}
}
/**
* Computes random chance
*
* @param percentChance - Percentage of success.
* @return True if it was successful, else false.
*/
public boolean random(int percentChance)
{
return randomNumberGenerator.nextInt(101) < percentChance;
}
/**
* Get random generator.
*
* @return a Random object
*/
public Random getRandom()
{
return randomNumberGenerator;
}
public String getTag()
{
return TAG;
}
public <T extends IModule> void registerModule(Class<T> clazz, T module)
{
// Check arguments.
if (clazz == null)
{
throw new IllegalArgumentException("Class cannot be null");
}
else if (module == null)
{
throw new IllegalArgumentException("Module cannot be null");
}
// Add module.
modules.put(clazz, module);
// Tell module to start.
module.starting();
}
/**
* Deregister a module.
*
* @param clazz - Class of the instance.
* @return Module that was removed. Returns null if no instance of the module
* is registered.
*/
public <T extends IModule> T deregisterModuleForClass(Class<T> clazz)
{
// Check arguments.
if (clazz == null)
{
throw new IllegalArgumentException("Class cannot be null");
}
// Grab module and tell it its closing.
T module = clazz.cast(modules.get(clazz));
if (module != null)
{
module.closing();
}
return module;
}
/**
* Retrieve a registered module.
*
* @param clazz - Class identifier.
* @return Module instance. Returns null is an instance of the given class
* has not been registered with the API.
*/
public <T extends IModule> T getModuleForClass(Class<T> clazz)
{
return clazz.cast(modules.get(clazz));
}
}
|
//BIG THANKS to EvilMidget38 for providing this handy UUID lookup tool to the Bukkit community! :)
package me.ryanhamshire.GriefPrevention;
import com.google.common.base.Charsets;
import com.google.common.collect.ImmutableList;
import org.bukkit.OfflinePlayer;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.ByteBuffer;
import java.util.*;
import java.util.concurrent.Callable;
class UUIDFetcher implements Callable<Map<String, UUID>> {
private static final double PROFILES_PER_REQUEST = 100;
private static final String PROFILE_URL = "https://api.mojang.com/profiles/minecraft";
private final JSONParser jsonParser = new JSONParser();
private final List<String> names;
private final boolean rateLimiting;
//cache for username -> uuid lookups
private static HashMap<String, UUID> lookupCache;
public UUIDFetcher(List<String> names, boolean rateLimiting) {
this.names = ImmutableList.copyOf(names);
this.rateLimiting = rateLimiting;
}
public UUIDFetcher(List<String> names) {
this(names, true);
}
public Map<String, UUID> call() throws Exception {
Map<String, UUID> uuidMap = new HashMap<String, UUID>();
int requests = (int) Math.ceil(names.size() / PROFILES_PER_REQUEST);
for (int i = 0; i < requests; i++) {
HttpURLConnection connection = createConnection();
String body = JSONArray.toJSONString(names.subList(i * 100, Math.min((i + 1) * 100, names.size())));
writeBody(connection, body);
JSONArray array = (JSONArray) jsonParser.parse(new InputStreamReader(connection.getInputStream()));
for (Object profile : array) {
JSONObject jsonProfile = (JSONObject) profile;
String id = (String) jsonProfile.get("id");
String name = (String) jsonProfile.get("name");
UUID uuid = UUIDFetcher.getUUID(id);
uuidMap.put(name, uuid);
}
if (rateLimiting && i != requests - 1) {
Thread.sleep(100L);
}
}
return uuidMap;
}
private static void writeBody(HttpURLConnection connection, String body) throws Exception {
OutputStream stream = connection.getOutputStream();
stream.write(body.getBytes());
stream.flush();
stream.close();
}
private static HttpURLConnection createConnection() throws Exception {
URL url = new URL(PROFILE_URL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
return connection;
}
private static UUID getUUID(String id) {
return UUID.fromString(id.substring(0, 8) + "-" + id.substring(8, 12) + "-" + id.substring(12, 16) + "-" + id.substring(16, 20) + "-" +id.substring(20, 32));
}
public static byte[] toBytes(UUID uuid) {
ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[16]);
byteBuffer.putLong(uuid.getMostSignificantBits());
byteBuffer.putLong(uuid.getLeastSignificantBits());
return byteBuffer.array();
}
public static UUID fromBytes(byte[] array) {
if (array.length != 16) {
throw new IllegalArgumentException("Illegal byte array length: " + array.length);
}
ByteBuffer byteBuffer = ByteBuffer.wrap(array);
long mostSignificant = byteBuffer.getLong();
long leastSignificant = byteBuffer.getLong();
return new UUID(mostSignificant, leastSignificant);
}
public static UUID getUUIDOf(String name) throws Exception
{
if(lookupCache == null)
{
lookupCache = new HashMap<String, UUID>();
}
UUID result = lookupCache.get(name);
if(result == null)
{
if(lookupCache.containsKey(name)) return null;
//use local minecraft player data to try correcting a name to the correct casing
String correctCasingName = getNameWithCasing(name);
//online mode: look it up by calling Mojang's web service
if(GriefPrevention.instance.getServer().getOnlineMode() == true)
{
result = new UUIDFetcher(Arrays.asList(name)).call().get(correctCasingName);
}
//offline mode best guess
else
{
//search server's minecraft player data to find a UUID
OfflinePlayer [] players = GriefPrevention.instance.getServer().getOfflinePlayers();
for(OfflinePlayer player : players)
{
if(player.getName().equals(correctCasingName))
{
result = player.getUniqueId();
break;
}
}
//if that doesn't work, make a wild guess by imitating what Mojang reportedly does
if(result == null)
{
result = java.util.UUID.nameUUIDFromBytes(("OfflinePlayer:" + correctCasingName).getBytes(Charsets.UTF_8));
}
}
//if none of the above worked, throw up our hands and report the problem in the logs
//this player will lose his land claim blocks, but claims will stay in place as admin claims
if(result == null)
{
GriefPrevention.AddLogEntry(correctCasingName + "
lookupCache.put(name, null);
throw new IllegalArgumentException(name);
}
GriefPrevention.AddLogEntry(correctCasingName + " --> " + result.toString());
lookupCache.put(name, result);
}
return result;
}
private static String getNameWithCasing(String name)
{
OfflinePlayer [] players = GriefPrevention.instance.getServer().getOfflinePlayers();
for(OfflinePlayer player : players)
{
if(player.getName().equalsIgnoreCase(name))
{
if(!player.getName().equals(name))
{
GriefPrevention.AddLogEntry(name + " --> " + player.getName());
}
return player.getName();
}
}
return name;
}
}
|
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class HelloRegex {
public static void main(String... args) {
System.out.println("Hello Regex!");
findIt("foo", "foo");
findIt("foo", "foofoofoo");
findIt("cat.", "cats");
findIt("[bcr]at", "bat");
findIt("[bcr]at", "cat");
findIt("[bcr]at", "rat");
findIt("[bcr]at", "hat");
findIt("[^bcr]at", "bat");
findIt("[^bcr]at", "cat");
findIt("[^bcr]at", "rat");
findIt("[^bcr]at", "hat");
findIt("[a-c]", "a");
findIt("[a-c]", "b");
findIt("[a-c]", "c");
findIt("[a-c]", "d");
}
static void findIt(String regexString, String stringToSearch) {
Pattern pattern = Pattern.compile(regexString);
Matcher matcher = pattern.matcher(stringToSearch);
boolean found = false;
while (matcher.find()) {
System.out.printf("I found the text" + " \"%s\" starting at "
+ "index %d and ending at index %d.%n",
matcher.group(), matcher.start(), matcher.end());
found = true;
}
if (!found) {
System.out.printf("No match for regexString<%s> stringToSearch<%s>\n",
regexString, stringToSearch);
}
}
}
|
package navalwar.client.network;
import java.util.List;
import navalwar.client.gui.IGUIModule;
import navalwar.client.gui.NavalWarGUI;
import navalwar.server.gameengine.info.IWarInfo;
import navalwar.server.gameengine.info.IArmyInfo;
public class ClientNetworkModule implements IClientNetworkModule {
IGUIModule gui = null;
// Constructors & singleton pattern
private ClientNetworkModule() {
// TODO complete this constructor
}
private static ClientNetworkModule instance = null;
public static ClientNetworkModule getInstance() {
if (instance == null) instance = new ClientNetworkModule();
return instance;
}
// IClientNetworkModule methods
public void bindGUIModule(IGUIModule gui) {
this.gui = gui;
}
public int connect(String ip, int port) {
// TODO Auto-generated method stub
return 0;
}
public int disconnect() {
// TODO Auto-generated method stub
return 0;
}
public int createWar(String name, String desc) {
// TODO Auto-generated method stub
return 0;
}
public int startWar(int warID) {
// TODO Auto-generated method stub
return 0;
}
public List<IWarInfo> getWarsList() {
// TODO Auto-generated method stub
return null;
}
public int regArmy(int warID, String name, String[] units, int[] rows,
int[] cols) {
// TODO Auto-generated method stub
return 0;
}
public int shot(int warID, int attackArmyID, int targetArmyID, int row,
int col) {
// TODO Auto-generated method stub
return 0;
}
public IWarInfo getWarInfo(int warID) {
// TODO Auto-generated method stub
return null;
}
public IArmyInfo getArmyInfo(int warID, int armyID) {
// TODO Auto-generated method stub
return null;
}
}
|
package net.domesdaybook.parser.tree;
import java.io.UnsupportedEncodingException;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import net.domesdaybook.parser.ParseException;
import net.domesdaybook.util.bytes.ByteUtilities;
/**
* A utility class of static helper methods to use when parsing expressions.
*
* @author Matt Palmer
*/
public final class ParseTreeUtils {
// Constants //
private static final String TYPE_ERROR = "Parse tree type id [&d] with description [%s] is not supported by the parser.";
private static final String QUOTE = "\'";
// Constructor //
/**
* Private constructor as this is a static utility class, so should not be
* constructed.
*/
private ParseTreeUtils() {
}
// Public static methods //
/**
* Returns a byte from its hexadecimal string representation.
*
* @param hexByte
* a hexadecimal representation of a byte.
* @return the byte encoded by the hex representation.
* @throws ParseException if the string cannot be parsed as a hex byte, or is null or empty.
*/
public static byte parseHexByte(final String hexByte) throws ParseException {
try {
final int value = Integer.parseInt(hexByte, 16);
if (value < 0 || value > 255) {
throw new ParseException("The hex string [" + hexByte +
"] is not a byte value between 0 and 255 inclusive: "
+ value);
}
return (byte) value;
} catch (NumberFormatException nfe) {
throw new ParseException("Could not parse into a hex byte: [" + hexByte + "]");
}
}
/**
* Returns the first child of a node, or throws a ParseException if
* there is no such child.
*
* @param node The node to get the first child of.
* @return A node which is the first child of the node passed in.
* @throws ParseException If there is no such child node.
*/
public static ParseTree getFirstChild(final ParseTree node) throws ParseException {
final List<ParseTree> children = node.getChildren();
if (children.size() > 0) {
return children.get(0);
}
throw new ParseException("No children exist for node type: " +
node.getParseTreeType().name());
}
/**
* Returns the first range value of a node passed in. A range is defined by
* a node with two integer child nodes. Each range value must be an integer
* in the range 0 to 255, as they define byte values, and the node passed in
* must have the type {@link net.domesdaybook.parser.tree.ParseTreeType.RANGE}.
*
* @param rangeNode The node with two integer child nodes defining a range.
* @return The integer value of the first range value.
* @throws ParseException If a problem occurs parsing the range value,
* or the range node or value is not correct.
*/
public static int getFirstRangeValue(final ParseTree rangeNode) throws ParseException {
return getRangeValue(rangeNode, 0);
}
/**
* Returns the second range value of a node passed in. A range is defined by
* a node with two integer child nodes. Each range value must be an integer
* in the range 0 to 255, as they define byte values, and the node passed in
* must have the type {@link net.domesdaybook.parser.tree.ParseTreeType.RANGE}.
*
* @param rangeNode The node with two integer child nodes defining a range.
* @return The integer value of the second range value.
* @throws ParseException If a problem occurs parsing the range value,
* or the range node or value is not correct.
*/
public static int getSecondRangeValue(final ParseTree rangeNode) throws ParseException {
return getRangeValue(rangeNode, 1);
}
/**
* Returns a collection of unique Bytes representing all the bytes covered by the inclusive
* range node passed in.
*
* @param range The range node passed in.
* @return A collection of unique bytes representing all the bytes in a range node passed in.
* @throws ParseException If the node is not a range node, or does not have correct range
* values as child nodes, or if another problem occurs parsing the node.
*/
public static Collection<Byte> getRangeValues(final ParseTree range) throws ParseException {
final int range1 = getFirstRangeValue(range);
final int range2 = getSecondRangeValue(range);
final Set<Byte> values = new LinkedHashSet<Byte>(64);
ByteUtilities.addBytesInRange(range1, range2, values);
return values;
}
/**
* Returns the first repeat value of a node passed in. A repeat is defined by
* a node with three child nodes. The first node is always an integer node, defining
* the minimum number of repeats. The second node can either be an integer node,
* or a Many node type, defining the maximum number of repeats. The third node
* is the node which must be repeated.
*
* @param repeatNode The node defining a repeat.
* @return The first repeat value (minimum number of repeats) for the repeat node.
* @throws ParseException If the node passed in does not have type
* {@link net.domesdaybook.parser.tree.ParseTreeType.REPEAT},
* the number of child nodes is not correct, there is no
* first repeat value, or another problem occurs parsing.
*/
public static int getFirstRepeatValue(final ParseTree repeatNode) throws ParseException {
return getRepeatValue(repeatNode, 0);
}
/**
* Returns the second repeat value of a node passed in. A repeat is defined by
* a node with three child nodes. The first node is always an integer node, defining
* the minimum number of repeats. The second node can either be an integer node,
* or a Many node type, defining the maximum number of repeats. The third node
* is the node which must be repeated.
* <p>
* If the maximum value is MANY, rather than a specified integer, then this method
* will return -1 to indicate that the number of repeats is unlimited.
*
* @param repeatNode The node defining a repeat.
* @return The second repeat value (maximum number of repeats) for the repeat node.
* @throws ParseException If the node passed in does not have type
* {@link net.domesdaybook.parser.tree.ParseTreeType.REPEAT},
* the number of child nodes is not correct, there is no
* second repeat value, or another problem occurs parsing.
*/
public static int getSecondRepeatValue(final ParseTree repeatNode) throws ParseException {
return getRepeatValue(repeatNode, 1);
}
/**
* Returns the node which should be repeated by a node of type
* {@link net.domesdaybook.parser.tree.ParseTreeType.REPEAT}.
*
* @param repeatNode The parent repeat instruction node.
* @return The node which should be repeated.
* @throws ParseException
*/
public static ParseTree getNodeToRepeat(final ParseTree repeatNode) throws ParseException {
final List<ParseTree> repeatChildren = repeatNode.getChildren();
if (repeatChildren.size() != 3) {
throw new ParseException("Repeats must have three child nodes. " +
"Actual number of children was: " + repeatChildren.size());
}
return repeatChildren.get(2);
}
/**
* Returns a collection of unique byte values matching a bitmask, where all the bits
* must match the bitmask.
*
* @param allBitmask The all bitmask node.
* @return A collection of bytes which match the all-bits bitmask.
* @throws ParseException If there is no bitmask byte value or another problem occurs
* parsing the value.
*/
public static Collection<Byte> getAllBitmaskValues(final ParseTree allBitmask) throws ParseException {
return ByteUtilities.getBytesMatchingAllBitMask(allBitmask.getByteValue());
}
/**
* Returns a collection of unique byte values matching a bitmask, where any of the bits
* must match the bitmask.
*
* @param allBitmask The any bitmask node.
* @return A collection of bytes which match the any-bits bitmask.
* @throws ParseException If there is no bitmask byte value or another problem occurs
* parsing the value.
*/
public static Collection<Byte> getAnyBitmaskValues(final ParseTree anyBitmask) throws ParseException {
return ByteUtilities.getBytesMatchingAnyBitMask(anyBitmask.getByteValue());
}
/**
* Returns a collection of unique byte values which consist of the byte values of the
* String passed in, when encoded as ISO 8859-1 bytes.
*
* @param string The string to get the bytes for.
* @return A collection of bytes representing the unique bytes defined in the string passed in.
* @throws ParseException If the string cannot be converted to ISO 8859-1 encoding.
*/
public static Collection<Byte> getStringAsSet(final ParseTree string) throws ParseException {
final Set<Byte> values = new LinkedHashSet<Byte>();
try {
final byte[] utf8Value = string.getTextValue().getBytes("ISO-8859-1");
ByteUtilities.addAll(utf8Value, values);
return values;
} catch (UnsupportedEncodingException e) {
throw new ParseException(e);
}
}
/**
* Returns a collection of unique byte values that represent all the byte values
* in a String when encoded as ISO 8859-1 bytes. Any lower or upper case characters
* will have their counterpart added to the collection, ensuring case-insensitivity.
*
* @param caseInsensitive The string to get a set of case insensitive byte values for.
* @return A collection of bytes giving all the case insensitive bytes that string might match.
* @throws ParseException If the string cannot be encoded in ISO 8859-1.
*/
public static Collection<Byte> getCaseInsensitiveStringAsSet(final ParseTree caseInsensitive) throws ParseException {
try {
final byte[] byteValues = caseInsensitive.getTextValue().getBytes("ISO-8859-1");
final Set<Byte> values = new LinkedHashSet<Byte>();
for (int charIndex = 0; charIndex < byteValues.length; charIndex++) {
final byte charAt = byteValues[charIndex];
if (charAt >= 'a' && charAt <= 'z') {
values.add((byte) Character.toUpperCase(charAt));
} else if (charAt >= 'A' && charAt <= 'A') {
values.add((byte) Character.toLowerCase(charAt));
}
values.add(charAt);
}
return values;
} catch (UnsupportedEncodingException e) {
throw new ParseException(e);
}
}
/**
* Calculates the value of a set given the parent set node (or inverted set
* node). Sets can contain bytes, strings (case sensitive & insensitive),
* ranges, other sets nested inside them (both normal and inverted) and
* bitmasks.
* <p>
* This method does invert the set of bytes returned if the set node passed in
* is inverted. If you want to calculate the values of the set as defined in
* the set (regardless of whether the set node itself is inverted), then
* use the method {@link #getSetValues(ParseTree)}.
*
* @param set
* The set node to calculate a set of byte values for, taking into
* account whether the set node is inverted or not.
* @return A set of byte values defined by the node.
* @throws ParseException
* If a problem occurs parsing the node.
*/
public static Set<Byte> calculateSetValues(final ParseTree set) throws ParseException {
final Set<Byte> setValues = getSetValues(set);
if (set.isValueInverted()) {
return ByteUtilities.invertedSet(setValues);
}
return setValues;
}
/**
* Calculates a value of a set given the parent set node (or inverted set
* node). Sets can contain bytes, strings (case sensitive & insensitive),
* ranges, other sets nested inside them (both normal and inverted) and
* bitmasks.
* <p>
* This method does not invert the set bytes returned if the root set node is inverted.
* It preserves the bytes as-defined in the set, leaving the question of whether to
* invert the bytes defined in the set passed in to any clients of the code.
* <p>
* If you want the set values calculating taking into account the inversion
* status of the set node itself, please call the method {@link #calculateSetValues(ParseTree)}.
* <p>
* This can be recursive procedure if sets are nested within one another.
*
* @param set
* The set node to calculate a set of byte values for.
* @return A set of byte values defined by the node.
* @throws ParseException
* If a problem occurs parsing the node.
*/
public static Set<Byte> getSetValues(final ParseTree set)
throws ParseException {
final Set<Byte> setValues = new LinkedHashSet<Byte>(192);
for (final ParseTree child : set.getChildren()) {
switch (child.getParseTreeType()) {
case SEQUENCE: // Drop through: treat all possible types of node which may hold
case ALTERNATIVES: // byte value bearing children as just containers of those values.
case SET: // The idea is you can pass any regular expression node into this
case ZERO_TO_MANY: // function, and get the set of all byte values which *could* be
case ONE_TO_MANY: // matched by that expression.
case OPTIONAL: setValues.addAll(calculateSetValues(child)); break;
case REPEAT: setValues.addAll(calculateSetValues(getNodeToRepeat(child))); break;
case BYTE: setValues.add(child.getByteValue()); break;
case RANGE: setValues.addAll(getRangeValues(child)); break;
case ALL_BITMASK: setValues.addAll(getAllBitmaskValues(child)); break;
case ANY_BITMASK: setValues.addAll(getAnyBitmaskValues(child)); break;
case STRING: setValues.addAll(getStringAsSet(child)); break;
case CASE_INSENSITIVE_STRING: setValues.addAll(getCaseInsensitiveStringAsSet(child)); break;
default: throw new ParseException(getTypeError(child));
}
}
return setValues;
}
// Private static methods //
/**
* Private utility method which gets the nominated range value and validates it
* to make sure it is between 0 and 255. Also validates that the range node itself
* only has two children, and that the range node has type ParseTreeType.RANGE.
*
* @param rangeNode The range node to get a value for.
* @param valueIndex The number of the range value (first: 0 or second: 1).
* @return The integer value of the first or second range value.
* @throws ParseException If a problem occurs parsing the range value,
* or the range node or value is not correct.
*/
private static int getRangeValue(final ParseTree rangeNode, final int valueIndex) throws ParseException {
if (rangeNode.getParseTreeType() != ParseTreeType.RANGE) {
throw new ParseException("Node is not a RANGE node. It has type: " + rangeNode.getParseTreeType());
}
final List<ParseTree> rangeChildren = rangeNode.getChildren();
if (rangeChildren.size() != 2) {
throw new ParseException("Ranges must have two integer values as child nodes." +
"Actual number of children was: " + rangeChildren.size());
}
final int rangeValue = rangeChildren.get(0).getIntValue();
if (rangeValue < 0 || rangeValue > 255) {
throw new ParseException("Range values must be between 0 and 255." +
"Actual value was: " + rangeValue);
}
return rangeValue;
}
/**
* Private utility method which gets the nominated repeat value and validates it
* to make sure it is either a positive integer, or a MANY node. Also validates that
* the repeat node itself has three children, and that the repeat node has type
* ParseTreetype.REPEAT.
*
* @param repeatNode The repeat node to get a repeat value for.
* @param valueIndex the number of the repeat value (min:0, max: 1).
* @return An integer value of the min or max repeat. If the max repeat is unlimited,
* then -1 will be returned.
* @throws ParseException If the repeat node does not have type ParseTreeType.REPEAT,
* it does not have three children, or an integer value supplied
* is not positive.
*/
private static int getRepeatValue(final ParseTree repeatNode, final int valueIndex) throws ParseException {
if (repeatNode.getParseTreeType() != ParseTreeType.REPEAT) {
throw new ParseException("Node is not a REPEAT node. It has type: " + repeatNode.getParseTreeType());
}
final List<ParseTree> repeatChildren = repeatNode.getChildren();
if (repeatChildren.size() != 3) {
throw new ParseException("Repeats must have three child nodes. " +
"Actual number of children was: " +repeatChildren.size());
}
final ParseTree repeatValue = repeatChildren.get(valueIndex);
if (repeatValue.getParseTreeType() == ParseTreeType.INTEGER) {
final int intValue = repeatValue.getIntValue();
if (intValue < 1) {
throw new ParseException("Repeat integer values must be at least one. " +
"Actual value was: " + intValue);
}
return intValue;
}
return -1; //FIXME: need to test for MANY node, which doesn't exist at the moment...
// But this function should return a negative number for a many node,
// and throw a ParseException if the node isn't an integer or a many node.
}
/**
* Returns a nicely formatted type error message given a node.
*
* @param node The node to get a type error message for.
* @return A type error message for that node.
*/
private static String getTypeError(final ParseTree node) {
final ParseTreeType type = node.getParseTreeType();
return String.format(TYPE_ERROR, type, type.getDescription());
}
}
|
package net.hillsdon.svnwiki.web.taglib;
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
import net.hillsdon.svnwiki.wiki.InternalLinker;
public class WikiLinkTag extends TagSupport {
private static final long serialVersionUID = 1L;
private String _page;
public String getPage() {
return _page;
}
public void setPage(final String page) {
_page = page;
}
public int doStartTag() throws JspException {
try {
InternalLinker linker = (InternalLinker) pageContext.getRequest().getAttribute("internalLinker");
if (linker != null) {
JspWriter out = pageContext.getOut();
out.write(linker.link(getPage()));
}
}
catch (IOException e) {
throw new JspException(e);
}
return SKIP_BODY;
}
}
|
package net.transitdata.siri;
import java.math.*;
import java.util.GregorianCalendar;
import javax.xml.bind.JAXBContext;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.validation.Schema;
import uk.org.siri.siri.*;
import uk.org.siri.siri.AnnotatedStopPointStructure.Lines;
public class NewStopPointsDiscovery {
JAXBContext jc;
DatatypeFactory df = null;
Schema schema = null;
/**
* @param args
*/
public static void main(String[] args) {
//NOTE need a way to exclude lines that are not currently served. URL param?
NewStopPointsDiscovery nspd = new NewStopPointsDiscovery();
Util ut = new Util();
StopPointsDeliveryStructure spds = nspd.getStopPointsRequest();
Siri siri = new Siri();
siri.setStopPointsDelivery(spds);
String xml = ut.getXMLFromObject(siri, true);
//String json = ut.getJSONFromObject(siri, true);
System.out.println("XML:\n" + xml );
//System.out.println("JSON:\n" + json);
ut.validateXML(xml);
}
private StopPointsDeliveryStructure getStopPointsRequest(){
try {
df = DatatypeFactory.newInstance();
} catch (DatatypeConfigurationException e1) {
e1.printStackTrace();
}
StopPointsDeliveryStructure spds = new StopPointsDeliveryStructure();
NaturalLanguageStringStructure stopName = new NaturalLanguageStringStructure();
stopName.setValue("Stop A");
DirectionRefStructure direction0 = new DirectionRefStructure();
direction0.setValue("0");
DirectionRefStructure direction1 = new DirectionRefStructure();
direction1.setValue("1");
LineRefStructure line1 = new LineRefStructure();
line1.setValue("Agency_1");
LineDirectionStructure lineDirStruct1 = new LineDirectionStructure();
lineDirStruct1.setDirectionRef(direction0);
lineDirStruct1.setLineRef(line1);
LineRefStructure line2 = new LineRefStructure();
line2.setValue("Agency_2");
LineDirectionStructure lineDirStruct2 = new LineDirectionStructure();
lineDirStruct2.setDirectionRef(direction1);
lineDirStruct2.setLineRef(line2);
Lines lines = new Lines();
lines.getLineRefOrLineDirection().add(lineDirStruct1);
lines.getLineRefOrLineDirection().add(lineDirStruct2);
BigDecimal stopLat = new BigDecimal(44.12345);
BigDecimal stopLon = new BigDecimal(-74.12345);
LocationStructure location = new LocationStructure();
location.setLongitude(stopLon);
location.setLatitude(stopLat);
AnnotatedStopPointStructure asps = new AnnotatedStopPointStructure();
asps.setLines(lines);
StopPointRefStructure spr = new StopPointRefStructure();
spr.setValue("Agency_1234");
GregorianCalendar gregorianCalendar = new GregorianCalendar();
XMLGregorianCalendar nowTime = df.newXMLGregorianCalendar(gregorianCalendar);
// minimum: "Return only the name and identifier of the stop"
spds.setResponseTimestamp(nowTime);
asps.getStopName().add(stopName);
// normal: "Return name, identifier and coordinates of the stop."
asps.setLocation(location);
// full : "Return all available data for each stop."
asps.setStopPointRef(spr);
spds.getAnnotatedStopPointRef().add(asps);
return spds;
}
}
|
// This file is part of the "OPeNDAP 4 Data Server (aka Hyrax)" project.
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.
package opendap.gateway.dapResponders;
import opendap.bes.Version;
import opendap.coreServlet.ReqInfo;
import opendap.coreServlet.Scrub;
import opendap.gateway.BesGatewayApi;
import opendap.coreServlet.HttpResponder;
import org.jdom.Document;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.slf4j.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.util.regex.Pattern;
public class NetcdfFileOut extends HttpResponder {
private Logger log;
private static String defaultRegex = ".*\\.nc";
public NetcdfFileOut(String sysPath) {
super(sysPath, null, defaultRegex);
log = org.slf4j.LoggerFactory.getLogger(this.getClass());
}
public NetcdfFileOut(String sysPath, String pathPrefix) {
super(sysPath, pathPrefix, defaultRegex);
log = org.slf4j.LoggerFactory.getLogger(this.getClass());
}
public void respondToHttpRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
String relativeUrl = ReqInfo.getRelativeUrl(request);
String dataSource = ReqInfo.getBesDataSourceID(relativeUrl);
String fullSourceName = ReqInfo.getRelativeUrl(request);
String constraintExpression = ReqInfo.getConstraintExpression(request);
String dataSourceUrl = BesGatewayApi.getDataSourceUrl(request, getPathPrefix());
log.debug("respondToHttpRequest(): Sending netCDF File Out response for dataset: " + dataSource + "?" +
constraintExpression);
String downloadFileName = fullSourceName.substring(fullSourceName.lastIndexOf("/")+1,fullSourceName.length());
Pattern startsWithNumber = Pattern.compile("[0-9].*");
if(startsWithNumber.matcher(downloadFileName).matches())
downloadFileName = "nc_"+downloadFileName;
log.debug("sendNetcdfFileOut() downloadFileName: " + downloadFileName );
String contentDisposition = " attachment; filename=" +downloadFileName;
response.setContentType("application/x-netcdf");
response.setHeader("Content-Disposition", Scrub.fileName(contentDisposition));
Version.setOpendapMimeHeaders(request, response);
response.setStatus(HttpServletResponse.SC_OK);
String xdap_accept = request.getHeader("XDAP-Accept");
OutputStream os = response.getOutputStream();
ByteArrayOutputStream erros = new ByteArrayOutputStream();
Document reqDoc = BesGatewayApi.getRequestDocument(
BesGatewayApi.DAP2,
dataSourceUrl,
constraintExpression,
xdap_accept,
null,
null,
"netcdf",
BesGatewayApi.DAP2_ERRORS);
XMLOutputter xmlo = new XMLOutputter(Format.getPrettyFormat());
log.debug("BesGatewayApi.getRequestDocument() returned:\n "+xmlo.outputString(reqDoc));
if(!BesGatewayApi.besTransaction(dataSource,reqDoc,os,erros)){
String msg = new String(erros.toByteArray());
log.error("sendDDX() encountered a BESError: "+msg);
os.write(msg.getBytes());
}
os.flush();
log.info("Sent DAP2 data as netCDF file.");
}
}
|
/*
* $Id: DefinablePlugin.java,v 1.10 2005-03-23 17:03:25 troberts Exp $
*/
package org.lockss.plugin.definable;
import org.lockss.plugin.base.*;
import org.lockss.plugin.*;
import org.lockss.config.Configuration;
import org.lockss.daemon.*;
import org.lockss.app.*;
import org.lockss.util.*;
import org.lockss.util.urlconn.*;
import java.util.*;
import java.io.FileNotFoundException;
/**
* <p>DefinablePlugin: a plugin which uses the data stored in an
* ExternalizableMap to configure it self.</p>
* @author Claire Griffin
* @version 1.0
*/
public class DefinablePlugin extends BasePlugin {
// configuration map keys
static final public String CM_NAME_KEY = "plugin_name";
static final public String CM_VERSION_KEY = "plugin_version";
static final public String CM_CONFIG_PROPS_KEY = "plugin_config_props";
static final public String CM_EXCEPTION_HANDLER_KEY =
"plugin_cache_result_handler";
static final public String CM_EXCEPTION_LIST_KEY =
"plugin_cache_result_list";
static final public String CM_CRAWL_TYPE =
"plugin_crawl_type";
static final public String CM_FOLLOW_LINKS = "plugin_follow_link";
static final public String DEFAULT_PLUGIN_VERSION = "1";
static final public String MAP_SUFFIX = ".xml";
static final public String[] CRAWL_TYPES = {"HTML Links", "OAI"};
protected String mapName = null;
static Logger log = Logger.getLogger("DefinablePlugin");
protected ExternalizableMap definitionMap = new ExternalizableMap();
protected CacheResultHandler resultHandler = null;
protected ClassLoader classLoader;
public void initPlugin(LockssDaemon daemon, String extMapName)
throws FileNotFoundException {
initPlugin(daemon, extMapName, this.getClass().getClassLoader());
}
public void initPlugin(LockssDaemon daemon, String extMapName,
ClassLoader loader)
throws FileNotFoundException {
mapName = extMapName;
this.classLoader = loader;
// convert the plugin class name to an xml file name
String mapFile = mapName.replace('.', '/') + MAP_SUFFIX;
// load the configuration map from jar file
definitionMap.loadMapFromResource(mapFile, classLoader);
// then call the overridden initializaton.
super.initPlugin(daemon);
}
public String getPluginName() {
String default_name = StringUtil.shortName(getPluginId());
return definitionMap.getString(CM_NAME_KEY, default_name);
}
public String getVersion() {
return definitionMap.getString(CM_VERSION_KEY, DEFAULT_PLUGIN_VERSION);
}
public List getAuConfigDescrs() throws InvalidDefinitionException {
List auConfigDescrs =
(List) definitionMap.getCollection(CM_CONFIG_PROPS_KEY, null);
if (auConfigDescrs == null) {
throw new InvalidDefinitionException(mapName +
" missing ConfigParamDescrs");
}
return auConfigDescrs;
}
public ArchivalUnit createAu(Configuration auConfig)
throws ArchivalUnit.ConfigurationException {
DefinableArchivalUnit au =
new DefinableArchivalUnit(this, definitionMap, classLoader);
au.setConfiguration(auConfig);
return au;
}
ExternalizableMap getDefinitionMap() {
return definitionMap;
}
CacheResultHandler getCacheResultHandler() {
return resultHandler;
}
protected void initResultMap() throws InvalidDefinitionException {
resultMap = new HttpResultMap();
// we support two form of result handlers... either a class which handles
// installing the numbers as well as handling any exceptions
String handler_class = null;
handler_class = definitionMap.getString(CM_EXCEPTION_HANDLER_KEY, null);
if (handler_class != null) {
try {
resultHandler =
(CacheResultHandler) Class.forName(handler_class).newInstance();
resultHandler.init(resultMap);
}
catch (Exception ex) {
throw new InvalidDefinitionException(mapName
+ " has invalid Exception handler: " + handler_class);
}
catch (LinkageError le) {
throw new InvalidDefinitionException(
mapName + "has invalid Exception handler: " + handler_class , le);
}
}
else {// or a list of individual exception remappings
Collection results;
results = definitionMap.getCollection(CM_EXCEPTION_LIST_KEY, null);
if (results != null) {
// add each entry
for (Iterator it = results.iterator(); it.hasNext(); ) {
String entry = (String) it.next();
try {
Vector s_vec = StringUtil.breakAt(entry, '=', 2, true, true);
String class_name = (String) s_vec.get(1);
int code = Integer.parseInt(((String) s_vec.get(0)));
// now lets add the entry into the map.
Class result_class = null;
result_class = Class.forName(class_name);
( (HttpResultMap) resultMap).storeMapEntry(code, result_class);
}
catch (Exception ex1) {
throw new InvalidDefinitionException(mapName
+ " has invalid entry: "
+ entry);
}
}
}
}
}
public String getPluginId() {
String class_name;
if(mapName != null) {
class_name = mapName;
}
else {
//@TODO: eliminate this when we eliminate subclasses
class_name = this.getClass().getName();
}
return class_name;
}
public static class InvalidDefinitionException extends RuntimeException {
private Throwable nestedException;
public InvalidDefinitionException(String msg) {
super(msg);
}
public InvalidDefinitionException(String msg, Throwable e) {
super(msg + (e.getMessage() == null ? "" : (": " + e.getMessage())));
this.nestedException = e;
}
public Throwable getNestedException() {
return nestedException;
}
}
}
|
package org.myrobotlab.service;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JSlider;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
import org.myrobotlab.framework.Service;
import org.myrobotlab.logging.Level;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.Logging;
import org.myrobotlab.logging.LoggingFactory;
import org.myrobotlab.service.Python.Script;
import org.slf4j.Logger;
/**
* based on _TemplateService
*/
/**
*
* @author LunDev (github), Ma. Vo. (MyRobotlab)
*/
public class InMoovGestureCreator extends Service {
private static final long serialVersionUID = 1L;
public final static Logger log = LoggerFactory
.getLogger(InMoovGestureCreator.class);
ServoItemHolder[][] servoitemholder;
ArrayList<FrameItemHolder> frameitemholder;
ArrayList<PythonItemHolder> pythonitemholder;
boolean[] tabs_main_checkbox_states;
boolean moverealtime = false;
InMoov i01;
String pythonscript;
String pythonname;
String referencename;
public InMoovGestureCreator(String n) {
super(n);
// intializing variables
servoitemholder = new ServoItemHolder[6][];
frameitemholder = new ArrayList<FrameItemHolder>();
pythonitemholder = new ArrayList<PythonItemHolder>();
tabs_main_checkbox_states = new boolean[6];
}
@Override
public void startService() {
super.startService();
}
@Override
public void stopService() {
super.stopService();
}
@Override
public String getDescription() {
return "an easier way to create gestures for InMoov";
}
public void tabs_main_checkbox_states_changed(
boolean[] tabs_main_checkbox_states2) {
// checkbox states (on the main site) (for the services) changed
tabs_main_checkbox_states = tabs_main_checkbox_states2;
}
public void control_connect(JButton control_connect) {
// Connect / Disconnect to / from the InMoov service (button
// bottom-left)
if (control_connect.getText().equals("Connect")) {
if (referencename == null) {
referencename = "i01";
}
i01 = (InMoov) Runtime.getService(referencename);
control_connect.setText("Disconnect");
} else {
i01 = null;
control_connect.setText("Connect");
}
}
public void control_loadscri(JList control_list) {
// Load the Python-Script (out Python-Service) (button bottom-left)
Python python = (Python) Runtime.getService("python");
Script script = python.getScript();
pythonscript = script.getCode();
parsescript(control_list);
}
public void control_savescri() {
// Save the Python-Script (in Python-Service) (button bottom-left)
JFrame frame = new JFrame();
frame.setSize(500, 500);
JTextArea textarea = new JTextArea();
textarea.setText(pythonscript);
textarea.setEditable(false);
textarea.setLineWrap(true);
JScrollPane scrollpane = new JScrollPane(textarea);
scrollpane
.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollpane
.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
frame.add(scrollpane);
frame.setVisible(true);
}
public void control_loadgest(JList control_list, JList framelist,
JTextField control_gestname, JTextField control_funcname) {
// Load the current gesture from the script (button bottom-left)
int posl = control_list.getSelectedIndex();
if (posl != -1) {
if (pythonitemholder.get(posl).modifyable) {
frameitemholder.clear();
String defname = null;
String code = pythonitemholder.get(posl).code;
String[] codesplit = code.split("\n");
FrameItemHolder fih = null;
boolean ismove = false;
boolean isspeed = false;
boolean head = false;
boolean rhand = false;
boolean lhand = false;
boolean rarm = false;
boolean larm = false;
boolean torso = false;
boolean keepgoing = true;
int pos = 0;
while (keepgoing) {
if (fih == null) {
fih = new FrameItemHolder();
}
String line;
if (pos < codesplit.length) {
line = codesplit[pos];
} else {
line = "pweicmfh - only one run";
keepgoing = false;
}
String linewithoutspace = line.replace(" ", "");
if (linewithoutspace.equals("")) {
pos++;
continue;
}
String line2 = line.replace(" ", "");
if (!(ismove) && !(isspeed)) {
if (line2.startsWith("def")) {
String defn = line.substring(line.indexOf(" ") + 1,
line.lastIndexOf("():"));
defname = defn;
pos++;
} else if (line2.startsWith("sleep")) {
String sleeptime = line.substring(
line.indexOf("(") + 1,
line.lastIndexOf(")"));
fih.sleep = Integer.parseInt(sleeptime);
fih.speech = null;
fih.name = null;
frameitemholder.add(fih);
fih = null;
pos++;
} else if (line2.startsWith(pythonname)) {
if (line2.startsWith(pythonname + ".mouth.speak")) {
fih.sleep = -1;
fih.speech = line.substring(
line.indexOf("(") + 1,
line.lastIndexOf(")"));
fih.name = null;
frameitemholder.add(fih);
fih = null;
pos++;
} else if (line2.startsWith(pythonname + ".move")) {
ismove = true;
String good = line2.substring(
line2.indexOf("(") + 1,
line2.lastIndexOf(")"));
String[] goodsplit = good.split(",");
if (line2.startsWith(pythonname + ".moveHead")) {
fih.neck = Integer.parseInt(goodsplit[0]);
fih.rothead = Integer
.parseInt(goodsplit[1]);
if (goodsplit.length > 2) {
fih.eyeX = Integer
.parseInt(goodsplit[2]);
fih.eyeY = Integer
.parseInt(goodsplit[3]);
fih.jaw = Integer
.parseInt(goodsplit[4]);
} else {
fih.eyeX = 90;
fih.eyeY = 90;
fih.jaw = 90;
}
head = true;
pos++;
} else if (line2.startsWith(pythonname
+ ".moveHand")) {
String gs = goodsplit[0];
String side = gs.substring(
gs.indexOf("\"") + 1,
gs.lastIndexOf("\""));
if (side.equals("right")) {
fih.rthumb = Integer
.parseInt(goodsplit[1]);
fih.rindex = Integer
.parseInt(goodsplit[2]);
fih.rmajeure = Integer
.parseInt(goodsplit[3]);
fih.rringfinger = Integer
.parseInt(goodsplit[4]);
fih.rpinky = Integer
.parseInt(goodsplit[5]);
if (goodsplit.length > 6) {
fih.rwrist = Integer
.parseInt(goodsplit[6]);
} else {
fih.rwrist = 90;
}
rhand = true;
pos++;
} else if (side.equals("left")) {
fih.lthumb = Integer
.parseInt(goodsplit[1]);
fih.lindex = Integer
.parseInt(goodsplit[2]);
fih.lmajeure = Integer
.parseInt(goodsplit[3]);
fih.lringfinger = Integer
.parseInt(goodsplit[4]);
fih.lpinky = Integer
.parseInt(goodsplit[5]);
if (goodsplit.length > 6) {
fih.lwrist = Integer
.parseInt(goodsplit[6]);
} else {
fih.lwrist = 90;
}
lhand = true;
pos++;
}
} else if (line2.startsWith(pythonname
+ ".moveArm")) {
String gs = goodsplit[0];
String side = gs.substring(
gs.indexOf("\"") + 1,
gs.lastIndexOf("\""));
if (side.equals("right")) {
fih.rbicep = Integer
.parseInt(goodsplit[1]);
fih.rrotate = Integer
.parseInt(goodsplit[2]);
fih.rshoulder = Integer
.parseInt(goodsplit[3]);
fih.romoplate = Integer
.parseInt(goodsplit[4]);
rarm = true;
pos++;
} else if (side.equals("left")) {
fih.lbicep = Integer
.parseInt(goodsplit[1]);
fih.lrotate = Integer
.parseInt(goodsplit[2]);
fih.lshoulder = Integer
.parseInt(goodsplit[3]);
fih.lomoplate = Integer
.parseInt(goodsplit[4]);
larm = true;
pos++;
}
} else if (line2.startsWith(pythonname
+ ".moveTorso")) {
fih.topStom = Integer
.parseInt(goodsplit[0]);
fih.midStom = Integer
.parseInt(goodsplit[1]);
fih.lowStom = Integer
.parseInt(goodsplit[2]);
torso = true;
pos++;
}
} else if (line2.startsWith(pythonname + ".set")) {
isspeed = true;
String good = line2.substring(
line2.indexOf("(") + 1,
line2.lastIndexOf(")"));
String[] goodsplit = good.split(",");
if (line2.startsWith(pythonname
+ ".setHeadSpeed")) {
fih.neckspeed = Float
.parseFloat(goodsplit[0]);
fih.rotheadspeed = Float
.parseFloat(goodsplit[1]);
if (goodsplit.length > 2) {
fih.eyeXspeed = Float
.parseFloat(goodsplit[2]);
fih.eyeYspeed = Float
.parseFloat(goodsplit[3]);
fih.jawspeed = Float
.parseFloat(goodsplit[4]);
} else {
fih.eyeXspeed = 1.0f;
fih.eyeYspeed = 1.0f;
fih.jawspeed = 1.0f;
}
head = true;
pos++;
} else if (line2.startsWith(pythonname
+ ".setHandSpeed")) {
String gs = goodsplit[0];
String side = gs.substring(
gs.indexOf("\"") + 1,
gs.lastIndexOf("\""));
if (side.equals("right")) {
fih.rthumbspeed = Float
.parseFloat(goodsplit[1]);
fih.rindexspeed = Float
.parseFloat(goodsplit[2]);
fih.rmajeurespeed = Float
.parseFloat(goodsplit[3]);
fih.rringfingerspeed = Float
.parseFloat(goodsplit[4]);
fih.rpinkyspeed = Float
.parseFloat(goodsplit[5]);
if (goodsplit.length > 6) {
fih.rwristspeed = Float
.parseFloat(goodsplit[6]);
} else {
fih.rwristspeed = 1.0f;
}
rhand = true;
pos++;
} else if (side.equals("left")) {
fih.lthumbspeed = Float
.parseFloat(goodsplit[1]);
fih.lindexspeed = Float
.parseFloat(goodsplit[2]);
fih.lmajeurespeed = Float
.parseFloat(goodsplit[3]);
fih.lringfingerspeed = Float
.parseFloat(goodsplit[4]);
fih.lpinkyspeed = Float
.parseFloat(goodsplit[5]);
if (goodsplit.length > 6) {
fih.lwristspeed = Float
.parseFloat(goodsplit[6]);
} else {
fih.lwristspeed = 1.0f;
}
lhand = true;
pos++;
}
} else if (line2.startsWith(pythonname
+ ".setArmSpeed")) {
String gs = goodsplit[0];
String side = gs.substring(
gs.indexOf("\"") + 1,
gs.lastIndexOf("\""));
if (side.equals("right")) {
fih.rbicepspeed = Float
.parseFloat(goodsplit[1]);
fih.rrotatespeed = Float
.parseFloat(goodsplit[2]);
fih.rshoulderspeed = Float
.parseFloat(goodsplit[3]);
fih.romoplatespeed = Float
.parseFloat(goodsplit[4]);
rarm = true;
pos++;
} else if (side.equals("left")) {
fih.lbicepspeed = Float
.parseFloat(goodsplit[1]);
fih.lrotatespeed = Float
.parseFloat(goodsplit[2]);
fih.lshoulderspeed = Float
.parseFloat(goodsplit[3]);
fih.lomoplatespeed = Float
.parseFloat(goodsplit[4]);
larm = true;
pos++;
}
} else if (line2.startsWith(pythonname
+ ".setTorsoSpeed")) {
fih.topStomspeed = Float
.parseFloat(goodsplit[0]);
fih.midStomspeed = Float
.parseFloat(goodsplit[1]);
fih.lowStomspeed = Float
.parseFloat(goodsplit[2]);
torso = true;
pos++;
}
}
}
} else if (ismove && !(isspeed)) {
if (line2.startsWith(pythonname + ".move")) {
String good = line2.substring(
line2.indexOf("(") + 1,
line2.lastIndexOf(")"));
String[] goodsplit = good.split(",");
if (line2.startsWith(pythonname + ".moveHead")) {
fih.neck = Integer.parseInt(goodsplit[0]);
fih.rothead = Integer.parseInt(goodsplit[1]);
if (goodsplit.length > 2) {
fih.eyeX = Integer.parseInt(goodsplit[2]);
fih.eyeY = Integer.parseInt(goodsplit[3]);
fih.jaw = Integer.parseInt(goodsplit[4]);
} else {
fih.eyeX = 90;
fih.eyeY = 90;
fih.jaw = 90;
}
head = true;
pos++;
} else if (line2.startsWith(pythonname
+ ".moveHand")) {
String gs = goodsplit[0];
String side = gs.substring(
gs.indexOf("\"") + 1,
gs.lastIndexOf("\""));
if (side.equals("right")) {
fih.rthumb = Integer.parseInt(goodsplit[1]);
fih.rindex = Integer.parseInt(goodsplit[2]);
fih.rmajeure = Integer
.parseInt(goodsplit[3]);
fih.rringfinger = Integer
.parseInt(goodsplit[4]);
fih.rpinky = Integer.parseInt(goodsplit[5]);
if (goodsplit.length > 6) {
fih.rwrist = Integer
.parseInt(goodsplit[6]);
} else {
fih.rwrist = 90;
}
rhand = true;
pos++;
} else if (side.equals("left")) {
fih.lthumb = Integer.parseInt(goodsplit[1]);
fih.lindex = Integer.parseInt(goodsplit[2]);
fih.lmajeure = Integer
.parseInt(goodsplit[3]);
fih.lringfinger = Integer
.parseInt(goodsplit[4]);
fih.lpinky = Integer.parseInt(goodsplit[5]);
if (goodsplit.length > 6) {
fih.lwrist = Integer
.parseInt(goodsplit[6]);
} else {
fih.lwrist = 90;
}
lhand = true;
pos++;
}
} else if (line2
.startsWith(pythonname + ".moveArm")) {
String gs = goodsplit[0];
String side = gs.substring(
gs.indexOf("\"") + 1,
gs.lastIndexOf("\""));
if (side.equals("right")) {
fih.rbicep = Integer.parseInt(goodsplit[1]);
fih.rrotate = Integer
.parseInt(goodsplit[2]);
fih.rshoulder = Integer
.parseInt(goodsplit[3]);
fih.romoplate = Integer
.parseInt(goodsplit[4]);
rarm = true;
pos++;
} else if (side.equals("left")) {
fih.lbicep = Integer.parseInt(goodsplit[1]);
fih.lrotate = Integer
.parseInt(goodsplit[2]);
fih.lshoulder = Integer
.parseInt(goodsplit[3]);
fih.lomoplate = Integer
.parseInt(goodsplit[4]);
larm = true;
pos++;
}
} else if (line2.startsWith(pythonname
+ ".moveTorso")) {
fih.topStom = Integer.parseInt(goodsplit[0]);
fih.midStom = Integer.parseInt(goodsplit[1]);
fih.lowStom = Integer.parseInt(goodsplit[2]);
torso = true;
pos++;
}
} else {
if (!head) {
fih.neck = 90;
fih.rothead = 90;
fih.eyeX = 90;
fih.eyeY = 90;
fih.jaw = 90;
}
if (!rhand) {
fih.rthumb = 90;
fih.rindex = 90;
fih.rmajeure = 90;
fih.rringfinger = 90;
fih.rpinky = 90;
fih.rwrist = 90;
}
if (!lhand) {
fih.lthumb = 90;
fih.lindex = 90;
fih.lmajeure = 90;
fih.lringfinger = 90;
fih.lpinky = 90;
fih.lwrist = 90;
}
if (!rarm) {
fih.rbicep = 90;
fih.rrotate = 90;
fih.rshoulder = 90;
fih.romoplate = 90;
}
if (!larm) {
fih.lbicep = 90;
fih.lrotate = 90;
fih.lshoulder = 90;
fih.lomoplate = 90;
}
if (!torso) {
fih.topStom = 90;
fih.midStom = 90;
fih.lowStom = 90;
}
fih.sleep = -1;
fih.speech = null;
fih.name = "SEQ";
frameitemholder.add(fih);
fih = null;
ismove = false;
head = false;
rhand = false;
lhand = false;
rarm = false;
larm = false;
torso = false;
}
} else if (!(ismove) && isspeed) {
if (line2.startsWith(pythonname + ".set")) {
String good = line2.substring(
line2.indexOf("(") + 1,
line2.lastIndexOf(")"));
String[] goodsplit = good.split(",");
if (line2.startsWith(pythonname + ".setHeadSpeed")) {
fih.neckspeed = Float.parseFloat(goodsplit[0]);
fih.rotheadspeed = Float
.parseFloat(goodsplit[1]);
if (goodsplit.length > 2) {
fih.eyeXspeed = Float
.parseFloat(goodsplit[2]);
fih.eyeYspeed = Float
.parseFloat(goodsplit[3]);
fih.jawspeed = Float
.parseFloat(goodsplit[4]);
} else {
fih.eyeXspeed = 1.0f;
fih.eyeYspeed = 1.0f;
fih.jawspeed = 1.0f;
}
head = true;
pos++;
} else if (line2.startsWith(pythonname
+ ".setHandSpeed")) {
String gs = goodsplit[0];
String side = gs.substring(
gs.indexOf("\"") + 1,
gs.lastIndexOf("\""));
if (side.equals("right")) {
fih.rthumbspeed = Float
.parseFloat(goodsplit[1]);
fih.rindexspeed = Float
.parseFloat(goodsplit[2]);
fih.rmajeurespeed = Float
.parseFloat(goodsplit[3]);
fih.rringfingerspeed = Float
.parseFloat(goodsplit[4]);
fih.rpinkyspeed = Float
.parseFloat(goodsplit[5]);
if (goodsplit.length > 6) {
fih.rwristspeed = Float
.parseFloat(goodsplit[6]);
} else {
fih.rwristspeed = 1.0f;
}
rhand = true;
pos++;
} else if (side.equals("left")) {
fih.lthumbspeed = Float
.parseFloat(goodsplit[1]);
fih.lindexspeed = Float
.parseFloat(goodsplit[2]);
fih.lmajeurespeed = Float
.parseFloat(goodsplit[3]);
fih.lringfingerspeed = Float
.parseFloat(goodsplit[4]);
fih.lpinkyspeed = Float
.parseFloat(goodsplit[5]);
if (goodsplit.length > 6) {
fih.lwristspeed = Float
.parseFloat(goodsplit[6]);
} else {
fih.lwristspeed = 1.0f;
}
lhand = true;
pos++;
}
} else if (line2.startsWith(pythonname
+ ".setArmSpeed")) {
String gs = goodsplit[0];
String side = gs.substring(
gs.indexOf("\"") + 1,
gs.lastIndexOf("\""));
if (side.equals("right")) {
fih.rbicepspeed = Float
.parseFloat(goodsplit[1]);
fih.rrotatespeed = Float
.parseFloat(goodsplit[2]);
fih.rshoulderspeed = Float
.parseFloat(goodsplit[3]);
fih.romoplatespeed = Float
.parseFloat(goodsplit[4]);
rarm = true;
pos++;
} else if (side.equals("left")) {
fih.lbicepspeed = Float
.parseFloat(goodsplit[1]);
fih.lrotatespeed = Float
.parseFloat(goodsplit[2]);
fih.lshoulderspeed = Float
.parseFloat(goodsplit[3]);
fih.lomoplatespeed = Float
.parseFloat(goodsplit[4]);
larm = true;
pos++;
}
} else if (line2.startsWith(pythonname
+ ".setTorsoSpeed")) {
fih.topStomspeed = Float
.parseFloat(goodsplit[0]);
fih.midStomspeed = Float
.parseFloat(goodsplit[1]);
fih.lowStomspeed = Float
.parseFloat(goodsplit[2]);
torso = true;
pos++;
}
} else {
if (!head) {
fih.neckspeed = 1.0f;
fih.rotheadspeed = 1.0f;
fih.eyeXspeed = 1.0f;
fih.eyeYspeed = 1.0f;
fih.jawspeed = 1.0f;
}
if (!rhand) {
fih.rthumbspeed = 1.0f;
fih.rindexspeed = 1.0f;
fih.rmajeurespeed = 1.0f;
fih.rringfingerspeed = 1.0f;
fih.rpinkyspeed = 1.0f;
fih.rwristspeed = 1.0f;
}
if (!lhand) {
fih.lthumbspeed = 1.0f;
fih.lindexspeed = 1.0f;
fih.lmajeurespeed = 1.0f;
fih.lringfingerspeed = 1.0f;
fih.lpinkyspeed = 1.0f;
fih.lwristspeed = 1.0f;
}
if (!rarm) {
fih.rbicepspeed = 1.0f;
fih.rrotatespeed = 1.0f;
fih.rshoulderspeed = 1.0f;
fih.romoplatespeed = 1.0f;
}
if (!larm) {
fih.lbicepspeed = 1.0f;
fih.lrotatespeed = 1.0f;
fih.lshoulderspeed = 1.0f;
fih.lomoplatespeed = 1.0f;
}
if (!torso) {
fih.topStomspeed = 1.0f;
fih.midStomspeed = 1.0f;
fih.lowStomspeed = 1.0f;
}
fih.sleep = -1;
fih.speech = null;
fih.name = null;
frameitemholder.add(fih);
fih = null;
isspeed = false;
head = false;
rhand = false;
lhand = false;
rarm = false;
larm = false;
torso = false;
}
} else {
// this shouldn't be reached
// ismove & isspeed true
// wrong
}
}
framelistact(framelist);
int defnamepos = pythonscript.indexOf(defname);
int earpos1 = pythonscript.lastIndexOf("\n", defnamepos);
int earpos2 = pythonscript.indexOf("\n", defnamepos);
String earline = pythonscript.substring(earpos1 + 1, earpos2);
if (earline.startsWith("ear.addCommand")) {
String good = earline.substring(earline.indexOf("("),
earline.lastIndexOf(")"));
String[] goodsplit = good.split(",");
String funcnamedirty = goodsplit[0];
String funcname = funcnamedirty.substring(
funcnamedirty.indexOf("\"") + 1,
funcnamedirty.lastIndexOf("\""));
control_gestname.setText(funcname);
control_funcname.setText(defname);
}
}
}
}
public void control_addgest(JList control_list,
JTextField control_gestname, JTextField control_funcname) {
// Add the current gesture to the script (button bottom-left)
String defname = control_funcname.getText();
String gestname = control_gestname.getText();
String code = "";
for (FrameItemHolder fih : frameitemholder) {
String code1;
if (fih.sleep != -1) {
code1 = " sleep(" + fih.sleep + ")\n";
} else if (fih.speech != null) {
code1 = " " + pythonname + ".mouth.speakBlocking(\""
+ fih.speech + "\")\n";
} else if (fih.name != null) {
String code11 = "";
String code12 = "";
String code13 = "";
String code14 = "";
String code15 = "";
String code16 = "";
if (tabs_main_checkbox_states[0]) {
code11 = " " + pythonname + ".moveHead(" + fih.neck
+ "," + fih.rothead + "," + fih.eyeX + ","
+ fih.eyeY + "," + fih.jaw + ")\n";
}
if (tabs_main_checkbox_states[1]) {
code12 = " " + pythonname + ".moveArm(\"left\","
+ fih.lbicep + "," + fih.lrotate + ","
+ fih.lshoulder + "," + fih.lomoplate + ")\n";
}
if (tabs_main_checkbox_states[2]) {
code13 = " " + pythonname + ".moveArm(\"right\","
+ fih.rbicep + "," + fih.rrotate + ","
+ fih.rshoulder + "," + fih.romoplate + ")\n";
}
if (tabs_main_checkbox_states[3]) {
code14 = " " + pythonname + ".moveHand(\"left\","
+ fih.lthumb + "," + fih.lindex + ","
+ fih.lmajeure + "," + fih.lringfinger + ","
+ fih.lpinky + "," + fih.lwrist + ")\n";
}
if (tabs_main_checkbox_states[4]) {
code15 = " " + pythonname + ".moveHand(\"right\","
+ fih.rthumb + "," + fih.rindex + ","
+ fih.rmajeure + "," + fih.rringfinger + ","
+ fih.rpinky + "," + fih.rwrist + ")\n";
}
if (tabs_main_checkbox_states[5]) {
code16 = " " + pythonname + ".moveTorso(" + fih.topStom
+ "," + fih.midStom + "," + fih.lowStom + ")\n";
}
code1 = code11 + code12 + code13 + code14 + code15 + code16;
} else {
String code11 = "";
String code12 = "";
String code13 = "";
String code14 = "";
String code15 = "";
String code16 = "";
if (tabs_main_checkbox_states[0]) {
code11 = " " + pythonname + ".setHeadSpeed("
+ fih.neckspeed + "," + fih.rotheadspeed + ","
+ fih.eyeXspeed + "," + fih.eyeYspeed + ","
+ fih.jawspeed + ")\n";
}
if (tabs_main_checkbox_states[1]) {
code12 = " " + pythonname + ".setArmSpeed(\"left\","
+ fih.lbicepspeed + "," + fih.lrotatespeed + ","
+ fih.lshoulderspeed + "," + fih.lomoplatespeed
+ ")\n";
}
if (tabs_main_checkbox_states[2]) {
code13 = " " + pythonname + ".setArmSpeed(\"right\","
+ fih.rbicepspeed + "," + fih.rrotatespeed + ","
+ fih.rshoulderspeed + "," + fih.romoplatespeed
+ ")\n";
}
if (tabs_main_checkbox_states[3]) {
code14 = " " + pythonname + ".setHandSpeed(\"left\","
+ fih.lthumbspeed + "," + fih.lindexspeed + ","
+ fih.lmajeurespeed + "," + fih.lringfingerspeed
+ "," + fih.lpinkyspeed + "," + fih.lwristspeed
+ ")\n";
}
if (tabs_main_checkbox_states[4]) {
code15 = " " + pythonname + ".setHandSpeed(\"right\","
+ fih.rthumbspeed + "," + fih.rindexspeed + ","
+ fih.rmajeurespeed + "," + fih.rringfingerspeed
+ "," + fih.rpinkyspeed + "," + fih.rwristspeed
+ ")\n";
}
if (tabs_main_checkbox_states[5]) {
code16 = " " + pythonname + ".setTorsoSpeed("
+ fih.topStomspeed + "," + fih.midStomspeed + ","
+ fih.lowStomspeed + ")\n";
}
code1 = code11 + code12 + code13 + code14 + code15 + code16;
}
code = code + code1;
}
String finalcode = "def " + defname + "():\n" + code;
String insert = "ear.addCommand(\"" + gestname + "\", \"python\", \""
+ defname + "\")";
int posear = pythonscript.lastIndexOf("ear.addCommand");
int pos = pythonscript.indexOf("\n", posear);
pythonscript = pythonscript.substring(0, pos) + "\n" + insert
+ pythonscript.substring(pos, pythonscript.length());
pythonscript = pythonscript + "\n" + finalcode;
parsescript(control_list);
}
public void control_updategest(JList control_list,
JTextField control_gestname, JTextField control_funcname) {
// Update the current gesture in the script (button bottom-left)
int posl = control_list.getSelectedIndex();
if (posl != -1) {
if (pythonitemholder.get(posl).function
&& !pythonitemholder.get(posl).notfunction) {
String codeold = pythonitemholder.get(posl).code;
String defnameold = codeold.substring(
codeold.indexOf("def ") + 4, codeold.indexOf("():"));
String defname = control_funcname.getText();
String gestname = control_gestname.getText();
String code = "";
for (FrameItemHolder fih : frameitemholder) {
String code1;
if (fih.sleep != -1) {
code1 = " sleep(" + fih.sleep + ")\n";
} else if (fih.speech != null) {
code1 = " " + pythonname + ".mouth.speakBlocking(\""
+ fih.speech + "\")\n";
} else if (fih.name != null) {
String code11 = "";
String code12 = "";
String code13 = "";
String code14 = "";
String code15 = "";
String code16 = "";
if (tabs_main_checkbox_states[0]) {
code11 = " " + pythonname + ".moveHead("
+ fih.neck + "," + fih.rothead + ","
+ fih.eyeX + "," + fih.eyeY + "," + fih.jaw
+ ")\n";
}
if (tabs_main_checkbox_states[1]) {
code12 = " " + pythonname + ".moveArm(\"left\","
+ fih.lbicep + "," + fih.lrotate + ","
+ fih.lshoulder + "," + fih.lomoplate
+ ")\n";
}
if (tabs_main_checkbox_states[2]) {
code13 = " " + pythonname
+ ".moveArm(\"right\"," + fih.rbicep + ","
+ fih.rrotate + "," + fih.rshoulder + ","
+ fih.romoplate + ")\n";
}
if (tabs_main_checkbox_states[3]) {
code14 = " " + pythonname
+ ".moveHand(\"left\"," + fih.lthumb + ","
+ fih.lindex + "," + fih.lmajeure + ","
+ fih.lringfinger + "," + fih.lpinky + ","
+ fih.lwrist + ")\n";
}
if (tabs_main_checkbox_states[4]) {
code15 = " " + pythonname
+ ".moveHand(\"right\"," + fih.rthumb + ","
+ fih.rindex + "," + fih.rmajeure + ","
+ fih.rringfinger + "," + fih.rpinky + ","
+ fih.rwrist + ")\n";
}
if (tabs_main_checkbox_states[5]) {
code16 = " " + pythonname + ".moveTorso("
+ fih.topStom + "," + fih.midStom + ","
+ fih.lowStom + ")\n";
}
code1 = code11 + code12 + code13 + code14 + code15
+ code16;
} else {
String code11 = "";
String code12 = "";
String code13 = "";
String code14 = "";
String code15 = "";
String code16 = "";
if (tabs_main_checkbox_states[0]) {
code11 = " " + pythonname + ".setHeadSpeed("
+ fih.neckspeed + "," + fih.rotheadspeed
+ "," + fih.eyeXspeed + "," + fih.eyeYspeed
+ "," + fih.jawspeed + ")\n";
}
if (tabs_main_checkbox_states[1]) {
code12 = " " + pythonname
+ ".setArmSpeed(\"left\","
+ fih.lbicepspeed + "," + fih.lrotatespeed
+ "," + fih.lshoulderspeed + ","
+ fih.lomoplatespeed + ")\n";
}
if (tabs_main_checkbox_states[2]) {
code13 = " " + pythonname
+ ".setArmSpeed(\"right\","
+ fih.rbicepspeed + "," + fih.rrotatespeed
+ "," + fih.rshoulderspeed + ","
+ fih.romoplatespeed + ")\n";
}
if (tabs_main_checkbox_states[3]) {
code14 = " " + pythonname
+ ".setHandSpeed(\"left\","
+ fih.lthumbspeed + "," + fih.lindexspeed
+ "," + fih.lmajeurespeed + ","
+ fih.lringfingerspeed + ","
+ fih.lpinkyspeed + "," + fih.lwristspeed
+ ")\n";
}
if (tabs_main_checkbox_states[4]) {
code15 = " " + pythonname
+ ".setHandSpeed(\"right\","
+ fih.rthumbspeed + "," + fih.rindexspeed
+ "," + fih.rmajeurespeed + ","
+ fih.rringfingerspeed + ","
+ fih.rpinkyspeed + "," + fih.rwristspeed
+ ")\n";
}
if (tabs_main_checkbox_states[5]) {
code16 = " " + pythonname + ".setTorsoSpeed("
+ fih.topStomspeed + "," + fih.midStomspeed
+ "," + fih.lowStomspeed + ")\n";
}
code1 = code11 + code12 + code13 + code14 + code15
+ code16;
}
code = code + code1;
}
String finalcode = "def " + defname + "():\n" + code;
String insert = "ear.addCommand(\"" + gestname
+ "\", \"python\", \"" + defname + "\")";
int olddefpos = pythonscript.indexOf(defnameold);
int pos1 = pythonscript.lastIndexOf("\n", olddefpos);
int pos2 = pythonscript.indexOf("\n", olddefpos);
pythonscript = pythonscript.substring(0, pos1) + "\n" + insert
+ pythonscript.substring(pos2, pythonscript.length());
int posscript = pythonscript.lastIndexOf(defnameold);
int posscriptnextdef = pythonscript.indexOf("def", posscript);
if (posscriptnextdef == -1) {
posscriptnextdef = pythonscript.length();
}
pythonscript = pythonscript.substring(0, posscript - 4)
+ "\n"
+ finalcode
+ pythonscript.substring(posscriptnextdef - 1,
pythonscript.length());
parsescript(control_list);
}
}
}
public void control_removegest(JList control_list) {
// Remove the selected gesture from the script (button bottom-left)
int posl = control_list.getSelectedIndex();
if (posl != -1) {
if (pythonitemholder.get(posl).function
&& !pythonitemholder.get(posl).notfunction) {
String codeold = pythonitemholder.get(posl).code;
String defnameold = codeold.substring(
codeold.indexOf("def ") + 4, codeold.indexOf("():"));
int olddefpos = pythonscript.indexOf(defnameold);
int pos1 = pythonscript.lastIndexOf("\n", olddefpos);
int pos2 = pythonscript.indexOf("\n", olddefpos);
pythonscript = pythonscript.substring(0, pos1)
+ pythonscript.substring(pos2, pythonscript.length());
int posscript = pythonscript.lastIndexOf(defnameold);
int posscriptnextdef = pythonscript.indexOf("def", posscript);
if (posscriptnextdef == -1) {
posscriptnextdef = pythonscript.length();
}
pythonscript = pythonscript.substring(0, posscript - 4)
+ pythonscript.substring(posscriptnextdef - 1,
pythonscript.length());
parsescript(control_list);
}
}
}
public void control_testgest() {
// test (execute) the created gesture (button bottom-left)
if (i01 != null) {
for (FrameItemHolder fih : frameitemholder) {
if (fih.sleep != -1) {
sleep(fih.sleep);
} else if (fih.speech != null) {
i01.mouth.speakBlocking(fih.speech);
} else if (fih.name != null) {
if (tabs_main_checkbox_states[0]) {
i01.moveHead(fih.neck, fih.rothead, fih.eyeX, fih.eyeY,
fih.jaw);
}
if (tabs_main_checkbox_states[1]) {
i01.moveArm("left", fih.lbicep, fih.lrotate,
fih.lshoulder, fih.lomoplate);
}
if (tabs_main_checkbox_states[2]) {
i01.moveArm("right", fih.rbicep, fih.rrotate,
fih.rshoulder, fih.romoplate);
}
if (tabs_main_checkbox_states[3]) {
i01.moveHand("left", fih.lthumb, fih.lindex,
fih.lmajeure, fih.lringfinger, fih.lpinky,
fih.lwrist);
}
if (tabs_main_checkbox_states[4]) {
i01.moveHand("right", fih.rthumb, fih.rindex,
fih.rmajeure, fih.rringfinger, fih.rpinky,
fih.rwrist);
}
if (tabs_main_checkbox_states[5]) {
i01.moveTorso(fih.topStom, fih.midStom, fih.lowStom);
}
} else {
if (tabs_main_checkbox_states[0]) {
i01.setHeadSpeed(fih.neckspeed, fih.rotheadspeed,
fih.eyeXspeed, fih.eyeYspeed, fih.jawspeed);
}
if (tabs_main_checkbox_states[1]) {
i01.setArmSpeed("left", fih.lbicepspeed,
fih.lrotatespeed, fih.lshoulderspeed,
fih.lomoplatespeed);
}
if (tabs_main_checkbox_states[2]) {
i01.setArmSpeed("right", fih.rbicepspeed,
fih.rrotatespeed, fih.rshoulderspeed,
fih.romoplatespeed);
}
if (tabs_main_checkbox_states[3]) {
i01.setHandSpeed("left", fih.lthumbspeed,
fih.lindexspeed, fih.lmajeurespeed,
fih.lringfingerspeed, fih.lpinkyspeed,
fih.lwristspeed);
}
if (tabs_main_checkbox_states[4]) {
i01.setHandSpeed("right", fih.rthumbspeed,
fih.rindexspeed, fih.rmajeurespeed,
fih.rringfingerspeed, fih.rpinkyspeed,
fih.rwristspeed);
}
if (tabs_main_checkbox_states[5]) {
i01.setTorsoSpeed(fih.topStomspeed, fih.midStomspeed,
fih.lowStomspeed);
}
}
}
}
}
public void controllistact(JList control_list) {
String[] listdata = new String[pythonitemholder.size()];
for (int i = 0; i < pythonitemholder.size(); i++) {
PythonItemHolder pih = pythonitemholder.get(i);
String pre;
if (!(pih.modifyable)) {
pre = "X ";
} else {
pre = " ";
}
int he = 21;
if (pih.code.length() < he) {
he = pih.code.length();
}
String des = pih.code.substring(0, he);
String displaytext = pre + des;
listdata[i] = displaytext;
}
control_list.setListData(listdata);
}
public void frame_add(JList framelist, JTextField frame_add_textfield) {
// Add a servo movement frame to the framelist (button bottom-right)
FrameItemHolder fih = new FrameItemHolder();
fih.rthumb = servoitemholder[0][0].sli.getValue();
fih.rindex = servoitemholder[0][1].sli.getValue();
fih.rmajeure = servoitemholder[0][2].sli.getValue();
fih.rringfinger = servoitemholder[0][3].sli.getValue();
fih.rpinky = servoitemholder[0][4].sli.getValue();
fih.rwrist = servoitemholder[0][5].sli.getValue();
fih.rbicep = servoitemholder[1][0].sli.getValue();
fih.rrotate = servoitemholder[1][1].sli.getValue();
fih.rshoulder = servoitemholder[1][2].sli.getValue();
fih.romoplate = servoitemholder[1][3].sli.getValue();
fih.lthumb = servoitemholder[2][0].sli.getValue();
fih.lindex = servoitemholder[2][1].sli.getValue();
fih.lmajeure = servoitemholder[2][2].sli.getValue();
fih.lringfinger = servoitemholder[2][3].sli.getValue();
fih.lpinky = servoitemholder[2][4].sli.getValue();
fih.lwrist = servoitemholder[2][5].sli.getValue();
fih.lbicep = servoitemholder[3][0].sli.getValue();
fih.lrotate = servoitemholder[3][1].sli.getValue();
fih.lshoulder = servoitemholder[3][2].sli.getValue();
fih.lomoplate = servoitemholder[3][3].sli.getValue();
fih.neck = servoitemholder[4][0].sli.getValue();
fih.rothead = servoitemholder[4][1].sli.getValue();
fih.eyeX = servoitemholder[4][2].sli.getValue();
fih.eyeY = servoitemholder[4][3].sli.getValue();
fih.jaw = servoitemholder[4][4].sli.getValue();
fih.topStom = servoitemholder[5][0].sli.getValue();
fih.midStom = servoitemholder[5][1].sli.getValue();
fih.lowStom = servoitemholder[5][2].sli.getValue();
fih.sleep = -1;
fih.speech = null;
fih.name = frame_add_textfield.getText();
frameitemholder.add(fih);
framelistact(framelist);
}
public void frame_addspeed(JList framelist) {
// Add a speed setting frame to the framelist (button bottom-right)
FrameItemHolder fih = new FrameItemHolder();
fih.rthumbspeed = Float.parseFloat(servoitemholder[0][0].spe.getText());
fih.rindexspeed = Float.parseFloat(servoitemholder[0][1].spe.getText());
fih.rmajeurespeed = Float.parseFloat(servoitemholder[0][2].spe
.getText());
fih.rringfingerspeed = Float.parseFloat(servoitemholder[0][3].spe
.getText());
fih.rpinkyspeed = Float.parseFloat(servoitemholder[0][4].spe.getText());
fih.rwristspeed = Float.parseFloat(servoitemholder[0][5].spe.getText());
fih.rbicepspeed = Float.parseFloat(servoitemholder[1][0].spe.getText());
fih.rrotatespeed = Float
.parseFloat(servoitemholder[1][1].spe.getText());
fih.rshoulderspeed = Float.parseFloat(servoitemholder[1][2].spe
.getText());
fih.romoplatespeed = Float.parseFloat(servoitemholder[1][3].spe
.getText());
fih.lthumbspeed = Float.parseFloat(servoitemholder[2][0].spe.getText());
fih.lindexspeed = Float.parseFloat(servoitemholder[2][1].spe.getText());
fih.lmajeurespeed = Float.parseFloat(servoitemholder[2][2].spe
.getText());
fih.lringfingerspeed = Float.parseFloat(servoitemholder[2][3].spe
.getText());
fih.lpinkyspeed = Float.parseFloat(servoitemholder[2][4].spe.getText());
fih.lwristspeed = Float.parseFloat(servoitemholder[2][5].spe.getText());
fih.lbicepspeed = Float.parseFloat(servoitemholder[3][0].spe.getText());
fih.lrotatespeed = Float
.parseFloat(servoitemholder[3][1].spe.getText());
fih.lshoulderspeed = Float.parseFloat(servoitemholder[3][2].spe
.getText());
fih.lomoplatespeed = Float.parseFloat(servoitemholder[3][3].spe
.getText());
fih.neckspeed = Float.parseFloat(servoitemholder[4][0].spe.getText());
fih.rotheadspeed = Float
.parseFloat(servoitemholder[4][1].spe.getText());
fih.eyeXspeed = Float.parseFloat(servoitemholder[4][2].spe.getText());
fih.eyeYspeed = Float.parseFloat(servoitemholder[4][3].spe.getText());
fih.jawspeed = Float.parseFloat(servoitemholder[4][4].spe.getText());
fih.topStomspeed = Float
.parseFloat(servoitemholder[5][0].spe.getText());
fih.midStomspeed = Float
.parseFloat(servoitemholder[5][1].spe.getText());
fih.lowStomspeed = Float
.parseFloat(servoitemholder[5][2].spe.getText());
fih.sleep = -1;
fih.speech = null;
fih.name = null;
frameitemholder.add(fih);
framelistact(framelist);
}
public void frame_addsleep(JList framelist,
JTextField frame_addsleep_textfield) {
// Add a sleep frame to the framelist (button bottom-right)
FrameItemHolder fih = new FrameItemHolder();
fih.sleep = Integer.parseInt(frame_addsleep_textfield.getText());
fih.speech = null;
fih.name = null;
frameitemholder.add(fih);
framelistact(framelist);
}
public void frame_addspeech(JList framelist,
JTextField frame_addspeech_textfield) {
// Add a speech frame to the framelist (button bottom-right)
FrameItemHolder fih = new FrameItemHolder();
fih.sleep = -1;
fih.speech = frame_addspeech_textfield.getText();
fih.name = null;
frameitemholder.add(fih);
framelistact(framelist);
}
public void frame_importminresmax() {
// Import the Min- / Res- / Max- settings of your InMoov
if (i01 != null) {
for (int i1 = 0; i1 < servoitemholder.length; i1++) {
for (int i2 = 0; i2 < servoitemholder[i1].length; i2++) {
InMoovHand inmhand = null;
InMoovArm inmarm = null;
InMoovHead inmhead = null;
InMoovTorso inmtorso = null;
if (i1 == 0) {
inmhand = i01.rightHand;
} else if (i1 == 1) {
inmarm = i01.rightArm;
} else if (i1 == 2) {
inmhand = i01.leftHand;
} else if (i1 == 3) {
inmarm = i01.rightArm;
} else if (i1 == 4) {
inmhead = i01.head;
} else if (i1 == 5) {
inmtorso = i01.torso;
}
Servo servo = null;
if (i1 == 0 || i1 == 2) {
if (i2 == 0) {
servo = inmhand.thumb;
} else if (i2 == 1) {
servo = inmhand.index;
} else if (i2 == 2) {
servo = inmhand.majeure;
} else if (i2 == 3) {
servo = inmhand.ringFinger;
} else if (i2 == 4) {
servo = inmhand.pinky;
} else if (i2 == 5) {
servo = inmhand.wrist;
}
} else if (i1 == 1 || i1 == 3) {
if (i2 == 0) {
servo = inmarm.bicep;
} else if (i2 == 1) {
servo = inmarm.rotate;
} else if (i2 == 2) {
servo = inmarm.shoulder;
} else if (i2 == 3) {
servo = inmarm.omoplate;
}
} else if (i1 == 4) {
if (i2 == 0) {
servo = inmhead.neck;
} else if (i2 == 1) {
servo = inmhead.rothead;
} else if (i2 == 2) {
servo = inmhead.eyeX;
} else if (i2 == 3) {
servo = inmhead.eyeY;
} else if (i2 == 4) {
servo = inmhead.jaw;
}
} else if (i1 == 5) {
if (i2 == 0) {
servo = inmtorso.topStom;
} else if (i2 == 1) {
servo = inmtorso.midStom;
} else if (i2 == 2) {
servo = inmtorso.lowStom;
}
}
int min = servo.getMin();
int res = servo.getRest();
int max = servo.getMax();
servoitemholder[i1][i2].min.setText(min + "");
servoitemholder[i1][i2].res.setText(res + "");
servoitemholder[i1][i2].max.setText(max + "");
// servoitemholder[i1][i2].sli.setMinimum(min);
// servoitemholder[i1][i2].sli.setMaximum(max);
servoitemholder[i1][i2].sli.setValue(res);
}
}
}
}
public void frame_remove(JList framelist) {
// Remove this frame from the framelist (button bottom-right)
int pos = framelist.getSelectedIndex();
if (pos != -1) {
frameitemholder.remove(pos);
framelistact(framelist);
}
}
public void frame_load(JList framelist, JTextField frame_add_textfield,
JTextField frame_addsleep_textfield,
JTextField frame_addspeech_textfield) {
// Load this frame from the framelist (button bottom-right)
int pos = framelist.getSelectedIndex();
if (pos != -1) {
// sleep || speech || servo movement || speed setting
if (frameitemholder.get(pos).sleep != -1) {
frame_addsleep_textfield.setText(frameitemholder.get(pos).sleep
+ "");
} else if (frameitemholder.get(pos).speech != null) {
frame_addspeech_textfield
.setText(frameitemholder.get(pos).speech);
} else if (frameitemholder.get(pos).name != null) {
servoitemholder[0][0].sli
.setValue(frameitemholder.get(pos).rthumb);
servoitemholder[0][1].sli
.setValue(frameitemholder.get(pos).rindex);
servoitemholder[0][2].sli
.setValue(frameitemholder.get(pos).rmajeure);
servoitemholder[0][3].sli
.setValue(frameitemholder.get(pos).rringfinger);
servoitemholder[0][4].sli
.setValue(frameitemholder.get(pos).rpinky);
servoitemholder[0][5].sli
.setValue(frameitemholder.get(pos).rwrist);
servoitemholder[1][0].sli
.setValue(frameitemholder.get(pos).rbicep);
servoitemholder[1][1].sli
.setValue(frameitemholder.get(pos).rrotate);
servoitemholder[1][2].sli
.setValue(frameitemholder.get(pos).rshoulder);
servoitemholder[1][3].sli
.setValue(frameitemholder.get(pos).romoplate);
servoitemholder[2][0].sli
.setValue(frameitemholder.get(pos).lthumb);
servoitemholder[2][1].sli
.setValue(frameitemholder.get(pos).lindex);
servoitemholder[2][2].sli
.setValue(frameitemholder.get(pos).lmajeure);
servoitemholder[2][3].sli
.setValue(frameitemholder.get(pos).lringfinger);
servoitemholder[2][4].sli
.setValue(frameitemholder.get(pos).lpinky);
servoitemholder[2][5].sli
.setValue(frameitemholder.get(pos).lwrist);
servoitemholder[3][0].sli
.setValue(frameitemholder.get(pos).lbicep);
servoitemholder[3][1].sli
.setValue(frameitemholder.get(pos).lrotate);
servoitemholder[3][2].sli
.setValue(frameitemholder.get(pos).lshoulder);
servoitemholder[3][3].sli
.setValue(frameitemholder.get(pos).lomoplate);
servoitemholder[4][0].sli
.setValue(frameitemholder.get(pos).neck);
servoitemholder[4][1].sli
.setValue(frameitemholder.get(pos).rothead);
servoitemholder[4][2].sli
.setValue(frameitemholder.get(pos).eyeX);
servoitemholder[4][3].sli
.setValue(frameitemholder.get(pos).eyeY);
servoitemholder[4][4].sli
.setValue(frameitemholder.get(pos).jaw);
servoitemholder[5][0].sli
.setValue(frameitemholder.get(pos).topStom);
servoitemholder[5][1].sli
.setValue(frameitemholder.get(pos).midStom);
servoitemholder[5][2].sli
.setValue(frameitemholder.get(pos).lowStom);
frame_add_textfield.setText(frameitemholder.get(pos).name);
} else {
servoitemholder[0][0].spe
.setText(frameitemholder.get(pos).rthumbspeed + "");
servoitemholder[0][1].spe
.setText(frameitemholder.get(pos).rindexspeed + "");
servoitemholder[0][2].spe
.setText(frameitemholder.get(pos).rmajeurespeed + "");
servoitemholder[0][3].spe
.setText(frameitemholder.get(pos).rringfingerspeed + "");
servoitemholder[0][4].spe
.setText(frameitemholder.get(pos).rpinkyspeed + "");
servoitemholder[0][5].spe
.setText(frameitemholder.get(pos).rwristspeed + "");
servoitemholder[1][0].spe
.setText(frameitemholder.get(pos).rbicepspeed + "");
servoitemholder[1][1].spe
.setText(frameitemholder.get(pos).rrotatespeed + "");
servoitemholder[1][2].spe
.setText(frameitemholder.get(pos).rshoulderspeed + "");
servoitemholder[1][3].spe
.setText(frameitemholder.get(pos).romoplatespeed + "");
servoitemholder[2][0].spe
.setText(frameitemholder.get(pos).lthumbspeed + "");
servoitemholder[2][1].spe
.setText(frameitemholder.get(pos).lindexspeed + "");
servoitemholder[2][2].spe
.setText(frameitemholder.get(pos).lmajeurespeed + "");
servoitemholder[2][3].spe
.setText(frameitemholder.get(pos).lringfingerspeed + "");
servoitemholder[2][4].spe
.setText(frameitemholder.get(pos).lpinkyspeed + "");
servoitemholder[2][5].spe
.setText(frameitemholder.get(pos).lwristspeed + "");
servoitemholder[3][0].spe
.setText(frameitemholder.get(pos).lbicepspeed + "");
servoitemholder[3][1].spe
.setText(frameitemholder.get(pos).lrotatespeed + "");
servoitemholder[3][2].spe
.setText(frameitemholder.get(pos).lshoulderspeed + "");
servoitemholder[3][3].spe
.setText(frameitemholder.get(pos).lomoplatespeed + "");
servoitemholder[4][0].spe
.setText(frameitemholder.get(pos).neckspeed + "");
servoitemholder[4][1].spe
.setText(frameitemholder.get(pos).rotheadspeed + "");
servoitemholder[4][2].spe
.setText(frameitemholder.get(pos).eyeXspeed + "");
servoitemholder[4][3].spe
.setText(frameitemholder.get(pos).eyeYspeed + "");
servoitemholder[4][4].spe
.setText(frameitemholder.get(pos).jawspeed + "");
servoitemholder[5][0].spe
.setText(frameitemholder.get(pos).topStomspeed + "");
servoitemholder[5][1].spe
.setText(frameitemholder.get(pos).midStomspeed + "");
servoitemholder[5][2].spe
.setText(frameitemholder.get(pos).lowStomspeed + "");
}
}
}
public void frame_update(JList framelist, JTextField frame_add_textfield,
JTextField frame_addsleep_textfield,
JTextField frame_addspeech_textfield) {
// Update this frame on the framelist (button bottom-right)
int pos = framelist.getSelectedIndex();
if (pos != -1) {
FrameItemHolder fih = new FrameItemHolder();
// sleep || speech || servo movement || speed setting
if (frameitemholder.get(pos).sleep != -1) {
fih.sleep = Integer
.parseInt(frame_addsleep_textfield.getText());
fih.speech = null;
fih.name = null;
} else if (frameitemholder.get(pos).speech != null) {
fih.sleep = -1;
fih.speech = frame_addspeech_textfield.getText();
fih.name = null;
} else if (frameitemholder.get(pos).name != null) {
fih.rthumb = servoitemholder[0][0].sli.getValue();
fih.rindex = servoitemholder[0][1].sli.getValue();
fih.rmajeure = servoitemholder[0][2].sli.getValue();
fih.rringfinger = servoitemholder[0][3].sli.getValue();
fih.rpinky = servoitemholder[0][4].sli.getValue();
fih.rwrist = servoitemholder[0][5].sli.getValue();
fih.rbicep = servoitemholder[1][0].sli.getValue();
fih.rrotate = servoitemholder[1][1].sli.getValue();
fih.rshoulder = servoitemholder[1][2].sli.getValue();
fih.romoplate = servoitemholder[1][3].sli.getValue();
fih.lthumb = servoitemholder[2][0].sli.getValue();
fih.lindex = servoitemholder[2][1].sli.getValue();
fih.lmajeure = servoitemholder[2][2].sli.getValue();
fih.lringfinger = servoitemholder[2][3].sli.getValue();
fih.lpinky = servoitemholder[2][4].sli.getValue();
fih.lwrist = servoitemholder[2][5].sli.getValue();
fih.lbicep = servoitemholder[3][0].sli.getValue();
fih.lrotate = servoitemholder[3][1].sli.getValue();
fih.lshoulder = servoitemholder[3][2].sli.getValue();
fih.lomoplate = servoitemholder[3][3].sli.getValue();
fih.neck = servoitemholder[4][0].sli.getValue();
fih.rothead = servoitemholder[4][1].sli.getValue();
fih.eyeX = servoitemholder[4][2].sli.getValue();
fih.eyeY = servoitemholder[4][3].sli.getValue();
fih.jaw = servoitemholder[4][4].sli.getValue();
fih.topStom = servoitemholder[5][0].sli.getValue();
fih.midStom = servoitemholder[5][1].sli.getValue();
fih.lowStom = servoitemholder[5][2].sli.getValue();
fih.sleep = -1;
fih.speech = null;
fih.name = frame_add_textfield.getText();
} else {
fih.rthumbspeed = Float.parseFloat(servoitemholder[0][0].spe
.getText());
fih.rindexspeed = Float.parseFloat(servoitemholder[0][1].spe
.getText());
fih.rmajeurespeed = Float.parseFloat(servoitemholder[0][2].spe
.getText());
fih.rringfingerspeed = Float
.parseFloat(servoitemholder[0][3].spe.getText());
fih.rpinkyspeed = Float.parseFloat(servoitemholder[0][4].spe
.getText());
fih.rwristspeed = Float.parseFloat(servoitemholder[0][5].spe
.getText());
fih.rbicepspeed = Float.parseFloat(servoitemholder[1][0].spe
.getText());
fih.rrotatespeed = Float.parseFloat(servoitemholder[1][1].spe
.getText());
fih.rshoulderspeed = Float.parseFloat(servoitemholder[1][2].spe
.getText());
fih.romoplatespeed = Float.parseFloat(servoitemholder[1][3].spe
.getText());
fih.lthumbspeed = Float.parseFloat(servoitemholder[2][0].spe
.getText());
fih.lindexspeed = Float.parseFloat(servoitemholder[2][1].spe
.getText());
fih.lmajeurespeed = Float.parseFloat(servoitemholder[2][2].spe
.getText());
fih.lringfingerspeed = Float
.parseFloat(servoitemholder[2][3].spe.getText());
fih.lpinkyspeed = Float.parseFloat(servoitemholder[2][4].spe
.getText());
fih.lwristspeed = Float.parseFloat(servoitemholder[2][5].spe
.getText());
fih.lbicepspeed = Float.parseFloat(servoitemholder[3][0].spe
.getText());
fih.lrotatespeed = Float.parseFloat(servoitemholder[3][1].spe
.getText());
fih.lshoulderspeed = Float.parseFloat(servoitemholder[3][2].spe
.getText());
fih.lomoplatespeed = Float.parseFloat(servoitemholder[3][3].spe
.getText());
fih.neckspeed = Float.parseFloat(servoitemholder[4][0].spe
.getText());
fih.rotheadspeed = Float.parseFloat(servoitemholder[4][1].spe
.getText());
fih.eyeXspeed = Float.parseFloat(servoitemholder[4][2].spe
.getText());
fih.eyeYspeed = Float.parseFloat(servoitemholder[4][3].spe
.getText());
fih.jawspeed = Float.parseFloat(servoitemholder[4][4].spe
.getText());
fih.topStomspeed = Float.parseFloat(servoitemholder[5][0].spe
.getText());
fih.midStomspeed = Float.parseFloat(servoitemholder[5][1].spe
.getText());
fih.lowStomspeed = Float.parseFloat(servoitemholder[5][2].spe
.getText());
fih.sleep = -1;
fih.speech = null;
fih.name = null;
}
frameitemholder.set(pos, fih);
framelistact(framelist);
}
}
public void frame_copy(JList framelist) {
// Copy this frame on the framelist (button bottom-right)
int pos = framelist.getSelectedIndex();
if (pos != -1) {
FrameItemHolder fih = frameitemholder.get(pos);
frameitemholder.add(fih);
framelistact(framelist);
}
}
public void frame_up(JList framelist) {
// Move this frame one up on the framelist (button bottom-right)
int pos = framelist.getSelectedIndex();
if (pos != -1) {
FrameItemHolder fih = frameitemholder.remove(pos);
frameitemholder.add(pos - 1, fih);
framelistact(framelist);
}
}
public void frame_down(JList framelist) {
// Move this frame one down on the framelist (button bottom-right)
int pos = framelist.getSelectedIndex();
if (pos != -1) {
FrameItemHolder fih = frameitemholder.remove(pos);
frameitemholder.add(pos + 1, fih);
framelistact(framelist);
}
}
public void frame_test(JList framelist) {
// Test this frame (execute)
int pos = framelist.getSelectedIndex();
if (i01 != null && pos != -1) {
FrameItemHolder fih = frameitemholder.get(pos);
// sleep || speech || servo movement || speed setting
if (fih.sleep != -1) {
sleep(fih.sleep);
} else if (fih.speech != null) {
i01.mouth.speakBlocking(fih.speech);
} else if (fih.name != null) {
if (tabs_main_checkbox_states[0]) {
i01.moveHead(fih.neck, fih.rothead, fih.eyeX, fih.eyeY,
fih.jaw);
}
if (tabs_main_checkbox_states[1]) {
i01.moveArm("left", fih.lbicep, fih.lrotate, fih.lshoulder,
fih.lomoplate);
}
if (tabs_main_checkbox_states[2]) {
i01.moveArm("right", fih.rbicep, fih.rrotate,
fih.rshoulder, fih.romoplate);
}
if (tabs_main_checkbox_states[3]) {
i01.moveHand("left", fih.lthumb, fih.lindex, fih.lmajeure,
fih.lringfinger, fih.lpinky, fih.lwrist);
}
if (tabs_main_checkbox_states[4]) {
i01.moveHand("right", fih.rthumb, fih.rindex, fih.rmajeure,
fih.rringfinger, fih.rpinky, fih.rwrist);
}
if (tabs_main_checkbox_states[5]) {
i01.moveTorso(fih.topStom, fih.midStom, fih.lowStom);
}
} else {
if (tabs_main_checkbox_states[0]) {
i01.setHeadSpeed(fih.neckspeed, fih.rotheadspeed,
fih.eyeXspeed, fih.eyeYspeed, fih.jawspeed);
}
if (tabs_main_checkbox_states[1]) {
i01.setArmSpeed("left", fih.lbicepspeed, fih.lrotatespeed,
fih.lshoulderspeed, fih.lomoplatespeed);
}
if (tabs_main_checkbox_states[2]) {
i01.setArmSpeed("right", fih.rbicepspeed, fih.rrotatespeed,
fih.rshoulderspeed, fih.romoplatespeed);
}
if (tabs_main_checkbox_states[3]) {
i01.setHandSpeed("left", fih.lthumbspeed, fih.lindexspeed,
fih.lmajeurespeed, fih.lringfingerspeed,
fih.lpinkyspeed, fih.lwristspeed);
}
if (tabs_main_checkbox_states[4]) {
i01.setHandSpeed("right", fih.rthumbspeed, fih.rindexspeed,
fih.rmajeurespeed, fih.rringfingerspeed,
fih.rpinkyspeed, fih.rwristspeed);
}
if (tabs_main_checkbox_states[5]) {
i01.setTorsoSpeed(fih.topStomspeed, fih.midStomspeed,
fih.lowStomspeed);
}
}
}
}
public void framelistact(JList framelist) {
// Re-Build the framelist
String[] listdata = new String[frameitemholder.size()];
for (int i = 0; i < frameitemholder.size(); i++) {
FrameItemHolder fih = frameitemholder.get(i);
String displaytext = "";
// servo movement || sleep || speech || speed setting
if (fih.sleep != -1) {
displaytext = "SLEEP " + fih.sleep;
} else if (fih.speech != null) {
displaytext = "SPEECH " + fih.speech;
} else if (fih.name != null) {
String displaytext1 = "";
String displaytext2 = "";
String displaytext3 = "";
String displaytext4 = "";
String displaytext5 = "";
String displaytext6 = "";
if (tabs_main_checkbox_states[0]) {
displaytext1 = fih.rthumb + " " + fih.rindex + " "
+ fih.rmajeure + " " + fih.rringfinger + " "
+ fih.rpinky + " " + fih.rwrist;
}
if (tabs_main_checkbox_states[1]) {
displaytext2 = fih.rbicep + " " + fih.rrotate + " "
+ fih.rshoulder + " " + fih.romoplate;
}
if (tabs_main_checkbox_states[2]) {
displaytext3 = fih.lthumb + " " + fih.lindex + " "
+ fih.lmajeure + " " + fih.lringfinger + " "
+ fih.lpinky + " " + fih.lwrist;
}
if (tabs_main_checkbox_states[3]) {
displaytext4 = fih.lbicep + " " + fih.lrotate + " "
+ fih.lshoulder + " " + fih.lomoplate;
}
if (tabs_main_checkbox_states[4]) {
displaytext5 = fih.neck + " " + fih.rothead + " "
+ fih.eyeX + " " + fih.eyeY + " " + fih.jaw;
}
if (tabs_main_checkbox_states[5]) {
displaytext6 = fih.topStom + " " + fih.midStom + " "
+ fih.lowStom;
}
displaytext = fih.name + ": " + displaytext1 + " | "
+ displaytext2 + " | " + displaytext3 + " | "
+ displaytext4 + " | " + displaytext5 + " | "
+ displaytext6;
} else {
String displaytext1 = "";
String displaytext2 = "";
String displaytext3 = "";
String displaytext4 = "";
String displaytext5 = "";
String displaytext6 = "";
if (tabs_main_checkbox_states[0]) {
displaytext1 = fih.rthumbspeed + " " + fih.rindexspeed
+ " " + fih.rmajeurespeed + " "
+ fih.rringfingerspeed + " " + fih.rpinkyspeed
+ " " + fih.rwristspeed;
}
if (tabs_main_checkbox_states[1]) {
displaytext2 = fih.rbicepspeed + " " + fih.rrotatespeed
+ " " + fih.rshoulderspeed + " "
+ fih.romoplatespeed;
}
if (tabs_main_checkbox_states[2]) {
displaytext3 = fih.lthumbspeed + " " + fih.lindexspeed
+ " " + fih.lmajeurespeed + " "
+ fih.lringfingerspeed + " " + fih.lpinkyspeed
+ " " + fih.lwristspeed;
}
if (tabs_main_checkbox_states[3]) {
displaytext4 = fih.lbicepspeed + " " + fih.lrotatespeed
+ " " + fih.lshoulderspeed + " "
+ fih.lomoplatespeed;
}
if (tabs_main_checkbox_states[4]) {
displaytext5 = fih.neckspeed + " " + fih.rotheadspeed + " "
+ fih.eyeXspeed + " " + fih.eyeYspeed + " "
+ fih.jawspeed;
}
if (tabs_main_checkbox_states[5]) {
displaytext6 = fih.topStomspeed + " " + fih.midStomspeed
+ " " + fih.lowStomspeed;
}
displaytext = "SPEED " + displaytext1 + " | " + displaytext2
+ " | " + displaytext3 + " | " + displaytext4 + " | "
+ displaytext5 + " | " + displaytext6;
}
listdata[i] = displaytext;
}
framelist.setListData(listdata);
}
public void frame_moverealtime(JCheckBox frame_moverealtime) {
moverealtime = frame_moverealtime.isSelected();
}
public void servoitemholder_slider_changed(int t1, int t2) {
// One slider were adjusted
servoitemholder[t1][t2].akt.setText(servoitemholder[t1][t2].sli
.getValue() + "");
// Move the Servos in "Real-Time"
if (moverealtime && i01 != null) {
FrameItemHolder fih = new FrameItemHolder();
fih.rthumb = servoitemholder[0][0].sli.getValue();
fih.rindex = servoitemholder[0][1].sli.getValue();
fih.rmajeure = servoitemholder[0][2].sli.getValue();
fih.rringfinger = servoitemholder[0][3].sli.getValue();
fih.rpinky = servoitemholder[0][4].sli.getValue();
fih.rwrist = servoitemholder[0][5].sli.getValue();
fih.rbicep = servoitemholder[1][0].sli.getValue();
fih.rrotate = servoitemholder[1][1].sli.getValue();
fih.rshoulder = servoitemholder[1][2].sli.getValue();
fih.romoplate = servoitemholder[1][3].sli.getValue();
fih.lthumb = servoitemholder[2][0].sli.getValue();
fih.lindex = servoitemholder[2][1].sli.getValue();
fih.lmajeure = servoitemholder[2][2].sli.getValue();
fih.lringfinger = servoitemholder[2][3].sli.getValue();
fih.lpinky = servoitemholder[2][4].sli.getValue();
fih.lwrist = servoitemholder[2][5].sli.getValue();
fih.lbicep = servoitemholder[3][0].sli.getValue();
fih.lrotate = servoitemholder[3][1].sli.getValue();
fih.lshoulder = servoitemholder[3][2].sli.getValue();
fih.lomoplate = servoitemholder[3][3].sli.getValue();
fih.neck = servoitemholder[4][0].sli.getValue();
fih.rothead = servoitemholder[4][1].sli.getValue();
fih.eyeX = servoitemholder[4][2].sli.getValue();
fih.eyeY = servoitemholder[4][3].sli.getValue();
fih.jaw = servoitemholder[4][4].sli.getValue();
fih.topStom = servoitemholder[5][0].sli.getValue();
fih.midStom = servoitemholder[5][1].sli.getValue();
fih.lowStom = servoitemholder[5][2].sli.getValue();
if (tabs_main_checkbox_states[0]) {
i01.moveHead(fih.neck, fih.rothead, fih.eyeX, fih.eyeY, fih.jaw);
}
if (tabs_main_checkbox_states[1]) {
i01.moveArm("left", fih.lbicep, fih.lrotate, fih.lshoulder,
fih.lomoplate);
}
if (tabs_main_checkbox_states[2]) {
i01.moveArm("right", fih.rbicep, fih.rrotate, fih.rshoulder,
fih.romoplate);
}
if (tabs_main_checkbox_states[3]) {
i01.moveHand("left", fih.lthumb, fih.lindex, fih.lmajeure,
fih.lringfinger, fih.lpinky, fih.lwrist);
}
if (tabs_main_checkbox_states[4]) {
i01.moveHand("right", fih.rthumb, fih.rindex, fih.rmajeure,
fih.rringfinger, fih.rpinky, fih.rwrist);
}
if (tabs_main_checkbox_states[5]) {
i01.moveTorso(fih.topStom, fih.midStom, fih.lowStom);
}
}
}
public void servoitemholder_set_sih1(int i1, ServoItemHolder[] sih1) {
// Setting references
servoitemholder[i1] = sih1;
}
public void parsescript(JList control_list) {
pythonitemholder.clear();
if (true) {
String pscript = pythonscript;
String[] pscriptsplit = pscript.split("\n");
// get the name of the InMoov-reference
for (String line : pscriptsplit) {
if (line.contains(" = Runtime.createAndStart(")
|| line.contains("Runtime.start(")) {
if (line.contains(", \"InMoov\")")) {
pythonname = line.substring(0, line.indexOf(" = "));
referencename = line.substring(line.indexOf("(\"") + 2,
line.indexOf("\", \"InMoov\")"));
}
}
}
PythonItemHolder pih = null;
boolean keepgoing = true;
int pos = 0;
while (keepgoing) {
if (pih == null) {
pih = new PythonItemHolder();
}
if (pos >= pscriptsplit.length) {
keepgoing = false;
break;
}
String line = pscriptsplit[pos];
String linewithoutspace = line.replace(" ", "");
if (linewithoutspace.equals("")) {
pos++;
continue;
}
if (linewithoutspace.startsWith("
pih.code = pih.code + "\n" + line;
pos++;
continue;
}
line = line.replace(" ", " "); // 2 -> 4
line = line.replace(" ", " "); // 3 -> 4
line = line.replace(" ", " "); // 5 -> 4
line = line.replace(" ", " "); // 6 -> 4
if (!(pih.function) && !(pih.notfunction)) {
if (line.startsWith("def")) {
pih.function = true;
pih.notfunction = false;
pih.modifyable = false;
pih.code = line;
pos++;
} else {
pih.notfunction = true;
pih.function = false;
pih.modifyable = false;
pih.code = line;
pos++;
}
} else if (pih.function && !(pih.notfunction)) {
if (line.startsWith(" ")) {
pih.code = pih.code + "\n" + line;
pos++;
} else {
pythonitemholder.add(pih);
pih = null;
}
} else if (!(pih.function) && pih.notfunction) {
if (!(line.startsWith("def"))) {
pih.code = pih.code + "\n" + line;
pos++;
} else {
pythonitemholder.add(pih);
pih = null;
}
} else {
// it should never end here ...
// .function & .notfunction true ...
// would be wrong ...
}
}
pythonitemholder.add(pih);
}
if (true) {
ArrayList<PythonItemHolder> pythonitemholder1 = pythonitemholder;
pythonitemholder = new ArrayList<PythonItemHolder>();
for (PythonItemHolder pih : pythonitemholder1) {
if (pih.function && !(pih.notfunction)) {
String code = pih.code;
String[] codesplit = code.split("\n");
String code2 = "";
for (String line : codesplit) {
line = line.replace(" ", "");
if (line.startsWith("def")) {
line = "";
} else if (line.startsWith("sleep")) {
line = "";
} else if (line.startsWith(pythonname)) {
if (line.startsWith(pythonname + ".move")) {
if (line.startsWith(pythonname + ".moveHead")) {
line = "";
} else if (line.startsWith(pythonname
+ ".moveHand")) {
line = "";
} else if (line.startsWith(pythonname
+ ".moveArm")) {
line = "";
} else if (line.startsWith(pythonname
+ ".moveTorso")) {
line = "";
}
} else if (line.startsWith(pythonname + ".set")) {
if (line.startsWith(pythonname
+ ".setHeadSpeed")) {
line = "";
} else if (line.startsWith(pythonname
+ ".setHandSpeed")) {
line = "";
} else if (line.startsWith(pythonname
+ ".setArmSpeed")) {
line = "";
} else if (line.startsWith(pythonname
+ ".setTorsoSpeed")) {
line = "";
}
} else if (line.startsWith(pythonname
+ ".mouth.speak")) {
line = "";
}
}
code2 = code2 + line;
}
if (code2.length() > 0) {
pih.modifyable = false;
} else {
pih.modifyable = true;
}
} else if (!(pih.function) && pih.notfunction) {
pih.modifyable = false;
} else {
// shouldn't get here
// both true or both false
// wrong
}
pythonitemholder.add(pih);
}
}
controllistact(control_list);
}
public static class ServoItemHolder {
public JLabel fin;
public JLabel min;
public JLabel res;
public JLabel max;
public JSlider sli;
public JLabel akt;
public JTextField spe;
}
public static class FrameItemHolder {
int rthumb, rindex, rmajeure, rringfinger, rpinky, rwrist;
int rbicep, rrotate, rshoulder, romoplate;
int lthumb, lindex, lmajeure, lringfinger, lpinky, lwrist;
int lbicep, lrotate, lshoulder, lomoplate;
int neck, rothead, eyeX, eyeY, jaw;
int topStom, midStom, lowStom;
float rthumbspeed, rindexspeed, rmajeurespeed, rringfingerspeed,
rpinkyspeed, rwristspeed;
float rbicepspeed, rrotatespeed, rshoulderspeed, romoplatespeed;
float lthumbspeed, lindexspeed, lmajeurespeed, lringfingerspeed,
lpinkyspeed, lwristspeed;
float lbicepspeed, lrotatespeed, lshoulderspeed, lomoplatespeed;
float neckspeed, rotheadspeed, eyeXspeed, eyeYspeed, jawspeed;
float topStomspeed, midStomspeed, lowStomspeed;
int sleep;
String speech;
String name;
}
public static class PythonItemHolder {
String code;
boolean modifyable;
boolean function;
boolean notfunction;
}
public static void main(String[] args) throws InterruptedException {
LoggingFactory.getInstance().configure();
LoggingFactory.getInstance().setLevel(Level.INFO);
try {
Runtime.start("gui", "GUIService");
Runtime.start("inmoovgesturecreator", "InMoovGestureCreator");
} catch (Exception e) {
Logging.logException(e);
}
}
}
|
package org.ojalgo.finance.portfolio;
import static org.ojalgo.constant.BigMath.*;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.ojalgo.ProgrammingError;
import org.ojalgo.access.Access1D;
import org.ojalgo.constant.PrimitiveMath;
import org.ojalgo.matrix.BasicMatrix;
import org.ojalgo.optimisation.Expression;
import org.ojalgo.optimisation.ExpressionsBasedModel;
import org.ojalgo.optimisation.Optimisation;
import org.ojalgo.optimisation.Optimisation.State;
import org.ojalgo.optimisation.Variable;
import org.ojalgo.scalar.Scalar;
import org.ojalgo.type.context.NumberContext;
/**
* <p>
* The Markowitz model, in this class, is defined as:
* </p>
* <p>
* min (RAF/2) [w]<sup>T</sup>[C][w] - [w]<sup>T</sup>[r] <br>
* subject to |[w]| = 1
* </p>
* <p>
* RAF stands for Risk Aversion Factor. Instead of specifying a desired risk or return level you specify a
* level of risk aversion that is used to balance the risk and return.
* </p>
* <p>
* The expected returns for each of the assets must be excess returns. Otherwise this formulation is wrong.
* </p>
* <p>
* The total weights of all assets will always be 100%, but shorting can be allowed or not according to your
* preference. ( {@linkplain #setShortingAllowed(boolean)} ) In addition you may set lower and upper limits on
* any individual asset. ( {@linkplain #setLowerLimit(int, BigDecimal)} and
* {@linkplain #setUpperLimit(int, BigDecimal)} )
* </p>
* <p>
* Risk-free asset: That means there is no excess return and zero variance. Don't (try to) include a risk-free
* asset here.
* </p>
* <p>
* Do not worry about the minus sign in front of the return part of the objective function - it is
* handled/negated for you. When you're asked to supply the expected excess returns you should supply
* precisely that.
* </p>
* <p>
* Basic usage instructions
* </p>
* After you've instantiated the MarkowitzModel you need to do one of three different things:
* <ol>
* <li>{@link #setRiskAversion(Number)} unless this was already set in the {@link MarketEquilibrium} or
* {@link FinancePortfolio.Context} used to instantiate the MarkowitzModel</li>
* <li>{@link #setTargetReturn(BigDecimal)}</li>
* <li>{@link #setTargetVariance(BigDecimal)}</li>
* </ol>
* <p>
* Optionally you may {@linkplain #setLowerLimit(int, BigDecimal)},
* {@linkplain #setUpperLimit(int, BigDecimal)} or {@linkplain #setShortingAllowed(boolean)}.
* </p>
* <p>
* To get the optimal asset weighs you simply call {@link #getWeights()} or {@link #getAssetWeights()}.
* </p>
*
* @author apete
*/
public final class MarkowitzModel extends EquilibriumModel {
private static final double _0_0 = ZERO.doubleValue();
private static final String BALANCE = "Balance";
private static final double INIT = Math.sqrt(PrimitiveMath.TEN);
private static final double MAX = PrimitiveMath.HUNDRED * PrimitiveMath.HUNDRED;
private static final double MIN = PrimitiveMath.HUNDREDTH;
private static final NumberContext TARGET_CONTEXT = NumberContext.getGeneral(7, 14);
private static final String VARIANCE = "Variance";
private final HashMap<int[], LowerUpper> myConstraints = new HashMap<int[], LowerUpper>();
private final BasicMatrix myExpectedExcessReturns;
private transient ExpressionsBasedModel myOptimisationModel;
private transient State myOptimisationState = State.UNEXPLORED;
private transient Expression myOptimisationVariance;
private boolean myShortingAllowed = false;
private BigDecimal myTargetReturn;
private BigDecimal myTargetVariance;
private final Variable[] myVariables;
public MarkowitzModel(final BasicMatrix covarianceMatrix, final BasicMatrix expectedExcessReturns) {
this(new MarketEquilibrium(covarianceMatrix), expectedExcessReturns);
}
public MarkowitzModel(final FinancePortfolio.Context portfolioContext) {
super(portfolioContext);
myExpectedExcessReturns = portfolioContext.getAssetReturns();
final String[] tmpSymbols = this.getMarketEquilibrium().getAssetKeys();
myVariables = new Variable[tmpSymbols.length];
for (int i = 0; i < tmpSymbols.length; i++) {
myVariables[i] = new Variable(tmpSymbols[i]);
myVariables[i].weight(myExpectedExcessReturns.toBigDecimal(i, 0).negate());
}
}
public MarkowitzModel(final MarketEquilibrium marketEquilibrium, final BasicMatrix expectedExcessReturns) {
super(marketEquilibrium);
myExpectedExcessReturns = expectedExcessReturns;
final String[] tmpSymbols = this.getMarketEquilibrium().getAssetKeys();
myVariables = new Variable[tmpSymbols.length];
for (int i = 0; i < tmpSymbols.length; i++) {
myVariables[i] = new Variable(tmpSymbols[i]);
myVariables[i].weight(myExpectedExcessReturns.toBigDecimal(i, 0).negate());
}
if (marketEquilibrium.size() != (int) expectedExcessReturns.count()) {
throw new IllegalArgumentException("Wrong dimensions!");
}
}
@SuppressWarnings("unused")
private MarkowitzModel(final MarketEquilibrium marketEquilibrium) {
super(marketEquilibrium);
myExpectedExcessReturns = null;
myVariables = null;
ProgrammingError.throwForIllegalInvocation();
}
/**
* Will add a constraint on the sum of the asset weights specified by the asset indices. Either (but not
* both) of the limits may be null.
*/
public LowerUpper addConstraint(final BigDecimal lowerLimit, final BigDecimal upperLimit, final int... assetIndeces) {
BigDecimal myUpperLimit = upperLimit == null ? BigDecimal.ONE : upperLimit;
BigDecimal myLowerLimit = lowerLimit == null ? myShortingAllowed ? BigDecimal.valueOf(-1): BigDecimal.ZERO : lowerLimit;
return myConstraints.put(assetIndeces, new LowerUpper(myLowerLimit, myUpperLimit));
}
public final void clearAllConstraints() {
myConstraints.clear();
this.reset();
}
public final State getOptimisationState() {
if (myOptimisationState == null) {
myOptimisationState = State.UNEXPLORED;
}
return myOptimisationState;
}
public final void setLowerLimit(final int assetIndex, final BigDecimal lowerLimit) {
myVariables[assetIndex].lower(lowerLimit);
this.reset();
}
public final void setShortingAllowed(final boolean allowed) {
myShortingAllowed = allowed;
this.reset();
}
/**
* <p>
* Will set the target return to whatever you input and the target variance to <code>null</code>.
* </p>
* <p>
* Setting the target return implies that you disregard the risk aversion factor and want the minimum risk
* portfolio with return that is equal to or as close to the target as possible.
* </p>
* <p>
* There is a performance penalty for setting a target return as the underlying optimisation model has to
* be solved several (many) times with different pararmeters (different risk aversion factors).
* </p>
* <p>
* Setting a target return (or variance) is not recommnded. It's much better to simply modify the risk
* aversion factor.
* </p>
*
* @see #setTargetVariance(BigDecimal)
*/
public final void setTargetReturn(final BigDecimal targetReturn) {
myTargetReturn = targetReturn;
myTargetVariance = null;
this.reset();
}
/**
* <p>
* Will set the target variance to whatever you input and the target return to <code>null</code>.
* </p>
* <p>
* Setting the target variance implies that you disregard the risk aversion factor and want the maximum
* return portfolio with risk that is equal to or as close to the target as possible.
* </p>
* <p>
* There is a performance penalty for setting a target variance as the underlying optimisation model has
* to be solved several (many) times with different pararmeters (different risk aversion factors).
* </p>
* <p>
* Setting a target variance is not recommnded. It's much better to modify the risk aversion factor.
* </p>
*
* @see #setTargetReturn(BigDecimal)
*/
public final void setTargetVariance(final BigDecimal targetVariance) {
myTargetVariance = targetVariance;
myTargetReturn = null;
this.reset();
}
public final void setUpperLimit(final int assetIndex, final BigDecimal upperLimit) {
myVariables[assetIndex].upper(upperLimit);
this.reset();
}
@Override
public String toString() {
if (myOptimisationModel == null) {
this.calculateAssetWeights();
}
return myOptimisationModel.toString();
}
private ExpressionsBasedModel generateOptimisationModel(final double riskAversion) {
if ((myOptimisationModel == null) || (myOptimisationVariance == null)) {
final Variable[] tmpVariables = new Variable[myVariables.length];
for (int i = 0; i < tmpVariables.length; i++) {
tmpVariables[i] = myVariables[i].copy();
if (!myShortingAllowed && ((myVariables[i].getLowerLimit() == null) || (myVariables[i].getLowerLimit().signum() == -1))) {
tmpVariables[i].lower(ZERO);
}
}
myOptimisationModel = new ExpressionsBasedModel(tmpVariables);
myOptimisationVariance = myOptimisationModel.addExpression(VARIANCE);
final BasicMatrix tmpCovariances = this.getCovariances();
for (int j = 0; j < tmpVariables.length; j++) {
for (int i = 0; i < tmpVariables.length; i++) {
myOptimisationVariance.set(i, j, tmpCovariances.toBigDecimal(i, j));
}
}
final Expression tmpBalanceExpression = myOptimisationModel.addExpression(BALANCE);
for (int i = 0; i < tmpVariables.length; i++) {
tmpBalanceExpression.set(i, ONE);
}
tmpBalanceExpression.level(ONE);
for (final Map.Entry<int[], LowerUpper> tmpConstraintSet : myConstraints.entrySet()) {
final int[] tmpKey = tmpConstraintSet.getKey();
final LowerUpper tmpValue = tmpConstraintSet.getValue();
final Expression tmpExpr = myOptimisationModel.addExpression(Arrays.toString(tmpKey));
for (int i = 0; i < tmpKey.length; i++) {
tmpExpr.set(tmpKey[i], ONE);
}
tmpExpr.lower(tmpValue.lower).upper(tmpValue.upper);
}
}
myOptimisationVariance.weight(riskAversion / 2.0);
// myOptimisationModel.options.debug(ConvexSolver.class);
return myOptimisationModel;
}
private Optimisation.Result optimise() {
// BasicLogger.debug();
// BasicLogger.debug("
// BasicLogger.debug("BEGIN RAF: {} MarkowitzModel optimisation", this.getRiskAversion());
// BasicLogger.debug("
// BasicLogger.debug();
Optimisation.Result retVal;
if ((myTargetReturn != null) || (myTargetVariance != null)) {
final double tmpTargetValue;
if (myTargetVariance != null) {
tmpTargetValue = myTargetVariance.doubleValue();
} else if (myTargetReturn != null) {
tmpTargetValue = myTargetReturn.doubleValue();
} else {
tmpTargetValue = _0_0;
}
retVal = this.generateOptimisationModel(_0_0).minimise();
double tmpTargetNow = _0_0;
double tmpTargetDiff = _0_0;
double tmpTargetLast = _0_0;
if (myTargetVariance != null) {
tmpTargetLast = this.calculatePortfolioVariance(retVal).doubleValue();
} else if (myTargetReturn != null) {
tmpTargetLast = this.calculatePortfolioReturn(retVal, myExpectedExcessReturns).doubleValue();
} else {
tmpTargetLast = tmpTargetValue;
}
if (retVal.getState().isFeasible() && (tmpTargetValue < tmpTargetLast)) {
// tmpTargetLast at this point is at max possible target value
double tmpCurrent;
double tmpLow;
double tmpHigh;
if (this.isDefaultRiskAversion()) {
tmpCurrent = INIT;
tmpLow = MAX;
tmpHigh = MIN;
} else {
tmpCurrent = this.getRiskAversion().doubleValue();
tmpLow = tmpCurrent * INIT;
tmpHigh = tmpCurrent / INIT;
}
do {
retVal = this.generateOptimisationModel(tmpCurrent).minimise();
tmpTargetLast = tmpTargetNow;
if (myTargetVariance != null) {
tmpTargetNow = this.calculatePortfolioVariance(retVal).doubleValue();
} else if (myTargetReturn != null) {
tmpTargetNow = this.calculatePortfolioReturn(retVal, myExpectedExcessReturns).doubleValue();
} else {
tmpTargetNow = tmpTargetValue;
}
tmpTargetDiff = tmpTargetNow - tmpTargetValue;
if (tmpTargetDiff < _0_0) {
tmpLow = tmpCurrent;
} else if (tmpTargetDiff > _0_0) {
tmpHigh = tmpCurrent;
}
tmpCurrent = Math.sqrt(tmpLow * tmpHigh);
// BasicLogger.debug();
// BasicLogger.debug("Iter: {}", tmpIterCount);
// BasicLogger.debug("RAF: {}", tmpCurrent);
// BasicLogger.debug("Last: {}", tmpTargetLast);
// BasicLogger.debug("Now: {}", tmpTargetNow);
// BasicLogger.debug("Target: {}", tmpTargetValue);
// BasicLogger.debug("Diff: {}", tmpTargetDiff);
} while (!TARGET_CONTEXT.isSmall(tmpTargetValue, tmpTargetDiff) && TARGET_CONTEXT.isDifferent(tmpTargetLast, tmpTargetNow));
}
} else {
retVal = this.generateOptimisationModel(this.getRiskAversion().doubleValue()).minimise();
}
// if (retVal.getState().isFeasible()) {
// final List<Variable> tmpVariables = myOptimisationModel.getVariables();
// for (int v = 0; v < tmpVariables.size(); v++) {
// final BigDecimal tmpBigDecimal = TypeUtils.toBigDecimal(retVal.get(v), WEIGHT_CONTEXT);
// tmpVariables.get(v).setValue(tmpBigDecimal);
return retVal;
}
@Override
protected BasicMatrix calculateAssetReturns() {
return myExpectedExcessReturns;
}
/**
* Constrained optimisation.
*/
@Override
protected BasicMatrix calculateAssetWeights() {
final Optimisation.Result tmpResult = this.optimise();
myOptimisationState = tmpResult.getState();
return MATRIX_FACTORY.columns(tmpResult);
}
@Override
protected void reset() {
super.reset();
myOptimisationModel = null;
myOptimisationVariance = null;
myOptimisationState = State.UNEXPLORED;
}
final Scalar<?> calculatePortfolioReturn(final Access1D<?> weightsVctr, final BasicMatrix returnsVctr) {
return super.calculatePortfolioReturn(MATRIX_FACTORY.columns(weightsVctr), returnsVctr);
}
final Scalar<?> calculatePortfolioVariance(final Access1D<?> weightsVctr) {
return super.calculatePortfolioVariance(MATRIX_FACTORY.columns(weightsVctr));
}
}
|
package org.protorabbit.communicator;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.protorabbit.json.JSONSerializer;
import org.protorabbit.json.SerializationFactory;
import org.protorabbit.stats.IClientIdGenerator;
import org.protorabbit.stats.IStat;
import org.protorabbit.stats.impl.PollManager;
import org.protorabbit.stats.impl.StatsItem;
import org.protorabbit.stats.impl.StatsManager;
import org.protorabbit.util.ClassUtil;
public class HandlerFactory {
public static String HANDLER_NAME = "org.protorabbit.HANDLER_NAME";
protected List<String> searchPackages = new ArrayList<String>();
private JSONSerializer jsonSerializer;
private String handlerName = "Handler";
private StatsManager statsManager = null;
private IClientIdGenerator cg = null;
public HandlerFactory(ServletContext ctx) {
statsManager = (StatsManager)ctx.getAttribute(StatsManager.STATS_MANAGER);
cg = statsManager.getClientIdGenerator( ctx );
String cHName = (String)ctx.getAttribute( HANDLER_NAME );
if ( cHName != null ) {
handlerName = cHName;
}
}
private static Logger logger = null;
static final Logger getLogger() {
if (logger == null) {
logger = Logger.getLogger("org.protrabbit");
}
return logger;
}
public void addSearchPackage(String p) {
searchPackages.add(p);
}
public void processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
// find the suitable action
String path = request.getServletPath();
String handler = null;
String handlerMethod = null;
String handlerNameSpace = null;
int namespace = path.lastIndexOf("/");
if (namespace != -1) {
handlerNameSpace = path.substring( 0,namespace );
namespace +=1;
} else {
namespace = 0;
}
int startHandlerMethod = path.indexOf("!");
int endHandler = path.lastIndexOf(".");
if (startHandlerMethod != -1 && endHandler != -1) {
handlerMethod = path.substring(startHandlerMethod +1, endHandler);
handler = path.substring(namespace, startHandlerMethod);
} else if (endHandler != -1){
handler = path.substring(namespace, endHandler);
}
Handler thandler = null;
String result = null;
// send a 404
if (handler == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
// find the handler class
String klassName = handler.substring(0,1).toUpperCase() +
handler.substring(1,handler.length()) + handlerName;
Class<?> klass = null;
for ( String s : searchPackages) {
try {
klass = this.getClass().getClassLoader().loadClass(s + "." + klassName);
// break if we find it
break;
} catch (ClassNotFoundException e) {
// do nothing
}
}
// if we have the class invoke it
if ( klass == null) {
getLogger().log(Level.WARNING, "Handler " + klassName + " not found in search packages.");
response.sendError( HttpServletResponse.SC_NOT_FOUND );
return;
} else {
try {
Object target = klass.newInstance();
thandler = (Handler)target;
// prepare the handler by setting the request / response
thandler.setRequest(request);
thandler.setResponse(response);
// map parameters to the setters
mapParameters(thandler,request);
if (handlerMethod != null) {
// check for the Namespace
if (klass.isAnnotationPresent(Namespace.class)) {
Namespace n = (Namespace) klass.getAnnotation(Namespace.class);
if (n != null && handlerNameSpace != null) {
if (handlerNameSpace.equals(n.value())) {
// a match so we keep going
} else {
getLogger().info("Namespace " + n.value() + " required.");
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
} else {
getLogger().info("Namespace " + n.value() + " required.");
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
}
try {
Object [] args = {};
Class<?> [] cargs = {};
Method m = thandler.getClass().getMethod(handlerMethod, cargs);
if (m.getReturnType() == String.class) {
try {
result = (String)m.invoke(target, args);
} catch (SecurityException e) {
getLogger().log(Level.WARNING, "SecurityException invoking Handler " + handlerMethod);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getLocalizedMessage());
return;
} catch (InvocationTargetException e) {
getLogger().log(Level.WARNING, "InvocationTargetException invoking Handler " + handlerMethod);
request.setAttribute("javax.servlet.error.message", e);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getLocalizedMessage());
return;
}
} else {
getLogger().log(Level.WARNING, "Handler " + handlerMethod + " must return a String");
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
} catch (NoSuchMethodException e) {
getLogger().log(Level.WARNING, "Handler " + handlerMethod + " not found.");
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
} catch (IllegalArgumentException e) {
getLogger().log( Level.WARNING, e.getLocalizedMessage() );
}
// invoke default handler
} else {
result = thandler.doExecute();
}
} catch (InstantiationException e) {
getLogger().log(Level.WARNING, "InstantiationException creating Handler " + handlerMethod);
response.getOutputStream().write(e.getLocalizedMessage().getBytes());
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
} catch (IllegalAccessException e) {
getLogger().log(Level.WARNING, "IllegalAccessException creating Handler " + handlerMethod);
response.getOutputStream().write(e.getLocalizedMessage().getBytes());
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
} catch (ClassCastException cce) {
getLogger().log(Level.WARNING, "ClassCastException creating Handler " + klassName);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
// all other errors end in a error message
} catch (Throwable e) {
if (thandler != null ) {
thandler.addActionError( e.getLocalizedMessage() );
}
getLogger().log(Level.SEVERE, "Error processing function: ", e);
}
}
int bytesServed = 0;
if (thandler == null) {
getLogger().info("Could not find a handler with name " + klassName + " in any of the search packages.");
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
try {
// do the JSON post processing
bytesServed = processHandler(thandler,result, request,response);
} catch (IOException iox ) {
thandler.getErrors().add( iox.getLocalizedMessage() );
} finally {
// record stats
IStat stat = new StatsItem();
if ( thandler.isPoller() ) {
stat.setIsPoller( true );
}
stat.setTimestamp( System.currentTimeMillis() );
stat.setPath( path );
stat.setPathInfo( request.getPathInfo() );
stat.setRemoteClient( cg.getClientId(request) );
stat.setType( StatsItem.types.JSON );
stat.setRequestURI( request.getRequestURI() );
stat.setContentLength( new Long(bytesServed) );
stat.setContentType( "application/json" );
if ( (thandler.getErrors() != null && thandler.getErrors().size() > 0) ) {
stat.setHasErrors( true );
stat.setErrors( thandler.getErrors() );
}
long endTime = System.currentTimeMillis();
Long st = (Long)request.getAttribute( CommunicatorServlet.START_REQUEST_TIMESTAMP );
long iStartTime = 0;
if ( st != null) {
iStartTime = st.longValue();
stat.setProcessTime( new Long( endTime - iStartTime) );
}
statsManager.add( stat );
}
}
@SuppressWarnings("unchecked")
protected void mapParameters(Handler h,
HttpServletRequest request){
Enumeration<String> params = request.getParameterNames();
while(params.hasMoreElements()) {
String param = params.nextElement();
// get a list of possible methods that are setters for this param
List<Method> methods = ClassUtil.getMethods(h, param, true);
// populate the values
ClassUtil.mapParam(methods, param, request.getParameter(param), h);
}
}
protected int processHandler(Handler h, String result,
HttpServletRequest request,
HttpServletResponse response) throws IOException {
if (this.jsonSerializer == null) {
jsonSerializer = new SerializationFactory().getInstance();
}
JSONResponse jr = new JSONResponse();
if (h.isPoller()) {
PollManager pm = PollManager.getInstance();
jr.setPollInterval(pm.getPollInterval(request));
}
if (h.getErrors() != null) {
jr.setResult("error");
jr.setErrors(h.getErrors());
} else {
jr.setResult(result);
}
// get the model
jr.setData( h.getModel() );
response.setHeader("Content-Type", "application/json");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("pragma", "NO-CACHE");
// now that we have the json object print out the string
Object responseObject = jsonSerializer.serialize(jr);
response.getWriter().write(responseObject.toString());
return responseObject.toString().getBytes().length;
}
}
|
package org.wikipedia.tools;
import java.io.IOException;
import java.util.*;
import org.wikipedia.*;
public class FeaturedPictureCuration
{
private static final Wiki enWiki = Wiki.createInstance("en.wikipedia.org");
/**
* Runs this program.
* @param args the command line arguments
* @throws IOException if a network error occurs
*/
public static void main(String[] args) throws IOException
{
Map<String, String> parsedargs = new CommandLineParser()
.synopsis("org.wikipedia.tools.FeaturedPictureCuration", "[options]")
.description("A tool for curating featured pictures.")
.addHelp()
.addVersion("FeaturedPictureCuration v0.01\n" + CommandLineParser.GPL_VERSION_STRING)
.addBooleanFlag("--checktags", "Check whether FPs are tagged correctly (en.wp ONLY).")
.addBooleanFlag("--checkusage", "Checks whether FPs are used in articles (en.wp or commons ONLY).")
.addSingleArgumentFlag("--wiki", "example.org", "Fetch FPs from this wiki (see --checkusage).")
.parse(args);
if (parsedargs.containsKey("--checktags"))
checkFPTags();
if (parsedargs.containsKey("--checkusage"))
{
Wiki wiki = Wiki.createInstance(parsedargs.get("--wiki"));
Set<String> fpcanonical = getFeaturedPicturesFromList(wiki);
// There is a small amount of contamination of non-featured pictures
// on Commons.
enWiki.setQueryLimit(100);
for (String image : fpcanonical)
{
String[] usage = enWiki.imageUsage(image, Wiki.MAIN_NAMESPACE);
System.out.println("\"" + image + "\"," + usage.length + ",\"" + Arrays.toString(usage));
}
}
}
/**
* Fetches the canonical list of featured pictures on the supplied wiki,
* being the list of pictures used on subpages of [[Project:Featured pictures]].
*
* @param wiki the wiki to fetch FPs for
* @return (see above)
* @throws IOException if a network error occurs
*/
public static Set<String> getFeaturedPicturesFromList(Wiki wiki) throws IOException
{
String[] allfppages;
String domain = wiki.getDomain();
if (domain.equals("en.wikipedia.org"))
allfppages = wiki.getCategoryMembers("Category:Wikipedia featured pictures categories");
else if (domain.equals("commons.wikimedia.org"))
allfppages = wiki.getCategoryMembers("Category:Featured picture galleries");
else
return Collections.emptySet();
Set<String> fps = new HashSet<>();
for (String fppage : allfppages)
fps.addAll(Arrays.asList(wiki.getImagesOnPage(fppage)));
return fps;
}
/**
* Checks whether all pictures listed at [[Wikipedia:Featured pictures]]
* are actually tagged, and vice versa.
* @throws IOException if a network error occurs
*/
public static void checkFPTags() throws IOException
{
Set<String> fpcanonical = getFeaturedPicturesFromList(enWiki);
List<String> fpcat = Arrays.asList(enWiki.getCategoryMembers("Category:Featured pictures", Wiki.FILE_NAMESPACE));
// check for FPs that are no longer tagged as such
List<String> missingfps = new ArrayList(fpcanonical);
missingfps.removeAll(fpcat);
System.out.println("Images that should be tagged FP, but aren't:");
System.out.println(Pages.toWikitextList(missingfps, Pages.LIST_OF_LINKS, false));
// check for images tagged as FP, but aren't listed at [[WP:FP]]
missingfps.clear();
missingfps.addAll(fpcat);
missingfps.removeAll(fpcanonical);
System.out.println("Images that are tagged as FP, but aren't listed at [[WP:FP]]:");
System.out.println(Pages.toWikitextList(missingfps, Pages.LIST_OF_LINKS, false));
}
}
|
package com.dw.lib;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.util.UUID;
public class MD5Generator {
public String generateValue() throws Exception {
return generateValue(UUID.randomUUID().toString());
}
private static final char[] hexCode = "0123456789abcdef".toCharArray();
public static String toHexString(byte[] data) {
if (data == null) {
return null;
}
StringBuilder r = new StringBuilder(data.length * 2);
for (byte b : data) {
r.append(hexCode[(b >> 4) & 0xF]);
r.append(hexCode[(b & 0xF)]);
}
return r.toString();
}
public String generateValue(String param) throws Exception {
try {
MessageDigest algorithm = MessageDigest.getInstance("MD5");
algorithm.reset();
algorithm.update(param.getBytes());
byte[] messageDigest = algorithm.digest();
return toHexString(messageDigest);
} catch (Exception e) {
throw new Exception("OAuth Token cannot be generated.", e);
}
}
public String generateFileValue(String filePath) throws Exception {
try {
MessageDigest algorithm = MessageDigest.getInstance("MD5");
algorithm.reset();
algorithm.update(Files.readAllBytes(Paths.get(filePath)));
byte[] messageDigest = algorithm.digest();
return toHexString(messageDigest);
} catch (Exception e) {
throw new Exception("Generate MD5 of file show exceptions: ", e);
}
}
public static void main(String[] args) {
MD5Generator m = new MD5Generator();
try {
System.out.println(m.generateFileValue("/Users/di.wu/test/1.json"));
System.out.println(m.generateValue("1234"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package com.mfk.web.client;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dev.util.collect.HashMap;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;
import com.google.gwt.json.client.JSONException;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class MfkWeb implements EntryPoint {
/** Display names for the 4 assignment options. */
public static final String[] mfkText = { "?", "Marry", "Fuck", "Kill" };
/** Wire names for the 4 assignment options. */
public static final String[] mfkShortText = { "E", "m", "f", "k" };
public enum Mfk {NONE, MARRY, FUCK, KILL};
/** Display area for the 3 entities. */
public static HTML entityHtml[] = {new HTML(), new HTML(), new HTML()};
/** Entity IDs. */
public static String entities[] = {null, null, null};
public static VoteGroupHandler groups[] = {null, null, null};
public static DialogBox errorDialog;
public static HTML errorHtml;
public static Button voteButton = new Button("Vote!");
public static Button skipButton = new Button("Skip!");
private static Label statusLabel = new Label();
public static void setStatus(String status) {
System.out.println("Setting status: " + status);
MfkWeb.statusLabel.setText(status);
}
public static void showError(String errorMsg) {
System.out.println("Showing error: " + errorMsg);
MfkWeb.errorHtml.setHTML("<div class='errorText'>" + errorMsg + "</div>");
MfkWeb.errorDialog.center();
}
private static void addVoteButtons(String id, int groupNum) {
RootPanel rp = RootPanel.get(id);
VerticalPanel vp = new VerticalPanel();
rp.add(vp);
VoteGroupHandler group = new VoteGroupHandler(groupNum);
for (int i = 1; i < 4; i++) {
Button b = new Button(MfkWeb.mfkText[i]);
b.setWidth("200px");
b.addClickHandler(new VoteChangeHandler(MfkWeb.Mfk.values()[i], group));
vp.add(b);
}
}
public static DialogBox makeErrorDialog(HTML html) {
final DialogBox dialog = new DialogBox();
dialog.setText("Error!");
dialog.setAnimationEnabled(false);
final Button closeButton = new Button("Close");
closeButton.getElement().setId("closeButton");
VerticalPanel dialogVPanel = new VerticalPanel();
dialogVPanel.addStyleName("dialogVPanel");
dialogVPanel.add(html);
dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
dialogVPanel.add(closeButton);
dialog.setWidget(dialogVPanel);
closeButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
dialog.hide();
}
});
return dialog;
}
public void onModuleLoad() {
// Is the index-vs-label numbering confusing here? Maybe. Maybe not.
MfkWeb.addVoteButtons("e1Vote", 0);
MfkWeb.addVoteButtons("e2Vote", 1);
MfkWeb.addVoteButtons("e3Vote", 2);
MfkWeb.voteButton.setEnabled(false);
voteButton.addClickHandler(new AssignmentHandler());
RootPanel.get("status").add(MfkWeb.statusLabel);
RootPanel.get("control").add(voteButton);
RootPanel.get("control").add(skipButton);
RootPanel.get("e1Display").add(entityHtml[0]);
RootPanel.get("e2Display").add(entityHtml[1]);
RootPanel.get("e3Display").add(entityHtml[2]);
MfkWeb.errorHtml = new HTML("No error.");
MfkWeb.errorDialog = MfkWeb.makeErrorDialog(MfkWeb.errorHtml);
final ClickHandler loadHandler = new LoadTripleHandler();
skipButton.addClickHandler(loadHandler);
// get an initial item
loadHandler.onClick(null);
MfkWeb.setStatus("Welcome to MFK!");
}
public static void setEntities(String one, String two, String three) {
// save entity IDs
MfkWeb.entities[0] = one;
MfkWeb.entities[1] = two;
MfkWeb.entities[2] = three;
// change the display itself
MfkWeb.entityHtml[0].setHTML(one);
MfkWeb.entityHtml[1].setHTML(two);
MfkWeb.entityHtml[2].setHTML(three);
}
public static void checkVoteStatus(VoteGroupHandler changedVote) {
System.out.println("checkVoteStatus: " + MfkWeb.groups[0].vote
+ " " + MfkWeb.groups[1].vote + " " + MfkWeb.groups[2].vote);
// a vote must exist for all buttons
if (MfkWeb.groups[0].vote == MfkWeb.Mfk.NONE
|| MfkWeb.groups[1].vote == MfkWeb.Mfk.NONE
|| MfkWeb.groups[2].vote == MfkWeb.Mfk.NONE) {
System.out.println("NOT enabled!");
MfkWeb.voteButton.setEnabled(false);
}
else {
// christ on a cracker. yes, this is it, in a nutshell.
boolean valid = MfkWeb.groups[0].vote != MfkWeb.groups[1].vote
&& MfkWeb.groups[1].vote != MfkWeb.groups[2].vote
&& MfkWeb.groups[2].vote != MfkWeb.groups[0].vote;
System.out.println("Set enabled = " + valid);
MfkWeb.voteButton.setEnabled(valid);
}
}
}
class LoadTripleHandler implements ClickHandler {
public static void loadNew() {
String url = "/rpc/vote/";
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
MfkWeb.setStatus("Getting new triple...");
MfkWeb.groups[0].vote = MfkWeb.Mfk.NONE;
MfkWeb.groups[1].vote = MfkWeb.Mfk.NONE;
MfkWeb.groups[2].vote = MfkWeb.Mfk.NONE;
MfkWeb.checkVoteStatus(null);
try {
builder.sendRequest(null, new RequestCallback() {
@Override
public void onError(Request request, Throwable exception) {
MfkWeb.showError("Error retrieving new triple!");
}
@Override
public void onResponseReceived(Request request, Response response) {
JSONObject json;
try {
json = JSONParser.parse(response.getText()).isObject();
}
catch (JSONException e) {
MfkWeb.showError("Couldn't parse JSON from server!");
return;
}
System.out.println("Got JSONObject: " + json);
try {
MfkWeb.setEntities(
json.get("one").isObject().get("name")
.isString().stringValue(),
json.get("two").isObject().get("name")
.isString().stringValue(),
json.get("three").isObject().get("name")
.isString().stringValue());
MfkWeb.setStatus("Getting new triple...done.");
}
catch (NullPointerException e) {
MfkWeb.showError("Malformed response from server!");
return;
}
}
});
} catch (RequestException e) {
e.printStackTrace();
}
}
@Override
public void onClick(ClickEvent event) {
LoadTripleHandler.loadNew();
}
}
/**
* Handler for individual button.
*/
class VoteChangeHandler implements ClickHandler {
private MfkWeb.Mfk vote;
private VoteGroupHandler group;
public VoteChangeHandler(MfkWeb.Mfk mfk, VoteGroupHandler group) {
this.vote = mfk;
this.group = group;
}
@Override
public void onClick(ClickEvent event) {
this.group.vote = this.vote;
System.out.println("Vote: " + this.vote + " " + this.group);
MfkWeb.setStatus(this.vote + " " + MfkWeb.entities[this.group.num]);
Button src = (Button)event.getSource();
this.group.onClick(event);
}
}
/**
* Handler for group of M/F/K buttons for one entity.
*/
class VoteGroupHandler implements ClickHandler {
public int num;
public MfkWeb.Mfk vote = MfkWeb.Mfk.NONE;
public VoteGroupHandler(int groupNum) {
this.num = groupNum;
MfkWeb.groups[this.num] = this;
}
@Override
public void onClick(ClickEvent event) {
MfkWeb.checkVoteStatus(this);
}
public String toString() {
return "<Group " + this.num + ": " + this.vote + ">";
}
}
/**
* Handler for making an actual assignment.
*/
class AssignmentHandler implements ClickHandler {
public void onClick(ClickEvent event) {
MfkWeb.setStatus("Voting... ");
String url = "/rpc/vote/";
RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url);
builder.setHeader("Content-Type", "application/x-www-form-urlencoded");
StringBuffer reqData = new StringBuffer();
reqData.append("e1=").append(MfkWeb.entities[0]);
reqData.append("&e2=").append(MfkWeb.entities[1]);
reqData.append("&e3=").append(MfkWeb.entities[2]);
reqData.append("&v1=");
reqData.append(MfkWeb.mfkShortText[MfkWeb.groups[0].vote.ordinal()]);
reqData.append("&v2=");
reqData.append(MfkWeb.mfkShortText[MfkWeb.groups[1].vote.ordinal()]);
reqData.append("&v3=");
reqData.append(MfkWeb.mfkShortText[MfkWeb.groups[2].vote.ordinal()]);
try {
builder.sendRequest(reqData.toString(), new RequestCallback() {
@Override
public void onError(Request request, Throwable exception) {
System.out.println("Error sending assignment request");
}
@Override
public void onResponseReceived(Request request,
Response response) {
if (response.getStatusCode() == 200) {
System.out.println("Successful assignment request: "
+ response.getText());
MfkWeb.setStatus("Voting... success!");
}
else {
System.out.println("Failed request: "
+ response.getStatusCode() + ": "
+ response.getText());
}
}
});
} catch (RequestException e) {
System.out.println("Error sending assignment: " + e);
}
LoadTripleHandler.loadNew();
}
}
|
package de.test.antennapod.util;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.filters.SmallTest;
import android.text.TextUtils;
import java.io.File;
import java.io.IOException;
import de.danoeh.antennapod.core.util.FileNameGenerator;
import org.junit.After;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@SmallTest
public class FilenameGeneratorTest {
private static final String VALID1 = "abc abc";
private static final String INVALID1 = "ab/c: <abc";
private static final String INVALID2 = "abc abc ";
public FilenameGeneratorTest() {
super();
}
@Test
public void testGenerateFileName() throws IOException {
String result = FileNameGenerator.generateFileName(VALID1);
assertEquals(result, VALID1);
createFiles(result);
}
@Test
public void testGenerateFileName1() throws IOException {
String result = FileNameGenerator.generateFileName(INVALID1);
assertEquals(result, VALID1);
createFiles(result);
}
@Test
public void testGenerateFileName2() throws IOException {
String result = FileNameGenerator.generateFileName(INVALID2);
assertEquals(result, VALID1);
createFiles(result);
}
@Test
public void testFeedTitleContainsApostrophe() {
String result = FileNameGenerator.generateFileName("Feed's Title ...");
assertEquals("Feeds Title", result);
}
@Test
public void testFeedTitleContainsDash() {
String result = FileNameGenerator.generateFileName("Left - Right");
assertEquals("Left - Right", result);
}
@Test
public void testInvalidInput() {
String result = FileNameGenerator.generateFileName("???");
assertFalse(TextUtils.isEmpty(result));
}
/**
* Tests if files can be created.
*
* @throws IOException
*/
private void createFiles(String name) throws IOException {
File cache = InstrumentationRegistry.getInstrumentation().getTargetContext().getExternalCacheDir();
File testFile = new File(cache, name);
testFile.mkdir();
assertTrue(testFile.exists());
testFile.delete();
assertTrue(testFile.createNewFile());
}
@After
public void tearDown() {
Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();
File f = new File(context.getExternalCacheDir(), VALID1);
f.delete();
}
}
|
package com.akexorcist.sleepingforless.util;
import android.animation.Animator;
import android.animation.AnimatorInflater;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.view.View;
import com.akexorcist.sleepingforless.R;
public class AnimationUtility {
private static AnimationUtility utility;
public static AnimationUtility getInstance() {
if (utility == null) {
utility = new AnimationUtility();
}
return utility;
}
public static final int DEFAULT_DURATION = 300;
public static final int DEFAULT_START_DELAY = 0;
public void fadeOut(View view) {
fadeOut(view, DEFAULT_DURATION, DEFAULT_START_DELAY, null);
}
public void fadeOut(View view, AnimationFinishCallback callback) {
fadeOut(view, DEFAULT_DURATION, DEFAULT_START_DELAY, callback);
}
public void fadeOut(View view, int duration) {
fadeOut(view, duration, DEFAULT_START_DELAY, null);
}
public void fadeOut(View view, int duration, AnimationFinishCallback callback) {
fadeOut(view, duration, DEFAULT_START_DELAY, callback);
}
public void fadeOut(View view, long startDelay) {
fadeOut(view, DEFAULT_DURATION, startDelay, null);
}
public void fadeOut(final View view, int duration, long startDelay, final AnimationFinishCallback callback) {
ObjectAnimator objectAnimator = (ObjectAnimator) AnimatorInflater.loadAnimator(Contextor.getContext(), R.animator.animator_default_fade_out);
objectAnimator.setTarget(view);
objectAnimator.setDuration(duration);
objectAnimator.setStartDelay(startDelay);
objectAnimator.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
view.setVisibility(View.GONE);
if (callback != null) {
callback.onAnimationFinished();
}
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
objectAnimator.start();
}
public void fadeIn(View view) {
fadeIn(view, DEFAULT_DURATION, DEFAULT_START_DELAY);
}
public void fadeIn(View view, int duration) {
fadeIn(view, duration, DEFAULT_START_DELAY);
}
public void fadeIn(View view, long startDelay) {
fadeIn(view, DEFAULT_DURATION, startDelay);
}
public void fadeIn(final View view, int duration, long startDelay) {
view.setVisibility(View.VISIBLE);
view.setEnabled(false);
ObjectAnimator objectAnimator = (ObjectAnimator) AnimatorInflater.loadAnimator(Contextor.getContext(), R.animator.animator_default_fade_in);
objectAnimator.setTarget(view);
objectAnimator.setDuration(duration);
objectAnimator.setStartDelay(startDelay);
objectAnimator.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
view.setEnabled(true);
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
objectAnimator.start();
}
public void scaleUp(final View view, int duration, long startDelay) {
AnimatorSet animatorSet = (AnimatorSet) AnimatorInflater.loadAnimator(Contextor.getContext(), R.animator.animator_default_scale_up);
animatorSet.setTarget(view);
animatorSet.setDuration(duration);
animatorSet.setStartDelay(startDelay);
animatorSet.start();
}
public void scaleUp(View view, long startDelay) {
scaleUp(view, DEFAULT_DURATION, startDelay);
}
public void scaleUp(View view, int duration) {
scaleUp(view, duration, DEFAULT_START_DELAY);
}
public void scaleUp(View view) {
scaleUp(view, DEFAULT_DURATION, DEFAULT_START_DELAY);
}
public void scaleBack(final View view, int duration, long startDelay) {
AnimatorSet animatorSet = (AnimatorSet) AnimatorInflater.loadAnimator(Contextor.getContext(), R.animator.animator_default_scale_back);
animatorSet.setTarget(view);
animatorSet.setDuration(duration);
animatorSet.setStartDelay(startDelay);
animatorSet.start();
}
public void scaleBack(View view, long startDelay) {
scaleBack(view, DEFAULT_DURATION, startDelay);
}
public void scaleBack(View view, int duration) {
scaleBack(view, duration, DEFAULT_START_DELAY);
}
public void scaleBack(View view) {
scaleBack(view, DEFAULT_DURATION, DEFAULT_START_DELAY);
}
public interface AnimationFinishCallback {
void onAnimationFinished();
}
}
|
package com.battlelancer.seriesguide.sync;
import android.content.Context;
import android.text.TextUtils;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.util.Pair;
import androidx.preference.PreferenceManager;
import com.battlelancer.seriesguide.backend.HexagonTools;
import com.battlelancer.seriesguide.backend.settings.HexagonSettings;
import com.battlelancer.seriesguide.provider.SgEpisode2ForSync;
import com.battlelancer.seriesguide.provider.SgEpisode2UpdateByNumber;
import com.battlelancer.seriesguide.provider.SgRoomDatabase;
import com.battlelancer.seriesguide.ui.episodes.EpisodeFlags;
import com.battlelancer.seriesguide.ui.episodes.EpisodeTools;
import com.battlelancer.seriesguide.util.Errors;
import com.google.api.client.util.DateTime;
import com.uwetrottmann.androidutils.AndroidUtils;
import com.uwetrottmann.seriesguide.backend.episodes.Episodes;
import com.uwetrottmann.seriesguide.backend.episodes.model.Episode;
import com.uwetrottmann.seriesguide.backend.episodes.model.EpisodeList;
import com.uwetrottmann.seriesguide.backend.episodes.model.SgCloudEpisode;
import com.uwetrottmann.seriesguide.backend.episodes.model.SgCloudEpisodeList;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import timber.log.Timber;
public class HexagonEpisodeSync {
public static final int MAX_BATCH_SIZE = 500;
private final Context context;
private final HexagonTools hexagonTools;
public HexagonEpisodeSync(Context context, HexagonTools hexagonTools) {
this.context = context;
this.hexagonTools = hexagonTools;
}
/**
* Downloads all episodes changed since the last time this was called and applies changes to
* the database.
*/
public boolean downloadChangedFlags(@NonNull Map<Integer, Long> tmdbIdsToShowIds) {
long currentTime = System.currentTimeMillis();
SgRoomDatabase database = SgRoomDatabase.getInstance(context);
DateTime lastSyncTime = new DateTime(HexagonSettings.getLastEpisodesSyncTime(context));
Timber.d("downloadChangedFlags: since %s", lastSyncTime);
List<SgCloudEpisode> episodes;
String cursor = null;
boolean hasMoreEpisodes = true;
Map<Long, Long> showIdsToLastWatched = new HashMap<>();
while (hasMoreEpisodes) {
try {
// get service each time to check if auth was removed
Episodes episodesService = hexagonTools.getEpisodesService();
if (episodesService == null) {
return false;
}
Episodes.GetSgEpisodes request = episodesService.getSgEpisodes()
.setUpdatedSince(lastSyncTime); // use default server limit
if (!TextUtils.isEmpty(cursor)) {
request.setCursor(cursor);
}
SgCloudEpisodeList response = request.execute();
if (response == null) {
// we're done here
Timber.d("downloadChangedFlags: response was null, done here");
break;
}
episodes = response.getEpisodes();
// check for more items
if (response.getCursor() != null) {
cursor = response.getCursor();
} else {
hasMoreEpisodes = false;
}
} catch (IOException | IllegalArgumentException e) {
Errors.logAndReportHexagon("get updated episodes", e);
return false;
}
if (episodes == null || episodes.size() == 0) {
// nothing to do here
break;
}
// build batch of episode flag updates
ArrayList<SgEpisode2UpdateByNumber> batch = new ArrayList<>();
for (SgCloudEpisode episode : episodes) {
Integer showTmdbId = episode.getShowTmdbId();
Long showId = tmdbIdsToShowIds.get(showTmdbId);
if (showId == null) {
continue; // ignore, show not added on this device
}
Integer watchedFlag = episode.getWatchedFlag();
Integer playsOrNull = null;
if (watchedFlag != null) {
if (watchedFlag == EpisodeFlags.WATCHED) {
// Watched.
// Note: plays may be null for legacy data. Protect against invalid data.
if (episode.getPlays() != null && episode.getPlays() >= 1) {
playsOrNull = episode.getPlays();
} else {
playsOrNull = 1;
}
} else {
// Skipped or not watched.
playsOrNull = 0;
}
// record the latest last watched time for a show
if (!EpisodeTools.isUnwatched(watchedFlag)) {
Long lastWatchedMs = showIdsToLastWatched.get(showId);
// episodes returned in reverse chrono order, so just get the first time
if (lastWatchedMs == null && episode.getUpdatedAt() != null) {
long updatedAtMs = episode.getUpdatedAt().getValue();
showIdsToLastWatched.put(showId, updatedAtMs);
}
}
}
batch.add(new SgEpisode2UpdateByNumber(
showId,
episode.getEpisodeNumber(),
episode.getSeasonNumber(),
watchedFlag,
playsOrNull,
episode.getIsInCollection()
));
}
// execute database update
database.sgEpisode2Helper().updateWatchedAndCollectedByNumber(batch);
}
if (!showIdsToLastWatched.isEmpty()) {
// Temporarily turned off during migration to TMDB phase to avoid incorrect
// updates as new episode entities are created (with current timestamp)
// during migration.
// Accept that this breaks last watched updates when using multiple devices,
// which should have less impact.
// Will restore in future version.
// database.sgShow2Helper().updateLastWatchedMsIfLater(showIdsToLastWatched);
}
// store new last sync time
PreferenceManager.getDefaultSharedPreferences(context).edit()
.putLong(HexagonSettings.KEY_LAST_SYNC_EPISODES, currentTime)
.apply();
return true;
}
/**
* Downloads watched, skipped or collected episodes of this show from Hexagon and applies
* those flags and plays to episodes in the database.
* <p>
* If a TVDB ID is given tries to use legacy data if no data using TMDB ID is found.
*
* @return Whether the download was successful and all changes were applied to the database.
*/
public boolean downloadFlags(long showId, int showTmdbId, Integer showTvdbId) {
Timber.d("downloadFlags: for show %s", showId);
DownloadFlagsResult result = downloadFlagsByTmdbId(showId, showTmdbId);
if (result.getNoData() && showTvdbId != null) {
// If no data by TMDB ID, try to get legacy data by TVDB ID.
Timber.d("downloadFlags: no data by TMDB ID, trying by TVDB ID");
result = downloadFlagsByTvdbId(showId, showTvdbId);
if (result.getSuccess()) {
// If had to use legacy show data, schedule episode upload (using TMDB IDs).
SgRoomDatabase.getInstance(context).sgShow2Helper()
.setHexagonMergeNotCompleted(showId);
}
}
if (result.getLastWatchedMs() != null) {
SgRoomDatabase.getInstance(context).sgShow2Helper()
.updateLastWatchedMsIfLater(showId, result.getLastWatchedMs());
}
return result.getSuccess();
}
private DownloadFlagsResult downloadFlagsByTmdbId(long showId, int showTmdbId) {
List<SgCloudEpisode> episodes;
boolean onFirstPage = true;
boolean hasMoreEpisodes = true;
String cursor = null;
Long lastWatchedMs = null;
while (hasMoreEpisodes) {
// abort if connection is lost
if (!AndroidUtils.isNetworkConnected(context)) {
Timber.e("downloadFlags: no network connection");
return DownloadFlagsResult.FAILED;
}
try {
// get service each time to check if auth was removed
Episodes episodesService = hexagonTools.getEpisodesService();
if (episodesService == null) {
return DownloadFlagsResult.FAILED;
}
// build request
Episodes.GetSgEpisodes request = episodesService.getSgEpisodes()
.setShowTmdbId(showTmdbId); // use default server limit
if (!TextUtils.isEmpty(cursor)) {
request.setCursor(cursor);
}
// execute request
SgCloudEpisodeList response = request.execute();
if (response == null) {
// If empty should send status 200 and empty list, so no body is a failure.
return DownloadFlagsResult.FAILED;
}
episodes = response.getEpisodes();
// check for more items
if (response.getCursor() != null) {
cursor = response.getCursor();
} else {
hasMoreEpisodes = false;
}
} catch (IOException | IllegalArgumentException e) {
Errors.logAndReportHexagon("get episodes of show", e);
return DownloadFlagsResult.FAILED;
}
if (episodes == null || episodes.size() == 0) {
if (onFirstPage) {
// If there is no data by TMDB ID at all, try again using TVDB ID.
return DownloadFlagsResult.NO_DATA;
} else {
// no more updates to apply
break;
}
}
onFirstPage = false;
// build batch of episode flag updates
ArrayList<SgEpisode2UpdateByNumber> batch = new ArrayList<>();
for (SgCloudEpisode episode : episodes) {
Pair<SgEpisode2UpdateByNumber, Long> update = buildSgEpisodeUpdate(
episode.getWatchedFlag(),
episode.getPlays(),
episode.getIsInCollection(),
episode.getUpdatedAt(),
episode.getEpisodeNumber(),
episode.getSeasonNumber(),
showId,
lastWatchedMs
);
if (update != null) {
batch.add(update.first);
}
lastWatchedMs = update.second;
}
// execute database update
SgRoomDatabase.getInstance(context).sgEpisode2Helper()
.updateWatchedAndCollectedByNumber(batch);
}
return new DownloadFlagsResult(true, false, lastWatchedMs);
}
private DownloadFlagsResult downloadFlagsByTvdbId(long showId, int showTvdbId) {
List<Episode> episodes;
boolean hasMoreEpisodes = true;
String cursor = null;
Long lastWatchedMs = null;
while (hasMoreEpisodes) {
// abort if connection is lost
if (!AndroidUtils.isNetworkConnected(context)) {
Timber.e("downloadFlags: no network connection");
return DownloadFlagsResult.FAILED;
}
try {
// get service each time to check if auth was removed
Episodes episodesService = hexagonTools.getEpisodesService();
if (episodesService == null) {
return DownloadFlagsResult.FAILED;
}
// build request
Episodes.Get request = episodesService.get()
.setShowTvdbId(showTvdbId); // use default server limit
if (!TextUtils.isEmpty(cursor)) {
request.setCursor(cursor);
}
// execute request
EpisodeList response = request.execute();
if (response == null) {
// If empty should send status 200 and empty list, so no body is a failure.
return DownloadFlagsResult.FAILED;
}
episodes = response.getEpisodes();
// check for more items
if (response.getCursor() != null) {
cursor = response.getCursor();
} else {
hasMoreEpisodes = false;
}
} catch (IOException | IllegalArgumentException e) {
Errors.logAndReportHexagon("get episodes of show", e);
return DownloadFlagsResult.FAILED;
}
if (episodes == null || episodes.size() == 0) {
// nothing to do here
break;
}
// build batch of episode flag updates
ArrayList<SgEpisode2UpdateByNumber> batch = new ArrayList<>();
for (Episode episode : episodes) {
Pair<SgEpisode2UpdateByNumber, Long> update = buildSgEpisodeUpdate(
episode.getWatchedFlag(),
episode.getPlays(),
episode.getIsInCollection(),
episode.getUpdatedAt(),
episode.getEpisodeNumber(),
episode.getSeasonNumber(),
showId,
lastWatchedMs
);
if (update != null) {
batch.add(update.first);
}
lastWatchedMs = update.second;
}
// execute database update
SgRoomDatabase.getInstance(context).sgEpisode2Helper()
.updateWatchedAndCollectedByNumber(batch);
}
return new DownloadFlagsResult(true, false, lastWatchedMs);
}
@Nullable
private Pair<SgEpisode2UpdateByNumber, Long> buildSgEpisodeUpdate(
Integer watchedFlag,
Integer plays,
Boolean isInCollection,
DateTime updatedAt,
int episodeNumber,
int seasonNumber,
long showId,
Long lastWatchedMs
) {
Integer watchedFlagOrNull = null;
Integer playsOrNull = null;
if (watchedFlag != null && watchedFlag != EpisodeFlags.UNWATCHED) {
// Watched or skipped.
watchedFlagOrNull = watchedFlag;
if (watchedFlag == EpisodeFlags.WATCHED) {
// Note: plays may be null for legacy data. Protect against invalid data.
if (plays != null && plays >= 1) {
playsOrNull = plays;
} else {
playsOrNull = 1;
}
}
// record last watched time by taking latest updatedAt of watched/skipped
if (updatedAt != null) {
long lastWatchedMsNew = updatedAt.getValue();
if (lastWatchedMs == null || lastWatchedMs < lastWatchedMsNew) {
lastWatchedMs = lastWatchedMsNew;
}
}
}
boolean inCollection = isInCollection != null && isInCollection;
if (watchedFlag == null && !inCollection) {
// skip if episode has no watched flag and is not in collection
return null;
}
return new Pair<>(
new SgEpisode2UpdateByNumber(
showId,
episodeNumber,
seasonNumber,
watchedFlagOrNull,
playsOrNull,
isInCollection
),
lastWatchedMs
);
}
/**
* Uploads all watched, skipped including plays or collected episodes of this show to Hexagon.
*
* @return Whether the upload was successful.
*/
boolean uploadFlags(long showId, int showTmdbId) {
// query for watched, skipped or collected episodes
List<SgEpisode2ForSync> episodesForSync = SgRoomDatabase.getInstance(context)
.sgEpisode2Helper()
.getEpisodesForHexagonSync(showId);
if (episodesForSync.isEmpty()) {
Timber.d("uploadFlags: uploading none for show %d", showId);
return true;
} else {
Timber.d("uploadFlags: uploading %d for show %d", episodesForSync.size(), showId);
}
// build list of episodes to upload
List<SgCloudEpisode> episodes = new ArrayList<>();
int count = episodesForSync.size();
for (int i = 0; i < count; i++) {
SgEpisode2ForSync episodeForSync = episodesForSync.get(i);
SgCloudEpisode episode = new SgCloudEpisode();
episode.setSeasonNumber(episodeForSync.getSeason());
episode.setEpisodeNumber(episodeForSync.getNumber());
int watchedFlag = episodeForSync.getWatched();
if (!EpisodeTools.isUnwatched(watchedFlag)) {
// Skipped or watched.
episode.setWatchedFlag(watchedFlag);
episode.setPlays(episodeForSync.getPlays());
}
if (episodeForSync.getCollected()) {
episode.setIsInCollection(true);
}
episodes.add(episode);
// upload a batch
boolean isLast = i + 1 == count;
if (episodes.size() == MAX_BATCH_SIZE || isLast) {
SgCloudEpisodeList episodeList = new SgCloudEpisodeList();
episodeList.setEpisodes(episodes);
episodeList.setShowTmdbId(showTmdbId);
try {
// get service each time to check if auth was removed
Episodes episodesService = hexagonTools.getEpisodesService();
if (episodesService == null) {
return false;
}
episodesService.saveSgEpisodes(episodeList).execute();
} catch (IOException e) {
// abort
Errors.logAndReportHexagon("save episodes of show", e);
return false;
}
// clear array
episodes = new ArrayList<>();
}
}
return true;
}
}
|
package com.bolyartech.forge.skeleton.dagger.basic.app;
import android.os.StrictMode;
import com.bolyartech.forge.android.app_unit.UnitApplication;
import com.bolyartech.forge.android.task.ForgeAndroidTaskExecutor;
import com.bolyartech.forge.base.misc.ForUnitTestsOnly;
import com.bolyartech.forge.skeleton.dagger.basic.R;
import com.bolyartech.forge.skeleton.dagger.basic.dagger.DefaultMyAppDaggerComponent;
import com.bolyartech.forge.skeleton.dagger.basic.dagger.DependencyInjector;
import org.acra.ACRA;
import org.acra.ACRAConfiguration;
import org.acra.annotation.ReportsCrashes;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import javax.inject.Inject;
@ReportsCrashes(formUri = "placeholder")
public class MyApp extends UnitApplication {
private final org.slf4j.Logger mLogger = LoggerFactory.getLogger(this.getClass()
.getSimpleName());
@Inject
ForgeAndroidTaskExecutor mForgeAndroidTaskExecutor;
@Override
public void onCreate() {
super.onCreate();
mLogger.debug("presni");
initInjector();
if (getResources().getBoolean(R.bool.build_conf_dev_mode)) {
initAcra(false);
}
if (getResources().getBoolean(R.bool.build_conf_dev_mode)) {
enableStrictMode();
}
}
protected void initInjector() {
DependencyInjector.init(DefaultMyAppDaggerComponent.create(this));
DependencyInjector.getInstance().inject(this);
onInjectorInitialized();
}
protected void onInjectorInitialized() {
}
private void enableStrictMode() {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork()
.penaltyLog()
.penaltyDeath()
.build());
StrictMode.VmPolicy.Builder b = new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.penaltyLog()
.penaltyDeath();
StrictMode.setVmPolicy(b.build());
}
private void initAcra(boolean disableLogcatCollection) {
ACRAConfiguration conf = ACRA.getNewDefaultConfig(this);
conf.setFormUri(getString(R.string.build_conf_acra_url));
conf.setAdditionalSharedPreferences(new String[]{"glasuvalnik"});
conf.setAdditionalSharedPreferences(new String[]{"login prefs"});
conf.setExcludeMatchingSharedPreferencesKeys(new String[]{"^Username.*",
"^Password.*"});
KeyStore ks;
try {
ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(getResources().openRawResource(R.raw.forge_skeleton), getString(R.string.bks_keystore_password).toCharArray());
} catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException e) {
throw new AssertionError("Cannot initialize SSL cert for ACRA");
}
conf.setKeyStore(ks);
ACRA.init(this, conf);
}
@ForUnitTestsOnly
public ForgeAndroidTaskExecutor getForgeAndroidTaskExecutor() {
return mForgeAndroidTaskExecutor;
}
}
|
package com.hhua.android.producthunt.activities;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import com.hhua.android.producthunt.R;
import com.hhua.android.producthunt.fragments.ActivitiesFragment;
import com.hhua.android.producthunt.fragments.CollectionsFragment;
import com.hhua.android.producthunt.fragments.TechPostsFragment;
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawer;
private Toolbar toolbar;
private NavigationView nvDrawer;
private ActionBarDrawerToggle drawerToggle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Find our drawer view
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerToggle = setupDrawerToggle();
// Tie DrawerLayout events to the ActionBarToggle
mDrawer.setDrawerListener(drawerToggle);
// Find our drawer view
nvDrawer = (NavigationView) findViewById(R.id.nvView);
// Setup drawer view
setupDrawerContent(nvDrawer);
// Menu menu = nvDrawer.getMenu();
// MenuItem menuItem = menu.findItem(R.id.nav_switch);
// View actionView = MenuItemCompat.getActionView(menuItem);
// actionView.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// switch (item.getItemId()) {
// case android.R.id.home:
// mDrawer.openDrawer(GravityCompat.START);
// return true;
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
// Make sure this is the method with just `Bundle` as the signature
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
drawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
drawerToggle.onConfigurationChanged(newConfig);
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
selectDrawerItem(menuItem);
return true;
}
});
// Set up startup fragment
Class defaultFragmentClass = TechPostsFragment.class;
Fragment defaultFragment = null;
try {
defaultFragment = (Fragment) defaultFragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, defaultFragment).commit();
setTitle("Products");
}
public void selectDrawerItem(MenuItem menuItem) {
// Create a new fragment and specify the planet to show based on
// position
Fragment fragment = null;
Class fragmentClass;
switch(menuItem.getItemId()) {
case R.id.nav_first_fragment:
fragmentClass = TechPostsFragment.class;
break;
case R.id.nav_second_fragment:
fragmentClass = CollectionsFragment.class;
break;
case R.id.nav_third_fragment:
fragmentClass = ActivitiesFragment.class;
break;
default:
fragmentClass = TechPostsFragment.class;
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
// Highlight the selected item, update the title, and close the drawer
menuItem.setChecked(true);
setTitle(menuItem.getTitle());
mDrawer.closeDrawers();
}
private ActionBarDrawerToggle setupDrawerToggle() {
return new ActionBarDrawerToggle(this, mDrawer, toolbar, R.string.drawer_open, R.string.drawer_close);
}
}
|
package com.mikepenz.materialdrawer.app;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import com.mikepenz.google_material_typeface_library.GoogleMaterial;
import com.mikepenz.iconics.typeface.FontAwesome;
import com.mikepenz.materialdrawer.Drawer;
import com.mikepenz.materialdrawer.model.PrimaryDrawerItem;
import com.mikepenz.materialdrawer.model.SecondaryDrawerItem;
import com.mikepenz.materialdrawer.model.SectionDrawerItem;
import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem;
import com.mikepenz.materialdrawer.model.interfaces.Nameable;
public class SimpleDrawerActivity extends ActionBarActivity {
private Drawer.Result result = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
//supportRequestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample);
// Handle Toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
result = new Drawer()
.withActivity(this)
.withToolbar(toolbar)
.withActionBarDrawerToggle(true)
.addDrawerItems(
new PrimaryDrawerItem().withName(R.string.drawer_item_action_bar).withIcon(FontAwesome.Icon.faw_home).withIdentifier(1),
new PrimaryDrawerItem().withName(R.string.drawer_item_multi_drawer).withIcon(FontAwesome.Icon.faw_gamepad).withIdentifier(2),
new PrimaryDrawerItem().withName(R.string.drawer_item_non_translucent_status_drawer).withIcon(FontAwesome.Icon.faw_eye).withIdentifier(3),
new SectionDrawerItem().withName(R.string.drawer_item_section_header),
new SecondaryDrawerItem().withName(R.string.drawer_item_settings).withIcon(FontAwesome.Icon.faw_cog),
new SecondaryDrawerItem().withName(R.string.drawer_item_help).withIcon(FontAwesome.Icon.faw_question).setEnabled(false),
new SecondaryDrawerItem().withName(R.string.drawer_item_open_source).withIcon(GoogleMaterial.Icon.gmd_format_color_fill).withIdentifier(5),
new SecondaryDrawerItem().withName(R.string.drawer_item_contact).withIcon(FontAwesome.Icon.faw_bullhorn)
)
.withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id, IDrawerItem drawerItem) {
if (drawerItem instanceof Nameable) {
Toast.makeText(SimpleDrawerActivity.this, SimpleDrawerActivity.this.getString(((Nameable) drawerItem).getNameRes()), Toast.LENGTH_SHORT).show();
}
if (drawerItem.getIdentifier() == 1) {
Intent intent = new Intent(SimpleDrawerActivity.this, ActionBarDrawerActivity.class);
SimpleDrawerActivity.this.startActivity(intent);
} else if (drawerItem.getIdentifier() == 2) {
Intent intent = new Intent(SimpleDrawerActivity.this, MultiDrawerActivity.class);
SimpleDrawerActivity.this.startActivity(intent);
} else if (drawerItem.getIdentifier() == 3) {
Intent intent = new Intent(SimpleDrawerActivity.this, SimpleNonTranslucentDrawerActivity.class);
SimpleDrawerActivity.this.startActivity(intent);
}
}
})
.withSavedInstance(savedInstanceState)
.build();
result.setSelectionByIdentifier(5);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
outState = result.saveInstanceState(outState);
super.onSaveInstanceState(outState);
}
}
|
package com.noprestige.kanaquiz.questions;
import android.app.Application;
import android.content.Context;
import android.content.res.Resources;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import com.noprestige.kanaquiz.R;
import com.noprestige.kanaquiz.options.OptionsControl;
import com.noprestige.kanaquiz.options.QuestionSelectionItem;
import com.noprestige.kanaquiz.reference.ReferenceCell;
import com.noprestige.kanaquiz.reference.ReferenceTable;
import org.apmem.tools.layouts.FlowLayout;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class QuestionManagement
{
public static QuestionManagement HIRAGANA;
public static QuestionManagement KATAKANA;
public static QuestionManagement VOCABULARY;
private final int categoryCount;
private final Map<SetCode, Question[]> questionSets;
private final String[] prefIds;
private final String[] setTitles;
private final String[] setNoDiacriticsTitles;
public int getCategoryCount()
{
return categoryCount;
}
static class SetCode implements Comparable<SetCode>
{
final int number;
final Diacritic diacritic;
final String digraphs;
SetCode(int number, Diacritic diacritic, String digraphs)
{
this.number = number;
this.diacritic = diacritic;
this.digraphs = digraphs;
}
@Override
public int compareTo(SetCode o)
{
int returnValue = number - o.number;
if (returnValue == 0)
{
returnValue = diacritic.ordinal() - o.diacritic.ordinal();
if (returnValue == 0)
{
if ((digraphs == null) && (o.digraphs != null))
returnValue = 1;
else if ((digraphs != null) && (o.digraphs == null))
returnValue = -1;
else if ((digraphs != null) && (o.digraphs != null))
returnValue = digraphs.compareTo(o.digraphs);
}
}
return returnValue;
}
}
private Question[] getQuestionSet(int number, Diacritic diacritic, String digraphs)
{
return questionSets.get(new SetCode(number, diacritic, digraphs));
}
public String getPrefId(int number)
{
return prefIds[number - 1];
}
public CharSequence getSetTitle(int number)
{
return getSetTitle(number, OptionsControl.getBoolean(R.string.prefid_diacritics));
}
private CharSequence getSetTitle(int number, boolean isDiacriticsActive)
{
return (isDiacriticsActive || (setNoDiacriticsTitles[number - 1] == null)) ? setTitles[number - 1] :
setNoDiacriticsTitles[number - 1];
}
public QuestionManagement(int xmlRefId, Resources resources)
{
Map<SetCode, Question[]> questionSetList = new TreeMap<>();
List<String> prefIdList = new ArrayList<>();
List<String> setTitleList = new ArrayList<>();
List<String> setNoDiacriticsTitleList = new ArrayList<>();
XmlParser.parseXmlDocument(xmlRefId, resources, questionSetList, prefIdList, setTitleList,
setNoDiacriticsTitleList);
categoryCount = prefIdList.size();
questionSets = questionSetList;
prefIds = prefIdList.toArray(new String[0]);
setTitles = setTitleList.toArray(new String[0]);
setNoDiacriticsTitles = setNoDiacriticsTitleList.toArray(new String[0]);
}
public static void initialize(Application context)
{
if (HIRAGANA == null)
HIRAGANA = new QuestionManagement(R.xml.hiragana, context.getResources());
if (KATAKANA == null)
KATAKANA = new QuestionManagement(R.xml.katakana, context.getResources());
if (VOCABULARY == null)
VOCABULARY = new QuestionManagement(R.xml.vocabulary, context.getResources());
}
private static QuestionBank questionBank;
private static boolean[] prefRecord;
public static void refreshStaticQuestionBank()
{
if ((prefRecord == null) || (questionBank == null))
{
prefRecord = getCurrentPrefRecord();
questionBank = getFullQuestionBank();
questionBank.newQuestion();
}
else
{
boolean[] currentPrefRecord = getCurrentPrefRecord();
//TODO: Add something to handle repetition control changes so we can update the previousQuestion record
if (!Arrays.equals(prefRecord, currentPrefRecord))
{
prefRecord = currentPrefRecord;
questionBank = getFullQuestionBank();
questionBank.newQuestion();
}
}
}
private static boolean[] getCurrentPrefRecord()
{
boolean[] currentPrefRecord =
new boolean[HIRAGANA.getCategoryCount() + KATAKANA.getCategoryCount() + VOCABULARY.getCategoryCount() +
2];
currentPrefRecord[0] = OptionsControl.getBoolean(R.string.prefid_digraphs);
currentPrefRecord[1] = OptionsControl.getBoolean(R.string.prefid_diacritics);
int i = 2;
for (int j = 1; j <= HIRAGANA.getCategoryCount(); j++)
{
currentPrefRecord[i] = HIRAGANA.getPref(j);
i++;
}
for (int j = 1; j <= KATAKANA.getCategoryCount(); j++)
{
currentPrefRecord[i] = KATAKANA.getPref(j);
i++;
}
for (int j = 1; j <= VOCABULARY.getCategoryCount(); j++)
{
currentPrefRecord[i] = VOCABULARY.getPref(j);
i++;
}
return currentPrefRecord;
}
public static QuestionBank getStaticQuestionBank()
{
return questionBank;
}
public static QuestionBank getFullQuestionBank()
{
QuestionBank bank = new QuestionBank();
HIRAGANA.buildQuestionBank(bank);
KATAKANA.buildQuestionBank(bank);
VOCABULARY.buildQuestionBank(bank);
return bank;
}
public boolean getPref(int number)
{
return OptionsControl.getBoolean(getPrefId(number));
}
public QuestionBank getQuestionBank()
{
QuestionBank questionBank = new QuestionBank();
buildQuestionBank(questionBank);
return questionBank;
}
public void buildQuestionBank(QuestionBank questionBank)
{
boolean isDigraphs = OptionsControl.getBoolean(R.string.prefid_digraphs) && getPref(9);
boolean isDiacritics = OptionsControl.getBoolean(R.string.prefid_diacritics);
for (int i = 1; i <= getCategoryCount(); i++)
if (getPref(i))
{
questionBank.addQuestions(getQuestionSet(i, Diacritic.NO_DIACRITIC, null));
if (isDiacritics)
{
questionBank.addQuestions(getQuestionSet(i, Diacritic.DAKUTEN, null));
questionBank.addQuestions(getQuestionSet(i, Diacritic.HANDAKUTEN, null));
}
if (isDigraphs)
{
questionBank.addQuestions(getQuestionSet(i, Diacritic.NO_DIACRITIC, getPrefId(9)));
if (isDiacritics)
{
questionBank.addQuestions(getQuestionSet(i, Diacritic.DAKUTEN, getPrefId(9)));
questionBank.addQuestions(getQuestionSet(i, Diacritic.HANDAKUTEN, getPrefId(9)));
}
}
questionBank.addQuestions(getQuestionSet(i, Diacritic.CONSONANT, null));
}
}
public boolean anySelected()
{
for (int i = 1; i <= getCategoryCount(); i++)
if (getPref(i))
return true;
return false;
}
public boolean diacriticsSelected()
{
if (OptionsControl.getBoolean(R.string.prefid_diacritics))
for (int i = 1; i <= getCategoryCount(); i++)
if (getPref(i) && ((getQuestionSet(i, Diacritic.DAKUTEN, null) != null) ||
(getQuestionSet(i, Diacritic.HANDAKUTEN, null) != null)))
return true;
return false;
}
public boolean digraphsSelected()
{
if (OptionsControl.getBoolean(R.string.prefid_digraphs) && getPref(9))
for (int i = 1; i <= getCategoryCount(); i++)
if (getPref(i) && (getQuestionSet(i, Diacritic.NO_DIACRITIC, getPrefId(9)) != null))
return true;
return false;
}
public boolean diacriticDigraphsSelected()
{
if (OptionsControl.getBoolean(R.string.prefid_diacritics) &&
OptionsControl.getBoolean(R.string.prefid_digraphs) && getPref(9))
for (int i = 1; i <= getCategoryCount(); i++)
if (getPref(i) && ((getQuestionSet(i, Diacritic.DAKUTEN, getPrefId(9)) != null) ||
(getQuestionSet(i, Diacritic.HANDAKUTEN, getPrefId(9)) != null)))
return true;
return false;
}
private String getQuestionSetDisplay(int setNumber, Diacritic diacritic)
{
StringBuilder returnValue = new StringBuilder();
Question[] questionSet = getQuestionSet(setNumber, diacritic, null);
if (questionSet != null)
for (Question question : questionSet)
if (question.getClass().equals(KanaQuestion.class))
{
returnValue.append(question.getQuestionText());
if (questionSet.length <= 10)
returnValue.append('\u00A0');
else
returnValue.append(' ');
}
else if (question.getClass().equals(WordQuestion.class))
{
returnValue.append(question.fetchCorrectAnswer().replace(' ', '\u00A0'));
returnValue.append(", ");
}
if (returnValue.length() > 1)
returnValue.setCharAt(returnValue.length() - 1, ' ');
return returnValue.toString();
}
private CharSequence displayContents(int setNumber)
{
boolean isDiacritics = OptionsControl.getBoolean(R.string.prefid_diacritics);
StringBuilder returnValue = new StringBuilder(getQuestionSetDisplay(setNumber, Diacritic.NO_DIACRITIC));
if (isDiacritics)
{
returnValue.append(getQuestionSetDisplay(setNumber, Diacritic.DAKUTEN));
returnValue.append(getQuestionSetDisplay(setNumber, Diacritic.HANDAKUTEN));
}
returnValue.append(getQuestionSetDisplay(setNumber, Diacritic.CONSONANT));
if (returnValue.codePointAt(returnValue.length() - 2) == ',')
returnValue.deleteCharAt(returnValue.length() - 2);
return returnValue.toString();
}
public ReferenceTable getMainReferenceTable(Context context)
{
ReferenceTable table = new ReferenceTable(context);
boolean isFullReference = OptionsControl.getBoolean(R.string.prefid_full_reference);
for (int i = 1; i <= 7; i++)
if (isFullReference || getPref(i))
table.addView(ReferenceCell.buildRow(context, getQuestionSet(i, Diacritic.NO_DIACRITIC, null)));
if (isFullReference || getPref(9))
table.addView(ReferenceCell.buildSpecialRow(context, getQuestionSet(9, Diacritic.NO_DIACRITIC, null)));
if (isFullReference || getPref(8))
table.addView(ReferenceCell.buildRow(context, getQuestionSet(8, Diacritic.NO_DIACRITIC, null)));
if (isFullReference || getPref(10))
{
table.addView(ReferenceCell.buildSpecialRow(context, getQuestionSet(10, Diacritic.NO_DIACRITIC, null)));
table.addView(ReferenceCell.buildSpecialRow(context, getQuestionSet(10, Diacritic.CONSONANT, null)));
}
return table;
}
public ReferenceTable getDiacriticReferenceTable(Context context)
{
ReferenceTable table = new ReferenceTable(context);
boolean isFullReference = OptionsControl.getBoolean(R.string.prefid_full_reference);
for (int i = 1; i <= getCategoryCount(); i++)
if (isFullReference || getPref(i))
{
table.addView(ReferenceCell.buildRow(context, getQuestionSet(i, Diacritic.DAKUTEN, null)));
table.addView(ReferenceCell.buildRow(context, getQuestionSet(i, Diacritic.HANDAKUTEN, null)));
}
return table;
}
public ReferenceTable getMainDigraphsReferenceTable(Context context)
{
ReferenceTable table = new ReferenceTable(context);
boolean isFullReference = OptionsControl.getBoolean(R.string.prefid_full_reference);
for (int i = 1; i <= getCategoryCount(); i++)
if (isFullReference || getPref(i))
table.addView(ReferenceCell.buildRow(context, getQuestionSet(i, Diacritic.NO_DIACRITIC, getPrefId(9))));
return table;
}
public ReferenceTable getDiacriticDigraphsReferenceTable(Context context)
{
ReferenceTable table = new ReferenceTable(context);
boolean isFullReference = OptionsControl.getBoolean(R.string.prefid_full_reference);
for (int i = 1; i <= getCategoryCount(); i++)
if (isFullReference || getPref(i))
{
table.addView(ReferenceCell.buildRow(context, getQuestionSet(i, Diacritic.DAKUTEN, getPrefId(9))));
table.addView(ReferenceCell.buildRow(context, getQuestionSet(i, Diacritic.HANDAKUTEN, getPrefId(9))));
}
return table;
}
public View getVocabReferenceTable(Context context, int setNumber)
{
FlowLayout layout = new FlowLayout(context);
layout.setGravity(Gravity.FILL);
Question[] questionSet = getQuestionSet(setNumber, Diacritic.NO_DIACRITIC, null);
int padding = context.getResources().getDimensionPixelSize(R.dimen.vocabReferenceCellHorizontalPadding);
for (Question question : questionSet)
{
ReferenceCell cell = question.generateReference(context);
cell.setPadding(padding, 0, padding, 0);
layout.addView(cell);
}
return layout;
}
public LinearLayout getSelectionScreen(Context context)
{
LinearLayout layout = new LinearLayout(context);
layout.setLayoutParams(
new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
layout.setOrientation(LinearLayout.VERTICAL);
for (int i = 1; i <= getCategoryCount(); i++)
{
QuestionSelectionItem item = new QuestionSelectionItem(context);
item.setTitle(getSetTitle(i));
item.setContents(displayContents(i));
item.setPrefId(getPrefId(i));
layout.addView(item);
}
return layout;
}
}
|
package com.noprestige.kanaquiz.questions;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.XmlResourceParser;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import com.noprestige.kanaquiz.R;
import com.noprestige.kanaquiz.options.KanaSelectionItem;
import com.noprestige.kanaquiz.options.OptionsControl;
import com.noprestige.kanaquiz.reference.ReferenceCell;
import com.noprestige.kanaquiz.reference.ReferenceTable;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
public abstract class QuestionManagement
{
private boolean isInitialized = false;
private int categoryCount = 0;
private KanaQuestion[][][][] kanaSets = new KanaQuestion[][][][]{};
private String[] prefIds = new String[]{};
private String[] setTitles = new String[]{};
private String[] setNoDiacriticsTitles = new String[]{};
private int getCategoryCount()
{
return categoryCount;
}
private KanaQuestion[] getKanaSet(int number, Diacritic diacritic, boolean isDigraphs) //TODO: Clean this up
{
try
{
return kanaSets[number - 1][diacritic.ordinal()][isDigraphs ? 1 : 0];
}
catch (ArrayIndexOutOfBoundsException ex)
{
return null;
}
}
private String getPrefId(int number)
{
try
{
return prefIds[number - 1];
}
catch (ArrayIndexOutOfBoundsException ex)
{
return null;
}
}
private String getSetTitle(int number)
{
try
{
return OptionsControl.getBoolean(R.string.prefid_diacritics) ?
setTitles[number - 1] : setNoDiacriticsTitles[number - 1];
}
catch (ArrayIndexOutOfBoundsException ex)
{
return null;
}
}
protected static void parseXml(XmlResourceParser xrp, Resources resources, QuestionManagement singletonObject)
{
if (!singletonObject.isInitialized)
{
ArrayList<KanaQuestion[][][]> kanaSetList = new ArrayList<>();
ArrayList<String> prefIdList = new ArrayList<>();
ArrayList<String> setTitleList = new ArrayList<>();
ArrayList<String> setNoDiacriticsTitleList = new ArrayList<>();
try
{
for (int eventType = xrp.getEventType(); eventType != XmlPullParser.END_DOCUMENT; eventType = xrp.next())
{
if (eventType == XmlPullParser.START_TAG && xrp.getName().equalsIgnoreCase("KanaSet"))
{
XmlParser.parseXmlKanaSet(xrp, resources, kanaSetList, prefIdList, setTitleList, setNoDiacriticsTitleList);
}
}
singletonObject.categoryCount = kanaSetList.size();
singletonObject.kanaSets = new KanaQuestion[singletonObject.categoryCount][][][];
kanaSetList.toArray(singletonObject.kanaSets);
singletonObject.prefIds = new String[singletonObject.categoryCount];
prefIdList.toArray(singletonObject.prefIds);
singletonObject.setTitles = new String[singletonObject.categoryCount];
setTitleList.toArray(singletonObject.setTitles);
singletonObject.setNoDiacriticsTitles = new String[singletonObject.categoryCount];
setNoDiacriticsTitleList.toArray(singletonObject.setNoDiacriticsTitles);
singletonObject.isInitialized = true;
}
catch (XmlPullParserException | IOException | ParseException ex)
{
}
}
}
public static void initialize(Context context)
{
Hiragana.initialize(context);
Katakana.initialize(context);
}
public static KanaQuestionBank getFullQuestionBank()
{
KanaQuestionBank bank = new KanaQuestionBank();
Hiragana.QUESTIONS.buildQuestionBank(bank);
Katakana.QUESTIONS.buildQuestionBank(bank);
return bank;
}
private boolean getPref(int number)
{
return OptionsControl.getBoolean(getPrefId(number));
}
public KanaQuestionBank getQuestionBank()
{
KanaQuestionBank questionBank = new KanaQuestionBank();
buildQuestionBank(questionBank);
return questionBank;
}
public void buildQuestionBank(KanaQuestionBank questionBank)
{
boolean isDigraphs = OptionsControl.getBoolean(R.string.prefid_digraphs) && getPref(9);
boolean isDiacritics = OptionsControl.getBoolean(R.string.prefid_diacritics);
for (int i = 1; i <= getCategoryCount(); i++)
if (getPref(i))
{
questionBank.addQuestions(getKanaSet(i, Diacritic.NO_DIACRITIC, false));
if (isDiacritics)
{
questionBank.addQuestions(getKanaSet(i, Diacritic.DAKUTEN, false));
questionBank.addQuestions(getKanaSet(i, Diacritic.HANDAKUTEN, false));
}
if (isDigraphs)
{
questionBank.addQuestions(getKanaSet(i, Diacritic.NO_DIACRITIC, true));
if (isDiacritics)
{
questionBank.addQuestions(getKanaSet(i, Diacritic.DAKUTEN, true));
questionBank.addQuestions(getKanaSet(i, Diacritic.HANDAKUTEN, true));
}
}
questionBank.addQuestions(getKanaSet(i, Diacritic.CONSONANT, false));
}
}
public boolean anySelected()
{
for (int i = 1; i <= getCategoryCount(); i++)
if (getPref(i))
return true;
return false;
}
public boolean diacriticsSelected()
{
if (OptionsControl.getBoolean(R.string.prefid_diacritics))
for (int i = 1; i <= getCategoryCount(); i++)
if (getPref(i) &&
(getKanaSet(i, Diacritic.DAKUTEN, false) != null ||
getKanaSet(i, Diacritic.HANDAKUTEN, false) != null))
return true;
return false;
}
public boolean digraphsSelected()
{
if (OptionsControl.getBoolean(R.string.prefid_digraphs) && getPref(9))
for (int i = 1; i <= getCategoryCount(); i++)
if (getPref(i) &&
(getKanaSet(i, Diacritic.NO_DIACRITIC, true) != null))
return true;
return false;
}
public boolean diacriticDigraphsSelected()
{
if (OptionsControl.getBoolean(R.string.prefid_diacritics) &&
OptionsControl.getBoolean(R.string.prefid_digraphs) && getPref(9))
for (int i = 1; i <= getCategoryCount(); i++)
if (getPref(i) &&
(getKanaSet(i, Diacritic.DAKUTEN, true) != null ||
getKanaSet(i, Diacritic.HANDAKUTEN, true) != null))
return true;
return false;
}
private String getKanaSetDisplay(int setNumber, Diacritic diacritic)
{
StringBuilder returnValue = new StringBuilder();
KanaQuestion[] kanaSet = getKanaSet(setNumber, diacritic, false);
if (kanaSet != null)
for (KanaQuestion question : kanaSet)
returnValue.append(question.getKana() + " ");
return returnValue.toString();
}
private String displayContents(int setNumber)
{
boolean isDiacritics = OptionsControl.getBoolean(R.string.prefid_diacritics);
StringBuilder returnValue = new StringBuilder(getKanaSetDisplay(setNumber, Diacritic.NO_DIACRITIC));
if (isDiacritics)
{
returnValue.append(getKanaSetDisplay(setNumber, Diacritic.DAKUTEN));
returnValue.append(getKanaSetDisplay(setNumber, Diacritic.HANDAKUTEN));
}
returnValue.append(getKanaSetDisplay(setNumber, Diacritic.CONSONANT));
return returnValue.toString();
}
public ReferenceTable getMainReferenceTable(Context context)
{
ReferenceTable table = new ReferenceTable(context);
boolean isFullReference = OptionsControl.getBoolean(R.string.prefid_full_reference);
for (int i = 1; i <= 7; i++)
if (isFullReference || getPref(i))
table.addView(ReferenceCell.buildRow(context, getKanaSet(i, Diacritic.NO_DIACRITIC, false)));
if (isFullReference || getPref(9))
table.addView(ReferenceCell.buildSpecialRow(context, getKanaSet(9, Diacritic.NO_DIACRITIC, false)));
if (isFullReference || getPref(8))
table.addView(ReferenceCell.buildRow(context, getKanaSet(8, Diacritic.NO_DIACRITIC, false)));
if (isFullReference || getPref(10))
{
table.addView(ReferenceCell.buildSpecialRow(context, getKanaSet(10, Diacritic.NO_DIACRITIC, false)));
table.addView(ReferenceCell.buildSpecialRow(context, getKanaSet(10, Diacritic.CONSONANT, false)));
}
return table;
}
public ReferenceTable getDiacriticReferenceTable(Context context)
{
ReferenceTable table = new ReferenceTable(context);
boolean isFullReference = OptionsControl.getBoolean(R.string.prefid_full_reference);
for (int i = 1; i <= getCategoryCount(); i++)
if (isFullReference || getPref(i))
{
table.addView(ReferenceCell.buildRow(context, getKanaSet(i, Diacritic.DAKUTEN, false)));
table.addView(ReferenceCell.buildRow(context, getKanaSet(i, Diacritic.HANDAKUTEN, false)));
}
return table;
}
public ReferenceTable getMainDigraphsReferenceTable(Context context)
{
ReferenceTable table = new ReferenceTable(context);
boolean isFullReference = OptionsControl.getBoolean(R.string.prefid_full_reference);
for (int i = 1; i <= getCategoryCount(); i++)
if (isFullReference || getPref(i))
table.addView(ReferenceCell.buildRow(context, getKanaSet(i, Diacritic.NO_DIACRITIC, true)));
return table;
}
public ReferenceTable getDiacriticDigraphsReferenceTable(Context context)
{
ReferenceTable table = new ReferenceTable(context);
boolean isFullReference = OptionsControl.getBoolean(R.string.prefid_full_reference);
for (int i = 1; i <= getCategoryCount(); i++)
if (isFullReference || getPref(i))
{
table.addView(ReferenceCell.buildRow(context, getKanaSet(i, Diacritic.DAKUTEN, true)));
table.addView(ReferenceCell.buildRow(context, getKanaSet(i, Diacritic.HANDAKUTEN, true)));
}
return table;
}
public LinearLayout getSelectionScreen(Context context)
{
LinearLayout layout = new LinearLayout(context);
layout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
layout.setOrientation(LinearLayout.VERTICAL);
for (int i = 1; i <= getCategoryCount(); i++)
{
KanaSelectionItem item = new KanaSelectionItem(context);
item.setTitle(getSetTitle(i));
item.setContents(displayContents(i));
item.setPrefId(getPrefId(i));
layout.addView(item);
}
return layout;
}
}
|
package com.planyourexchange.fragments.base;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.planyourexchange.R;
import com.planyourexchange.rest.model.BaseModel;
import com.planyourexchange.utils.Constants;
import com.planyourexchange.utils.InternationalNames;
import java.io.Serializable;
import java.util.Collections;
import java.util.List;
// -- Base model for handling information between fragments that share enormous similarities
public abstract class ListViewFragment<Key extends Serializable, Model extends List<BaseModel>, ModelView extends ListView> extends AbstractBaseFragment<Key, Model, ModelView> {
private final Fragment nextScreen;
// -- Need to be called by overriding class
protected ListViewFragment(final int titleName, final int inflateLayout, final int drawLayout, final Fragment nextScreen) {
super(titleName,inflateLayout,drawLayout);
this.nextScreen = nextScreen;
}
@Override
protected void drawModel(final Model modelList, ModelView modelView) {
// -- Sort Results Alphabetically by default
Collections.sort(modelList);
// -- Handle Model rendering
modelView.setAdapter(new ArrayAdapter<BaseModel>(getActivity(),R.layout.model_list,modelList) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) getLayoutInflater(null);
View rowView = inflater.inflate(R.layout.model_list,null,true);
BaseModel model = modelList.get(position);
ImageView imageView = (ImageView) rowView.findViewById(R.id.model_list_icon);
TextView textView = (TextView) rowView.findViewById(R.id.model_list_name);
ImageLoader.getInstance().displayImage(model.getIcon(), imageView);
textView.setText(InternationalNames.getInternationalName(getContext(),model.getName()));
return rowView;
}
});
// -- Handle onClick events
modelView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
BaseModel model = modelList.get(position);
Bundle bundle = new Bundle();
bundle.putSerializable(KEY_ID, createNextKey(model));
nextScreen.setArguments(bundle);
// -- Notify any Listener attached
notifyListener(bundle);
// -- Analytics click event for model
tracker.send(new HitBuilders.EventBuilder()
.setCategory(Constants.CATEGORY_NAVIGATION)
.setAction(Constants.ACTION_CLICK_ON_MODEL)
.setLabel(model.getName())
.build());
// -- Creating transaction and adding to back stack navigation
getFragmentManager().beginTransaction()
.replace(R.id.fragment_container, nextScreen)
.addToBackStack(null)
.commit();
}
});
// -- Notify that new data has arrived
modelView.deferNotifyDataSetChanged();
}
// -- Defaults to NO ACTION
protected void notifyListener(Bundle bundle) {
}
// -- Default is the model id as key
protected Serializable createNextKey(BaseModel model) {
return model.getId();
}
}
|
package com.qurux.coffeevizbeer.exceptions;
public class NullUserException extends Exception {
public NullUserException() {
super("Your details are not loaded yet");
}
}
|
package com.sashavarlamov.soldier_android;
import android.content.Intent;
import android.content.res.Resources;
import android.location.Location;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class AdminLobbyActivity extends LobbyActivity implements OnMapReadyCallback {
private Button startGameButton = null;
private Intent intent = null;
private MapFragment map = null;
private Marker teamOnePin = null;
private Marker teamTwoPin = null;
private boolean firstUpdate = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
intent = getIntent();
setContentView(R.layout.activity_admin_lobby);
startGameButton = (Button)findViewById(R.id.start_game_button);
// TODO: Get actual data from the intent
setPlayerCount(0);
map = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
map.getMapAsync(this);
System.out.println(map);
initTeamNames(intent.getStringExtra("teamOneName"), intent.getStringExtra("teamTwoName"));
}
public static void startGame(View view){
// TODO: Start a new game
System.out.println("Starting game...");
}
public void setPlayerCount(int i){
Resources res = getResources();
startGameButton.setText(res.getQuantityString(R.plurals.start_with_player_count, i, i));
if(i == 0){
startGameButton.setClickable(false);
} else{
startGameButton.setClickable(true);
}
}
public void onMapReady(GoogleMap m) {
System.out.println("Map is ready");
map.getMap().setMyLocationEnabled(true);
map.getMap().setMapType(GoogleMap.MAP_TYPE_SATELLITE);
map.getMap().setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
@Override
public void onMyLocationChange(Location arg0) {
if (firstUpdate) {
LatLng cur_Latlng = new LatLng(arg0.getLatitude(), arg0.getLongitude());
map.getMap().moveCamera(CameraUpdateFactory.newLatLng(cur_Latlng));
map.getMap().animateCamera(CameraUpdateFactory.zoomTo(16));
initPins(cur_Latlng, "Team One", "Team Two");
firstUpdate = false;
}
}
});
//map.getMap().moveCamera(new CameraUpdate());
}
private void initPins(LatLng ll, String t1, String t2){
LatLng llOne = new LatLng(ll.latitude + 0.001, ll.longitude);
teamOnePin = this.map.getMap().addMarker(new MarkerOptions().position(llOne).draggable(true).title(t1));
LatLng llTwo = new LatLng(ll.latitude - 0.001, ll.longitude);
teamTwoPin = this.map.getMap().addMarker(new MarkerOptions().position(llTwo).draggable(true).title(t2));
}
private void initTeamNames(String t1, String t2){
EditText teamOneB = (EditText)findViewById(R.id.team_one_text);
teamOneB.setText(t1);
EditText teamTwoB = (EditText)findViewById(R.id.team_two_text);
teamTwoB.setText(t2);
}
@Override
public void onBackPressed() {
System.out.println("Going Back");
cancelGame(null);
Intent intent = new Intent(this, DecisionActivity.class);
intent.putExtra("username", this.intent.getStringExtra("username"));
startActivity(intent);
}
public void cancelGame(View view){
// Cancel the game
SocketUtil.endGame();
System.out.println("Ended the Game");
}
}
|
package info.longlost.stockoverflow;
import android.content.Context;
import android.database.Cursor;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.SimpleCursorTreeAdapter;
import android.widget.Toast;
import info.longlost.stockoverflow.data.StockContract.PortfolioEntry;
import info.longlost.stockoverflow.data.StockContract.StockEntry;
import info.longlost.stockoverflow.data.StockContract.PortfolioStockMap;
import info.longlost.stockoverflow.util.FilterCursor;
import info.longlost.stockoverflow.util.SimpleEqualsFilter;
public class NavigationDrawerFragment extends Fragment implements
LoaderManager.LoaderCallbacks<Cursor> {
/**
* Remember the position of the selected item.
*/
private static final String STATE_SELECTED_PORTFOLIO_ID = "selected_portfolio_id";
private static final String STATE_SELECTED_STOCK_ID = "selected_stock_id";
/**
* Per the design guidelines, you should show the drawer on launch until the user manually
* expands it. This shared preference tracks this.
*/
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
private static final int PORTFOLIO_LOADER = 100;
private static final int STOCK_MAP_LOADER = 200;
/**
* A pointer to the current callbacks instance (the Activity).
*/
private NavigationDrawerCallbacks mCallbacks;
/**
* Helper component that ties the action bar to the navigation drawer.
*/
private ActionBarDrawerToggle mDrawerToggle;
private Cursor mPortfolioCursor;
private Cursor mStocksMapCursor;
private DrawerLayout mDrawerLayout;
private ExpandableListView mDrawerListView;
private SimpleCursorTreeAdapter mDrawerListAdapter;
private View mFragmentContainerView;
private long mSelectedPortfolioId = -1;
private long mSelectedStockId = -1;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
public NavigationDrawerFragment() {}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Read in the flag indicating whether or not the user has demonstrated awareness of the
// drawer. See PREF_USER_LEARNED_DRAWER for details.
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
long selectedPortfolioId = -1;
long selectedStockId = -1;
if (savedInstanceState != null) {
selectedPortfolioId = savedInstanceState.getLong(STATE_SELECTED_PORTFOLIO_ID, -1);
selectedStockId = savedInstanceState.getLong(STATE_SELECTED_STOCK_ID, -1);
mFromSavedInstanceState = true;
}
// Select either the default item (0) or the last selected item.
updateSelection(selectedPortfolioId, selectedStockId);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Indicate that this fragment would like to influence the set of actions in the action bar.
setHasOptionsMenu(true);
getLoaderManager().initLoader(PORTFOLIO_LOADER, null, this);
getLoaderManager().initLoader(STOCK_MAP_LOADER, null, this);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mDrawerListView = (ExpandableListView) inflater.inflate(
R.layout.fragment_navigation_drawer, container, false);
mDrawerListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
@Override
public boolean onGroupClick(ExpandableListView parent, View v, int portfolioPos, long portfolioId) {
setSelection(portfolioId, portfolioPos, -1, -1);
// return false so that the ExpandableListView handles expanding / collapsing.
return false;
}
});
mDrawerListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
@Override
public boolean onChildClick(ExpandableListView parent, View v, int portfolioPos, int stockPos, long stockMapId) {
int flatListPos =
parent.getFlatListPosition(
ExpandableListView.getPackedPositionForGroup(portfolioPos));
long portfolioId = parent.getItemIdAtPosition(flatListPos);
setSelection(portfolioId, portfolioPos, stockMapId, stockPos);
return true;
}
});
mDrawerListAdapter = new SimpleCursorTreeAdapter(this.getActivity(), null,
android.R.layout.simple_list_item_1,
android.R.layout.simple_list_item_activated_1,
new String[] {PortfolioEntry.COLUMN_PORTFOLIO_NAME},
new int[] {android.R.id.text1},
android.R.layout.simple_list_item_1,
android.R.layout.simple_list_item_1,
new String[] {StockEntry.COLUMN_TICKER},
new int[] {android.R.id.text1}) {
@Override
protected Cursor getChildrenCursor(Cursor groupCursor) { return null; }
};
mDrawerListView.setAdapter(mDrawerListAdapter);
return mDrawerListView;
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
/**
* Users of this fragment must call this method to set up the navigation drawer interactions.
*
* @param fragmentId The android:id of this fragment in its activity's layout.
* @param drawerLayout The DrawerLayout containing this fragment's UI.
*/
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the navigation drawer and the action bar app icon.
mDrawerToggle = new ActionBarDrawerToggle(
getActivity(), /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.navigation_drawer_open, /* "open drawer" description for accessibility */
R.string.navigation_drawer_close /* "close drawer" description for accessibility */
) {
@Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
@Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
if (!mUserLearnedDrawer) {
// The user manually opened the drawer; store this flag to prevent auto-showing
// the navigation drawer automatically in the future.
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
// If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
// per the navigation drawer design guidelines.
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
@Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void updateSelection(long selectedPortfolioId, long selectedStockId) {
int portfolioPos = -1;
int stockPos = -1;
// Validate selected portfolio and stock IDs.
// Set the position values based on the selected IDs.
if (mPortfolioCursor != null && mPortfolioCursor.getCount() > 0) {
Cursor portfolioCursor = mDrawerListAdapter.getCursor();
int portfolioIdIdx = portfolioCursor.getColumnIndex(PortfolioEntry._ID);
for (portfolioCursor.moveToFirst(); !portfolioCursor.isAfterLast(); portfolioCursor.moveToNext()) {
if (portfolioCursor.getLong(portfolioIdIdx) == selectedPortfolioId) {
portfolioPos = portfolioCursor.getPosition();
break;
}
}
if (portfolioPos < 0) {
// selectedPortfolioId does not exist in the cursor.
// Select the first portfolio and reset the selected stock
mPortfolioCursor.moveToFirst();
selectedPortfolioId = mPortfolioCursor.getLong(portfolioIdIdx);
portfolioPos = 0;
selectedStockId = -1;
} else if (mStocksMapCursor != null && mStocksMapCursor.getCount() > 0 && selectedStockId >= 0) {
int childCount = mDrawerListAdapter.getChildrenCount(portfolioPos);
for (int i = 0; i < childCount; i++) {
Cursor child = mDrawerListAdapter.getChild(portfolioPos, i);
int stockIdIdx = child.getColumnIndex(PortfolioStockMap._ID);
if (child.getLong(stockIdIdx) == selectedStockId) {
stockPos = i;
break;
}
}
}
}
setSelection(selectedPortfolioId, portfolioPos, selectedStockId, stockPos);
}
private void setSelection(long selectedPortfolioId,
int selectedPortfolioPos,
long selectedStockId,
int selectedStockPos) {
// update checked item if possible
if (mDrawerListView != null) {
int flatPos;
if (selectedStockId >= 0) {
flatPos = mDrawerListView.getFlatListPosition(
ExpandableListView.getPackedPositionForChild(selectedPortfolioPos,
selectedStockPos));
} else {
flatPos = mDrawerListView.getFlatListPosition(
ExpandableListView.getPackedPositionForGroup(selectedPortfolioPos));
}
mDrawerListView.setItemChecked(flatPos, true);
}
// close drawer if possible
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
// callback if necessary
if (mCallbacks != null) {
if (selectedStockId >= 0 && selectedStockId != mSelectedStockId) {
mCallbacks.onStockSelected(selectedStockId);
} else if (selectedStockId < 0 &&
selectedPortfolioId >= 0 &&
selectedPortfolioId != mSelectedPortfolioId) {
mCallbacks.onPortfolioSelected(selectedPortfolioId);
}
}
// update member variables
mSelectedPortfolioId = selectedPortfolioId;
mSelectedStockId = selectedStockId;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
@Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putLong(STATE_SELECTED_PORTFOLIO_ID, mSelectedPortfolioId);
outState.putLong(STATE_SELECTED_STOCK_ID, mSelectedStockId);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
mDrawerToggle.onConfigurationChanged(newConfig);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// If the drawer is open, show the global app actions in the action bar. See also
// showGlobalContextActionBar, which controls the top-left area of the action bar.
if (mDrawerLayout != null && isDrawerOpen()) {
inflater.inflate(R.menu.global, menu);
showGlobalContextActionBar();
}
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
if (item.getItemId() == R.id.action_example) {
Toast.makeText(getActivity(), "Example action.", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Per the navigation drawer design guidelines, updates the action bar to show the global app
* 'context', rather than just what's in the current screen.
*/
private void showGlobalContextActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setTitle(R.string.app_name);
}
private ActionBar getActionBar() {
return ((ActionBarActivity) getActivity()).getSupportActionBar();
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
switch (id) {
case PORTFOLIO_LOADER:
return new CursorLoader(getActivity(),
PortfolioEntry.CONTENT_URI,
new String[] {
PortfolioEntry._ID,
PortfolioEntry.COLUMN_PORTFOLIO_NAME
},
null,
null,
null);
case STOCK_MAP_LOADER:
return new CursorLoader(getActivity(),
PortfolioStockMap.CONTENT_URI,
new String[] {
PortfolioStockMap._ID,
PortfolioStockMap.COLUMN_PORTFOLIO_ID,
PortfolioStockMap.COLUMN_STOCK_ID,
StockEntry.COLUMN_TICKER
},
null,
null,
PortfolioStockMap.COLUMN_PORTFOLIO_ID + " ASC");
default:
return null;
}
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
switch (loader.getId()) {
case PORTFOLIO_LOADER:
mPortfolioCursor = data;
mDrawerListAdapter.setGroupCursor(data);
if (mStocksMapCursor != null) {
setStockCursors(mPortfolioCursor, mStocksMapCursor);
// defer this to the message loop
mDrawerLayout.post(new Runnable() {
@Override
public void run() {
updateSelection(mSelectedPortfolioId, mSelectedStockId);
}
});
}
break;
case STOCK_MAP_LOADER:
mStocksMapCursor = data;
if (mPortfolioCursor != null) {
setStockCursors(mPortfolioCursor, mStocksMapCursor);
// defer this to the message loop
mDrawerLayout.post(new Runnable() {
@Override
public void run() {
updateSelection(mSelectedPortfolioId, mSelectedStockId);
}
});
}
break;
}
}
private void setStockCursors(Cursor portfolioCursor, Cursor stocksCursor) {
int pos = 0;
long portfolioId;
int columnIdx = portfolioCursor.getColumnIndex(PortfolioEntry._ID);
for (portfolioCursor.moveToFirst(); !portfolioCursor.isAfterLast(); portfolioCursor.moveToNext()) {
portfolioId = portfolioCursor.getLong(columnIdx);
mDrawerListAdapter.setChildrenCursor(pos, new FilterCursor(stocksCursor,
new SimpleEqualsFilter(PortfolioStockMap.COLUMN_PORTFOLIO_ID,
Long.valueOf(portfolioId))));
pos++;
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
int pos = 0;
Cursor portfolioCursor = mDrawerListAdapter.getCursor();
int columnIdx = portfolioCursor.getColumnIndex(PortfolioEntry._ID);
switch (loader.getId()) {
case PORTFOLIO_LOADER:
for (portfolioCursor.moveToFirst(); !portfolioCursor.isAfterLast(); portfolioCursor.moveToNext()) {
mDrawerListAdapter.setChildrenCursor(pos, null);
pos++;
}
mDrawerListAdapter.setGroupCursor(null);
break;
case STOCK_MAP_LOADER:
for (portfolioCursor.moveToFirst(); !portfolioCursor.isAfterLast(); portfolioCursor.moveToNext()) {
mDrawerListAdapter.setChildrenCursor(pos, null);
pos++;
}
break;
}
}
/**
* Callbacks interface that all activities using this fragment must implement.
*/
public static interface NavigationDrawerCallbacks {
/**
* Called when an item in the navigation drawer is selected.
*/
void onPortfolioSelected(long portfolioId);
void onStockSelected(long stockId);
}
}
|
package org.apache.lucene;
public class SearchResult {
private String source;
private String title;
private String author;
private String origin1;
private String origin2;
private String content;
private int PMID;
public SearchResult(String source, String title, String author,
String origin1, String origin2, String content, int pMID) {
super();
this.source = source;
this.title = title;
this.author = author;
this.origin1 = origin1;
this.origin2 = origin2;
this.content = content;
PMID = pMID;
}
public String getSource() {
return source;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public String getOrigin1() {
return origin1;
}
public String getOrigin2() {
return origin2;
}
public String getContent() {
return content;
}
public int getPMID() {
return PMID;
}
public void setSource(String source) {
this.source = source;
}
public void setTitle(String title) {
this.title = title;
}
public void setAuthor(String author) {
this.author = author;
}
public void setOrigin1(String origin1) {
this.origin1 = origin1;
}
public void setOrigin2(String origin2) {
this.origin2 = origin2;
}
public void setContent(String content) {
this.content = content;
}
public void setPMID(int pMID) {
PMID = pMID;
}
}
|
package kr.ac.kumoh.railroApplication.fragments;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.Toolbar;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import com.wdullaer.materialdatetimepicker.date.DatePickerDialog;
import java.util.ArrayList;
import java.util.Calendar;
import butterknife.ButterKnife;
import butterknife.InjectView;
import kr.ac.kumoh.railroApplication.R;
import kr.ac.kumoh.railroApplication.classes.SetTripDate;
import kr.ac.kumoh.railroApplication.classes.UseDB;
import kr.ac.kumoh.railroApplication.fragments.tabs.SetTripPlanActivity;
import kr.ac.kumoh.railroApplication.fragments.tabs.TabFragment;
import me.drakeet.materialdialog.MaterialDialog;
/**
* A simple {@link Fragment} subclass.
* Use the {@link HomeFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class HomeFragment extends BaseFragment implements DatePickerDialog.OnDateSetListener, View.OnTouchListener {
/* @InjectView(R.id.collapsing_toolbar)
CollapsingToolbarLayout mCollapsingToolbar;*/
@InjectView(R.id.coordinator_layout)
CoordinatorLayout mCoordinatorLayout;
@InjectView(R.id.toolbar_flexible_space_with_image)
Toolbar mToolbar;
@InjectView(R.id.share_menu_item)
FloatingActionButton mFab;
MaterialDialog mMaterialDialog;
MaterialDialog mSetTripTitleDialog;
ViewFlipper viewFlipper;
EditText mEditText;
ListView mListView;
ArrayList<String> mList;
ArrayAdapter<String> mAdapter;
int mDays, mYear, mMonth, mDay = 0;
String mTripTitle;
UseDB mDB;
Context mContext;
SetTripDate mSetTripDate; // class
float xAtDown;
float xAtUp;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @return A new instance of fragment ParallaxFragment.
*/
Button mButton;
int year_x, month_x, day_x;
static final int DIALOG_ID = 0;
public static HomeFragment newInstance() {
return new HomeFragment();
}
public HomeFragment() {
// Required empty public constructor
}
@Override
public void onDestroyView() {
super.onDestroyView();
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mContext = getActivity().getApplicationContext();
// mCollapsingToolbar.setTitle(getString(getTitle()));
mToolbar.setTitle("");
mToolbar.setBackgroundColor(Color.TRANSPARENT);
int color = getResources().getColor(android.R.color.transparent);
mCoordinatorLayout.setStatusBarBackgroundColor(color);
mButton = ButterKnife.findById(getActivity(), R.id.date_picker_btn);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// new DatePickerDialog(getActivity(), dpickerListener, year_x, month_x, day_x).show();
/* Calendar now = Calendar.getInstance();
DatePickerDialog dpd = DatePickerDialog.newInstance(
HomeFragment.this,
now.get(Calendar.YEAR),
now.get(Calendar.MONTH),
now.get(Calendar.DAY_OF_MONTH)
);
dpd.show(getActivity().getFragmentManager(), "Datepickerdialog");*/
MyTripListFragment myTripListFragment = new MyTripListFragment();
// myTripListFragment.newInstance();
//mSetTripTitleDialog.dismiss();
}
});
viewFlipper = ButterKnife.findById(getActivity(), R.id.viewFlipper);
viewFlipper.setOnTouchListener(this);
mListView = new ListView(getActivity());
mList = new ArrayList<String>();
mList.add("5");
mList.add("7");
mAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, mList);
mListView.setAdapter(mAdapter);
mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
mEditText = new EditText(getActivity());
mFab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mMaterialDialog = new MaterialDialog(getActivity())
.setTitle("Q. ?")
.setMessage("Hello world!")
.setContentView(mListView)
.setPositiveButton("OK", new View.OnClickListener() {
@Override
public void onClick(View v) {
mMaterialDialog.dismiss();
Calendar now = Calendar.getInstance();
DatePickerDialog dpd = DatePickerDialog.newInstance(
HomeFragment.this,
now.get(Calendar.YEAR),
now.get(Calendar.MONTH),
now.get(Calendar.DAY_OF_MONTH)
);
dpd.vibrate(true);
dpd.show(getActivity().getFragmentManager(), "Datepickerdialog");
}
})
.setNegativeButton("CANCEL", new View.OnClickListener() {
@Override
public void onClick(View v) {
mMaterialDialog.dismiss();
}
});
mMaterialDialog.show();
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = parent.getItemAtPosition(position).toString();
switch (item) {
case "5":
Toast.makeText(getActivity(), "position1", Toast.LENGTH_SHORT).show();
mListView.setSelector(R.color.colorLight);
mDays = 5;
break;
case "7":
Toast.makeText(getActivity(), "position2", Toast.LENGTH_SHORT).show();
//mListView.setSelector(Color.rgb(246, 246, 246));
mListView.setSelector(R.color.colorLight);
mDays = 7;
break;
}
}
});
}
});
}
@Override
protected int getToolbarId() {
return R.id.toolbar_flexible_space_with_image;
}
@Override
protected int getTitle() {
return R.string.home;
}
@Override
public boolean hasCustomToolbar() {
return true;
}
@Override
protected int getLayout() {
return R.layout.fragment_home;
}
@Override
public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
mYear = year;
mMonth = monthOfYear + 1;
mDay = dayOfMonth;
String date = mYear + "/" + mMonth + "/" + mDay + " ";
// dateTextView.setText(date);
Toast.makeText(getActivity(), date, Toast.LENGTH_SHORT).show();
//ToDo :
mSetTripTitleDialog = new MaterialDialog(getActivity())
.setTitle(mDays + " -" + mYear + "/" + mMonth + "/" + mDay + " !\n"+" :)")
.setContentView(mEditText)
.setPositiveButton("OK", new View.OnClickListener() {
@Override
public void onClick(View v) {
String total_Date = String.valueOf(mYear)+String.valueOf(mMonth) + String.valueOf(mDay);
mDB = new UseDB(mContext);
mDB.Insert(String.valueOf(mEditText.getText()),String.valueOf(mYear),
String.valueOf(mMonth), String.valueOf(mDay)
,String.valueOf(mDays));
mSetTripTitleDialog.dismiss();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container, MyTripListFragment.newInstance(mContext));
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
})
.setNegativeButton("CANCEL", new View.OnClickListener() {
@Override
public void onClick(View v) {
mSetTripTitleDialog.dismiss();
}
});
mSetTripTitleDialog.show();
//TODO: DB
mButton.setText((monthOfYear + 1) + "/" + dayOfMonth);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
// ViewFlipper return
if (v != viewFlipper)
return false;
if (event.getAction() == MotionEvent.ACTION_DOWN) {
xAtDown = event.getX();
} else if (event.getAction() == MotionEvent.ACTION_UP) {
xAtUp = event.getX();
if (xAtUp < xAtDown) {
viewFlipper.setInAnimation(AnimationUtils.loadAnimation(getActivity(), R.anim.push_left_out));
viewFlipper.setOutAnimation(AnimationUtils.loadAnimation(getActivity(), R.anim.push_left_out));
// view
viewFlipper.showNext();
} else if (xAtUp > xAtDown) {
viewFlipper.setInAnimation(AnimationUtils.loadAnimation(getActivity(), R.anim.push_right_in));
viewFlipper.setOutAnimation(AnimationUtils.loadAnimation(getActivity(), R.anim.push_right_in));
// view
viewFlipper.showPrevious();
}
}
return true;
}
}
|
package org.janb.shoppinglist.fragments;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.ListFragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.media.Image;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.afollestad.materialdialogs.MaterialDialog;
import com.getbase.floatingactionbutton.FloatingActionButton;
import com.getbase.floatingactionbutton.FloatingActionsMenu;
import com.google.gson.Gson;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import org.janb.shoppinglist.CONSTS;
import org.janb.shoppinglist.LOGGER;
import org.janb.shoppinglist.R;
import org.janb.shoppinglist.api.ListAPI;
import org.janb.shoppinglist.api.ResponseHelper;
import org.janb.shoppinglist.api.ResultsListener;
import org.janb.shoppinglist.model.PredictionDbAdapterItem;
import org.janb.shoppinglist.model.ShoppingListAdapter;
import org.janb.shoppinglist.model.ShoppingListItem;
import org.json.JSONArray;
import org.json.JSONException;
import java.util.ArrayList;
import java.util.List;
public class ShoppingListFragment extends ListFragment implements SwipeRefreshLayout.OnRefreshListener, ResultsListener, View.OnClickListener {
ShoppingListAdapter mAdapter;
private ListView mListView;
private List<ShoppingListItem> ShoppingListItemList = new ArrayList<>();
private SwipeRefreshLayout swipeRefreshLayout;
private ListAPI api;
private Context context;
private FloatingActionsMenu action_main;
private MaterialDialog dialog;
private Boolean isImportant = false;
private Boolean isFavorite = false;
private Boolean hideChecked = false;
private ShoppingListFragment ref;
private ShoppingListItem openedItem;
private EditText dialogCount;
private PredictionDbAdapterItem dbHelperItem;
private AutoCompleteTextView dialog_add_custom_what;
private AutoCompleteTextView dialog_add_custom_category;
public ShoppingListFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getActivity().getApplicationContext();
setHasOptionsMenu(true);
ref = this;
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
((AppCompatActivity)getActivity()).getSupportActionBar().setTitle(getResources().getString(R.string.title_main));
View rootView = inflater.inflate(R.layout.fragment_list, container, false);
mListView = (ListView) rootView.findViewById(android.R.id.list);
mListView.setLongClickable(true);
mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long l) {
final ShoppingListItem item = ShoppingListItemList.get(position);
openedItem = item;
dialog = new MaterialDialog.Builder(getActivity())
.customView(R.layout.dialog_update_item, true)
.positiveText(getResources().getString(R.string.ok))
.negativeText(getResources().getString(R.string.cancel))
.callback(new MaterialDialog.ButtonCallback() {
@Override
public void onPositive(MaterialDialog dialog) {
String dialogCountText = ((EditText) dialog.findViewById(R.id.dialog_update_count)).getText().toString();
String dialogTitleText = ((EditText) dialog.findViewById(R.id.dialog_update_title)).getText().toString();
if (!dialogCountText.isEmpty() && (!dialogCountText.equals(openedItem.getItemCountString()) || !dialogTitleText.equals(openedItem.getItemTitle()))) {
saveItem(dialogTitleText, dialogCountText, "false");
}
if (!dialogTitleText.equals(openedItem.getItemTitle())) {
List<ShoppingListItem> delItems = new ArrayList();
delItems.add(0 , new ShoppingListItem(item.getItemTitle(), 1));
Gson gson = new Gson();
deleteMultiple(gson.toJson(delItems));
}
}
})
.show();
dialogCount = (EditText) dialog.findViewById(R.id.dialog_update_count);
Button minusCount = (Button) dialog.findViewById(R.id.dialog_update_minus);
minusCount.setOnClickListener(ref);
Button plusCount = (Button) dialog.findViewById(R.id.dialog_update_plus);
plusCount.setOnClickListener(ref);
dialogCount.setText(String.valueOf(item.getItemCount()));
TextView dialogTitle = (TextView)dialog.findViewById(R.id.dialog_update_title);
dialogTitle.setText(item.getItemTitle());
TextView fav = (TextView)dialog.findViewById(R.id.dialog_update_favorite);
fav.setOnClickListener(ref);
TextView del = (TextView)dialog.findViewById(R.id.dialog_update_delete);
del.setOnClickListener(ref);
if(getFavorites().contains(item.getItemTitle())){
isFavorite = true;
fav.setShadowLayer(15f, 0, 0, getResources().getColor(R.color.material_deep_teal_500));
}
return true;
}
});
mListView.setEmptyView(rootView.findViewById(android.R.id.empty));
swipeRefreshLayout = (SwipeRefreshLayout)rootView.findViewById(R.id.swipe_container);
swipeRefreshLayout.setOnRefreshListener(this);
mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
int topRowVerticalPosition =
(mListView == null || mListView.getChildCount() == 0) ?
0 : mListView.getChildAt(0).getTop();
swipeRefreshLayout.setEnabled(firstVisibleItem == 0 && topRowVerticalPosition >= 0);
}
});
FloatingActionButton action_a = (FloatingActionButton) rootView.findViewById(R.id.main_action_a);
action_a.setOnClickListener(this);
FloatingActionButton action_b = (FloatingActionButton) rootView.findViewById(R.id.main_action_b);
action_b.setOnClickListener(this);
FloatingActionButton action_c = (FloatingActionButton) rootView.findViewById(R.id.main_action_c);
action_c.setOnClickListener(this);
action_main = (FloatingActionsMenu) rootView.findViewById(R.id.main_multiple_actions);
action_main.setAlpha(0.7f);
action_a.setAlpha(0.7f);
action_b.setAlpha(0.7f);
getList();
return rootView;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
getActivity().getMenuInflater().inflate(R.menu.menu_main, menu);
}
private void saveItem(String itemTitle, String itemCount, String itemChecked) {
setRefreshing();
api = new ListAPI(context);
api.setOnResultsListener(this);
ListAPI.setFunction(ListAPI.FUNCTION_SAVEITEM);
api.execute(itemTitle, String.valueOf(itemCount), itemChecked);
}
private void saveMultiple(String jsonData) {
setRefreshing();
api = new ListAPI(context);
api.setOnResultsListener(this);
ListAPI.setFunction(ListAPI.FUNCTION_SAVE_MULTIPLE);
api.execute(jsonData);
}
private void deleteMultiple(String jsonData) {
setRefreshing();
api = new ListAPI(context);
api.setOnResultsListener(this);
ListAPI.setFunction(ListAPI.FUNCTION_DELETE_MULTIPLE);
api.execute(jsonData);
}
private void addQRcodeItem(String QRcode) {
setRefreshing();
api = new ListAPI(context);
api.setOnResultsListener(this);
ListAPI.setFunction(ListAPI.FUNCTION_ADD_QRCODE_ITEM);
api.execute(QRcode);
}
private void clearList() {
setRefreshing();
api = new ListAPI(context);
api.setOnResultsListener(this);
ListAPI.setFunction(ListAPI.FUNCTION_CLEARLIST);
api.execute();
}
private void getList() {
swipeRefreshLayout.post(new Runnable() {
@Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
}
});
api = new ListAPI(getActivity().getApplicationContext());
api.setOnResultsListener(this);
ListAPI.setFunction(ListAPI.FUNCTION_GETLIST);
api.execute();
}
@Override
public void onListItemClick(ListView l, View view, final int position, long id) {
super.onListItemClick(l, view, position, id);
ShoppingListItem clickedItem = ShoppingListItemList.get(position);
clickedItem.toggleChecked();
int index = mListView.getFirstVisiblePosition();
View v = mListView.getChildAt(0);
int top = (v == null) ? 0 : (v.getTop() - mListView.getPaddingTop());
mAdapter = new ShoppingListAdapter(getActivity(), ShoppingListItemList, hideChecked);
setListAdapter(mAdapter);
mListView.setSelectionFromTop(index, top);
saveItem(clickedItem.getItemTitle(), Integer.toString(clickedItem.getItemCount()), clickedItem.isChecked() ? "true" : "false");
}
public void setEmptyText(CharSequence emptyText) {
View emptyView = mListView.getEmptyView();
if (emptyView instanceof TextView) {
((TextView) emptyView).setText(emptyText);
}
}
@Override
public void onRefresh() {
getList();
}
public void onResponse(final ResponseHelper response) {
resetRefreshing();
Log.d("API CODE", String.valueOf(response.getType()));
if (response.getType() >= 5000 && response.getType() < 6000){
onError(response);
return;
}
if (response.getType() >= 6000){
showAPIError(response.getContent());
return;
}
switch(response.getType()){
case CONSTS.API_SUCCESS_LIST:
ShoppingListItemList = response.getItems();
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
buildList();
}
});
break;
case CONSTS.API_SUCCESS_LIST_EMPTY:
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if ( ShoppingListItemList != null && mAdapter != null) {
ShoppingListItemList.clear();
mAdapter.notifyDataSetChanged();
}
setEmptyText(getResources().getString(R.string.empty_view_list));
}
});
break;
case CONSTS.API_SUCCESS_SAVE:
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getActivity(), response.getContent(),Toast.LENGTH_SHORT).show();
getList();
}
});
break;
case CONSTS.API_SUCCESS_DELETE:
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getActivity(), response.getContent(),Toast.LENGTH_SHORT).show();
getList();
}
});
break;
case CONSTS.API_SUCCESS_CLEAR:
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getActivity(), response.getContent(),Toast.LENGTH_SHORT).show();
getList();
}
});
break;
case CONSTS.API_SUCCESS_UPDATE:
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getActivity(), response.getContent(),Toast.LENGTH_SHORT).show();
getList();
}
});
break;
case CONSTS.API_SUCCESS_IMPORTANT:
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getActivity(), response.getContent(),Toast.LENGTH_SHORT).show();
getList();
}
});
break;
}
}
private void showAPIError(final String content) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(context, content, Toast.LENGTH_SHORT).show();
}
});
}
public void buildList(){
SharedPreferences prefs = context.getSharedPreferences("settings", Context.MODE_PRIVATE);
Gson gson = new Gson();
String json = gson.toJson(ShoppingListItemList);
prefs.edit().putString("cached_list", json).apply();
mAdapter = new ShoppingListAdapter(getActivity(), ShoppingListItemList, hideChecked);
setListAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
if(mAdapter.isEmpty()){
setEmptyText(getResources().getString(R.string.empty_view_list));
}
}
//Errors thrown by app and api
@Override
public void onError(ResponseHelper error) {
if(error.getType() == CONSTS.APP_ERROR_IO) {
getList();
return;
}
resetRefreshing();
ErrorFragment errFR;
Bundle args = new Bundle();
args.putString("error_code", error.getContent());
errFR = new ErrorFragment();
errFR.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.fragment_container, errFR);
transaction.addToBackStack(null);
transaction.commitAllowingStateLoss();
}
private void resetRefreshing() {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
swipeRefreshLayout.setRefreshing(false);
}
});
}
private void setRefreshing() {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
}
});
}
@Override
public void onClick(View view) {
switch(view.getId()){
case R.id.main_action_a:
final InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
action_main.collapse();
dbHelperItem = new PredictionDbAdapterItem(context);
dbHelperItem.open();
dialog = new MaterialDialog.Builder(getActivity())
.customView(R.layout.dialog_add_custom, true)
.positiveText(getResources().getString(R.string.ok))
.negativeText(getResources().getString(R.string.cancel))
.callback(new MaterialDialog.ButtonCallback() {
@Override
public void onPositive(MaterialDialog dialog) {
TextView dialog_add_custom_how_much = (TextView) dialog.findViewById(R.id.dialog_add_count);
imm.hideSoftInputFromWindow(dialog_add_custom_what.getWindowToken(), 0);
if (!dialog_add_custom_what.getText().toString().isEmpty()) {
saveItem(dialog_add_custom_what.getText().toString(), dialog_add_custom_how_much.getText().toString(), "false");
dbHelperItem.addPrediction(dialog_add_custom_what.getText().toString());
if (isFavorite) {
addToFavorites(dialog_add_custom_what.getText().toString());
isFavorite = false;
}
}
dbHelperItem.close();
}
@Override
public void onNegative(MaterialDialog dialog) {
imm.hideSoftInputFromWindow(dialog_add_custom_what.getWindowToken(), 0);
dbHelperItem.close();
}
})
.show();
PredictionAdapter adapter = new PredictionAdapter(dbHelperItem);
dialog_add_custom_what = (AutoCompleteTextView) dialog.findViewById(R.id.dialog_add_what);
dialog_add_custom_what.setAdapter(adapter);
dialog_add_custom_what.setOnItemClickListener(adapter);
dialog_add_custom_what.setFocusable(true);
dialog_add_custom_what.requestFocus();
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
dialog.findViewById(R.id.dialog_add_favorite).setOnClickListener(this);
break;
case R.id.main_action_b:
final List<String> favorites = getFavorites();
if (favorites.isEmpty()){
Toast.makeText(context, getResources().getString(R.string.toast_no_favorites), Toast.LENGTH_SHORT).show();
return;
}
final String[] simpleArray = new String[ favorites.size() ];
favorites.toArray(simpleArray);
action_main.collapse();
dialog = new MaterialDialog.Builder(getActivity())
.items(simpleArray)
.itemsCallbackMultiChoice(null, new MaterialDialog.ListCallbackMultiChoice() {
@Override
public boolean onSelection(MaterialDialog materialDialog, Integer[] selectedItems, CharSequence[] charSequences) {
if(selectedItems.length > 0) {
List<ShoppingListItem> itemList = new ArrayList<>();
int i = 0;
for (int selectedItem : selectedItems) {
itemList.add(i++, new ShoppingListItem(favorites.get(selectedItem), 1));
}
Gson gson = new Gson();
saveMultiple(gson.toJson(itemList));
}
return true;
}
})
.positiveText(getResources().getString(R.string.ok))
.show();
break;
case R.id.main_action_c:
action_main.collapse();
SharedPreferences prefs = context.getSharedPreferences("settings", Context.MODE_PRIVATE);
int cameraId = prefs.getBoolean("scanQRfront", false) ? 1 : 0;
IntentIntegrator integrator = new IntentIntegrator(this);
integrator.initiateScan(cameraId);
break;
case R.id.dialog_add_favorite:
TextView favoriteAdd = (TextView)dialog.findViewById(R.id.dialog_add_favorite);
if (isFavorite){
isFavorite = false;
favoriteAdd.setShadowLayer(0, 0, 0, 0);
} else {
isFavorite = true;
favoriteAdd.setShadowLayer(15f, 0, 0, getResources().getColor(R.color.material_deep_teal_500));
}
break;
case R.id.dialog_update_favorite:
TextView favoriteUpdate = (TextView)dialog.findViewById(R.id.dialog_update_favorite);
if (isFavorite){
isFavorite = false;
favoriteUpdate.setShadowLayer(0, 0, 0, 0);
removeFromFavorites(openedItem.getItemTitle());
} else {
isFavorite = true;
favoriteUpdate.setShadowLayer(15f, 0, 0, getResources().getColor(R.color.material_deep_teal_500));
addToFavorites(openedItem.getItemTitle());
}
break;
case R.id.dialog_update_delete:
List<ShoppingListItem> delItems = new ArrayList();
delItems.add(0 , new ShoppingListItem(openedItem.getItemTitle(), 1));
Gson gson = new Gson();
deleteMultiple(gson.toJson(delItems));
dialog.dismiss();
break;
case R.id.dialog_update_minus:
if(!dialogCount.getText().toString().equals("1")) {
dialogCount = (EditText) dialog.findViewById(R.id.dialog_update_count);
dialogCount.setText(String.valueOf(Integer.valueOf(dialogCount.getText().toString()) - 1));
}
break;
case R.id.dialog_update_plus:
dialogCount = (EditText) dialog.findViewById(R.id.dialog_update_count);
dialogCount.setText(String.valueOf(Integer.valueOf(dialogCount.getText().toString())+1));
break;
}
}
private void addToFavorites(String itemTitle) {
SharedPreferences prefs = context.getSharedPreferences("settings", Context.MODE_PRIVATE);
List<String> favorites = getFavorites();
favorites.add(itemTitle);
JSONArray jsArray = new JSONArray(favorites);
prefs.edit().putString("favorites", jsArray.toString()).apply();
}
private void removeFromFavorites(String itemTitle) {
SharedPreferences prefs = context.getSharedPreferences("settings", Context.MODE_PRIVATE);
List<String> favorites = getFavorites();
favorites.remove(itemTitle);
JSONArray jsArray = new JSONArray(favorites);
prefs.edit().putString("favorites", jsArray.toString()).apply();
}
private List<String> getFavorites() {
SharedPreferences prefs = context.getSharedPreferences("settings", Context.MODE_PRIVATE);
JSONArray jsonArray;
List<String> favorites = new ArrayList<>();
try {
jsonArray = new JSONArray(prefs.getString("favorites", ""));
for (int i=0; i<jsonArray.length(); i++) {
favorites.add( jsonArray.getString(i) );
}
} catch (JSONException e) {
e.printStackTrace();
}
return favorites;
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanResult != null) {
Gson gson = new Gson();
try {
String QRcode = scanResult.getContents().toString();
Toast.makeText(getActivity().getApplicationContext(), QRcode, Toast.LENGTH_SHORT).show();
addQRcodeItem(QRcode);
} catch (Exception e){
Toast.makeText(getActivity().getApplicationContext(),"QR Code: Wrong data!", Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void onStop(){
super.onStop();
if (api != null){
api.cancel(true);
}
}
@Override
public void onPause(){
super.onPause();
if (api != null){
api.cancel(true);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
List<ShoppingListItem> delItems = new ArrayList();
switch (item.getItemId()) {
case R.id.action_hidechecked:
hideChecked = !hideChecked;
buildList();
return true;
case R.id.action_clearlist:
int i = 0;
for(ShoppingListItem SLitem:ShoppingListItemList){
if(SLitem.isChecked()){
delItems.add(i++ , new ShoppingListItem(SLitem.getItemTitle(), 1));
}
}
if(delItems.isEmpty()){
dialog = new MaterialDialog.Builder(getActivity())
.content(R.string.dialog_clear_confirm)
.positiveText(getResources().getString(R.string.ok))
.negativeText(getResources().getString(R.string.cancel))
.callback(new MaterialDialog.ButtonCallback() {
@Override
public void onPositive(MaterialDialog dialog) {
clearList();
}
})
.show();
} else {
Gson gson = new Gson();
deleteMultiple(gson.toJson(delItems));
}
return true;
case R.id.action_share:
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
StringBuilder sb = new StringBuilder();
for(ShoppingListItem listItem:ShoppingListItemList){
if(listItem.isChecked()){
sb.append("[ X ]\t");
} else {
sb.append("[ ]\t");
}
sb.append(listItem.getItemTitle());
sb.append("\t\t");
sb.append(listItem.getItemCount());
sb.append("\n");
}
sendIntent.putExtra(Intent.EXTRA_TEXT, sb.toString());
sendIntent.setType("text/plain");
startActivity(sendIntent);
break;
default:
break;
}
return true;
}
class PredictionAdapter extends CursorAdapter
implements AdapterView.OnItemClickListener {
private PredictionDbAdapterItem mDbHelper;
public PredictionAdapter(PredictionDbAdapterItem dbHelper) {
super(context, null, true);
mDbHelper = dbHelper;
}
@Override
public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
if (getFilterQueryProvider() != null) {
return getFilterQueryProvider().runQuery(constraint);
}
return mDbHelper.getPrediction(
(constraint != null ? constraint.toString() : "@@@@"));
}
public void bindView(View view, Context context, Cursor cursor) {
final int itemColumnIndex = cursor.getColumnIndexOrThrow("itemTitle");
TextView predictionText = (TextView) view.findViewById(R.id.text);
String prediction = cursor.getString(itemColumnIndex);
predictionText.setText(prediction);
}
public View newView(Context context, Cursor cursor, ViewGroup parent) {
final LayoutInflater inflater = LayoutInflater.from(context);
return inflater.inflate(R.layout.row_predictions, parent, false);
}
@Override
public void onItemClick(AdapterView<?> listView, View view, int position, long id) {
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
String itemTitle = cursor.getString(cursor.getColumnIndexOrThrow("itemTitle"));
dialog_add_custom_what.setText(itemTitle);
dialog_add_custom_what.setSelection(itemTitle.length());
}
}
}
|
package com.slugterra.main;
import com.slugterra.creativetabs.SlugterraCreativeTabs;
import com.slugterra.entity.SlugterraEntityRegistry;
import com.slugterra.entity.slingers.EntitySlingers;
import com.slugterra.events.SlugterraEventHandler;
import com.slugterra.events.SlugterraKeyHandler;
import com.slugterra.gui.GUIHandler;
import com.slugterra.lib.Strings;
import com.slugterra.packets.MechaAnimPacket;
import com.slugterra.packets.OpenGuiPacket;
import com.slugterra.packets.SyncPlayerPropsPacket;
import com.slugterra.packets.UpdateSlotPacket;
import net.minecraftforge.common.DimensionManager;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.Mod.Instance;
import net.minecraftforge.fml.common.SidedProxy;
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.network.NetworkRegistry;
import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper;
import net.minecraftforge.fml.relauncher.Side;
@Mod(modid = Strings.MODID, name = Strings.name, version = Strings.version)
public class MainRegistry {
@SidedProxy(clientSide = "com.slugterra.main.ClientProxy", serverSide = "com.slugterra.main.ServerProxy")
public static CommonProxy proxy;
@Instance(Strings.MODID)
public static MainRegistry modInstance = new MainRegistry();
public static boolean mcainstalled = false;
public static SimpleNetworkWrapper network;
private static int modGuiIndex = 0;
public static final int GUI_SLUG_INV = modGuiIndex++;
public static final int GUI_SLUG_RACK = modGuiIndex++;
public static final int dimensionIdSlugterra = DimensionManager.getNextFreeDimId();
/**
* Loads before
* @param PreEvent
*/
@EventHandler
public void PreLoad(FMLPreInitializationEvent PreEvent){
SlugterraCreativeTabs.initialiseTabs();
proxy.preInit(PreEvent);
// SlugterraBlocks.mainRegistry();
SlugterraEntityRegistry.mainRegistry();
// proxy.registerRenderThings();
EntitySlingers.mainRegistry();
//dimension stuff
// DimensionType dimensionTypeSlugterra = DimensionType.register("SLUGTERRA", "_slugterra", dimensionIdSlugterra, WorldProviderSlugterra.class, true);
// DimensionManager.registerDimension(dimensionIdSlugterra, dimensionTypeSlugterra);
// BiomeRegistry.mainRegistry();
//new packets
network = NetworkRegistry.INSTANCE.newSimpleChannel("SlugChannelNew");
network.registerMessage(MechaAnimPacket.Handler.class, MechaAnimPacket.class, 0, Side.SERVER);
network.registerMessage(OpenGuiPacket.Handler.class, OpenGuiPacket.class, 1, Side.SERVER);
network.registerMessage(SyncPlayerPropsPacket.Handler.class, SyncPlayerPropsPacket.class, 2, Side.CLIENT);
network.registerMessage(UpdateSlotPacket.Handler.class, UpdateSlotPacket.class, 3, Side.SERVER);
}
/**
* Loads during
* @param event
*/
@EventHandler
public void load(FMLInitializationEvent event){
proxy.init(event);
// proxy.registerRenderThings();
//tile entities
// GameRegistry.registerTileEntity(TileEntitySlugContainerEntity.class, "tileEntitySlugContainer");
//events
MinecraftForge.EVENT_BUS.register(new SlugterraEventHandler());
NetworkRegistry.INSTANCE.registerGuiHandler(MainRegistry.modInstance, new GUIHandler());
MinecraftForge.EVENT_BUS.register(new SlugterraKeyHandler());
//world generators
// GameRegistry.registerWorldGenerator(new WorldGeneratorTheDrop(), 1);
// GameRegistry.registerWorldGenerator(new WorldGeneratorGreatForge(), 2);
// GameRegistry.registerWorldGenerator(new WorldGeneratorBullseyeGhoul(), 2);
// GameRegistry.registerWorldGenerator(new WorldGenMushrooms(), 1);
// GameRegistry.registerWorldGenerator(new WorldGeneratorShaneHideout(), 3);
}
/**
* Loads after
* @param PostEvent
*/
@EventHandler
public void PostLoad(FMLPostInitializationEvent PostEvent){
proxy.postInit(PostEvent);
}
}
|
package org.mozilla.focus.autocomplete;
import android.content.Context;
import android.content.res.Resources;
import android.os.AsyncTask;
import org.mozilla.focus.R;
import org.mozilla.focus.widget.InlineAutocompleteEditText;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class UrlAutoCompleteFilter implements InlineAutocompleteEditText.OnFilterListener {
private List<String> domains;
public UrlAutoCompleteFilter(Context context) {
loadUrls(context);
}
/**
* Our autocomplete list is all lower case, however the search text might be mixed case.
* Our autocomplete EditText code does more string comparison, which fails if the suggestion
* doesn't exactly match searchText (ie. if casing differs). It's simplest to just build a suggestion
* that exactly matches the search text - which is what this method is for:
*/
private static String prepareAutocompleteResult(final String rawSearchText, final String lowerCaseResult) {
return rawSearchText + lowerCaseResult.substring(rawSearchText.length());
}
@Override
public void onFilter(final String rawSearchText, InlineAutocompleteEditText view) {
if (domains == null || view == null) {
return;
}
// Search terms are all lowercase already, we just need to lowercase the search text
final String searchText = rawSearchText.toLowerCase(Locale.US);
for (final String domain : domains) {
final String wwwDomain = "www." + domain;
if (wwwDomain.startsWith(searchText)) {
view.onAutocomplete(prepareAutocompleteResult(rawSearchText, wwwDomain));
return;
}
if (domain.startsWith(searchText)) {
view.onAutocomplete(prepareAutocompleteResult(rawSearchText, domain));
return;
}
}
}
private void loadUrls(Context context) {
new AsyncTask<Resources, Void, List<String>>() {
@Override
protected List<String> doInBackground(Resources... resources) {
try {
final BufferedReader reader = new BufferedReader(new InputStreamReader(
resources[0].openRawResource(R.raw.topdomains)));
final List<String> domains = new ArrayList<String>(460);
String line;
while ((line = reader.readLine()) != null) {
domains.add(line);
}
return domains;
} catch (IOException e) {
// No autocomplete for you!
return null;
}
}
@Override
protected void onPostExecute(List<String> domains) {
UrlAutoCompleteFilter.this.domains = domains;
}
}.execute(context.getResources());
}
}
|
package slimpleslickgame;
import java.util.HashMap;
import org.newdawn.slick.Color;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.ShapeFill;
import org.newdawn.slick.fills.GradientFill;
import org.newdawn.slick.geom.Polygon;
import org.newdawn.slick.geom.Shape;
import org.newdawn.slick.geom.Vector2f;
public abstract class Player {
protected Vector2f position;
protected Vector2f direction;
protected Shape shape;
protected ShapeFill shapeFill;
private float speed = 5;
protected byte id;
protected Gun gun;
protected boolean started;
private Vector2f moveTo;
protected HashMap<Integer, Creep> creeps;
private final float WIDTH = 20;
private final float HEIGHT = 20;
public void init(Vector2f centerPos){
position = new Vector2f(centerPos.x - WIDTH/2, centerPos.y - HEIGHT/2);
// shape = new Rectangle(position.x, position.y, WIDTH, HEIGHT);
shape = new Polygon(new float[]{position.x, position.y, position.x + WIDTH/2, position.y - HEIGHT, position.x + WIDTH, position.y});
shape.setLocation(position);
shapeFill = new GradientFill(0,0, new Color(255, 0, 0), 50, 50, new Color(0, 0, 255), true);
direction = new Vector2f(0,0);
gun = new Gun();
moveTo = null;
creeps = new HashMap<Integer, Creep>();
}
public abstract int update(int delta, Shape containerShape);
protected void updatePosition(Shape containerShape){
if(position != null){
position.add(direction);
shape.setLocation(position);
if(shape.intersects(containerShape)){
if(shape.getX() <= containerShape.getMinX()){
position.set(containerShape.getMinX(), position.y);
}else if(shape.getMaxX() >= containerShape.getMaxX()){
position.set(containerShape.getMaxX()-WIDTH, position.y);
}
shape.setLocation(position);
}
}
}
public void render(Graphics graphics){
for(Creep c : creeps.values()){
c.render(graphics);
}
gun.render(graphics);
// graphics.fill(shape, shapeFill);
graphics.draw(shape, shapeFill);
}
protected void setDirection(Vector2f dir) {
dir.normalise();
this.direction = dir.scale(speed);
}
public void moveTo(Vector2f pos){
moveTo = pos;
setDirection(pos.sub(this.position));
}
}
|
package com.hida.model;
import java.util.Arrays;
import javax.persistence.Column;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.Type;
/**
* An object used to model every Pid. By definition, each Pid will have a unique
name associated with it. However, to determine uniqueness, each newly created
Pid must be compared to previously existing Ids.
Comparisons will be made by using Sets collection. Depending on which set is
used, the Comparable interface and an overridden equals and hashCode methods
were overridden to accommodate.
*
* @author lruffin
*/
@Entity
@Table(name="ID_TABLE")
public abstract class Pid implements Comparable<Pid> {
/**
* missing javadoc
*/
@Id
@Column(name = "NAME", updatable = false, nullable = false)
private String Name;
// fields
protected int[] BaseMap;
protected boolean Unique = true;
protected String Prefix;
// Logger; logfile to be stored in resource folder
private static final Logger Logger = LoggerFactory.getLogger(Pid.class);
/**
* A no-arg constructor to be used by Hibernate
*/
public Pid(){
}
/**
* Copy constructor; primarily used to copy values of the BaseMap from one
* Id to another.
*
* @param id The Id to copy from.
*/
public Pid(Pid id) {
this.Prefix = id.Prefix;
this.BaseMap = Arrays.copyOf(id.getBaseMap(), id.getBaseMap().length);
this.Unique = id.Unique;
}
public Pid(int[] baseMap, String Prefix) {
this.BaseMap = Arrays.copyOf(baseMap, baseMap.length);
this.Prefix = Prefix;
}
public abstract boolean incrementId();
public abstract String getRootName();
public String getName(){
return this.Name;
}
public void setName(String name){
this.Name = name;
}
@Override
public int hashCode() {
// arbitrarily chosen prime numbers
final int prime1 = 37;
final int prime2 = 257;
int hash = prime1 * prime2 + Arrays.hashCode(this.BaseMap);
return hash;
}
/**
* Overridden so that id's can be identified solely by its baseName.
*
* @param obj the Object this id is being compared to
* @return true if the two Objects are the same.
*/
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (!(obj instanceof Pid)) {
return false;
}
final Pid paramId = (Pid) obj;
return Arrays.equals(this.BaseMap, paramId.BaseMap);
}
/**
* The BaseMap is the numerical representation of this Pid's name. Used in
* conjunction with TokenMap to return the string representation of this
* id's name in its toString method.
*
* @return The array used to create the name
*/
public int[] getBaseMap() {
return BaseMap;
}
/**
* The BaseMap is the numerical representation of this Pid's name. Used in
* conjunction with TokenMap to return the string representation of this
* id's name in its toString method.
*
* Be warned that the array must have a unique address for it to work with
* Sets. The length of the array must be equal to TokenMap, otherwise an
* IndexOutOfBounds error will be thrown in the getRootName method.
*
* @param baseMap The new array to replace the name.
*/
public void setBaseMap(int[] baseMap) {
this.BaseMap = baseMap;
}
/**
* Determines whether or not particular Pid is not the first to be created
with it's particular BaseMap.
*
* Returns true by default unless previously modified.
*
* @return returns whether or not this id is unique against the database.
*/
public boolean isUnique() {
return Unique;
}
/**
* Determines whether or not particular Pid is not the first to be created
with it's particular BaseMap.
*
* Should only be used to set false whenever it is determined that this
Pid is not the first to have it's BaseMap value with a given prefix.
*
* @param isUnique sets the uniqueness value
*/
public void setUnique(boolean isUnique) {
this.Unique = isUnique;
}
/**
* Method to retrieve the prefix of the id
* @return
*/
public String getPrefix() {
return Prefix;
}
/**
* Used to define the natural ordering of how id's should be listed. When
* invoked, the two id's will be compared by their arrays as they represent
* the names.
*
* @param t second Pid being compared.
* @return used to sort values in descending order.
*/
@Override
public int compareTo(Pid t) {
int[] t1Array = this.getBaseMap();
int[] t2Array = t.getBaseMap();
if (this.equals(t)) {
return 0;
} else {
for (int i = 0; i < t1Array.length; i++) {
// if the first Pid has a smaller value than the second Pid
if (t1Array[i] < t2Array[i]) {
return -1;
} // if the first Pid has a larger value than the second Pid
else if (t1Array[i] > t2Array[i]) {
return 1;
}
}
}
// if the arrays of both Ids are equal
return 0;
}
}
|
package com.apptentive.android.sdk;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import com.apptentive.android.sdk.Apptentive.LoginCallback;
import com.apptentive.android.sdk.comm.ApptentiveClient;
import com.apptentive.android.sdk.comm.ApptentiveHttpClient;
import com.apptentive.android.sdk.comm.ApptentiveHttpResponse;
import com.apptentive.android.sdk.conversation.Conversation;
import com.apptentive.android.sdk.conversation.ConversationManager;
import com.apptentive.android.sdk.lifecycle.ApptentiveActivityLifecycleCallbacks;
import com.apptentive.android.sdk.model.Configuration;
import com.apptentive.android.sdk.model.EventPayload;
import com.apptentive.android.sdk.model.LogoutPayload;
import com.apptentive.android.sdk.module.engagement.EngagementModule;
import com.apptentive.android.sdk.module.engagement.interaction.InteractionManager;
import com.apptentive.android.sdk.module.engagement.interaction.model.MessageCenterInteraction;
import com.apptentive.android.sdk.module.messagecenter.MessageManager;
import com.apptentive.android.sdk.module.metric.MetricModule;
import com.apptentive.android.sdk.module.rating.IRatingProvider;
import com.apptentive.android.sdk.module.rating.impl.GooglePlayRatingProvider;
import com.apptentive.android.sdk.module.survey.OnSurveyFinishedListener;
import com.apptentive.android.sdk.notifications.ApptentiveNotification;
import com.apptentive.android.sdk.notifications.ApptentiveNotificationCenter;
import com.apptentive.android.sdk.notifications.ApptentiveNotificationObserver;
import com.apptentive.android.sdk.storage.AppRelease;
import com.apptentive.android.sdk.storage.AppReleaseManager;
import com.apptentive.android.sdk.storage.ApptentiveTaskManager;
import com.apptentive.android.sdk.storage.Sdk;
import com.apptentive.android.sdk.storage.SdkManager;
import com.apptentive.android.sdk.storage.VersionHistoryItem;
import com.apptentive.android.sdk.util.Constants;
import com.apptentive.android.sdk.util.StringUtils;
import com.apptentive.android.sdk.util.Util;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import static com.apptentive.android.sdk.ApptentiveLogTag.CONVERSATION;
import static com.apptentive.android.sdk.ApptentiveNotifications.NOTIFICATION_ACTIVITY_RESUMED;
import static com.apptentive.android.sdk.ApptentiveNotifications.NOTIFICATION_ACTIVITY_STARTED;
import static com.apptentive.android.sdk.ApptentiveNotifications.NOTIFICATION_APP_ENTERED_BACKGROUND;
import static com.apptentive.android.sdk.ApptentiveNotifications.NOTIFICATION_APP_ENTERED_FOREGROUND;
import static com.apptentive.android.sdk.ApptentiveNotifications.NOTIFICATION_AUTHENTICATION_FAILED;
import static com.apptentive.android.sdk.ApptentiveNotifications.NOTIFICATION_CONVERSATION_WILL_LOGOUT;
import static com.apptentive.android.sdk.ApptentiveNotifications.NOTIFICATION_INTERACTIONS_SHOULD_DISMISS;
import static com.apptentive.android.sdk.ApptentiveNotifications.NOTIFICATION_KEY_ACTIVITY;
import static com.apptentive.android.sdk.ApptentiveNotifications.NOTIFICATION_KEY_AUTHENTICATION_FAILED_REASON;
import static com.apptentive.android.sdk.ApptentiveNotifications.NOTIFICATION_KEY_CONVERSATION_ID;
import static com.apptentive.android.sdk.util.Constants.CONVERSATIONS_DIR;
/**
* This class contains only internal methods. These methods should not be access directly by the host app.
*/
public class ApptentiveInternal implements ApptentiveNotificationObserver {
private final ApptentiveTaskManager taskManager;
private final ApptentiveActivityLifecycleCallbacks lifecycleCallbacks;
private final ApptentiveHttpClient apptentiveHttpClient;
private final ConversationManager conversationManager;
// These variables are initialized in Apptentive.register(), and so they are freely thereafter. If they are unexpectedly null, then if means the host app did not register Apptentive.
private final Context appContext;
// We keep a readonly reference to AppRelease object since it won't change at runtime
private final AppRelease appRelease;
private boolean appIsInForeground;
private final SharedPreferences globalSharedPrefs;
private final String apptentiveKey;
private final String apptentiveSignature;
private String serverUrl;
private String androidId; // FIXME: remove this field (never used)
private String appPackageName;
// toolbar theme specified in R.attr.apptentiveToolbarTheme
private Resources.Theme apptentiveToolbarTheme;
// app default appcompat theme res id, if specified in app AndroidManifest
private int appDefaultAppCompatThemeId;
private int statusBarColorDefault;
private String defaultAppDisplayName = "this app";
// booleans to prevent starting multiple fetching asyncTasks simultaneously
private IRatingProvider ratingProvider;
private Map<String, String> ratingProviderArgs;
private WeakReference<OnSurveyFinishedListener> onSurveyFinishedListener;
private final LinkedBlockingQueue interactionUpdateListeners = new LinkedBlockingQueue();
private WeakReference<Apptentive.AuthenticationFailedListener> authenticationFailedListenerRef = null;
private final ExecutorService cachedExecutor;
// Holds reference to the current foreground activity of the host app
private WeakReference<Activity> currentTaskStackTopActivity;
// Used for temporarily holding customData that needs to be sent on the next message the consumer sends.
private Map<String, Object> customData;
private static final String PUSH_ACTION = "action";
private static final String PUSH_CONVERSATION_ID = "conversationid";
private enum PushAction {
pmc, // Present Message Center.
unknown; // Anything unknown will not be handled.
public static PushAction parse(String name) {
try {
return PushAction.valueOf(name);
} catch (IllegalArgumentException e) {
ApptentiveLog.d("Error parsing unknown PushAction: " + name);
}
return unknown;
}
}
@SuppressLint("StaticFieldLeak")
private static volatile ApptentiveInternal sApptentiveInternal;
// for unit testing
protected ApptentiveInternal() {
taskManager = null;
globalSharedPrefs = null;
apptentiveKey = null;
apptentiveSignature = null;
apptentiveHttpClient = null;
conversationManager = null;
appContext = null;
appRelease = null;
cachedExecutor = null;
lifecycleCallbacks = null;
}
private ApptentiveInternal(Application application, String apptentiveKey, String apptentiveSignature, String serverUrl) {
if (StringUtils.isNullOrEmpty(apptentiveKey)) {
throw new IllegalArgumentException("Apptentive Key is null or empty");
}
if (StringUtils.isNullOrEmpty(apptentiveSignature)) {
throw new IllegalArgumentException("Apptentive Signature is null or empty");
}
this.apptentiveKey = apptentiveKey;
this.apptentiveSignature = apptentiveSignature;
this.serverUrl = serverUrl;
appContext = application.getApplicationContext();
globalSharedPrefs = application.getSharedPreferences(Constants.PREF_NAME, Context.MODE_PRIVATE);
apptentiveHttpClient = new ApptentiveHttpClient(apptentiveKey, apptentiveSignature, getEndpointBase(globalSharedPrefs));
conversationManager = new ConversationManager(appContext, Util.getInternalDir(appContext, CONVERSATIONS_DIR, true));
appRelease = AppReleaseManager.generateCurrentAppRelease(application, this);
taskManager = new ApptentiveTaskManager(appContext, apptentiveHttpClient);
cachedExecutor = Executors.newCachedThreadPool();
lifecycleCallbacks = new ApptentiveActivityLifecycleCallbacks();
ApptentiveNotificationCenter.defaultCenter()
.addObserver(NOTIFICATION_CONVERSATION_WILL_LOGOUT, this)
.addObserver(NOTIFICATION_AUTHENTICATION_FAILED, this);
}
public static boolean isApptentiveRegistered() {
return sApptentiveInternal != null;
}
public static boolean isConversationActive() {
return sApptentiveInternal != null && sApptentiveInternal.getConversation() != null;
}
/**
* Create a new or return a existing thread-safe instance of the Apptentive SDK. If this
* or any other {@link #getInstance()} has already been called in the application's lifecycle, the
* App key will be ignored and the current instance will be returned.
* <p/>
* This will be called from the application's onCreate(), before any other application objects have been
* created. Since the time spent in this function directly impacts the performance of starting the first activity,
* service, or receiver in the hosting app's process, the initialization of Apptentive is deferred to the first time
* {@link #getInstance()} is called.
*
* @param application the context of the app that is creating the instance
*/
static void createInstance(Application application, String apptentiveKey, String apptentiveSignature, final String serverUrl) {
if (application == null) {
throw new IllegalArgumentException("Application is null");
}
synchronized (ApptentiveInternal.class) {
if (sApptentiveInternal == null) {
// trim spaces
apptentiveKey = Util.trim(apptentiveKey);
apptentiveSignature = Util.trim(apptentiveSignature);
// if App key is not defined - try loading from AndroidManifest.xml
if (StringUtils.isNullOrEmpty(apptentiveKey)) {
apptentiveKey = Util.getManifestMetadataString(application, Constants.MANIFEST_KEY_APPTENTIVE_KEY);
// TODO: check if Apptentive Key is still empty
}
// if App signature is not defined - try loading from AndroidManifest.xml
if (StringUtils.isNullOrEmpty(apptentiveSignature)) {
apptentiveSignature = Util.getManifestMetadataString(application, Constants.MANIFEST_KEY_APPTENTIVE_SIGNATURE);
// TODO: check if Apptentive Signature is still empty
}
try {
ApptentiveLog.v("Initializing Apptentive instance: apptentiveKey=%s apptentiveSignature=%s", apptentiveKey, apptentiveSignature);
sApptentiveInternal = new ApptentiveInternal(application, apptentiveKey, apptentiveSignature, serverUrl);
sApptentiveInternal.start(); // TODO: check the result of this call
application.registerActivityLifecycleCallbacks(sApptentiveInternal.lifecycleCallbacks);
} catch (Exception e) {
ApptentiveLog.e(e, "Exception while initializing ApptentiveInternal instance");
}
} else {
ApptentiveLog.w("Apptentive instance is already initialized");
}
}
}
/**
* Retrieve the existing instance of the Apptentive class. If {@link Apptentive#register(Application)} is
* not called prior to this, it will return null; Otherwise, it will return the singleton instance initialized.
*
* @return the existing instance of the Apptentive SDK fully initialized with API key, or null
*/
public static ApptentiveInternal getInstance() {
synchronized (ApptentiveInternal.class) {
return sApptentiveInternal;
}
}
/**
* Use this method to set or clear the internal state (pass in null)
* Note: designed to be used for unit testing only
*
* @param instance the internal instance to be set to
*/
public static void setInstance(ApptentiveInternal instance) {
sApptentiveInternal = instance;
}
/*
* Set default theme whom Apptentive UI will inherit theme attributes from. Apptentive will only
* inherit from an AppCompat theme
* @param themeResId : resource id of the theme style definition, such as R.style.MyAppTheme
* @return true if the theme is set for inheritance successfully.
*/
private boolean setApplicationDefaultTheme(int themeResId) {
try {
if (themeResId != 0) {
// If passed theme res id does not exist, an exception would be thrown and caught
appContext.getResources().getResourceName(themeResId);
// Check if the theme to be inherited from is an AppCompat theme.
Resources.Theme appDefaultTheme = appContext.getResources().newTheme();
appDefaultTheme.applyStyle(themeResId, true);
TypedArray a = appDefaultTheme.obtainStyledAttributes(android.support.v7.appcompat.R.styleable.AppCompatTheme);
try {
if (a.hasValue(android.support.v7.appcompat.R.styleable.AppCompatTheme_colorPrimaryDark)) {
// Only set to use if it's an AppCompat theme. See updateApptentiveInteractionTheme() for theme inheritance chain
appDefaultAppCompatThemeId = themeResId;
return true;
}
} finally {
a.recycle();
}
}
} catch (Resources.NotFoundException e) {
ApptentiveLog.e("Theme Res id not found");
}
return false;
}
/**
* Must be called after {@link ApptentiveInternal#setApplicationDefaultTheme(int)}
*
* @return true it the app is using an AppCompat theme
*/
public boolean isAppUsingAppCompatTheme() {
return appDefaultAppCompatThemeId != 0;
}
// Object getter methods reqiure an instance. Get an instance with ApptentiveInternal.getInstance()
public Context getApplicationContext() {
return appContext;
}
public int getApplicationVersionCode() {
return appRelease.getVersionCode();
}
public String getApplicationVersionName() {
return appRelease.getVersionName();
}
public ApptentiveActivityLifecycleCallbacks getRegisteredLifecycleCallbacks() {
return lifecycleCallbacks;
}
/* Get the foreground activity from the current application, i.e. at the top of the task
* It is tracked through {@link #onActivityStarted(Activity)} and {@link #onActivityStopped(Activity)}
*
* If Apptentive interaction is to be launched from a non-activity context, use the current activity at
* the top of the task stack, i.e. the foreground activity.
*/
public Activity getCurrentTaskStackTopActivity() {
if (currentTaskStackTopActivity != null) {
return currentTaskStackTopActivity.get();
}
return null;
}
public MessageManager getMessageManager() {
final Conversation conversation = getConversation();
return conversation != null ? conversation.getMessageManager() : null;
}
public ApptentiveTaskManager getApptentiveTaskManager() {
return taskManager;
}
public ConversationManager getConversationManager() {
return conversationManager;
}
public Resources.Theme getApptentiveToolbarTheme() {
return apptentiveToolbarTheme;
}
int getDefaultStatusBarColor() {
return statusBarColorDefault;
}
public Conversation getConversation() {
return conversationManager.getActiveConversation();
}
public String getApptentiveKey() {
return apptentiveKey;
}
public String getApptentiveSignature() {
return apptentiveSignature;
}
public String getServerUrl() {
if (serverUrl == null) {
return Constants.CONFIG_DEFAULT_SERVER_URL;
}
return serverUrl;
}
public String getDefaultAppDisplayName() {
return defaultAppDisplayName;
}
public boolean isApptentiveDebuggable() {
return appRelease.isDebug();
}
public SharedPreferences getGlobalSharedPrefs() {
return globalSharedPrefs;
}
// FIXME: remove app release from this class
public AppRelease getAppRelease() {
return appRelease;
}
public ApptentiveHttpClient getApptentiveHttpClient() {
return apptentiveHttpClient;
}
public void onAppLaunch(final Context appContext) {
EngagementModule.engageInternal(appContext, EventPayload.EventLabel.app__launch.getLabelName());
}
public void onAppExit(final Context appContext) {
EngagementModule.engageInternal(appContext, EventPayload.EventLabel.app__exit.getLabelName());
}
public void onActivityStarted(Activity activity) {
if (activity != null) {
// Set current foreground activity reference whenever a new activity is started
currentTaskStackTopActivity = new WeakReference<>(activity);
// Post a notification
ApptentiveNotificationCenter.defaultCenter().postNotification(NOTIFICATION_ACTIVITY_STARTED,
NOTIFICATION_KEY_ACTIVITY, activity);
}
}
public void onActivityResumed(Activity activity) {
if (activity != null) {
// Set current foreground activity reference whenever a new activity is started
currentTaskStackTopActivity = new WeakReference<>(activity);
// Post a notification
ApptentiveNotificationCenter.defaultCenter().postNotification(NOTIFICATION_ACTIVITY_RESUMED,
NOTIFICATION_KEY_ACTIVITY, activity);
}
}
public void onAppEnterForeground() {
appIsInForeground = true;
// Post a notification
ApptentiveNotificationCenter.defaultCenter().postNotification(NOTIFICATION_APP_ENTERED_FOREGROUND);
}
public void onAppEnterBackground() {
appIsInForeground = false;
currentTaskStackTopActivity = null;
// Post a notification
ApptentiveNotificationCenter.defaultCenter().postNotification(NOTIFICATION_APP_ENTERED_BACKGROUND);
}
/* Apply Apptentive styling layers to the theme to be used by interaction. The layers include
* Apptentive defaults, and app/activity theme inheritance and app specific overrides.
*
* When the Apptentive fragments are hosted by ApptentiveViewActivity(by default), the value of theme attributes
* are obtained in the following order: ApptentiveTheme.Base.Versioned specified in Apptentive's AndroidManifest.xml ->
* app default theme specified in app AndroidManifest.xml (force) -> ApptentiveThemeOverride (force)
*
* @param interactionTheme The base theme to apply Apptentive styling layers
* @param context The context that will host Apptentive interaction fragment, either ApptentiveViewActivity
* or application context
*/
public void updateApptentiveInteractionTheme(Resources.Theme interactionTheme, Context context) {
/* Step 1: Apply Apptentive default theme layer.
* If host activity is an activity, the base theme already has Apptentive defaults applied, so skip Step 1.
* If parent activity is NOT an activity, first apply Apptentive defaults.
*/
if (!(context instanceof Activity)) {
// If host context is not an activity, i.e. application context, treat it as initial theme setup
interactionTheme.applyStyle(R.style.ApptentiveTheme_Base_Versioned, true);
}
// Step 2: Inherit app default appcompat theme if there is one specified in app's AndroidManifest
if (appDefaultAppCompatThemeId != 0) {
interactionTheme.applyStyle(appDefaultAppCompatThemeId, true);
}
// Step 3: Restore Apptentive UI window properties that may have been overridden in Step 2. This theme
// is to ensure Apptentive interaction has a modal feel-n-look.
interactionTheme.applyStyle(R.style.ApptentiveBaseFrameTheme, true);
// Step 4: Apply optional theme override specified in host app's style
int themeOverrideResId = context.getResources().getIdentifier("ApptentiveThemeOverride",
"style", getApplicationContext().getPackageName());
if (themeOverrideResId != 0) {
interactionTheme.applyStyle(themeOverrideResId, true);
}
// Step 5: Update status bar color
/* Obtain the default status bar color. When an Apptentive Modal interaction is shown,
* a translucent overlay would be applied on top of statusBarColorDefault
*/
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
int transparentColor = ContextCompat.getColor(context, android.R.color.transparent);
TypedArray a = interactionTheme.obtainStyledAttributes(new int[]{android.R.attr.statusBarColor});
try {
statusBarColorDefault = a.getColor(0, transparentColor);
} finally {
a.recycle();
}
}
// Step 6: Update toolbar overlay theme
int toolbarThemeId = Util.getResourceIdFromAttribute(interactionTheme, R.attr.apptentiveToolbarTheme);
apptentiveToolbarTheme.setTo(interactionTheme);
apptentiveToolbarTheme.applyStyle(toolbarThemeId, true);
}
private boolean start() {
boolean bRet = true;
/* If Message Center feature has never been used before, don't initialize message polling thread.
* Message Center feature will be seen as used, if one of the following conditions has been met:
* 1. Message Center has been opened for the first time
* 2. The first Push is received which would open Message Center
* 3. An unreadMessageCountListener() is set up
*/
long start = System.currentTimeMillis();
boolean conversationLoaded = conversationManager.loadActiveConversation(getApplicationContext());
ApptentiveLog.i(CONVERSATION, "Active conversation is%s loaded. Took %d ms", conversationLoaded ? "" : " not", System.currentTimeMillis() - start);
if (conversationLoaded) {
Conversation activeConversation = conversationManager.getActiveConversation();
// FIXME: don't accept the pull request before this one is resolved
// boolean featureEverUsed = activeConversation.isMessageCenterFeatureUsed();
// if (featureEverUsed) {
// messageManager.init();
}
apptentiveToolbarTheme = appContext.getResources().newTheme();
boolean apptentiveDebug = false;
String logLevelOverride = null;
try {
appPackageName = appContext.getPackageName();
PackageManager packageManager = appContext.getPackageManager();
PackageInfo packageInfo = packageManager.getPackageInfo(appPackageName, PackageManager.GET_META_DATA | PackageManager.GET_RECEIVERS);
ApplicationInfo ai = packageInfo.applicationInfo;
Bundle metaData = ai.metaData;
if (metaData != null) {
logLevelOverride = Util.trim(metaData.getString(Constants.MANIFEST_KEY_APPTENTIVE_LOG_LEVEL));
apptentiveDebug = metaData.getBoolean(Constants.MANIFEST_KEY_APPTENTIVE_DEBUG);
}
// Used for application theme inheritance if the theme is an AppCompat theme.
setApplicationDefaultTheme(ai.theme);
checkSendVersionChanges();
defaultAppDisplayName = packageManager.getApplicationLabel(packageManager.getApplicationInfo(packageInfo.packageName, 0)).toString();
// Prevent delayed run-time exception if the app upgrades from pre-2.0 and doesn't remove NetworkStateReceiver from manifest
ActivityInfo[] registered = packageInfo.receivers;
if (registered != null) {
for (ActivityInfo activityInfo : registered) {
// Throw assertion error when relict class found in manifest.
if (activityInfo.name.equals("com.apptentive.android.sdk.comm.NetworkStateReceiver")) {
throw new AssertionError("NetworkStateReceiver has been removed from Apptentive SDK, please make sure it's also removed from manifest file");
}
}
}
} catch (Exception e) {
ApptentiveLog.e("Unexpected error while reading application or package info.", e);
bRet = false;
}
// Set debuggable and appropriate log level.
if (apptentiveDebug) {
ApptentiveLog.i("Apptentive debug logging set to VERBOSE.");
setMinimumLogLevel(ApptentiveLog.Level.VERBOSE);
} else if (logLevelOverride != null) {
ApptentiveLog.i("Overriding log level: %s", logLevelOverride);
setMinimumLogLevel(ApptentiveLog.Level.parse(logLevelOverride));
} else {
if (appRelease.isDebug()) {
setMinimumLogLevel(ApptentiveLog.Level.VERBOSE);
}
}
ApptentiveLog.i("Debug mode enabled? %b", appRelease.isDebug());
// The app key can be passed in programmatically, or we can fallback to checking in the manifest.
if (TextUtils.isEmpty(apptentiveKey) || apptentiveKey.contains(Constants.EXAMPLE_APPTENTIVE_KEY_VALUE)) {
String errorMessage = "The Apptentive Key is not defined. You may provide your Apptentive Key in Apptentive.register(), or in as meta-data in your AndroidManifest.xml.\n" +
"<meta-data android:name=\"apptentive_key\"\n" +
" android:value=\"@string/your_apptentive_key\"/>";
if (appRelease.isDebug()) {
throw new RuntimeException(errorMessage);
} else {
ApptentiveLog.e(errorMessage);
}
} else {
ApptentiveLog.d("Using cached Apptentive App Key");
}
ApptentiveLog.d("Apptentive App Key: %s", apptentiveKey);
// The app signature can be passed in programmatically, or we can fallback to checking in the manifest.
if (TextUtils.isEmpty(apptentiveSignature) || apptentiveSignature.contains(Constants.EXAMPLE_APPTENTIVE_SIGNATURE_VALUE)) {
String errorMessage = "The Apptentive Signature is not defined. You may provide your Apptentive Signature in Apptentive.register(), or in as meta-data in your AndroidManifest.xml.\n" +
"<meta-data android:name=\"apptentive_signature\"\n" +
" android:value=\"@string/your_apptentive_signature\"/>";
if (appRelease.isDebug()) {
throw new RuntimeException(errorMessage);
} else {
ApptentiveLog.e(errorMessage);
}
} else {
ApptentiveLog.d("Using cached Apptentive App Signature");
}
ApptentiveLog.d("Apptentive App Signature: %s", apptentiveSignature);
// Grab app info we need to access later on.
ApptentiveLog.d("Default Locale: %s", Locale.getDefault().toString());
return bRet;
}
private void checkSendVersionChanges() {
final Conversation conversation = getConversation();
if (conversation == null) {
ApptentiveLog.e("Can't check session data changes: session data is not initialized");
return;
}
boolean appReleaseChanged = false;
boolean sdkChanged = false;
final VersionHistoryItem lastVersionItemSeen = conversation.getVersionHistory().getLastVersionSeen();
final int currentVersionCode = appRelease.getVersionCode();
final String currentVersionName = appRelease.getVersionName();
Integer previousVersionCode = null;
String previousVersionName = null;
if (lastVersionItemSeen == null) {
appReleaseChanged = true;
} else {
previousVersionCode = lastVersionItemSeen.getVersionCode();
Apptentive.Version lastSeenVersionNameVersion = new Apptentive.Version();
previousVersionName = lastVersionItemSeen.getVersionName();
lastSeenVersionNameVersion.setVersion(previousVersionName);
if (!(currentVersionCode == previousVersionCode) || !currentVersionName.equals(lastSeenVersionNameVersion.getVersion())) {
appReleaseChanged = true;
}
}
// TODO: Move this into a session became active handler.
final String lastSeenSdkVersion = conversation.getLastSeenSdkVersion();
final String currentSdkVersion = Constants.APPTENTIVE_SDK_VERSION;
if (!TextUtils.equals(lastSeenSdkVersion, currentSdkVersion)) {
sdkChanged = true;
}
if (appReleaseChanged) {
ApptentiveLog.i("Version changed: Name: %s => %s, Code: %d => %d", previousVersionName, currentVersionName, previousVersionCode, currentVersionCode);
conversation.getVersionHistory().updateVersionHistory(Util.currentTimeSeconds(), currentVersionCode, currentVersionName);
}
Sdk sdk = SdkManager.generateCurrentSdk();
if (sdkChanged) {
ApptentiveLog.i("SDK version changed: %s => %s", lastSeenSdkVersion, currentSdkVersion);
conversation.setLastSeenSdkVersion(currentSdkVersion);
conversation.setSdk(sdk);
}
if (appReleaseChanged || sdkChanged) {
taskManager.addPayload(AppReleaseManager.getPayload(sdk, appRelease));
invalidateCaches();
}
}
/**
* We want to make sure the app is using the latest configuration from the server if the app or sdk version changes.
*/
private void invalidateCaches() {
Conversation conversation = getConversation();
if (conversation != null) {
conversation.setInteractionExpiration(0L);
}
Configuration config = Configuration.load();
config.setConfigurationCacheExpirationMillis(System.currentTimeMillis());
config.save();
}
/**
* Fetches the global app configuration from the server and stores the keys into our SharedPreferences.
*/
private void fetchAppConfiguration() { // FIXME: remove unused method
ApptentiveLog.i("Fetching new Configuration task started.");
ApptentiveHttpResponse response = ApptentiveClient.getAppConfiguration();
try {
Map<String, String> headers = response.getHeaders();
if (headers != null) {
String cacheControl = headers.get("Cache-Control");
Integer cacheSeconds = Util.parseCacheControlHeader(cacheControl);
if (cacheSeconds == null) {
cacheSeconds = Constants.CONFIG_DEFAULT_APP_CONFIG_EXPIRATION_DURATION_SECONDS;
}
ApptentiveLog.d("Caching configuration for %d seconds.", cacheSeconds);
Configuration config = new Configuration(response.getContent());
config.setConfigurationCacheExpirationMillis(System.currentTimeMillis() + cacheSeconds * 1000);
config.save();
}
} catch (JSONException e) {
ApptentiveLog.e("Error parsing app configuration from server.", e);
}
}
public IRatingProvider getRatingProvider() {
if (ratingProvider == null) {
ratingProvider = new GooglePlayRatingProvider();
}
return ratingProvider;
}
void setRatingProvider(IRatingProvider ratingProvider) {
this.ratingProvider = ratingProvider;
}
public Map<String, String> getRatingProviderArgs() {
return ratingProviderArgs;
}
void putRatingProviderArg(String key, String value) {
if (ratingProviderArgs == null) {
ratingProviderArgs = new HashMap<>();
}
ratingProviderArgs.put(key, value);
}
void setOnSurveyFinishedListener(OnSurveyFinishedListener onSurveyFinishedListener) {
if (onSurveyFinishedListener != null) {
this.onSurveyFinishedListener = new WeakReference<>(onSurveyFinishedListener);
} else {
this.onSurveyFinishedListener = null;
}
}
public OnSurveyFinishedListener getOnSurveyFinishedListener() {
return (onSurveyFinishedListener == null) ? null : onSurveyFinishedListener.get();
}
public void addInteractionUpdateListener(InteractionManager.InteractionUpdateListener listener) {
interactionUpdateListeners.add(listener);
}
public void removeInteractionUpdateListener(InteractionManager.InteractionUpdateListener listener) {
interactionUpdateListeners.remove(listener);
}
public void setAuthenticationFailureListener(Apptentive.AuthenticationFailedListener listener) {
authenticationFailedListenerRef = new WeakReference<>(listener);
}
public void notifyAuthenticationFailedListener(Apptentive.AuthenticationFailedReason reason, String conversationIdOfFailedRequest) {
if (isConversationActive()) {
String activeConversationId = getConversation().getConversationId();
if (activeConversationId.equals(conversationIdOfFailedRequest)) {
Apptentive.AuthenticationFailedListener listener = authenticationFailedListenerRef.get();
if (listener != null) {
listener.onAuthenticationFailed(reason);
}
return;
}
}
}
/**
* Pass in a log level to override the default, which is {@link ApptentiveLog.Level#INFO}
*/
private void setMinimumLogLevel(ApptentiveLog.Level level) {
ApptentiveLog.overrideLogLevel(level);
}
private String pushCallbackActivityName;
public void setPushCallbackActivity(Class<? extends Activity> activity) {
pushCallbackActivityName = activity.getName();
ApptentiveLog.d("Setting push callback activity name to %s", pushCallbackActivityName);
}
public String getPushCallbackActivityName() {
return pushCallbackActivityName;
}
/**
* The key that is used to store extra data on an Apptentive push notification.
*/
static final String APPTENTIVE_PUSH_EXTRA_KEY = "apptentive";
static final String PUSH_EXTRA_KEY_PARSE = "com.parse.Data";
static final String PUSH_EXTRA_KEY_UA = "com.urbanairship.push.EXTRA_PUSH_MESSAGE_BUNDLE";
static final String TITLE_DEFAULT = "title";
static final String BODY_DEFAULT = "body";
static final String BODY_PARSE = "alert";
static final String BODY_UA = "com.urbanairship.push.ALERT";
static String getApptentivePushNotificationData(Intent intent) {
if (intent != null) {
ApptentiveLog.v("Got an Intent.");
return getApptentivePushNotificationData(intent.getExtras());
}
return null;
}
/**
* <p>Internal use only.</p>
* This bundle could be any bundle sent to us by a push Intent from any supported platform. For that reason, it needs to be checked in multiple ways.
*
* @param pushBundle a Bundle, or null.
* @return a String, or null.
*/
static String getApptentivePushNotificationData(Bundle pushBundle) {
if (pushBundle != null) {
if (pushBundle.containsKey(PUSH_EXTRA_KEY_PARSE)) { // Parse
ApptentiveLog.v("Got a Parse Push.");
String parseDataString = pushBundle.getString(PUSH_EXTRA_KEY_PARSE);
if (parseDataString == null) {
ApptentiveLog.e("com.parse.Data is null.");
return null;
}
try {
JSONObject parseJson = new JSONObject(parseDataString);
return parseJson.optString(APPTENTIVE_PUSH_EXTRA_KEY, null);
} catch (JSONException e) {
ApptentiveLog.e("com.parse.Data is corrupt: %s", parseDataString);
return null;
}
} else if (pushBundle.containsKey(PUSH_EXTRA_KEY_UA)) { // Urban Airship
ApptentiveLog.v("Got an Urban Airship push.");
Bundle uaPushBundle = pushBundle.getBundle(PUSH_EXTRA_KEY_UA);
if (uaPushBundle == null) {
ApptentiveLog.e("Urban Airship push extras bundle is null");
return null;
}
return uaPushBundle.getString(APPTENTIVE_PUSH_EXTRA_KEY);
} else if (pushBundle.containsKey(APPTENTIVE_PUSH_EXTRA_KEY)) { // All others
// Straight FCM / GCM / SNS, or nested
ApptentiveLog.v("Found apptentive push data.");
return pushBundle.getString(APPTENTIVE_PUSH_EXTRA_KEY);
} else {
ApptentiveLog.e("Got an unrecognizable push.");
}
}
ApptentiveLog.e("Push bundle was null.");
return null;
}
static String getApptentivePushNotificationData(Map<String, String> pushData) {
if (pushData != null) {
return pushData.get(APPTENTIVE_PUSH_EXTRA_KEY);
}
return null;
}
public void showAboutInternal(Context context, boolean showBrandingBand) {
Intent intent = new Intent();
intent.setClass(context, ApptentiveViewActivity.class);
intent.putExtra(Constants.FragmentConfigKeys.TYPE, Constants.FragmentTypes.ABOUT);
intent.putExtra(Constants.FragmentConfigKeys.EXTRA, showBrandingBand);
if (!(context instanceof Activity)) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
}
context.startActivity(intent);
}
static PendingIntent generatePendingIntentFromApptentivePushData(String apptentivePushData) {
ApptentiveLog.d("Generating Apptentive push PendingIntent.");
if (!TextUtils.isEmpty(apptentivePushData)) {
try {
JSONObject pushJson = new JSONObject(apptentivePushData);
// we need to check if current user is actually the receiver of this notification
final String conversationId = pushJson.optString(PUSH_CONVERSATION_ID, null);
if (conversationId != null) {
final Conversation conversation = ApptentiveInternal.getInstance().getConversation();
// do we have a conversation right now?
if (conversation == null) {
ApptentiveLog.i("Can't generate pending intent from Apptentive push data: no active conversation");
return null;
}
// is it an actual receiver?
if (!StringUtils.equal(conversation.getConversationId(), conversationId)) {
ApptentiveLog.i("Can't generate pending intent from Apptentive push data: push conversation id doesn't match active conversation");
return null;
}
}
ApptentiveInternal.PushAction action = ApptentiveInternal.PushAction.unknown;
if (pushJson.has(ApptentiveInternal.PUSH_ACTION)) {
action = ApptentiveInternal.PushAction.parse(pushJson.getString(ApptentiveInternal.PUSH_ACTION));
}
switch (action) {
case pmc: {
// Prefetch message when push for message center is received
MessageManager mgr = ApptentiveInternal.getInstance().getMessageManager();
if (mgr != null) {
mgr.startMessagePreFetchTask();
}
// Construct a pending intent to launch message center
return ApptentiveInternal.prepareMessageCenterPendingIntent(ApptentiveInternal.getInstance().getApplicationContext());
}
default:
ApptentiveLog.w("Unknown Apptentive push notification action: \"%s\"", action.name());
}
} catch (JSONException e) {
ApptentiveLog.e("Error parsing JSON from push notification.", e);
MetricModule.sendError(e, "Parsing Apptentive Push", apptentivePushData);
}
}
return null;
}
public boolean showMessageCenterInternal(Context context, Map<String, Object> customData) {
boolean interactionShown = false;
if (canShowMessageCenterInternal()) {
if (customData != null) {
Iterator<String> keysIterator = customData.keySet().iterator();
while (keysIterator.hasNext()) {
String key = keysIterator.next();
Object value = customData.get(key);
if (value != null) {
if (!(value instanceof String ||
value instanceof Boolean ||
value instanceof Long ||
value instanceof Double ||
value instanceof Float ||
value instanceof Integer ||
value instanceof Short)) {
ApptentiveLog.w("Removing invalid customData type: %s", value.getClass().getSimpleName());
keysIterator.remove();
}
}
}
}
this.customData = customData;
interactionShown = EngagementModule.engageInternal(context, MessageCenterInteraction.DEFAULT_INTERNAL_EVENT_NAME);
if (!interactionShown) {
this.customData = null;
}
} else {
showMessageCenterFallback(context);
}
return interactionShown;
}
public void showMessageCenterFallback(Context context) {
EngagementModule.launchMessageCenterErrorActivity(context);
}
public boolean canShowMessageCenterInternal() {
return EngagementModule.canShowInteraction("com.apptentive", "app", MessageCenterInteraction.DEFAULT_INTERNAL_EVENT_NAME);
}
public Map<String, Object> getAndClearCustomData() {
Map<String, Object> customData = this.customData;
this.customData = null;
return customData;
}
public void resetSdkState() {
globalSharedPrefs.edit().clear().apply();
taskManager.reset(appContext);
}
public void notifyInteractionUpdated(boolean successful) {
Iterator it = interactionUpdateListeners.iterator();
while (it.hasNext()) {
InteractionManager.InteractionUpdateListener listener = (InteractionManager.InteractionUpdateListener) it.next();
if (listener != null) {
listener.onInteractionUpdated(successful);
}
}
}
public static PendingIntent prepareMessageCenterPendingIntent(Context context) {
Intent intent;
if (Apptentive.canShowMessageCenter()) {
intent = new Intent();
intent.setClass(context, ApptentiveViewActivity.class);
intent.putExtra(Constants.FragmentConfigKeys.TYPE, Constants.FragmentTypes.ENGAGE_INTERNAL_EVENT);
intent.putExtra(Constants.FragmentConfigKeys.EXTRA, MessageCenterInteraction.DEFAULT_INTERNAL_EVENT_NAME);
} else {
intent = MessageCenterInteraction.generateMessageCenterErrorIntent(context);
}
return (intent != null) ? PendingIntent.getActivity(context, 0, intent,
PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT) : null;
}
/**
* Checks to see if Apptentive was properly registered, and logs a message if not.
*
* @return true if properly registered, else false.
*/
public static boolean checkRegistered() {
if (!ApptentiveInternal.isApptentiveRegistered()) {
ApptentiveLog.e("Error: You have failed to call Apptentive.register() in your Application.onCreate()");
return false;
}
return true;
}
//region Helpers
private String getEndpointBase(SharedPreferences prefs) {
String url = prefs.getString(Constants.PREF_KEY_SERVER_URL, null);
if (url == null) {
url = Constants.CONFIG_DEFAULT_SERVER_URL;
prefs.edit().putString(Constants.PREF_KEY_SERVER_URL, url).apply();
}
return url;
}
//endregion
//region Login/Logout
void login(String token, final LoginCallback callback) {
LoginCallback wrapperCallback = new LoginCallback() {
@Override
public void onLoginFinish() {
EngagementModule.engageInternal(getApplicationContext(), "login");
if (callback != null) {
callback.onLoginFinish();
}
}
@Override
public void onLoginFail(String errorMessage) {
if (callback != null) {
callback.onLoginFail(errorMessage);
}
}
};
conversationManager.login(token, wrapperCallback);
}
void logout() {
EngagementModule.engageInternal(getApplicationContext(), "logout");
conversationManager.logout();
}
//endregion
/**
* Dismisses any currently-visible interactions. This method is for internal use and is subject to change.
*/
public static void dismissAllInteractions() {
ApptentiveNotificationCenter.defaultCenter().postNotification(NOTIFICATION_INTERACTIONS_SHOULD_DISMISS);
}
@Override
public void onReceiveNotification(ApptentiveNotification notification) {
if (notification.hasName(NOTIFICATION_CONVERSATION_WILL_LOGOUT)) {
getApptentiveTaskManager().addPayload(new LogoutPayload());
} else if (notification.hasName(NOTIFICATION_AUTHENTICATION_FAILED)) {
String conversationIdOfFailedRequest = notification.getUserInfo(NOTIFICATION_KEY_CONVERSATION_ID, String.class);
Apptentive.AuthenticationFailedReason authenticationFailedReason = notification.getUserInfo(NOTIFICATION_KEY_AUTHENTICATION_FAILED_REASON, Apptentive.AuthenticationFailedReason.class);
notifyAuthenticationFailedListener(authenticationFailedReason, conversationIdOfFailedRequest);
}
}
}
|
/*
* Author : Stephen Chong
* Created: Nov 21, 2003
*/
package polyglot.pth;
import java.io.File;
import java.util.*;
import polyglot.util.ErrorInfo;
import polyglot.util.SilentErrorQueue;
public class SourceFileTest extends AbstractTest {
protected final List sourceFilenames;
protected String extensionClassname = null;
protected String[] extraArgs;
protected final SilentErrorQueue eq;
protected String destDir;
protected List expectedFailures;
public SourceFileTest(String filename) {
super(new File(filename).getName());
this.sourceFilenames = Collections.singletonList(filename);
this.eq = new SilentErrorQueue(100, this.getName());
}
public SourceFileTest(List filenames) {
super(filenames.toString());
this.sourceFilenames = filenames;
this.eq = new SilentErrorQueue(100, this.getName());
}
public SourceFileTest(String[] filenames) {
this(Arrays.asList(filenames).toString());
}
public void setExpectedFailures(List expectedFailures) {
this.expectedFailures = expectedFailures;
}
protected boolean runTest() {
for (Iterator i = sourceFilenames.iterator(); i.hasNext(); ) {
File sourceFile = new File((String)i.next());
if (!sourceFile.exists()) {
setFailureMessage("File not found.");
return false;
}
}
// invoke the compiler on the file.
try {
invokePolyglot(getSourceFileNames());
}
catch (polyglot.main.Main.TerminationException e) {
if (e.getMessage() != null) {
setFailureMessage(e.getMessage());
return false;
}
else {
if (!eq.hasErrors()) {
setFailureMessage("Failed to compile for unknown reasons: " +
e.toString());
return false;
}
}
}
catch (RuntimeException e) {
if (e.getMessage() != null) {
setFailureMessage(e.getMessage());
e.printStackTrace();
return false;
}
else {
setFailureMessage("Uncaught " + e.getClass().getName());
e.printStackTrace();
return false;
}
}
return checkErrorQueue(eq);
}
protected void postRun() {
output.finishTest(this, eq);
}
protected boolean checkErrorQueue(SilentErrorQueue eq) {
List errors = new ArrayList(eq.getErrors());
boolean swallowRemainingFailures = false;
for (Iterator i = expectedFailures.iterator(); i.hasNext(); ) {
ExpectedFailure f = (ExpectedFailure)i.next();
if (f instanceof AnyExpectedFailure) {
swallowRemainingFailures = true;
continue;
}
boolean found = false;
for (Iterator j = errors.iterator(); j.hasNext(); ) {
ErrorInfo e =(ErrorInfo)j.next();
if (f.matches(e)) {
// this error info has been matched. remove it.
found = true;
j.remove();
break;
}
}
if (!found) {
setFailureMessage("Expected to see " + f.toString());
return false;
}
}
// are there any unaccounted for errors?
if (!errors.isEmpty() && !swallowRemainingFailures) {
StringBuffer sb = new StringBuffer();
for (Iterator iter = errors.iterator(); iter.hasNext(); ) {
ErrorInfo err = (ErrorInfo)iter.next();
sb.append(err.getMessage());
if (err.getPosition() != null) {
sb.append(" (");
sb.append(err.getPosition());
sb.append(")");
}
if (iter.hasNext()) sb.append("; ");
}
setFailureMessage(sb.toString());
}
return errors.isEmpty() || swallowRemainingFailures;
}
protected String[] getSourceFileNames() {
return (String[])sourceFilenames.toArray(new String[0]);
}
protected void invokePolyglot(String[] files)
throws polyglot.main.Main.TerminationException
{
File tmpdir = new File("pthOutput");
int i = 1;
while (tmpdir.exists()) {
tmpdir = new File("pthOutput." + i);
i++;
}
tmpdir.mkdir();
setDestDir(tmpdir.getPath());
String[] cmdLine = buildCmdLine(files);
polyglot.main.Main polyglotMain = new polyglot.main.Main();
try {
polyglotMain.start(cmdLine, eq);
}
finally {
if (Main.options.deleteOutputFiles) {
deleteDir(tmpdir);
}
setDestDir(null);
}
}
protected void deleteDir(File dir) {
File[] list = dir.listFiles();
for (int i = 0; i < list.length; i++) {
if (list[i].isDirectory()) {
deleteDir(list[i]);
}
else {
list[i].delete();
}
}
dir.delete();
}
protected String[] buildCmdLine(String[] files) {
ArrayList args = new ArrayList();
String s;
String[] sa;
if ((s = getExtensionClassname()) != null) {
args.add("-extclass");
args.add(s);
}
if ((s = getAdditionalClasspath()) != null) {
args.add("-cp");
args.add(s);
}
if ((s = getDestDir()) != null) {
args.add("-d");
args.add(s);
}
if ((s = getSourceDir()) != null) {
args.add("-sourcepath");
args.add(s);
}
char pathSep = File.pathSeparatorChar;
if ((s = Main.options.extraArgs) != null) {
sa = breakString(Main.options.extraArgs);
for (int i = 0; i < sa.length; i++) {
String sas = sa[i];
if (pathSep != ':' && sas.indexOf(':') >= 0) {
sas = replacePathSep(sas, pathSep);
}
args.add(sas);
}
}
if ((sa = getExtraCmdLineArgs()) != null) {
for (int i = 0; i < sa.length; i++) {
String sas = sa[i];
if (pathSep != ':' && sas.indexOf(':') >= 0) {
sas = replacePathSep(sas, pathSep);
}
args.add(sas);
}
}
args.addAll(Arrays.asList(files));
return (String[])args.toArray(new String[0]);
}
/**
* @param sas
* @param pathSep
* @return
*/
private String replacePathSep(String sas, char pathSep) {
// replace path separater ':' with appropriate
// system specific one
StringBuffer sb = new StringBuffer();
for (int j = 0; j < sas.length(); j++) {
if (sas.charAt(j) == '\\' && (j+1) < sas.length() && sas.charAt(j+1) == ':') {
// escaped ':'
j++;
sb.append(':');
}
else if (sas.charAt(j) == ':') {
sb.append(pathSep);
}
else {
sb.append(sas.charAt(j));
}
}
return sb.toString();
}
protected String getExtensionClassname() {
return extensionClassname;
}
protected void setExtensionClassname(String extClassname) {
this.extensionClassname = extClassname;
}
protected String[] getExtraCmdLineArgs() {
return this.extraArgs;
}
protected static String[] breakString(String s) {
StringTokenizer st = new StringTokenizer(s);
ArrayList l = new ArrayList(st.countTokens());
while (st.hasMoreTokens()) {
l.add(st.nextToken());
}
return (String[])l.toArray(new String[l.size()]);
}
protected void setExtraCmdLineArgs(String args) {
if (args != null) {
this.extraArgs = breakString(args);
}
}
protected String getAdditionalClasspath() {
return Main.options.classpath;
}
protected void setDestDir(String dir) {
this.destDir = dir;
}
protected String getDestDir() {
return destDir;
}
protected String getSourceDir() {
return null;
}
}
|
package net.tomp2p.dht;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NavigableMap;
import java.util.Random;
import java.util.TreeMap;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import net.tomp2p.connection.Bindings;
import net.tomp2p.connection.ChannelClientConfiguration;
import net.tomp2p.connection.ChannelServerConfiguration;
import net.tomp2p.connection.PeerException;
import net.tomp2p.connection.PeerException.AbortCause;
import net.tomp2p.futures.BaseFuture;
import net.tomp2p.futures.BaseFutureAdapter;
import net.tomp2p.futures.FutureBootstrap;
import net.tomp2p.futures.FutureDirect;
import net.tomp2p.futures.FutureDone;
import net.tomp2p.futures.FuturePeerConnection;
import net.tomp2p.message.Buffer;
import net.tomp2p.p2p.AutomaticFuture;
import net.tomp2p.p2p.Peer;
import net.tomp2p.p2p.PeerBuilder;
import net.tomp2p.p2p.RequestP2PConfiguration;
import net.tomp2p.p2p.RoutingConfiguration;
import net.tomp2p.peers.Number160;
import net.tomp2p.peers.Number320;
import net.tomp2p.peers.Number480;
import net.tomp2p.peers.Number640;
import net.tomp2p.peers.PeerAddress;
import net.tomp2p.peers.PeerMap;
import net.tomp2p.peers.PeerMapConfiguration;
import net.tomp2p.peers.PeerStatistic;
import net.tomp2p.rpc.DigestResult;
import net.tomp2p.rpc.ObjectDataReply;
import net.tomp2p.rpc.RawDataReply;
import net.tomp2p.storage.Data;
import net.tomp2p.storage.DataBuffer;
import net.tomp2p.utils.Utils;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TestDHT {
final private static Random rnd = new Random(42L);
private static final Logger LOG = LoggerFactory.getLogger(TestDHT.class);
@Rule
public TestRule watcher = new TestWatcher() {
protected void starting(Description description) {
System.out.println("Starting test: " + description.getMethodName());
}
};
@Test
public void testPutBig() throws Exception {
PeerDHT[] peers = null;
try {
peers = testPutBig1("1");
//Thread.sleep(5 * 1000);
//master = testPutBig1("2");
//Thread.sleep(5 * 1000);
//master = testPutBig1("3");
//Thread.sleep(5 * 1000);
//Thread.sleep(Integer.MAX_VALUE);
} finally {
for (PeerDHT peerDHT:peers) {
if(peerDHT!=null) {
peerDHT.shutdown().await();
}
}
System.out.println("done");
}
}
private PeerDHT[] testPutBig1(String key) throws Exception {
Peer[] peers = UtilsDHT2.createRealNodes(10, rnd, 4001, new AutomaticFuture() {
@Override
public void futureCreated(BaseFuture future) { }
});
PeerDHT[] peers2 = new PeerDHT[10];
for(int i=0;i<peers.length;i++) {
peers2[i] = new PeerBuilderDHT(peers[i]).start();
}
UtilsDHT2.perfectRouting(peers2);
Data data1 = new Data(new byte[10*1024*1024]);
RequestP2PConfiguration rp = new RequestP2PConfiguration(1, 0, 0);
//for(int i=0;i<10000;i++) {
PutBuilder pb = peers2[0].put(Number160.createHash(key)).requestP2PConfiguration(rp).data(data1);
FuturePut futurePut = pb.start();
futurePut.awaitUninterruptibly();
Assert.assertEquals(true, futurePut.isSuccess());
System.out.println("stored on "+futurePut.result());
FutureRemove fr = peers2[0].remove(Number160.createHash(key)).start().awaitUninterruptibly();
System.out.println("removed from "+fr.result());
return peers2;
}
@Test
public void testPutTwo() throws Exception {
PeerDHT master = null;
try {
PeerDHT[] peers = UtilsDHT2.createNodes(10, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
final Data data1 = new Data(new byte[1]);
data1.ttlSeconds(3);
FuturePut futurePut = master.put(Number160.createHash("test")).data(data1).start();
futurePut.awaitUninterruptibly();
Assert.assertEquals(true, futurePut.isSuccess());
FutureGet futureGet = peers[1].get(Number160.createHash("test")).start();
futureGet.awaitUninterruptibly();
Assert.assertEquals(true, futureGet.isSuccess());
// LOG.error("done");
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testPutVersion() throws Exception {
final Random rnd = new Random(42L);
PeerDHT master = null;
try {
PeerDHT[] peers = UtilsDHT2.createNodes(10, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
final Data data1 = new Data(new byte[1]);
data1.ttlSeconds(3);
FuturePut futurePut = master.put(Number160.createHash("test")).versionKey(Number160.MAX_VALUE)
.data(data1).start();
futurePut.awaitUninterruptibly();
Assert.assertEquals(true, futurePut.isSuccess());
Map<Number640, Data> map = peers[0].storageLayer().get();
Assert.assertEquals(Number160.MAX_VALUE, map.entrySet().iterator().next().getKey().versionKey());
LOG.error("done");
} finally {
if (master != null) {
master.shutdown().awaitUninterruptibly();
master.shutdown().awaitListenersUninterruptibly();
}
}
}
@Test
public void testPutPerforomance() throws Exception {
PeerDHT master = null;
try {
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(2000, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
for (int i = 0; i < 500; i++) {
//long start = System.currentTimeMillis();
FuturePut fp = peers[444].put(Number160.createHash("1")).data(new Data("test")).start();
fp.awaitUninterruptibly();
fp.futureRequests().awaitUninterruptibly();
//long stop = System.currentTimeMillis();
//System.out.println("Test " + fp.failedReason() + " / " + (stop - start) + "ms");
Assert.assertEquals(true, fp.isSuccess());
}
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testPut() throws Exception {
PeerDHT master = null;
try {
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(2000, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
// do testing
Data data = new Data(new byte[44444]);
RoutingConfiguration rc = new RoutingConfiguration(2, 10, 2);
RequestP2PConfiguration pc = new RequestP2PConfiguration(3, 5, 0);
FuturePut fp = peers[444].put(peers[30].peerID())
.data(Number160.createHash("test"), new Number160(5), data).requestP2PConfiguration(pc)
.routingConfiguration(rc).start();
fp.awaitUninterruptibly();
fp.futureRequests().awaitUninterruptibly();
System.out.println("Test " + fp.failedReason());
Assert.assertEquals(true, fp.isSuccess());
peers[30].peerBean().peerMap();
// search top 3
TreeMap<PeerAddress, Integer> tmp = new TreeMap<PeerAddress, Integer>(PeerMap.createXORAddressComparator(peers[30]
.peer().peerID()));
int i = 0;
for (PeerDHT node : peers) {
tmp.put(node.peer().peerAddress(), i);
i++;
}
Entry<PeerAddress, Integer> e = tmp.pollFirstEntry();
System.out.println("1 (" + e.getValue() + ")" + e.getKey());
Assert.assertEquals(peers[e.getValue()].peerAddress(), peers[30].peerAddress());
testForArray(peers[e.getValue()], peers[30].peerID(), true);
e = tmp.pollFirstEntry();
System.out.println("2 (" + e.getValue() + ")" + e.getKey());
testForArray(peers[e.getValue()], peers[30].peerID(), true);
e = tmp.pollFirstEntry();
System.out.println("3 " + e.getKey());
testForArray(peers[e.getValue()], peers[30].peerID(), true);
e = tmp.pollFirstEntry();
System.out.println("4 " + e.getKey());
testForArray(peers[e.getValue()], peers[30].peerID(), false);
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testPutGetAlone() throws Exception {
PeerDHT master = null;
try {
master = new PeerBuilderDHT(new PeerBuilder(new Number160(rnd)).ports(4001).start()).start();
FuturePut fdht = master.put(Number160.ONE).data(new Data("hallo")).start();
fdht.awaitUninterruptibly();
fdht.futureRequests().awaitUninterruptibly();
Assert.assertEquals(true, fdht.isSuccess());
FutureGet fdht2 = master.get(Number160.ONE).start();
fdht2.awaitUninterruptibly();
System.out.println(fdht2.failedReason());
Assert.assertEquals(true, fdht2.isSuccess());
Data tmp = fdht2.data();
Assert.assertEquals("hallo", tmp.object().toString());
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testPutTimeout() throws Exception {
PeerDHT master = null;
try {
Peer pmaster = new PeerBuilder(new Number160(rnd)).ports(4001).start();
master = new PeerBuilderDHT(pmaster).storage(new StorageMemory(1)).start();
Data data = new Data("hallo");
data.ttlSeconds(1);
FuturePut fdht = master.put(Number160.ONE).data(data).start();
fdht.awaitUninterruptibly();
fdht.futureRequests().awaitUninterruptibly();
Assert.assertEquals(true, fdht.isSuccess());
Thread.sleep(3000);
FutureGet fdht2 = master.get(Number160.ONE).start();
fdht2.awaitUninterruptibly();
System.out.println(fdht2.failedReason());
//we get an empty result, this means it did not fail, just it did not return anything
Assert.assertEquals(true, fdht2.isSuccess());
Data tmp = fdht2.data();
Assert.assertNull(tmp);
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testPut2() throws Exception {
PeerDHT master = null;
try {
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(500, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
// do testing
Data data = new Data(new byte[44444]);
RoutingConfiguration rc = new RoutingConfiguration(0, 0, 1);
RequestP2PConfiguration pc = new RequestP2PConfiguration(1, 0, 0);
FuturePut fdht = peers[444].put(peers[30].peerID()).data(new Number160(5), data)
.domainKey(Number160.createHash("test")).routingConfiguration(rc)
.requestP2PConfiguration(pc).start();
fdht.awaitUninterruptibly();
fdht.futureRequests().awaitUninterruptibly();
Assert.assertEquals(true, fdht.isSuccess());
peers[30].peerBean().peerMap();
// search top 3
TreeMap<PeerAddress, Integer> tmp = new TreeMap<PeerAddress, Integer>(PeerMap.createXORAddressComparator(peers[30]
.peerID()));
int i = 0;
for (PeerDHT node : peers) {
tmp.put(node.peerAddress(), i);
i++;
}
Entry<PeerAddress, Integer> e = tmp.pollFirstEntry();
Assert.assertEquals(peers[e.getValue()].peerAddress(), peers[30].peerAddress());
testForArray(peers[e.getValue()], peers[30].peerID(), true);
e = tmp.pollFirstEntry();
testForArray(peers[e.getValue()], peers[30].peerID(), false);
e = tmp.pollFirstEntry();
testForArray(peers[e.getValue()], peers[30].peerID(), false);
e = tmp.pollFirstEntry();
testForArray(peers[e.getValue()], peers[30].peerID(), false);
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testPutGet() throws Exception {
PeerDHT master = null;
try {
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(2000, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
// do testing
RoutingConfiguration rc = new RoutingConfiguration(2, 10, 2);
RequestP2PConfiguration pc = new RequestP2PConfiguration(3, 5, 0);
Data data = new Data(new byte[44444]);
FuturePut fput = peers[444].put(peers[30].peerID()).data(new Number160(5), data)
.domainKey(Number160.createHash("test")).routingConfiguration(rc)
.requestP2PConfiguration(pc).start();
fput.awaitUninterruptibly();
fput.futureRequests().awaitUninterruptibly();
Assert.assertEquals(true, fput.isSuccess());
rc = new RoutingConfiguration(0, 0, 10, 1);
pc = new RequestP2PConfiguration(1, 0, 0);
FutureGet fget = peers[555].get(peers[30].peerID()).domainKey(Number160.createHash("test"))
.contentKey(new Number160(5)).routingConfiguration(rc).requestP2PConfiguration(pc).start();
fget.awaitUninterruptibly();
Assert.assertEquals(true, fget.isSuccess());
Assert.assertEquals(1, fget.rawData().size());
Assert.assertEquals(true, fget.isMinReached());
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testPutGetRelease() throws Exception {
PeerDHT master = null;
try {
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(2000, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
// do testing
RoutingConfiguration rc = new RoutingConfiguration(2, 10, 2);
RequestP2PConfiguration pc = new RequestP2PConfiguration(3, 5, 0);
Data data = new Data(new byte[44444]);
FuturePut fput = peers[444].put(peers[30].peerID()).data(new Number160(5), data)
.domainKey(Number160.createHash("test")).routingConfiguration(rc)
.requestP2PConfiguration(pc).start();
fput.awaitUninterruptibly();
fput.futureRequests().awaitUninterruptibly();
Assert.assertEquals(true, fput.isSuccess());
rc = new RoutingConfiguration(0, 0, 10, 1);
pc = new RequestP2PConfiguration(1, 0, 0);
FutureGet fget = peers[555].get(peers[30].peerID()).domainKey(Number160.createHash("test"))
.contentKey(new Number160(5)).routingConfiguration(rc).requestP2PConfiguration(pc).start();
fget.awaitUninterruptibly();
Assert.assertEquals(true, fget.isSuccess());
Assert.assertEquals(true, fget.rawData().values().iterator().next().values().iterator().next().isHeapBuffer());
Assert.assertEquals(true, fget.requests().get(0).responseMessage().dataMap(0).dataMap().values().iterator().next().isHeapBuffer());
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testPutConvert() throws Exception {
PeerDHT master = null;
try {
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(2000, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
// do testing
RoutingConfiguration rc = new RoutingConfiguration(2, 10, 2);
RequestP2PConfiguration pc = new RequestP2PConfiguration(3, 5, 0);
Data data = new Data(new byte[44444]);
NavigableMap<Number160, Data> tmp = new TreeMap<Number160, Data>();
tmp.put(new Number160(5), data);
FuturePut fput = peers[444].put(peers[30].peerID()).dataMapContent(tmp)
.domainKey(Number160.createHash("test")).routingConfiguration(rc)
.requestP2PConfiguration(pc).start();
fput.awaitUninterruptibly();
fput.futureRequests().awaitUninterruptibly();
System.out.println(fput.failedReason());
Assert.assertEquals(true, fput.isSuccess());
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testPutGet2() throws Exception {
PeerDHT master = null;
try {
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(1000, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
// do testing
RoutingConfiguration rc = new RoutingConfiguration(2, 10, 2);
RequestP2PConfiguration pc = new RequestP2PConfiguration(3, 5, 0);
Data data = new Data(new byte[44444]);
FuturePut fput = peers[444].put(peers[30].peerID()).data(new Number160(5), data)
.domainKey(Number160.createHash("test")).routingConfiguration(rc)
.requestP2PConfiguration(pc).start();
fput.awaitUninterruptibly();
fput.futureRequests().awaitUninterruptibly();
Assert.assertEquals(true, fput.isSuccess());
rc = new RoutingConfiguration(4, 0, 10, 1);
pc = new RequestP2PConfiguration(4, 0, 0);
FutureGet fget = peers[555].get(peers[30].peerID()).domainKey(Number160.createHash("test"))
.contentKey(new Number160(5)).routingConfiguration(rc).requestP2PConfiguration(pc).start();
fget.awaitUninterruptibly();
Assert.assertEquals(true, fget.isSuccess());
Assert.assertEquals(3, fget.rawData().size());
Assert.assertEquals(true, fget.isMinReached());
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testPutGet3() throws Exception {
PeerDHT master = null;
try {
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(2000, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
// do testing
Data data = new Data(new byte[44444]);
RoutingConfiguration rc = new RoutingConfiguration(2, 10, 2);
RequestP2PConfiguration pc = new RequestP2PConfiguration(3, 5, 0);
FuturePut fput = peers[444].put(peers[30].peerID()).data(new Number160(5), data)
.domainKey(Number160.createHash("test")).routingConfiguration(rc)
.requestP2PConfiguration(pc).start();
fput.awaitUninterruptibly();
fput.futureRequests().awaitUninterruptibly();
Assert.assertEquals(true, fput.isSuccess());
rc = new RoutingConfiguration(1, 0, 10, 1);
pc = new RequestP2PConfiguration(1, 0, 0);
for (int i = 0; i < 1000; i++) {
FutureGet fget = peers[100 + i].get(peers[30].peerID()).domainKey(Number160.createHash("test"))
.contentKey(new Number160(5)).routingConfiguration(rc).requestP2PConfiguration(pc)
.start();
fget.awaitUninterruptibly();
Assert.assertEquals(true, fget.isSuccess());
Assert.assertEquals(1, fget.rawData().size());
Assert.assertEquals(true, fget.isMinReached());
}
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testPutGetRemove() throws Exception {
PeerDHT master = null;
try {
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(2000, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
// do testing
Data data = new Data(new byte[44444]);
RoutingConfiguration rc = new RoutingConfiguration(2, 10, 2);
RequestP2PConfiguration pc = new RequestP2PConfiguration(3, 5, 0);
FuturePut fput = peers[444].put(peers[30].peerID()).domainKey(Number160.createHash("test"))
.data(new Number160(5), data).routingConfiguration(rc).requestP2PConfiguration(pc).start();
fput.awaitUninterruptibly();
fput.futureRequests().awaitUninterruptibly();
Assert.assertEquals(true, fput.isSuccess());
rc = new RoutingConfiguration(4, 0, 10, 1);
pc = new RequestP2PConfiguration(3, 0, 0);
FutureRemove frem = peers[222].remove(peers[30].peerID()).domainKey(Number160.createHash("test"))
.contentKey(new Number160(5)).routingConfiguration(rc).requestP2PConfiguration(pc).start();
frem.awaitUninterruptibly();
Assert.assertEquals(true, frem.isSuccess());
Assert.assertEquals(3, frem.rawKeys().size());
FutureGet fget = peers[555].get(peers[30].peerID()).domainKey(Number160.createHash("test"))
.contentKey(new Number160(5)).routingConfiguration(rc).requestP2PConfiguration(pc).start();
fget.awaitUninterruptibly();
Assert.assertEquals(true, fget.isEmpty());
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testPutGetRemove2() throws Exception {
PeerDHT master = null;
try {
// rnd.setSeed(253406013991563L);
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(2000, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
// do testing
Data data = new Data(new byte[44444]);
RoutingConfiguration rc = new RoutingConfiguration(2, 10, 2);
RequestP2PConfiguration pc = new RequestP2PConfiguration(3, 5, 0);
FuturePut fput = peers[444].put(peers[30].peerID()).data(new Number160(5), data)
.domainKey(Number160.createHash("test")).routingConfiguration(rc)
.requestP2PConfiguration(pc).start();
fput.awaitUninterruptibly();
fput.futureRequests().awaitUninterruptibly();
Assert.assertEquals(3, fput.rawResult().size());
Assert.assertEquals(true, fput.isSuccess());
System.out.println("remove");
rc = new RoutingConfiguration(4, 0, 10, 1);
pc = new RequestP2PConfiguration(3, 0, 0);
FutureRemove frem = peers[222].remove(peers[30].peerID()).returnResults()
.domainKey(Number160.createHash("test")).contentKey(new Number160(5))
.routingConfiguration(rc).requestP2PConfiguration(pc).start();
frem.awaitUninterruptibly();
Assert.assertEquals(true, frem.isSuccess());
Assert.assertEquals(3, frem.rawData().size());
System.out.println("get");
rc = new RoutingConfiguration(4, 0, 0, 1);
pc = new RequestP2PConfiguration(4, 0, 0);
FutureGet fget = peers[555].get(peers[30].peerID()).domainKey(Number160.createHash("test"))
.contentKey(new Number160(5)).routingConfiguration(rc).requestP2PConfiguration(pc).start();
fget.awaitUninterruptibly();
Assert.assertTrue(fget.isEmpty());
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testDirect() throws Exception {
PeerDHT master = null;
try {
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(1000, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
final AtomicInteger ai = new AtomicInteger(0);
for (int i = 0; i < peers.length; i++) {
peers[i].peer().objectDataReply(new ObjectDataReply() {
@Override
public Object reply(PeerAddress sender, Object request) throws Exception {
ai.incrementAndGet();
return "ja";
}
});
}
// do testing
FutureSend fdir = peers[400].send(new Number160(rnd)).object("hallo").start();
fdir.awaitUninterruptibly();
System.out.println(fdir.failedReason());
Assert.assertEquals(true, fdir.isSuccess());
Assert.assertEquals(true, ai.get() >= 3 && ai.get() <= 6);
System.out.println("called: " + ai.get());
Assert.assertEquals("ja", fdir.object());
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testAddListGet() throws Exception {
PeerDHT master = null;
try {
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(200, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
// do testing
Number160 nr = new Number160(rnd);
String toStore1 = "hallo1";
String toStore2 = "hallo1";
Data data1 = new Data(toStore1.getBytes());
Data data2 = new Data(toStore2.getBytes());
FuturePut fput = peers[30].add(nr).data(data1).list(true).start();
fput.awaitUninterruptibly();
System.out.println("added: " + toStore1 + " (" + fput.isSuccess() + ")");
fput = peers[50].add(nr).data(data2).list(true).start();
fput.awaitUninterruptibly();
System.out.println("added: " + toStore2 + " (" + fput.isSuccess() + ")");
FutureGet fget = peers[77].get(nr).all().start();
fget.awaitUninterruptibly();
Assert.assertEquals(true, fget.isSuccess());
// majority voting with getDataMap is not possible since we create
// random content key on the recipient
Assert.assertEquals(2, fget.rawData().values().iterator().next().values().size());
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testAddGet() throws Exception {
PeerDHT master = null;
try {
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(200, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
// do testing
Number160 nr = new Number160(rnd);
String toStore1 = "hallo1";
String toStore2 = "hallo2";
Data data1 = new Data(toStore1.getBytes());
Data data2 = new Data(toStore2.getBytes());
FuturePut fput = peers[30].add(nr).data(data1).start();
fput.awaitUninterruptibly();
System.out.println("added: " + toStore1 + " (" + fput.isSuccess() + ")");
fput = peers[50].add(nr).data(data2).start();
fput.awaitUninterruptibly();
System.out.println("added: " + toStore2 + " (" + fput.isSuccess() + ")");
FutureGet fget = peers[77].get(nr).all().start();
fget.awaitUninterruptibly();
Assert.assertEquals(true, fget.isSuccess());
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testDigest() throws Exception {
PeerDHT master = null;
try {
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(200, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
// do testing
Number160 nr = new Number160(rnd);
String toStore1 = "hallo1";
String toStore2 = "hallo2";
String toStore3 = "hallo3";
Data data1 = new Data(toStore1.getBytes());
Data data2 = new Data(toStore2.getBytes());
Data data3 = new Data(toStore3.getBytes());
FuturePut fput = peers[30].add(nr).data(data1).start();
fput.awaitUninterruptibly();
System.out.println("added: " + toStore1 + " (" + fput.isSuccess() + ")");
fput = peers[50].add(nr).data(data2).start();
fput.awaitUninterruptibly();
System.out.println("added: " + toStore2 + " (" + fput.isSuccess() + ")");
fput = peers[51].add(nr).data(data3).start();
fput.awaitUninterruptibly();
System.out.println("added: " + toStore3 + " (" + fput.isSuccess() + ")");
FutureDigest fget = peers[77].digest(nr).all().start();
fget.awaitUninterruptibly();
System.out.println(fget.failedReason());
Assert.assertEquals(true, fget.isSuccess());
Assert.assertEquals(3, fget.digest().keyDigest().size());
Number160 test = new Number160("0x37bb570100c9f5445b534757ebc613a32df3836d");
List<Number160> test2 = new ArrayList<Number160>();
test2.add(test);
fget = peers[67].digest(nr).contentKeys(test2).start();
fget.awaitUninterruptibly();
Assert.assertEquals(true, fget.isSuccess());
Assert.assertEquals(1, fget.digest().keyDigest().size());
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void removeTestLoop() throws IOException, ClassNotFoundException {
for(int i=0;i<100;i++) {
System.out.println("removeTestLoop() call nr "+i);
removeTest();
}
}
@Test
public void removeTest() throws IOException, ClassNotFoundException {
PeerDHT p1 = null;
PeerDHT p2 = null;
try {
p1 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(1)).ports(5000).start()).start();
p2 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(2)).masterPeer(p1.peer())
.start()).start();
p2.peer().bootstrap().peerAddress(p1.peerAddress()).start().awaitUninterruptibly();
String locationKey = "location";
String contentKey = "content";
String data = "testme";
// data.generateVersionKey();
p2.put(Number160.createHash(locationKey)).data(Number160.createHash(contentKey), new Data(data))
.versionKey(Number160.ONE).start().awaitUninterruptibly();
FutureRemove futureRemove = p1.remove(Number160.createHash(locationKey)).domainKey(Number160.ZERO)
.contentKey(Number160.createHash(contentKey)).versionKey(Number160.ONE).start();
futureRemove.awaitUninterruptibly();
FutureDigest futureDigest = p1.digest(Number160.createHash(locationKey)).domainKey(Number160.ZERO)
.contentKey(Number160.createHash(contentKey)).versionKey(Number160.ONE).start();
futureDigest.awaitUninterruptibly();
Assert.assertTrue(futureDigest.digest().keyDigest().isEmpty());
} finally {
if(p1 != null) {
p1.shutdown().awaitUninterruptibly();
}
if(p2 != null) {
p2.shutdown().awaitUninterruptibly();
}
}
}
@Test
public void testDigest2() throws Exception {
PeerDHT master = null;
try {
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(200, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
// do testing
Number160 nr = new Number160(rnd);
String toStore1 = "hallo1";
String toStore2 = "hallo2";
String toStore3 = "hallo3";
Data data1 = new Data(toStore1.getBytes());
Data data2 = new Data(toStore2.getBytes());
Data data3 = new Data(toStore3.getBytes());
Number160 key1 = new Number160(1);
Number160 key2 = new Number160(2);
Number160 key3 = new Number160(3);
FuturePut fput = peers[30].put(nr).data(key1, data1).start();
fput.awaitUninterruptibly();
System.out.println("added: " + toStore1 + " (" + fput.isSuccess() + ")");
fput = peers[50].put(nr).data(key2, data2).start();
fput.awaitUninterruptibly();
System.out.println("added: " + toStore2 + " (" + fput.isSuccess() + ")");
fput = peers[51].put(nr).data(key3, data3).start();
fput.awaitUninterruptibly();
System.out.println("added: " + toStore3 + " (" + fput.isSuccess() + ")");
Number640 from = new Number640(nr, Number160.ZERO, Number160.ZERO, Number160.ZERO);
Number640 to = new Number640(nr, Number160.MAX_VALUE, Number160.MAX_VALUE, Number160.MAX_VALUE);
FutureDigest fget = peers[77].digest(nr).from(from).to(to).returnNr(1).start();
fget.awaitUninterruptibly();
System.out.println(fget.failedReason());
Assert.assertEquals(true, fget.isSuccess());
Assert.assertEquals(1, fget.digest().keyDigest().size());
Assert.assertEquals(key1, fget.digest().keyDigest().keySet().iterator().next().contentKey());
fget = peers[67].digest(nr).from(from).to(to).returnNr(1).descending().start();
fget.awaitUninterruptibly();
System.out.println(fget.failedReason());
Assert.assertEquals(true, fget.isSuccess());
Assert.assertEquals(1, fget.digest().keyDigest().size());
Assert.assertEquals(key3, fget.digest().keyDigest().keySet().iterator().next().contentKey());
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testDigest3() throws Exception {
PeerDHT master = null;
try {
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(200, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
// initialize test data
Number160 lKey = new Number160(rnd);
String toStore1 = "hallo1";
String toStore2 = "hallo2";
String toStore3 = "hallo3";
Data data1 = new Data(toStore1.getBytes());
Data data2 = new Data(toStore2.getBytes());
Data data3 = new Data(toStore3.getBytes());
Number160 ckey = new Number160(rnd);
data1.addBasedOn(Number160.ONE);
Number160 versionKey1 = new Number160(1, data1.hash());
data2.addBasedOn(versionKey1);
Number160 versionKey2 = new Number160(2, data2.hash());
data3.addBasedOn(versionKey2);
Number160 versionKey3 = new Number160(3, data3.hash());
// put test data
FuturePut fput = peers[30].put(lKey).data(ckey, data1, versionKey1).start();
fput.awaitUninterruptibly();
fput = peers[50].put(lKey).data(ckey, data2, versionKey2).start();
fput.awaitUninterruptibly();
fput = peers[51].put(lKey).data(ckey, data3, versionKey3).start();
fput.awaitUninterruptibly();
// get digest
FutureDigest fget = peers[77].digest(lKey).all().start();
fget.awaitUninterruptibly();
DigestResult dr = fget.digest();
NavigableMap<Number640, Collection<Number160>> map = dr.keyDigest();
// verify fetched digest
Entry<Number640, Collection<Number160>> e1 = map.pollFirstEntry();
Assert.assertEquals(Number160.ONE, e1.getValue().iterator().next());
Assert.assertEquals(new Number640(lKey, Number160.ZERO, ckey, versionKey1), e1.getKey());
Entry<Number640, Collection<Number160>> e2 = map.pollFirstEntry();
Assert.assertEquals(versionKey1, e2.getValue().iterator().next());
Assert.assertEquals(new Number640(lKey, Number160.ZERO, ckey, versionKey2), e2.getKey());
Entry<Number640, Collection<Number160>> e3 = map.pollFirstEntry();
Assert.assertEquals(versionKey2, e3.getValue().iterator().next());
Assert.assertEquals(new Number640(lKey, Number160.ZERO, ckey, versionKey3), e3.getKey());
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testDigest4() throws Exception {
PeerDHT master = null;
try {
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(100, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
// initialize test data
Number160 lKey = new Number160(rnd);
Number160 dKey = new Number160(rnd);
Number160 ckey = new Number160(rnd);
NavigableMap<Number640, Data> dataMap = new TreeMap<Number640, Data>();
Number160 bKey = Number160.ONE;
for (int i = 0; i < 10; i++) {
Data data = new Data(UUID.randomUUID());
data.addBasedOn(bKey);
Number160 vKey = new Number160(i, data.hash());
dataMap.put(new Number640(lKey, dKey, ckey, vKey), data);
bKey = vKey;
}
// put test data
for (Number640 key : dataMap.keySet()) {
FuturePut fput = peers[rnd.nextInt(100)].put(lKey).domainKey(dKey)
.data(ckey, dataMap.get(key)).versionKey(key.versionKey()).start();
fput.awaitUninterruptibly();
}
// get digest
FutureDigest fget = peers[rnd.nextInt(100)].digest(lKey)
.from(new Number640(lKey, dKey, ckey, Number160.ZERO))
.to(new Number640(lKey, dKey, ckey, Number160.MAX_VALUE)).start();
fget.awaitUninterruptibly();
DigestResult dr = fget.digest();
NavigableMap<Number640, Collection<Number160>> fetchedDataMap = dr.keyDigest();
// verify fetched digest
Assert.assertEquals(dataMap.size(), fetchedDataMap.size());
for (Number640 key : dataMap.keySet()) {
Assert.assertTrue(fetchedDataMap.containsKey(key));
Assert.assertEquals(dataMap.get(key).basedOnSet().iterator().next(), fetchedDataMap.get(key)
.iterator().next());
}
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testData() throws Exception {
PeerDHT master = null;
try {
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(200, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
// do testing
ByteBuf c = Unpooled.buffer();
c.writeInt(77);
DataBuffer d = new DataBuffer(c);
peers[50].peer().rawDataReply(new RawDataReply() {
@Override
public Buffer reply(PeerAddress sender, Buffer requestBuffer, boolean complete) {
System.out.println(requestBuffer.buffer().readInt());
ByteBuf c = Unpooled.buffer();
c.writeInt(88);
Buffer ret = new Buffer(c);
return ret;
}
});
FutureDirect fd = master.peer().sendDirect(peers[50].peerAddress()).dataBuffer(d).start();
fd.await();
if (fd.buffer() == null) {
System.out.println("damm");
Assert.fail();
}
int read = fd.buffer().buffer().readInt();
Assert.assertEquals(88, read);
System.out.println("done");
// for(FutureBootstrap fb:tmp)
// fb.awaitUninterruptibly();
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testData2() throws Exception {
PeerDHT master = null;
try {
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(200, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
// do testing
ByteBuf c = Unpooled.buffer();
c.writeInt(77);
DataBuffer d = new DataBuffer(c);
peers[50].peer().rawDataReply(new RawDataReply() {
@Override
public Buffer reply(PeerAddress sender, Buffer requestBuffer, boolean complete) {
System.out.println("got it");
return requestBuffer;
}
});
FutureDirect fd = master.peer().sendDirect(peers[50].peerAddress()).dataBuffer(d).start();
fd.await();
System.out.println("done1 " + fd.failedReason());
Assert.assertEquals(true, fd.isSuccess());
Assert.assertNull(fd.buffer());
// int read = fd.getBuffer().readInt();
// Assert.assertEquals(88, read);
System.out.println("done2");
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testObjectLoop() throws Exception {
for (int i = 0; i < 1000; i++) {
if(i%10==0) {
System.out.println("nr: " + i);
}
testObject();
}
}
@Test
public void testObject() throws Exception {
PeerDHT master = null;
try {
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(100, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
// do testing
Number160 nr = new Number160(rnd);
String toStore1 = "hallo1";
String toStore2 = "hallo2";
Data data1 = new Data(toStore1);
Data data2 = new Data(toStore2);
//System.out.println("begin add : ");
FuturePut fput = peers[30].add(nr).data(data1).start();
fput.awaitUninterruptibly();
//System.out.println("stop added: " + toStore1 + " (" + fput.isSuccess() + ")");
fput = peers[50].add(nr).data(data2).start();
fput.awaitUninterruptibly();
fput.futureRequests().awaitUninterruptibly();
//System.out.println("added: " + toStore2 + " (" + fput.isSuccess() + ")");
FutureGet fget = peers[77].get(nr).all().start();
fget.awaitUninterruptibly();
fget.futureRequests().awaitUninterruptibly();
if (!fget.isSuccess())
System.out.println(fget.failedReason());
Assert.assertEquals(true, fget.isSuccess());
Assert.assertEquals(2, fget.dataMap().size());
//System.out.println("got it");
} finally {
if (master != null) {
master.shutdown().awaitListenersUninterruptibly();
}
}
}
@Test
public void testMaintenanceInit() throws Exception {
PeerDHT master = null;
try {
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(2000, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRoutingIndirect(peers);
// do testing
PeerStatistic peerStatatistic = master.peerBean().peerMap()
.nextForMaintenance(new ArrayList<PeerAddress>());
Assert.assertNotEquals(master.peerAddress(), peerStatatistic.peerAddress());
Thread.sleep(10000);
System.out.println("DONE");
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testAddGetPermits() throws Exception {
PeerDHT master = null;
try {
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(2000, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
// do testing
Number160 nr = new Number160(rnd);
List<FuturePut> list = new ArrayList<FuturePut>();
for (int i = 0; i < peers.length; i++) {
String toStore1 = "hallo" + i;
Data data1 = new Data(toStore1.getBytes());
FuturePut fput = peers[i].add(nr).data(data1).start();
list.add(fput);
}
for (FuturePut futureDHT : list) {
futureDHT.awaitUninterruptibly();
Assert.assertEquals(true, futureDHT.isSuccess());
}
System.out.println("DONE");
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testhalt() throws Exception {
PeerDHT master1 = null;
PeerDHT master2 = null;
PeerDHT master3 = null;
try {
master1 = new PeerBuilderDHT(new PeerBuilder(new Number160(rnd)).p2pId(1).ports(4001).start()).start();
master2 = new PeerBuilderDHT(new PeerBuilder(new Number160(rnd)).p2pId(1).ports(4002).start()).start();
master3 = new PeerBuilderDHT(new PeerBuilder(new Number160(rnd)).p2pId(1).ports(4003).start()).start();
// perfect routing
master1.peerBean().peerMap().peerFound(master2.peerAddress(), null, null, null);
master1.peerBean().peerMap().peerFound(master3.peerAddress(), null, null, null);
master2.peerBean().peerMap().peerFound(master1.peerAddress(), null, null, null);
master2.peerBean().peerMap().peerFound(master3.peerAddress(), null, null, null);
master3.peerBean().peerMap().peerFound(master1.peerAddress(), null, null, null);
master3.peerBean().peerMap().peerFound(master2.peerAddress(), null, null, null);
Number160 id = master2.peerID();
Data data = new Data(new byte[44444]);
RoutingConfiguration rc = new RoutingConfiguration(2, 10, 2);
RequestP2PConfiguration pc = new RequestP2PConfiguration(3, 5, 0);
FuturePut fput = master1.put(id).data(new Number160(5), data).domainKey(Number160.createHash("test"))
.requestP2PConfiguration(pc).routingConfiguration(rc).start();
fput.awaitUninterruptibly();
fput.futureRequests().awaitUninterruptibly();
// Collection<Number160> tmp = new ArrayList<Number160>();
// tmp.add(new Number160(5));
Assert.assertEquals(true, fput.isSuccess());
// search top 3
master2.shutdown().await();
FutureGet fget = master1.get(id).routingConfiguration(rc).requestP2PConfiguration(pc)
.domainKey(Number160.createHash("test")).contentKey(new Number160(5)).start();
fget.awaitUninterruptibly();
Assert.assertEquals(true, fget.isSuccess());
master1.peerBean().peerMap().peerFailed(master2.peerAddress(), new PeerException(AbortCause.SHUTDOWN, "shutdown"));
master3.peerBean().peerMap().peerFailed(master2.peerAddress(), new PeerException(AbortCause.SHUTDOWN, "shutdown"));
master2 = new PeerBuilderDHT(new PeerBuilder(new Number160(rnd)).p2pId(1).ports(4002).start()).start();
master1.peerBean().peerMap().peerFound(master2.peerAddress(), null, null, null);
master3.peerBean().peerMap().peerFound(master2.peerAddress(), null, null, null);
master2.peerBean().peerMap().peerFound(master1.peerAddress(), null, null, null);
master2.peerBean().peerMap().peerFound(master3.peerAddress(), null, null, null);
System.out.println("no more exceptions here!!");
fget = master1.get(id).routingConfiguration(rc).requestP2PConfiguration(pc)
.domainKey(Number160.createHash("test")).contentKey(new Number160(5)).start();
fget.awaitUninterruptibly();
Assert.assertEquals(true, fget.isSuccess());
} finally {
if (master1 != null) {
master1.shutdown().await();
}
if (master2 != null) {
master2.shutdown().await();
}
if (master3 != null) {
master3.shutdown().await();
}
}
}
@Test
public void testObjectSendExample() throws Exception {
Peer p1 = null;
Peer p2 = null;
try {
p1 = new PeerBuilder(new Number160(rnd)).ports(4001).start();
p2 = new PeerBuilder(new Number160(rnd)).ports(4002).start();
// attach reply handler
p2.objectDataReply(new ObjectDataReply() {
@Override
public Object reply(PeerAddress sender, Object request) throws Exception {
System.out.println("request [" + request + "]");
return "world";
}
});
FutureDirect futureData = p1.sendDirect(p2.peerAddress()).object("hello").start();
futureData.awaitUninterruptibly();
System.out.println("reply [" + futureData.object() + "]");
} finally {
if (p1 != null) {
p1.shutdown().await();
}
if (p2 != null) {
p2.shutdown().await();
}
}
}
@Test
public void testObjectSend() throws Exception {
PeerDHT master = null;
try {
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(500, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
for (int i = 0; i < peers.length; i++) {
System.out.println("node " + i);
peers[i].peer().objectDataReply(new ObjectDataReply() {
@Override
public Object reply(PeerAddress sender, Object request) throws Exception {
return request;
}
});
peers[i].peer().rawDataReply(new RawDataReply() {
@Override
public Buffer reply(PeerAddress sender, Buffer requestBuffer, boolean complete) throws Exception {
return requestBuffer;
}
});
}
// do testing
System.out.println("round start");
Random rnd = new Random(42L);
byte[] toStore1 = new byte[10 * 1024];
for (int j = 0; j < 5; j++) {
System.out.println("round " + j);
for (int i = 0; i < peers.length - 1; i++) {
send1(peers[rnd.nextInt(peers.length)], peers[rnd.nextInt(peers.length)], toStore1, 100);
send2(peers[rnd.nextInt(peers.length)], peers[rnd.nextInt(peers.length)],
Unpooled.wrappedBuffer(toStore1), 100);
System.out.println("round1 " + i);
}
}
System.out.println("DONE");
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testKeys() throws Exception {
final Random rnd = new Random(42L);
PeerDHT p1 = null;
PeerDHT p2 = null;
try {
Number160 n1 = new Number160(rnd);
Data d1 = new Data("hello");
Data d2 = new Data("world!");
// setup (step 1)
p1 = new PeerBuilderDHT(new PeerBuilder(new Number160(rnd)).ports(4001).start()).start();
FuturePut fput = p1.add(n1).data(d1).start();
fput.awaitUninterruptibly();
Assert.assertEquals(true, fput.isSuccess());
p2 = new PeerBuilderDHT(new PeerBuilder(new Number160(rnd)).ports(4002).start()).start();
p2.peer().bootstrap().peerAddress(p1.peerAddress()).start().awaitUninterruptibly();
// test (step 2)
fput = p1.add(n1).data(d2).start();
fput.awaitUninterruptibly();
Assert.assertEquals(true, fput.isSuccess());
FutureGet fget = p2.get(n1).all().start();
fget.awaitUninterruptibly();
Assert.assertEquals(2, fget.dataMap().size());
// test (step 3)
FutureRemove frem = p1.remove(n1).contentKey(d2.hash()).start();
frem.awaitUninterruptibly();
Assert.assertEquals(true, frem.isSuccess());
fget = p2.get(n1).all().start();
fget.awaitUninterruptibly();
Assert.assertEquals(1, fget.dataMap().size());
// test (step 4)
fput = p1.add(n1).data(d2).start();
fput.awaitUninterruptibly();
Assert.assertEquals(true, fput.isSuccess());
fget = p2.get(n1).all().start();
fget.awaitUninterruptibly();
Assert.assertEquals(2, fget.dataMap().size());
// test (remove all)
frem = p1.remove(n1).contentKey(d1.hash()).start();
frem.awaitUninterruptibly();
frem = p1.remove(n1).contentKey(d2.hash()).start();
frem.awaitUninterruptibly();
fget = p2.get(n1).all().start();
fget.awaitUninterruptibly();
Assert.assertEquals(0, fget.dataMap().size());
System.out.println("testKeys done");
} finally {
if (p1 != null) {
p1.shutdown().await();
}
if (p2 != null) {
p2.shutdown().await();
}
}
}
@Test
public void testKeys2() throws Exception {
final Random rnd = new Random(42L);
PeerDHT p1 = null;
PeerDHT p2 = null;
try {
Number160 n1 = new Number160(rnd);
Number160 n2 = new Number160(rnd);
Data d1 = new Data("hello");
Data d2 = new Data("world!");
// setup (step 1)
p1 = new PeerBuilderDHT(new PeerBuilder(new Number160(rnd)).ports(4001).start()).start();
FuturePut fput = p1.put(n1).data(d1).start();
fput.awaitUninterruptibly();
Assert.assertEquals(true, fput.isSuccess());
p2 = new PeerBuilderDHT(new PeerBuilder(new Number160(rnd)).ports(4002).start()).start();
p2.peer().bootstrap().peerAddress(p1.peerAddress()).start().awaitUninterruptibly();
// test (step 2)
fput = p1.put(n2).data(d2).start();
fput.awaitUninterruptibly();
Assert.assertEquals(true, fput.isSuccess());
FutureGet fget = p2.get(n2).start();
fget.awaitUninterruptibly();
Assert.assertEquals(1, fget.dataMap().size());
// test (step 3)
FutureRemove frem = p1.remove(n2).start();
frem.awaitUninterruptibly();
Assert.assertEquals(true, frem.isSuccess());
fget = p2.get(n2).start();
fget.awaitUninterruptibly();
Assert.assertEquals(0, fget.dataMap().size());
// test (step 4)
fput = p1.put(n2).data(d2).start();
fput.awaitUninterruptibly();
Assert.assertEquals(true, fput.isSuccess());
fget = p2.get(n2).start();
fget.awaitUninterruptibly();
Assert.assertEquals(1, fget.dataMap().size());
System.out.println("testKeys2 done");
} finally {
if (p1 != null) {
p1.shutdown().await();
}
if (p2 != null) {
p2.shutdown().await();
}
}
}
@Test
public void testPutGetAll() throws Exception {
final AtomicBoolean running = new AtomicBoolean(true);
PeerDHT master = null;
try {
// setup
final PeerDHT[] peers = UtilsDHT2.createNodes(100, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
final Number160 key = Number160.createHash("test");
final Data data1 = new Data("test1");
data1.ttlSeconds(3);
final Data data2 = new Data("test2");
data2.ttlSeconds(3);
// add every second a two values
Thread t = new Thread(new Runnable() {
@Override
public void run() {
while (running.get()) {
peers[10].add(key).data(data1).start().awaitUninterruptibly();
peers[10].add(key).data(data2).start().awaitUninterruptibly();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
t.start();
// wait until the first data is stored.
Thread.sleep(1000);
for (int i = 0; i < 30; i++) {
FutureGet fget = peers[20 + i].get(key).all().start();
fget.awaitUninterruptibly();
Assert.assertEquals(2, fget.dataMap().size());
Thread.sleep(1000);
}
} finally {
running.set(false);
if (master != null) {
master.shutdown().await();
}
}
}
/**
* This will probably fail on your machine since you have to have eth0
* configured. This testcase is suited for running on the tomp2p.net server
*
* @throws Exception
*/
@Test
public void testBindings() throws Exception {
final Random rnd = new Random(42L);
Peer p1 = null;
Peer p2 = null;
try {
// setup (step 1)
Bindings b = new Bindings();
p1 = new PeerBuilder(new Number160(rnd)).ports(4001).bindings(b).start();
p2 = new PeerBuilder(new Number160(rnd)).ports(4002).bindings(b).start();
FutureBootstrap fb = p2.bootstrap().peerAddress(p1.peerAddress()).start();
fb.awaitUninterruptibly();
Assert.assertEquals(true, fb.isSuccess());
System.out.println("testBindings done");
} finally {
if (p1 != null) {
p1.shutdown().await();
}
if (p2 != null) {
p2.shutdown().await();
}
}
}
@Test
public void testTooManyOpenFilesInSystem() throws Exception {
Peer master = null;
Peer slave = null;
try {
// since we have two peers, we need to reduce the connections -> we
// will have 300 * 2 (peer connection)
// plus 100 * 2 * 2. The last multiplication is due to discover,
// where the recipient creates a connection
// with its own limit. Since the limit is 1024 and we stop at 1000
// only for the connection, we may run into
// too many open files
PeerBuilder masterMaker = new PeerBuilder(new Number160(rnd)).ports(4001);
master = masterMaker.enableMaintenance(false).start();
PeerBuilder slaveMaker = new PeerBuilder(new Number160(rnd)).ports(4002);
slave = slaveMaker.enableMaintenance(false).start();
System.out.println("peers up and running");
slave.rawDataReply(new RawDataReply() {
@Override
public Buffer reply(PeerAddress sender, Buffer requestBuffer, boolean last) throws Exception {
final byte[] b1 = new byte[10000];
int i = requestBuffer.buffer().getInt(0);
ByteBuf buf = Unpooled.wrappedBuffer(b1);
buf.setInt(0, i);
return new Buffer(buf);
}
});
List<BaseFuture> list1 = new ArrayList<BaseFuture>();
List<BaseFuture> list2 = new ArrayList<BaseFuture>();
List<FuturePeerConnection> list3 = new ArrayList<FuturePeerConnection>();
for (int i = 0; i < 125; i++) {
final byte[] b = new byte[10000];
FuturePeerConnection pc = master.createPeerConnection(slave.peerAddress());
list1.add(master.sendDirect(pc).dataBuffer(new DataBuffer(Unpooled.wrappedBuffer(b))).start());
list3.add(pc);
// pc.close();
}
for (int i = 0; i < 20000; i++) {
list2.add(master.discover().peerAddress(slave.peerAddress()).start());
final byte[] b = new byte[1000];
byte[] me = Utils.intToByteArray(i);
System.arraycopy(me, 0, b, 0, 4);
list2.add(master.sendDirect(slave.peerAddress()).dataBuffer(new DataBuffer(Unpooled.wrappedBuffer(b)))
.start());
}
for (BaseFuture bf : list1) {
bf.awaitUninterruptibly();
bf.awaitListenersUninterruptibly();
if (bf.isFailed()) {
System.out.println("WTF " + bf.failedReason());
} else {
System.out.print(",");
}
Assert.assertEquals(true, bf.isSuccess());
}
for (BaseFuture bf : list2) {
bf.awaitUninterruptibly();
bf.awaitListenersUninterruptibly();
if (bf.isFailed()) {
System.out.println("WTF " + bf.failedReason());
} else {
System.out.print(".");
}
Assert.assertEquals(true, bf.isSuccess());
}
for (FuturePeerConnection pc : list3) {
pc.close().awaitUninterruptibly();
pc.close().awaitListenersUninterruptibly();
}
System.out.println("done!!");
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("done!1!");
if (master != null) {
master.shutdown().await();
}
if (slave != null) {
slave.shutdown().await();
}
}
}
@Test
public void testTooManyDiscover() throws Exception {
Peer master = null;
Peer slave = null;
try {
// since we have two peers, we need to reduce the connections -> we
// will have 300 * 2 (peer connection)
// plus 100 * 2 * 2. The last multiplication is due to discover,
// where the recipient creates a connection
// with its own limit. Since the limit is 1024 and we stop at 1000
// only for the connection, we may run into
// too many open files
PeerBuilder masterMaker = new PeerBuilder(new Number160(rnd)).ports(4001);
master = masterMaker.enableMaintenance(false).start();
PeerBuilder slaveMaker = new PeerBuilder(new Number160(rnd)).ports(4002);
slave = slaveMaker.enableMaintenance(false).start();
System.out.println("peers up and running");
List<BaseFuture> list2 = new ArrayList<BaseFuture>();
for (int i = 0; i < 20000; i++) {
list2.add(master.discover().peerAddress(slave.peerAddress()).start());
}
for (BaseFuture bf : list2) {
bf.awaitUninterruptibly();
bf.awaitListenersUninterruptibly();
if (bf.isFailed()) {
System.out.println("WTF " + bf.failedReason());
} else {
System.out.print(".");
}
Assert.assertEquals(true, bf.isSuccess());
}
System.out.println("done!!");
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("done!1!");
if (master != null) {
master.shutdown().await();
}
if (slave != null) {
slave.shutdown().await();
}
}
}
@Test
public void testThreads() throws Exception {
PeerDHT master = null;
PeerDHT slave = null;
try {
DefaultEventExecutorGroup eventExecutorGroup = new DefaultEventExecutorGroup(250);
ChannelClientConfiguration ccc1 = PeerBuilder.createDefaultChannelClientConfiguration();
ccc1.pipelineFilter(new PeerBuilder.EventExecutorGroupFilter(eventExecutorGroup));
ChannelServerConfiguration ccs1 = PeerBuilder.createDefaultChannelServerConfiguration();
ccs1.pipelineFilter(new PeerBuilder.EventExecutorGroupFilter(eventExecutorGroup));
master = new PeerBuilderDHT(new PeerBuilder(new Number160(rnd)).ports(4001).channelClientConfiguration(ccc1)
.channelServerConfiguration(ccs1).start()).start();
slave = new PeerBuilderDHT(new PeerBuilder(new Number160(rnd)).ports(4002).channelClientConfiguration(ccc1)
.channelServerConfiguration(ccs1).start()).start();
master.peer().bootstrap().peerAddress(slave.peerAddress()).start().awaitUninterruptibly();
slave.peer().bootstrap().peerAddress(master.peerAddress()).start().awaitUninterruptibly();
System.out.println("peers up and running");
final int count = 100;
final CountDownLatch latch = new CountDownLatch(count);
final AtomicBoolean correct = new AtomicBoolean(true);
for (int i = 0; i < count; i++) {
FuturePut futurePut = master.put(Number160.ONE).data(new Data("test")).start();
futurePut.addListener(new BaseFutureAdapter<FuturePut>() {
@Override
public void operationComplete(FuturePut future) throws Exception {
Thread.sleep(1000);
latch.countDown();
System.out.println("block in "+Thread.currentThread().getName());
if(!Thread.currentThread().getName().contains("EventExecutorGroup")) {
correct.set(false);
}
}
});
}
latch.await(10, TimeUnit.SECONDS);
Assert.assertTrue(correct.get());
} finally {
System.out.println("done!1!");
if (master != null) {
master.shutdown().await();
}
if (slave != null) {
slave.shutdown().await();
}
System.out.println("done!2!");
}
}
@Test
public void removeFromToTest3() throws IOException, ClassNotFoundException {
PeerDHT p1 = null;
PeerDHT p2 = null;
try {
p1 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(1)).ports(5000).start()).start();
p2 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(2)).masterPeer(p1.peer()).start()).start();
p2.peer().bootstrap().peerAddress(p1.peerAddress()).start().awaitUninterruptibly();
p1.peer().bootstrap().peerAddress(p2.peerAddress()).start().awaitUninterruptibly();
Number160 lKey = Number160.createHash("location");
Number160 dKey = Number160.createHash("domain");
Number160 cKey = Number160.createHash("content");
String data = "test";
p2.put(lKey).data(cKey, new Data(data)).domainKey(dKey).start().awaitUninterruptibly();
FutureRemove futureRemove = p1.remove(lKey).domainKey(dKey).contentKey(cKey).start();
futureRemove.awaitUninterruptibly();
// check with a normal digest
FutureDigest futureDigest = p1.digest(lKey).contentKey(cKey).domainKey(dKey).start();
futureDigest.awaitUninterruptibly();
Assert.assertTrue(futureDigest.digest().keyDigest().isEmpty());
// check with a from/to digest
futureDigest = p1.digest(lKey).from(new Number640(lKey, dKey, cKey, Number160.ZERO))
.to(new Number640(lKey, dKey, cKey, Number160.MAX_VALUE)).start();
futureDigest.awaitUninterruptibly();
Assert.assertTrue(futureDigest.digest().keyDigest().isEmpty());
} finally {
if (p1 != null) {
p1.shutdown().awaitUninterruptibly();
}
if (p2 != null) {
p2.shutdown().awaitUninterruptibly();
}
}
}
@Test
public void removeFromToTest4() throws IOException, ClassNotFoundException {
PeerDHT p1 = null;
PeerDHT p2 = null;
try {
p1 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(1)).ports(5000).start()).start();
p2 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(2)).masterPeer(p1.peer()).start()).start();
p2.peer().bootstrap().peerAddress(p1.peerAddress()).start().awaitUninterruptibly();
p1.peer().bootstrap().peerAddress(p2.peerAddress()).start().awaitUninterruptibly();
Number160 lKey = Number160.createHash("location");
Number160 dKey = Number160.createHash("domain");
Number160 cKey = Number160.createHash("content");
String data = "test";
p2.put(lKey).data(cKey, new Data(data)).domainKey(dKey).start().awaitUninterruptibly();
FutureRemove futureRemove = p1.remove(lKey).from(new Number640(lKey, dKey, cKey, Number160.ZERO))
.to(new Number640(lKey, dKey, cKey, Number160.MAX_VALUE)).start();
futureRemove.awaitUninterruptibly();
FutureDigest futureDigest = p1.digest(lKey).from(new Number640(lKey, dKey, cKey, Number160.ZERO))
.to(new Number640(lKey, dKey, cKey, Number160.MAX_VALUE)).start();
futureDigest.awaitUninterruptibly();
// should be empty
Assert.assertTrue(futureDigest.digest().keyDigest().isEmpty());
} finally {
if (p1 != null) {
p1.shutdown().awaitUninterruptibly();
}
if (p2 != null) {
p2.shutdown().awaitUninterruptibly();
}
}
}
@Test
public void testShutdown() throws Exception {
PeerDHT master = null;
try {
// setup
Random rnd = new Random();
final int nrPeers = 10;
final int port = 4001;
// Peer[] peers = Utils2.createNodes(nrPeers, rnd, port);
// Peer[] peers =
// createAndAttachNodesWithReplicationShortId(nrPeers, port);
// Peer[] peers = createNodes(nrPeers, rnd, port, null, true);
PeerDHT[] peers = createNodesWithShortId(nrPeers, rnd, port, null);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
// do testing
final int peerTest = 3;
peers[peerTest].put(Number160.createHash(1000)).data(new Data("Test")).start().awaitUninterruptibly();
for (int i = 0; i < nrPeers; i++) {
for (Data d : peers[i].storageLayer().get().values())
System.out.println("peer[" + i + "]: " + d.object().toString() + " ");
}
FutureDone<Void> futureShutdown = peers[peerTest].peer().announceShutdown().start();
futureShutdown.awaitUninterruptibly();
// we need to wait a bit, since the quit RPC is a fire and forget
// and we return immediately
Thread.sleep(2000);
peers[peerTest].shutdown().awaitUninterruptibly();
System.out.println("peer " + peerTest + " is shutdown");
for (int i = 0; i < nrPeers; i++) {
for (Data d : peers[i].storageLayer().get().values())
System.out.println("peer[" + i + "]: " + d.object().toString() + " ");
}
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testPutPreparePutConfirmGet() throws Exception {
PeerDHT master = null;
try {
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(10, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
// put data with a prepare flag
Data data = new Data("test").prepareFlag();
Number160 locationKey = Number160.createHash("location");
Number160 domainKey = Number160.createHash("domain");
Number160 contentKey = Number160.createHash("content");
Number160 versionKey = Number160.createHash("version");
FuturePut fput = peers[rnd.nextInt(10)].put(locationKey).data(contentKey, data)
.domainKey(domainKey).versionKey(versionKey).start();
fput.awaitUninterruptibly();
fput.futureRequests().awaitUninterruptibly();
Assert.assertEquals(true, fput.isSuccess());
// get shouldn't see provisional put
FutureGet fget = peers[rnd.nextInt(10)].get(locationKey).domainKey(domainKey)
.contentKey(contentKey).versionKey(versionKey).start();
fget.awaitUninterruptibly();
Assert.assertEquals(true, fget.isEmpty());
// confirm prepared put
Data tmp = new Data();
FuturePut fputConfirm = peers[rnd.nextInt(10)].put(locationKey).data(contentKey, tmp)
.domainKey(domainKey).versionKey(versionKey).putConfirm().start();
fputConfirm.awaitUninterruptibly();
fputConfirm.futureRequests().awaitUninterruptibly();
Assert.assertEquals(true, fputConfirm.isSuccess());
// get should see confirmed put
fget = peers[rnd.nextInt(10)].get(locationKey).domainKey(domainKey).contentKey(contentKey)
.versionKey(versionKey).start();
fget.awaitUninterruptibly();
Assert.assertEquals(true, fget.isSuccess());
Assert.assertEquals(data.object(), fget.data().object());
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
/**
* .../2b../4b-5b../7b..................................
* .....................................................
* 0-1-2a-3-4a-5a-6-7a..................................
*
* result should be 2b, 5b, 7a, 7b
*/
@Test
public void testGetLatestVersion1() throws Exception {
// create test data
NavigableMap<Number160, Data> sortedMap = new TreeMap<Number160, Data>();
String content0 = generateRandomString();
Number160 vKey0 = generateVersionKey(0, content0);
Data data0 = new Data(content0);
sortedMap.put(vKey0, data0);
String content1 = generateRandomString();
Number160 vKey1 = generateVersionKey(1, content1);
Data data1 = new Data(content1);
data1.addBasedOn(vKey0);
sortedMap.put(vKey1, data1);
String content2a = generateRandomString();
Number160 vKey2a = generateVersionKey(2, content2a);
Data data2a = new Data(content2a);
data2a.addBasedOn(vKey1);
sortedMap.put(vKey2a, data2a);
String content2b = generateRandomString();
Number160 vKey2b = generateVersionKey(2, content2b);
Data data2b = new Data(content2b);
data2b.addBasedOn(vKey1);
sortedMap.put(vKey2b, data2b);
String content3 = generateRandomString();
Number160 vKey3 = generateVersionKey(3, content3);
Data data3 = new Data(content3);
data3.addBasedOn(vKey2a);
sortedMap.put(vKey3, data3);
String content4a = generateRandomString();
Number160 vKey4a = generateVersionKey(4, content4a);
Data data4a = new Data(content4a);
data4a.addBasedOn(vKey3);
sortedMap.put(vKey4a, data4a);
String content4b = generateRandomString();
Number160 vKey4b = generateVersionKey(4, content4b);
Data data4b = new Data(content4b);
data4b.addBasedOn(vKey3);
sortedMap.put(vKey4b, data4b);
String content5a = generateRandomString();
Number160 vKey5a = generateVersionKey(5, content5a);
Data data5a = new Data(content5a);
data5a.addBasedOn(vKey4a);
sortedMap.put(vKey5a, data5a);
String content5b = generateRandomString();
Number160 vKey5b = generateVersionKey(5, content5b);
Data data5b = new Data(content5b);
data5b.addBasedOn(vKey4b);
sortedMap.put(vKey5b, data5b);
String content6 = generateRandomString();
Number160 vKey6 = generateVersionKey(6, content6);
Data data6 = new Data(content6);
data6.addBasedOn(vKey5a);
sortedMap.put(vKey6, data6);
String content7a = generateRandomString();
Number160 vKey7a = generateVersionKey(7, content7a);
Data data7a = new Data(content7a);
data7a.addBasedOn(vKey6);
sortedMap.put(vKey7a, data7a);
String content7b = generateRandomString();
Number160 vKey7b = generateVersionKey(7, content7b);
Data data7b = new Data(content7b);
data7b.addBasedOn(vKey6);
sortedMap.put(vKey7b, data7b);
PeerDHT master = null;
try {
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(10, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
// put test data
Number160 locationKey = Number160.createHash("location");
Number160 domainKey = Number160.createHash("domain");
Number160 contentKey = Number160.createHash("content");
for (Number160 vKey : sortedMap.keySet()) {
FuturePut fput = peers[rnd.nextInt(10)].put(locationKey)
.data(contentKey, sortedMap.get(vKey)).domainKey(domainKey).versionKey(vKey)
.start();
fput.awaitUninterruptibly();
fput.futureRequests().awaitUninterruptibly();
Assert.assertEquals(true, fput.isSuccess());
}
// get latest versions
FutureGet fget = peers[rnd.nextInt(10)].get(locationKey).domainKey(domainKey)
.contentKey(contentKey).getLatest().start();
fget.awaitUninterruptibly();
Assert.assertEquals(true, fget.isSuccess());
// check result
Map<Number640, Data> dataMap = fget.dataMap();
Assert.assertEquals(4, dataMap.size());
Number480 key480 = new Number480(locationKey, domainKey, contentKey);
Number640 key2b = new Number640(key480, vKey2b);
Assert.assertTrue(dataMap.containsKey(key2b));
Assert.assertEquals(data2b.object(), dataMap.get(key2b).object());
Number640 key5b = new Number640(key480, vKey5b);
Assert.assertTrue(dataMap.containsKey(key5b));
Assert.assertEquals(data5b.object(), dataMap.get(key5b).object());
Number640 key7a = new Number640(key480, vKey7a);
Assert.assertTrue(dataMap.containsKey(key7a));
Assert.assertEquals(data7a.object(), dataMap.get(key7a).object());
Number640 key7b = new Number640(key480, vKey7b);
Assert.assertTrue(dataMap.containsKey(key7b));
Assert.assertEquals(data7b.object(), dataMap.get(key7b).object());
// get latest versions with digest
FutureGet fgetWithDigest = peers[rnd.nextInt(10)].get(locationKey).domainKey(domainKey)
.contentKey(contentKey).getLatest().withDigest().start();
fgetWithDigest.awaitUninterruptibly();
Assert.assertTrue(fgetWithDigest.isSuccess());
// check digest result
DigestResult digestResult = fgetWithDigest.digest();
Assert.assertEquals(12, digestResult.keyDigest().size());
for (Number160 vKey : sortedMap.keySet()) {
Number640 key = new Number640(locationKey, domainKey, contentKey, vKey);
Assert.assertTrue(digestResult.keyDigest().containsKey(key));
Assert.assertEquals(sortedMap.get(vKey).basedOnSet().size(), digestResult.keyDigest()
.get(key).size());
for (Number160 bKey : sortedMap.get(vKey).basedOnSet()) {
Assert.assertTrue(digestResult.keyDigest().get(key).contains(bKey));
}
}
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
/**
* .........../5c.......................................
* .....................................................
* .../2b../4b-5b./6b...................................
* .....................................................
* 0-1-2a-3-4a-5a.-6a-7.................................
*
* result should be 2b, 5b, 5c, 6b, 7
*/
@Test
public void testGetLatestVersion2() throws Exception {
NavigableMap<Number160, Data> sortedMap = new TreeMap<Number160, Data>();
String content0 = generateRandomString();
Number160 vKey0;
vKey0 = generateVersionKey(0, content0);
Data data0 = new Data(content0);
sortedMap.put(vKey0, data0);
String content1 = generateRandomString();
Number160 vKey1 = generateVersionKey(1, content1);
Data data1 = new Data(content1);
data1.addBasedOn(vKey0);
sortedMap.put(vKey1, data1);
String content2a = generateRandomString();
Number160 vKey2a = generateVersionKey(2, content2a);
Data data2a = new Data(content2a);
data2a.addBasedOn(vKey1);
sortedMap.put(vKey2a, data2a);
String content2b = generateRandomString();
Number160 vKey2b = generateVersionKey(2, content2b);
Data data2b = new Data(content2b);
data2b.addBasedOn(vKey1);
sortedMap.put(vKey2b, data2b);
String content3 = generateRandomString();
Number160 vKey3 = generateVersionKey(3, content3);
Data data3 = new Data(content3);
data3.addBasedOn(vKey2a);
sortedMap.put(vKey3, data3);
String content4a = generateRandomString();
Number160 vKey4a = generateVersionKey(4, content4a);
Data data4a = new Data(content4a);
data4a.addBasedOn(vKey3);
sortedMap.put(vKey4a, data4a);
String content4b = generateRandomString();
Number160 vKey4b = generateVersionKey(4, content4b);
Data data4b = new Data(content4b);
data4b.addBasedOn(vKey3);
sortedMap.put(vKey4b, data4b);
String content5a = generateRandomString();
Number160 vKey5a = generateVersionKey(5, content5a);
Data data5a = new Data(content5a);
data5a.addBasedOn(vKey4a);
sortedMap.put(vKey5a, data5a);
String content5b = generateRandomString();
Number160 vKey5b = generateVersionKey(5, content5b);
Data data5b = new Data(content5b);
data5b.addBasedOn(vKey4b);
sortedMap.put(vKey5b, data5b);
String content5c = generateRandomString();
Number160 vKey5c = generateVersionKey(5, content5c);
Data data5c = new Data(content5c);
data5c.addBasedOn(vKey4b);
sortedMap.put(vKey5c, data5c);
String content6a = generateRandomString();
Number160 vKey6a = generateVersionKey(6, content6a);
Data data6a = new Data(content6a);
data6a.addBasedOn(vKey5a);
sortedMap.put(vKey6a, data6a);
String content6b = generateRandomString();
Number160 vKey6b = generateVersionKey(6, content6b);
Data data6b = new Data(content6b);
data6b.addBasedOn(vKey5a);
sortedMap.put(vKey6b, data6b);
String content7 = generateRandomString();
Number160 vKey7 = generateVersionKey(7, content7);
Data data7 = new Data(content7);
data7.addBasedOn(vKey6a);
sortedMap.put(vKey7, data7);
PeerDHT master = null;
try {
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(10, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
// put test data
Number160 locationKey = Number160.createHash("location");
Number160 domainKey = Number160.createHash("domain");
Number160 contentKey = Number160.createHash("content");
for (Number160 vKey : sortedMap.keySet()) {
FuturePut fput = peers[rnd.nextInt(10)].put(locationKey)
.data(contentKey, sortedMap.get(vKey)).domainKey(domainKey).versionKey(vKey)
.start();
fput.awaitUninterruptibly();
fput.futureRequests().awaitUninterruptibly();
Assert.assertEquals(true, fput.isSuccess());
}
// get latest versions
FutureGet fget = peers[rnd.nextInt(10)].get(locationKey).domainKey(domainKey)
.contentKey(contentKey).getLatest().start();
fget.awaitUninterruptibly();
Assert.assertEquals(true, fget.isSuccess());
// check result
Map<Number640, Data> dataMap = fget.dataMap();
Assert.assertEquals(5, dataMap.size());
Number480 key480 = new Number480(locationKey, domainKey, contentKey);
Number640 key2b = new Number640(key480, vKey2b);
Assert.assertTrue(dataMap.containsKey(key2b));
Assert.assertEquals(data2b.object(), dataMap.get(key2b).object());
Number640 key5b = new Number640(key480, vKey5b);
Assert.assertTrue(dataMap.containsKey(key5b));
Assert.assertEquals(data5b.object(), dataMap.get(key5b).object());
Number640 key5c = new Number640(key480, vKey5c);
Assert.assertTrue(dataMap.containsKey(key5c));
Assert.assertEquals(data5c.object(), dataMap.get(key5c).object());
Number640 key6b = new Number640(key480, vKey6b);
Assert.assertTrue(dataMap.containsKey(key6b));
Assert.assertEquals(data6b.object(), dataMap.get(key6b).object());
Number640 key7 = new Number640(key480, vKey7);
Assert.assertTrue(dataMap.containsKey(key7));
Assert.assertEquals(data7.object(), dataMap.get(key7).object());
// get latest versions with digest
FutureGet fgetWithDigest = peers[rnd.nextInt(10)].get(locationKey).domainKey(domainKey)
.contentKey(contentKey).getLatest().withDigest().start();
fgetWithDigest.awaitUninterruptibly();
Assert.assertTrue(fgetWithDigest.isSuccess());
// check digest result
DigestResult digestResult = fgetWithDigest.digest();
Assert.assertEquals(13, digestResult.keyDigest().size());
for (Number160 vKey : sortedMap.keySet()) {
Number640 key = new Number640(locationKey, domainKey, contentKey, vKey);
Assert.assertTrue(digestResult.keyDigest().containsKey(key));
Assert.assertEquals(sortedMap.get(vKey).basedOnSet().size(), digestResult.keyDigest()
.get(key).size());
for (Number160 bKey : sortedMap.get(vKey).basedOnSet()) {
Assert.assertTrue(digestResult.keyDigest().get(key).contains(bKey));
}
}
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
/**
* 0-1-2
*
* result should return version 2
*/
@Test
public void testGetLatestVersion3() throws Exception {
NavigableMap<Number160, Data> sortedMap = new TreeMap<Number160, Data>();
String content0 = generateRandomString();
Number160 vKey0;
vKey0 = generateVersionKey(0, content0);
Data data0 = new Data(content0);
sortedMap.put(vKey0, data0);
String content1 = generateRandomString();
Number160 vKey1 = generateVersionKey(1, content1);
Data data1 = new Data(content1);
data1.addBasedOn(vKey0);
sortedMap.put(vKey1, data1);
String content2 = generateRandomString();
Number160 vKey2 = generateVersionKey(2, content2);
Data data2 = new Data(content2);
data2.addBasedOn(vKey1);
sortedMap.put(vKey2, data2);
PeerDHT master = null;
try {
// setup
PeerDHT[] peers = UtilsDHT2.createNodes(10, rnd, 4001);
master = peers[0];
UtilsDHT2.perfectRouting(peers);
// put test data
Number160 locationKey = Number160.createHash("location");
Number160 domainKey = Number160.createHash("domain");
Number160 contentKey = Number160.createHash("content");
for (Number160 vKey : sortedMap.keySet()) {
FuturePut fput = peers[rnd.nextInt(10)].put(locationKey)
.data(contentKey, sortedMap.get(vKey)).domainKey(domainKey).versionKey(vKey)
.start();
fput.awaitUninterruptibly();
fput.futureRequests().awaitUninterruptibly();
Assert.assertEquals(true, fput.isSuccess());
}
// get latest versions
FutureGet fget = peers[rnd.nextInt(10)].get(locationKey).domainKey(domainKey)
.contentKey(contentKey).getLatest().start();
fget.awaitUninterruptibly();
Assert.assertEquals(true, fget.isSuccess());
// check result
Map<Number640, Data> dataMap = fget.dataMap();
Assert.assertEquals(1, dataMap.size());
Number480 key480 = new Number480(locationKey, domainKey, contentKey);
Number640 key2 = new Number640(key480, vKey2);
Assert.assertTrue(dataMap.containsKey(key2));
Assert.assertEquals(data2.object(), dataMap.get(key2).object());
// get latest versions with digest
FutureGet fgetWithDigest = peers[rnd.nextInt(10)].get(locationKey).domainKey(domainKey)
.contentKey(contentKey).getLatest().withDigest().start();
fgetWithDigest.awaitUninterruptibly();
Assert.assertTrue(fgetWithDigest.isSuccess());
// check digest result
DigestResult digestResult = fgetWithDigest.digest();
Assert.assertEquals(3, digestResult.keyDigest().size());
for (Number160 vKey : sortedMap.keySet()) {
Number640 key = new Number640(locationKey, domainKey, contentKey, vKey);
Assert.assertTrue(digestResult.keyDigest().containsKey(key));
Assert.assertEquals(sortedMap.get(vKey).basedOnSet().size(), digestResult.keyDigest()
.get(key).size());
for (Number160 bKey : sortedMap.get(vKey).basedOnSet()) {
Assert.assertTrue(digestResult.keyDigest().get(key).contains(bKey));
}
}
} finally {
if (master != null) {
master.shutdown().await();
}
}
}
@Test
public void testShutdown3Peers() throws IOException, ClassNotFoundException {
//create 3 peers, store data, shut one peer down, joins -> data should be there
PeerMapConfiguration pmc = new PeerMapConfiguration(Number160.createHash( "1" ) ).peerNoVerification();
PeerMap pm = new PeerMap(pmc);
PeerDHT peer1 = new PeerBuilderDHT( new PeerBuilder( Number160.createHash( "1" ) ).peerMap( pm ).ports( 3000 ).start() ).start();
PeerDHT peer2 = new PeerBuilderDHT( new PeerBuilder( Number160.createHash( "2" ) ).ports( 3001 ).start() ).start();
PeerDHT peer3 = new PeerBuilderDHT( new PeerBuilder( Number160.createHash( "3" ) ).ports( 3002 ).start() ).start();
BaseFuture fb1 = peer2.peer().bootstrap().peerAddress( peer1.peerAddress() ).start().awaitUninterruptibly();
BaseFuture fb2 = peer3.peer().bootstrap().peerAddress( peer1.peerAddress() ).start().awaitUninterruptibly();
Assert.assertTrue( fb1.isSuccess() );
Assert.assertTrue( fb2.isSuccess() );
FuturePut fp = peer2.put( Number160.ONE ).object( "test" ).start().awaitUninterruptibly();
Assert.assertTrue( fp.isSuccess() );
peer2.shutdown().awaitUninterruptibly();
peer2 = new PeerBuilderDHT( new PeerBuilder( Number160.createHash( "2" ) ).ports( 3001 ).start() ).start();
BaseFuture fb3 = peer2.peer().bootstrap().peerAddress( peer1.peerAddress() ).start().awaitUninterruptibly();
Assert.assertTrue( fb3.isSuccess() );
FutureGet fg1 = peer2.get( Number160.ONE ).start().awaitUninterruptibly();
Assert.assertTrue( fg1.isSuccess() );
Assert.assertEquals( "test", fg1.data().object() );
peer3.shutdown().awaitUninterruptibly();
peer3 = new PeerBuilderDHT( new PeerBuilder( Number160.createHash( "3" ) ).ports( 3002 ).start() ).start();
BaseFuture fb4 = peer3.peer().bootstrap().peerAddress( peer1.peerAddress() ).start().awaitUninterruptibly();
Assert.assertTrue( fb4.isSuccess() );
FutureGet fg2 = peer3.get( Number160.ONE ).start().awaitUninterruptibly();
Assert.assertTrue( fg2.isSuccess() );
Assert.assertEquals( "test", fg2.data().object() );
}
private static String generateRandomString() {
return UUID.randomUUID().toString();
}
private static Number160 generateVersionKey(long basedOnCounter, Serializable object) throws IOException {
// get a MD5 hash of the object itself
byte[] hash = generateMD5Hash(serializeObject(object));
return new Number160(basedOnCounter, new Number160(Arrays.copyOf(hash, Number160.BYTE_ARRAY_SIZE)));
}
private static byte[] generateMD5Hash(byte[] data) {
MessageDigest md = null;
try {
md = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
}
md.reset();
md.update(data, 0, data.length);
return md.digest();
}
private static byte[] serializeObject(Serializable object) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = null;
byte[] result = null;
try {
oos = new ObjectOutputStream(baos);
oos.writeObject(object);
result = baos.toByteArray();
} catch (IOException e) {
throw e;
} finally {
try {
if (oos != null)
oos.close();
if (baos != null)
baos.close();
} catch (IOException e) {
throw e;
}
}
return result;
}
public static PeerDHT[] createNodesWithShortId(int nrOfPeers, Random rnd, int port, AutomaticFuture automaticFuture) throws Exception {
if (nrOfPeers < 1) {
throw new IllegalArgumentException("Cannot create less than 1 peer");
}
final Peer master;
PeerDHT[] peers = new PeerDHT[nrOfPeers];
if (automaticFuture != null) {
master = new PeerBuilder(new Number160(1111))
.ports(port).start().addAutomaticFuture(automaticFuture);
peers[0] = new PeerBuilderDHT(master).start();
} else {
master = new PeerBuilder(new Number160(1111)).ports(port)
.start();
peers[0] = new PeerBuilderDHT(master).start();
}
for (int i = 1; i < nrOfPeers; i++) {
if (automaticFuture != null) {
Peer peer = new PeerBuilder(new Number160(i))
.masterPeer(master).start().addAutomaticFuture(automaticFuture);
peers[i] = new PeerBuilderDHT(peer).start();
} else {
Peer peer = new PeerBuilder(new Number160(i))
.masterPeer(master).start();
peers[i] = new PeerBuilderDHT(peer).start();
}
}
System.out.println("peers created.");
return peers;
}
private void send2(final PeerDHT p1, final PeerDHT p2, final ByteBuf toStore1, final int count) throws IOException {
if (count == 0) {
return;
}
DataBuffer b = new DataBuffer(toStore1);
FutureDirect fd = p1.peer().sendDirect(p2.peerAddress()).dataBuffer(b).start();
fd.addListener(new BaseFutureAdapter<FutureDirect>() {
@Override
public void operationComplete(FutureDirect future) throws Exception {
if (future.isFailed()) {
// System.out.println(future.getFailedReason());
send2(p1, p2, toStore1, count - 1);
}
}
});
}
private void send1(final PeerDHT p1, final PeerDHT p2, final byte[] toStore1, final int count) throws IOException {
if (count == 0) {
return;
}
FutureDirect fd = p1.peer().sendDirect(p2.peerAddress()).object(toStore1).start();
fd.addListener(new BaseFutureAdapter<FutureDirect>() {
@Override
public void operationComplete(FutureDirect future) throws Exception {
if (future.isFailed()) {
//System.out.println(future.getFailedReason());
send1(p1, p2, toStore1, count - 1);
}
}
});
}
private void testForArray(PeerDHT peer, Number160 locationKey, boolean find) {
Collection<Number160> tmp = new ArrayList<Number160>();
tmp.add(new Number160(5));
Number640 min = new Number640(locationKey, Number160.createHash("test"), Number160.ZERO, Number160.ZERO);
Number640 max = new Number640(locationKey, Number160.createHash("test"), Number160.MAX_VALUE,
Number160.MAX_VALUE);
Map<Number640, Data> test = peer.storageLayer().get(min, max, -1, true);
if (find) {
Assert.assertEquals(1, test.size());
Assert.assertEquals(
44444,
test.get(
new Number640(new Number320(locationKey, Number160.createHash("test")), new Number160(5),
Number160.ZERO)).length());
} else {
Assert.assertEquals(0, test.size());
}
for(Map.Entry<Number640, Data> entry: test.entrySet()) {
entry.getValue().release();
}
}
}
|
package model.states.gamestates;
import gameactions.GameActionStatePush;
import java.awt.Color;
import java.util.Collection;
import model.ItemEntityAssociation;
import model.KeyPreferences;
import model.area.Area;
import model.area.RadialArea;
import model.area.RealCoordinate;
import model.area.TileCoordinate;
import model.entity.Avatar;
import model.entity.EntityManager;
import model.entity.EntityMovementAssocation;
import model.entity.Smasher;
import model.event.HealthModifierEvent;
import model.event.ManaModifierEvent;
import model.item.Door;
import model.item.ObstacleItem;
import model.item.OneShotItem;
import model.item.TakeableItem;
import model.map.GameTerrain;
import model.map.tile.ImpassableTile;
import model.map.tile.PassableTile;
import model.statistics.EntityStatistics;
import model.trigger.PermanentTrigger;
import model.trigger.SingleUseTrigger;
import model.trigger.Trigger;
import model.trigger.TriggerManager;
import view.EntityView;
import view.item.BasicItemView;
import view.item.ItemView;
import view.layout.GameplayLayout;
import view.map.BasicTileView;
import view.map.TileView;
import controller.GameplayController;
import controller.listener.Listener;
import controller.listener.SingleUseListener;
public class GameplayState extends GameState {
private GameplayController controller;
private GameplayLayout layout;
private GameTerrain gameMap;
private ItemEntityAssociation itemEntityAssociation;
private Avatar avatar;
public GameplayState() {
layout = new GameplayLayout();
controller = new GameplayController();
gameMap = new GameTerrain();
}
@Override
public void onEnter() {
super.onEnter();
addTilesTest();
addEntityTest();
}
@Override
public void onResume() {
super.onResume();
setListeners(getContext().getPreferences());
}
@Override
public void onPause() {
controller.removeListeners();
layout.clearBindings();
}
public void addEntityTest() {
TileCoordinate loc = new TileCoordinate(3, 3);
EntityView eView = new EntityView(new Color(200, 200, 0), Color.orange,
TileCoordinate.convertToRealCoordinate(loc));
avatar = new Smasher("Smasher", eView, loc);
KeyPreferences preferences = new KeyPreferences();
getContext().setPreferences(preferences);
this.itemEntityAssociation = new ItemEntityAssociation(avatar);
setListeners(preferences);
EntityManager.getSingleton().setAvatar(avatar);
eView.registerWithGameMapView(layout.getGameEntityView(), new RealCoordinate(3, 3));
this.itemEntityAssociation = new ItemEntityAssociation(avatar);
ItemView takeableItemView = new BasicItemView(new Color(100, 60, 100), Color.GREEN);
TileCoordinate takeableItemViewPosition = new TileCoordinate(5, 5);
takeableItemView.registerWithGameItemView(layout.getGameItemView(), new RealCoordinate(5, 5));
itemEntityAssociation.addItem(new TakeableItem(takeableItemView),
new TileCoordinate(5,5));
ItemView takeableItemViewTwo = new BasicItemView(new Color(100, 60, 100), Color.DARK_GRAY);
TileCoordinate takeableItemViewPositionTwo = new TileCoordinate(5, 6);
takeableItemViewTwo.registerWithGameItemView(layout.getGameItemView(), new RealCoordinate(5, 6));
TakeableItem takeableItemTwo = new TakeableItem(takeableItemViewTwo);
itemEntityAssociation.addItem(new TakeableItem(takeableItemViewTwo), takeableItemViewPosition);
ItemView doorItemView = new BasicItemView(Color.RED, Color.MAGENTA);
TileCoordinate doorItemViewPosition = new TileCoordinate(15, 14);
doorItemView.registerWithGameItemView(layout.getGameItemView(), new RealCoordinate(15, 14));
Door doorItem = new Door(doorItemView, takeableItemTwo);
itemEntityAssociation.addItem(doorItem, doorItemViewPosition);
ItemView obstacleItemView = new BasicItemView(Color.GRAY, Color.BLACK);
TileCoordinate obstacleItemPosition = new TileCoordinate(9, 7);
obstacleItemView.registerWithGameItemView(layout.getGameItemView(), new RealCoordinate(9, 7));
itemEntityAssociation.addItem(new ObstacleItem(obstacleItemView), obstacleItemPosition);
ItemView oneshotItemView = new BasicItemView(Color.GRAY, Color.BLACK);
TileCoordinate oneshotItemPosition = new TileCoordinate(13, 9);
oneshotItemView.registerWithGameItemView(layout.getGameItemView(), new RealCoordinate(13, 9));
itemEntityAssociation.addItem(new OneShotItem(oneshotItemView, new EntityStatistics()), oneshotItemPosition);
}
private void addTriggersTest() {
TriggerManager triggerManager = TriggerManager.getSingleton();
// This may need a ViewableTriggerDecorator to display the Decal for the AreaEffect
TileCoordinate locOne = new TileCoordinate(2, 6);
Area areaOne = new RadialArea(20, locOne);
Trigger triggerOne = new SingleUseTrigger(areaOne, new HealthModifierEvent(2, -1));
TileCoordinate locTwo = new TileCoordinate(2, 7);
Area areaTwo = new RadialArea(1, locTwo);
Trigger triggerTwo = new PermanentTrigger(areaTwo, new ManaModifierEvent(10, 200));
triggerManager.addNonPartyTrigger(triggerOne);
triggerManager.addNonPartyTrigger(triggerTwo);
}
public void addTilesTest() {
for (int x = 0; x < 100; ++x) {
for (int y = 0; y < 100; ++y) {// Hardcoded for as long as the area
TileCoordinate p = new TileCoordinate(x, y);
if(x!=10 || y!=10){
TileView view = new BasicTileView(new Color(0, 200, 200), Color.WHITE);
view.registerWithGameMapView(layout.getGameTerrainView(), TileCoordinate.convertToRealCoordinate(p));
gameMap.add(new PassableTile(view), p);
}
else{
TileView view = new BasicTileView(new Color(200, 0, 200), Color.WHITE);
view.registerWithGameMapView(layout.getGameTerrainView(), TileCoordinate.convertToRealCoordinate(p));
gameMap.add(new ImpassableTile(view), p);
}
}
}
}
@Override
public GameplayLayout getLayout() {
return layout;
}
@Override
public GameplayController getController() {
return controller;
}
@Override
public void update() {
// TODO poll here.
}
}
|
package org.intermine.bio.dataconversion;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import org.apache.log4j.Logger;
import org.intermine.dataconversion.ItemWriter;
import org.intermine.metadata.Model;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.util.SAXParser;
import org.intermine.util.StringUtil;
import org.intermine.xml.full.Item;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
* DataConverter to parse psi data into items
* @author Julie Sullivan
*/
public class PsiConverter extends BioFileConverter
{
private static final Logger LOG = Logger.getLogger(PsiConverter.class);
private Map<String, String> organisms = new HashMap<String, String>();
private Map<String, String> pubs = new HashMap<String, String>();
private Map<String, Object> experimentNames = new HashMap<String, Object>();
private Map<String, String> terms = new HashMap<String, String>();
private String termId = null;
private Map<String, Item> genes = new HashMap<String, Item>();
protected IdResolverFactory resolverFactory;
private static final Map<String, String> IDENTIFIERS = new LinkedHashMap();
/**
* Constructor
* @param writer the ItemWriter used to handle the resultant items
* @param model the Model
*/
public PsiConverter(ItemWriter writer, Model model) {
super(writer, model, "IntAct", "IntAct data set");
// only construct factory here so can be replaced by mock factory in tests
resolverFactory = new FlyBaseIdResolverFactory("gene");
try {
termId = getTerm("MI:0117");
} catch (SAXException e) {
throw new RuntimeException("ack");
}
}
static {
IDENTIFIERS.put("primaryIdentifier", "primaryIdentifier");
IDENTIFIERS.put("ensembl", null);
// IDENTIFIERS.put("orf name", "secondaryIdentifier");
//IDENTIFIERS.put("gene name", "symbol");
// IDENTIFIERS.put("fullName", "secondaryIdentifier");
//IDENTIFIERS.put("shortLabel", "symbol");
}
/**
* A space separated list of of NCBI taxonomy ids for which we want to retrieve
* interactions.
* @param orgStr a list of taxon ids
*/
public void setOrganisms(String orgStr) {
List<String> orgArray = Arrays.asList(orgStr.split("\\s"));
for (Iterator iter = orgArray.iterator(); iter.hasNext();) {
String taxId = (String) iter.next();
try {
getOrganism(taxId);
} catch (SAXException e) {
throw new RuntimeException("ack");
}
}
}
/**
* {@inheritDoc}
*/
public void process(Reader reader) throws Exception {
PsiHandler handler = new PsiHandler();
try {
SAXParser.parse(new InputSource(reader), handler);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
/**
* Handles xml file
*/
class PsiHandler extends DefaultHandler
{
private Map<String, ExperimentHolder> experimentIds
= new HashMap<String, ExperimentHolder>();
private InteractionHolder holder = null;
private ExperimentHolder experimentHolder = null;
private InteractorHolder interactorHolder = null;
private Item gene = null, comment = null;
private String experimentId = null, interactorId = null;
private Map<String, String> identifiers = new HashMap<String, String>();
private Map<String, Item> validGenes = new HashMap<String, Item>();
private String regionName = null;
private Stack<String> stack = new Stack<String>();
private String attName = null;
private StringBuffer attValue = null;
/**
* {@inheritDoc}
*/
public void startElement(String uri, String localName, String qName, Attributes attrs)
throws SAXException {
attName = null;
// <experimentList><experimentDescription>
if (qName.equals("experimentDescription")) {
experimentId = attrs.getValue("id");
// <experimentList><experimentDescription id="2"><names><shortLabel>
} else if (qName.equals("shortLabel") && stack.peek().equals("names")
&& stack.search("experimentDescription") == 2) {
attName = "experimentName";
// <experimentList><experimentDescription id="2"><names><fullName>
} else if (qName.equals("fullName") && stack.peek().equals("names")
&& stack.search("experimentDescription") == 2) {
attName = "experimentDescr";
//<experimentList><experimentDescription><bibref><xref><primaryRef>
} else if (qName.equals("primaryRef") && stack.peek().equals("xref")
&& stack.search("bibref") == 2
&& stack.search("experimentDescription") == 3) {
String pubMedId = attrs.getValue("id");
if (StringUtil.allDigits(pubMedId)) {
String pub = getPub(pubMedId);
experimentHolder.setPublication(pub);
}
//<experimentList><experimentDescription><attributeList><attribute>
} else if (qName.equals("attribute") && stack.peek().equals("attributeList")
&& stack.search("experimentDescription") == 2) {
String name = attrs.getValue("name");
if (experimentHolder.experiment != null && name != null) {
comment = createItem("Comment");
comment.setAttribute("type", name);
attName = "experimentAttribute";
} else {
LOG.info("Can't create comment, bad experiment.");
}
// <hostOrganismList><hostOrganism ncbiTaxId="9534"><names><fullName>
} else if (qName.equals("hostOrganism")) {
attName = "hostOrganism";
//<interactionDetectionMethod><xref><primaryRef>
} else if (qName.equals("primaryRef") && stack.peek().equals("xref")
&& stack.search("interactionDetectionMethod") == 2) {
String termItemId = getTerm(attrs.getValue("id"));
experimentHolder.setMethod("interactionDetectionMethod", termItemId);
//<participantIdentificationMethod><xref> <primaryRef>
} else if (qName.equals("primaryRef") && stack.peek().equals("xref")
&& stack.search("participantIdentificationMethod") == 2) {
String termItemId = getTerm(attrs.getValue("id"));
experimentHolder.setMethod("participantIdentificationMethod", termItemId);
// <interactorList><interactor id="4">
} else if (qName.equals("interactor") && stack.peek().equals("interactorList")) {
interactorId = attrs.getValue("id");
// <interactorList><interactor id="4"><names><fullName>F15C11.2</fullName>
} else if ((qName.equals("fullName") || qName.equals("shortLabel"))
&& stack.search("interactor") == 2) {
attName = qName;
// <interactorList><interactor id="4"><xref>
// <secondaryRef db="sgd" dbAc="MI:0484" id="S000006331" secondary="YPR127W"/>
} else if ((qName.equals("primaryRef") || qName.equals("secondaryRef"))
&& stack.search("interactor") == 2) {
String db = attrs.getValue("db");
if (db != null) {
if (db.equalsIgnoreCase("sgd") || db.equalsIgnoreCase("flybase")
|| db.equalsIgnoreCase("ensembl")) {
if (!db.equals("ensembl")) {
db = "primaryIdentifier";
}
identifiers.put(db, attrs.getValue("id"));
}
}
// <interactorList><interactor id="4"><organism ncbiTaxId="7227">
} else if (qName.equals("organism") && stack.peek().equals("interactor")) {
String taxId = attrs.getValue("ncbiTaxId");
// if (organisms.containsKey(taxId)) {
if (!taxId.equals("-1") && !taxId.equals("-2")) {
try {
gene = getGene(taxId);
} catch (ObjectStoreException e) {
throw new RuntimeException("failed storing gene");
}
if (gene != null && !validGenes.containsKey(interactorId)) {
validGenes.put(interactorId, gene);
}
}
identifiers = new HashMap();
// <interactorList><interactor id="4"><names>
// <alias type="locus name" typeAc="MI:0301">HSC82</alias>
} else if (qName.equals("alias") && stack.peek().equals("names")
&& stack.search("interactor") == 2) {
attName = attrs.getValue("type");
// <interactorList><interactor id="4"><sequence>
} else if (qName.equals("sequence") && stack.peek().equals("interactor")) {
attName = "sequence";
//<interactionList><interaction id="1"><names><shortLabel>
} else if (qName.equals("shortLabel") && stack.peek().equals("names")
&& stack.search("interaction") == 2) {
attName = "interactionName";
//<interaction><confidenceList><confidence><unit><names><shortLabel>
} else if (qName.equals("shortLabel") && stack.peek().equals("names")
&& stack.search("confidence") == 3) {
attName = "confidenceUnit";
//<interactionList><interaction><confidenceList><confidence><value>
} else if (qName.equals("value") && stack.peek().equals("confidence")) {
attName = "confidence";
//<interactionList><interaction>
//<participantList><participant id="5"><interactorRef>
} else if (qName.equals("interactorRef")
&& stack.peek().equals("participant")) {
attName = "participantId";
// <participantList><participant id="5"><experimentalRole><names><shortLabel>
} else if (qName.equals("shortLabel") && stack.search("experimentalRole") == 2) {
attName = "proteinRole";
//<interactionList><interaction><experimentList><experimentRef>
} else if (qName.equals("experimentRef") && stack.peek().equals("experimentList")) {
attName = "experimentRef";
// <participantList><participant id="6919"><featureList><feature id="6920">
// <featureRangeList><featureRange><startStatus><names><shortLabel>
} else if (qName.equals("shortLabel") && stack.search("startStatus") == 2) {
attName = "startStatus";
// <participantList><participant id="6919"><featureList><feature id="6920">
// <featureRangeList><featureRange><endStatus><names><shortLabel>
} else if (qName.equals("shortLabel") && stack.search("endStatus") == 2) {
attName = "endStatus";
// <featureList><feature id="24"><names><shortLabel>
} else if (qName.equals("shortLabel") && stack.search("feature") == 2) {
attName = "regionName";
// <participantList><participant id="6919"><featureList><feature id="6920">
// <featureType><xref><primaryRef db="psi-mi" dbAc="MI:0488" id="MI:0117"
} else if (qName.equals("primaryRef") && stack.search("featureType") == 2
&& attrs.getValue("id").equals("MI:0117") && interactorHolder != null) {
interactorHolder.isRegionFeature = true;
// create interacting region
Item interactionRegion = createItem("InteractionRegion");
interactionRegion.setAttribute("name", regionName);
interactionRegion.setReference("gene", interactorHolder.geneRefId);
interactionRegion.setReference("ontologyTerm", termId);
// create new location object (start and end are coming later)
Item location = createItem("Location");
location.setReference("object", interactorHolder.geneRefId);
location.setReference("subject", interactionRegion.getIdentifier());
interactionRegion.setReference("location", location);
// add location and region to interaction object
interactorHolder.interactionRegion = interactionRegion;
interactorHolder.location = location;
holder.addRegion(interactionRegion.getIdentifier());
// <participantList><participant id="6919"><featureList><feature id="6920">
// <featureRangeList><featureRange><begin position="470"/>
} else if (qName.equals("begin")
&& stack.peek().equals("featureRange")
&& interactorHolder != null
&& interactorHolder.isRegionFeature) {
interactorHolder.setStart(attrs.getValue("position"));
// <participantList><participant id="6919"><featureList><feature id="6920">
// <featureRangeList><featureRange><end position="470"/>
} else if (qName.equals("end")
&& stack.peek().equals("featureRange")
&& interactorHolder != null
&& interactorHolder.isRegionFeature) {
interactorHolder.setEnd(attrs.getValue("position"));
//<interactorType><xref><primaryRef db="psi-mi" dbAc="MI:0488" id="MI:0326"
} else if (qName.equals("primaryRef") && stack.search("interactionType") == 2) {
String term = attrs.getValue("id");
if (term != null) {
holder.setType(getTerm(term));
}
}
super.startElement(uri, localName, qName, attrs);
stack.push(qName);
attValue = new StringBuffer();
}
/**
* {@inheritDoc}
*/
public void characters(char[] ch, int start, int length) {
int st = start;
int l = length;
if (attName != null) {
// DefaultHandler may call this method more than once for a single
// attribute content -> hold text & create attribute in endElement
while (l > 0) {
boolean whitespace = false;
switch(ch[st]) {
case ' ':
case '\r':
case '\n':
case '\t':
whitespace = true;
break;
default:
break;
}
if (!whitespace) {
break;
}
++st;
--l;
}
if (l > 0) {
StringBuffer s = new StringBuffer();
s.append(ch, st, l);
attValue.append(s);
}
}
}
/**
* {@inheritDoc}
*/
public void endElement(String uri, String localName, String qName)
throws SAXException {
super.endElement(uri, localName, qName);
stack.pop();
// <experimentList><experimentDescription><attributeList><attribute/>
// <attribute name="publication-year">2006</attribute>
if (attName != null && attName.equals("experimentAttribute")
&& qName.equals("attribute")) {
String s = attValue.toString();
if (comment != null && s != null && !s.equals("")) {
comment.setAttribute("text", s);
try {
store(comment);
} catch (ObjectStoreException e) {
throw new RuntimeException("error storing comment");
}
comment = null;
}
// <experimentList><experimentDescription><names><shortLabel>
} else if (attName != null && attName.equals("experimentName")
&& qName.equals("shortLabel")) {
String shortLabel = attValue.toString();
if (shortLabel != null) {
experimentHolder = getExperiment(shortLabel);
experimentIds.put(experimentId, experimentHolder);
experimentHolder.setName(shortLabel);
} else {
LOG.error("Experiment " + experimentId + " doesn't have a shortLabel");
}
// <experimentList><experimentDescription><names><fullName>
} else if (attName != null && attName.equals("experimentDescr")
&& qName.equals("fullName")) {
String descr = attValue.toString();
if (descr != null) {
experimentHolder.setDescription(descr);
}
// <hostOrganismList><hostOrganism ncbiTaxId="9534"><names><fullName>
} else if (attName != null && attName.equals("hostOrganism")
&& qName.equals("fullName")) {
// organism must be a string because several entries are in vivo or in vitro, with
// a taxonid of -1 or -2
String hostOrganism = attValue.toString();
if (hostOrganism != null) {
experimentHolder.setHostOrganism(hostOrganism);
}
// <interactorList><interactor id="4"><names><fullName>
} else if ((qName.equals("fullName") || qName.equals("shortLabel"))
&& stack.search("interactor") == 2) {
String name = attValue.toString();
if (name != null) {
identifiers.put(qName, name);
}
// <interactorList><interactor id="4">
} else if (qName.equals("alias")) {
String identifier = attValue.toString();
if (identifier != null && !identifier.equals("")) {
identifier = formatString(identifier);
identifiers.put(attName, identifier);
}
// <interactorList><interactor id="4"></interactor>
} else if (gene != null && qName.equals("interactor")) {
gene = null;
//<interactionList><interaction>
//<participantList><participant id="5"><interactorRef>
} else if (qName.equals("interactorRef") && stack.peek().equals("participant")) {
String id = attValue.toString();
if (validGenes.get(id) != null) {
Item interactor = validGenes.get(id);
String geneRefId = interactor.getIdentifier();
interactorHolder = new InteractorHolder(geneRefId);
String ident = fetchIdentifier(interactor);
if (ident != null) {
interactorHolder.identifier = ident;
holder.addInteractor(interactorHolder);
holder.addGene(geneRefId);
holder.addIdentifier(ident);
} else {
holder.isValid = false;
}
} else {
holder.isValid = false;
}
// <interactionList><interaction><names><shortLabel>
} else if (qName.equals("shortLabel") && attName != null
&& attName.equals("interactionName")) {
holder = new InteractionHolder(attValue.toString());
//<interactionList><interaction><experimentList><experimentRef>
} else if (qName.equals("experimentRef") && stack.peek().equals("experimentList")) {
String experimentRef = attValue.toString();
if (experimentIds.get(experimentRef) != null) {
holder.setExperiment(experimentIds.get(experimentRef));
} else {
LOG.error("Bad experiment: [" + experimentRef + "] of "
+ experimentIds.size() + " experiments");
}
//<interaction><confidenceList><confidence><unit><names><shortLabel>
} else if (qName.equals("shortLabel") && attName != null
&& attName.equals("confidenceUnit") && holder != null) {
String shortLabel = attValue.toString();
if (shortLabel != null) {
holder.confidenceUnit = shortLabel;
}
//<interactionList><interaction><confidenceList><confidence><value>
} else if (qName.equals("value") && attName != null && attName.equals("confidence")
&& holder != null) {
if (holder.confidenceUnit.equals("author-confidence")) {
String value = attValue.toString();
holder.setConfidence(value);
}
// <interactionList><interaction><participantList><participant id="5">
// <experimentalRole><names><shortLabel>
} else if (qName.equals("shortLabel") && stack.search("experimentalRole") == 2
&& interactorHolder != null) {
interactorHolder.role = attValue.toString();
// <participantList><participant id="6919"><featureList><feature id="6920">
// <featureRangeList><featureRange><startStatus><names><shortLabel>
} else if (qName.equals("shortLabel") && stack.search("startStatus") == 2
&& interactorHolder != null && interactorHolder.isRegionFeature) {
interactorHolder.startStatus = attValue.toString();
// <participantList><participant id="6919"><featureList><feature id="6920">
// <featureRangeList><featureRange><endStatus><names><shortLabel>
} else if (qName.equals("shortLabel") && stack.search("endStatus") == 2
&& interactorHolder != null && interactorHolder.isRegionFeature) {
interactorHolder.endStatus = attValue.toString();
// <featureList><feature id="24"><names><shortLabel>
} else if (qName.equals("shortLabel") && stack.search("feature") == 2
&& attName != null && attName.equals("regionName")) {
regionName = attValue.toString();
//<interactionList><interaction>
} else if (qName.equals("interaction") && holder != null) {
if (holder.isValid) {
storeAll(holder);
holder = null;
interactorHolder = null;
}
}
}
private void storeAll(InteractionHolder interactionHolder) throws SAXException {
Set interactors = interactionHolder.interactors;
// loop through proteins/interactors in this interaction
for (Iterator iter = interactors.iterator(); iter.hasNext();) {
interactorHolder = (InteractorHolder) iter.next();
// build & store interactions - one for each gene
Item interaction = createItem("Interaction");
String geneRefId = interactorHolder.geneRefId;
String identifier = interactorHolder.identifier;
String shortName = interactionHolder.shortName;
interaction.setAttribute("shortName", shortName);
interaction.setAttribute("role", interactorHolder.role);
String name = buildName(interactionHolder.primaryIdentifiers, identifier);
interaction.setAttribute("name", name);
if (interactionHolder.confidence != null) {
interaction.setAttribute("confidence", interactionHolder.confidence.toString());
}
if (interactionHolder.confidenceText != null) {
interaction.setAttribute("confidenceText", interactionHolder.confidenceText);
}
interaction.setReference("gene", geneRefId);
interaction.setReference("type", interactionHolder.termRefId);
interaction.setReference("experiment",
interactionHolder.eh.experiment.getIdentifier());
// interactingProteins
List<String> geneIds = new ArrayList(interactionHolder.geneIds);
geneIds.remove(geneRefId);
interaction.setCollection("interactingGenes", geneIds);
// interactingRegions
Set<String> regionIds = interactionHolder.regionIds;
if (!regionIds.isEmpty()) {
interaction.setCollection("interactingRegions", new ArrayList(regionIds));
}
/* store all protein interaction-related items */
try {
store(interaction);
} catch (ObjectStoreException e) {
throw new SAXException(e);
}
if (interactorHolder.interactionRegion != null) {
Item region = interactorHolder.interactionRegion;
if (interactorHolder.startStatus != null) {
region.setAttribute("startStatus", interactorHolder.startStatus);
}
if (interactorHolder.endStatus != null) {
region.setAttribute("endStatus", interactorHolder.endStatus);
}
region.setReference("interaction", interaction);
String regionIdentifier = shortName + "_" + identifier;
if (interactorHolder.start != null && !interactorHolder.start.equals("0")) {
regionIdentifier += ":" + interactorHolder.start;
regionIdentifier += "-" + interactorHolder.end;
}
region.setAttribute("primaryIdentifier", regionIdentifier);
try {
store(region);
store(interactorHolder.location);
} catch (ObjectStoreException e) {
}
}
}
/* store all experiment-related items */
ExperimentHolder eh = interactionHolder.eh;
if (!eh.isStored) {
eh.isStored = true;
try {
store(eh.experiment);
} catch (ObjectStoreException e) {
}
//TODO store comments here instead
//for (Object o : eh.comments) {
// writer.store(ItemHelper.convert((Item) o));
}
}
private String buildName(List<String> primaryIdentifiers, String identifier) {
String name = "IntAct:" + identifier;
Iterator it = primaryIdentifiers.iterator();
while (it.hasNext()) {
String primaryIdentifier = (String) it.next();
if (!primaryIdentifier.equals(identifier)) {
name = name + "_" + primaryIdentifier;
}
}
return name;
}
private Item getGene(String taxonId)
throws ObjectStoreException, SAXException {
String identifier = null, label = null;
for (String identifierType : IDENTIFIERS.keySet()) {
identifier = identifiers.get(identifierType);
if (identifier != null) {
if (identifierType.equals("ensembl")) {
if (identifier.startsWith("EN")) {
label = "primaryIdentifier";
} else {
// worm, dmel, yeast
label = "secondaryIdentifier";
}
} else {
label = IDENTIFIERS.get(identifierType);
}
break;
}
}
if (taxonId.equals("7227")) {
IdResolver resolver = resolverFactory.getIdResolver(false);
if (resolver != null) {
identifier = resolveGene(resolver, taxonId, identifier);
if (identifier == null) {
return null;
}
} else {
return null;
}
}
// everyone not using the resolver should have an identifier
if (identifier == null) {
if (!taxonId.equals("7227")) {
String msg = "no identifier found for organism:" + taxonId
+ " interactor " + interactorId;
LOG.error(msg);
}
return null;
}
Item item = genes.get(identifier);
if (item == null) {
item = createItem("Gene");
item.setAttribute(label, identifier);
item.setReference("organism", getOrganism(taxonId));
genes.put(identifier, item);
store(item);
}
return item;
}
private String resolveGene(IdResolver resolver, String taxonId, String id) {
String identifier = id;
int resCount = resolver.countResolutions(taxonId, identifier);
if (resCount != 1) {
LOG.info("RESOLVER: failed to resolve gene to one identifier, ignoring gene: "
+ identifier + " count: " + resCount + " FBgn: "
+ resolver.resolveId(taxonId, identifier));
return null;
}
identifier = resolver.resolveId(taxonId, identifier).iterator().next();
return identifier;
}
private String getPub(String pubMedId)
throws SAXException {
String itemId = pubs.get(pubMedId);
if (itemId == null) {
try {
Item pub = createItem("Publication");
pub.setAttribute("pubMedId", pubMedId);
itemId = pub.getIdentifier();
pubs.put(pubMedId, itemId);
store(pub);
} catch (ObjectStoreException e) {
throw new SAXException(e);
}
}
return itemId;
}
private ExperimentHolder getExperiment(String name) {
ExperimentHolder eh = (ExperimentHolder) experimentNames.get(name);
if (eh == null) {
eh = new ExperimentHolder(createItem("InteractionExperiment"));
experimentNames.put(name, eh);
}
return eh;
}
/**
* Holder object for ProteinInteraction. Holds all information about an interaction until
* it's verified that all organisms are in the list given.
* @author Julie Sullivan
*/
public class InteractionHolder
{
private String shortName;
private ExperimentHolder eh;
private Double confidence;
private String confidenceText;
private String confidenceUnit;
private Set<InteractorHolder> interactors = new LinkedHashSet<InteractorHolder>();
private boolean isValid = true;
private Set<String> geneIds = new HashSet<String>();
private List<String> primaryIdentifiers = new ArrayList<String>();
private Set<String> regionIds = new HashSet<String>();
private String termRefId;
/**
* Constructor
* @param shortName name of this interaction
*/
public InteractionHolder(String shortName) {
this.shortName = shortName;
}
/**
*
* @param experimentHolder object holding experiment object
*/
protected void setExperiment(ExperimentHolder experimentHolder) {
this.eh = experimentHolder;
}
/**
*
* @param confidence confidence score for interaction
*/
protected void setConfidence(String confidence) {
if (Character.isDigit(confidence.charAt(0))) {
this.confidence = new Double(confidence);
} else {
confidenceText = (confidenceText != null
? confidenceText + confidence : confidence);
}
}
/**
* @param ih object holding interactor
*/
protected void addInteractor(InteractorHolder ih) {
interactors.add(ih);
}
/**
* @param identifier primaryIdentifier for an interactor in this interaction
*/
protected void addIdentifier(String identifier) {
primaryIdentifiers.add(identifier);
}
/**
* @param geneId protein involved in interaction
*/
protected void addGene(String geneId) {
geneIds.add(geneId);
}
/**
* @param regionId Id of ProteinInteractionRegion object
*/
protected void addRegion(String regionId) {
regionIds.add(regionId);
}
/**
* @param refId id representing a term object
*/
protected void setType(String refId) {
termRefId = refId;
}
}
/**
* Holder object for ProteinInteraction. Holds all information about a gene in an
* interaction until it's verified that all organisms are in the list given.
* @author Julie Sullivan
*/
public class InteractorHolder
{
private String geneRefId; // protein.getIdentifier()
private String role;
private Item interactionRegion; // for storage later
private Item location; // for storage later
private String startStatus, start;
private String endStatus, end;
protected String identifier;
/* we only want to process the binding site feature. this flag is FALSE until
*
* <participantList><participant id="6919"><featureList>
* <feature id="6920"><featureType><xref>
* <primaryRef db="psi-mi" dbAc="MI:0488" id="MI:0117"
* id="MI:0117" (the id for binding site)
*
* then the flag is set to TRUE until </feature>
*/
private boolean isRegionFeature;
/**
* Constructor
* @param geneId Protein that's part of the interaction
*/
public InteractorHolder(String geneId) {
this.geneRefId = geneId;
}
/**
* @param start start position of region
*/
protected void setStart(String start) {
location.setAttribute("start", start);
this.start = start;
}
/**
* @param end the end position of the region
*/
protected void setEnd(String end) {
location.setAttribute("end", end);
this.end = end;
}
}
/**
* Holder object for ProteinInteraction. Holds all information about an experiment until
* an interaction is verified to have only valid organisms
* @author Julie Sullivan
*/
public class ExperimentHolder
{
protected String name, description;
protected Item experiment;
protected HashSet comments = new HashSet();
protected boolean isStored = false;
/**
* Constructor
* @param experiment experiment where this interaction was observed
*/
public ExperimentHolder(Item experiment) {
this.experiment = experiment;
}
/**
*
* @param name name of experiment
*/
protected void setName(String name) {
experiment.setAttribute("name", name);
this.name = name;
}
/**
* @param description description of experiment
*/
protected void setDescription(String description) {
experiment.setAttribute("description", description);
}
/**
*
* @param publication publication of this experiment
*/
protected void setPublication(String publication) {
experiment.setReference("publication", publication);
}
/**
*
* @param whichMethod method
* @param termItemId termID
*/
protected void setMethod(String whichMethod, String termItemId) {
experiment.setReference(whichMethod, termItemId);
}
/**
*
* @param ref name of organism
*/
protected void setHostOrganism(String ref) {
experiment.setAttribute("hostOrganism", ref);
}
}
}
/**
* create and store protein interaction terms
* @param identifier identifier for interaction term
* @return id representing term object
* @throws SAXException if term can't be stored
*/
protected String getTerm(String identifier) throws SAXException {
String itemId = terms.get(identifier);
if (itemId == null) {
try {
Item term = createItem("InteractionTerm");
term.setAttribute("identifier", identifier);
itemId = term.getIdentifier();
terms.put(identifier, itemId);
store(term);
} catch (ObjectStoreException e) {
throw new SAXException(e);
}
}
return itemId;
}
private String getOrganism(String taxId) throws SAXException {
String refId = organisms.get(taxId);
if (refId != null) {
return refId;
}
Item organism = createItem("Organism");
organism.setAttribute("taxonId", taxId);
try {
store(organism);
} catch (ObjectStoreException e) {
throw new SAXException(e);
}
refId = organism.getIdentifier();
organisms.put(taxId, refId);
return refId;
}
private String fetchIdentifier(Item interactor) {
String ident = null;
if (interactor.getAttribute("primaryIdentifier") != null) {
ident = interactor.getAttribute("primaryIdentifier").getValue();
}
if ((ident == null || ident.equals(""))
&& interactor.getAttribute("secondaryIdentifier") != null) {
ident = interactor.getAttribute("secondaryIdentifier").getValue();
}
if ((ident == null || ident.equals(""))
&& interactor.getAttribute("symbol") != null) {
ident = interactor.getAttribute("symbol").getValue();
}
return ident;
}
private String formatString(String ident) {
String identifier = ident;
if (identifier.startsWith("Dmel_")) {
identifier = identifier.substring(5);
}
if (identifier.startsWith("cg")) {
identifier = "CG" + identifier.substring(2);
}
return identifier;
}
}
|
package org.intermine.webservice.server.complexes;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.intermine.api.InterMineAPI;
import org.intermine.api.results.ExportResultsIterator;
import org.intermine.api.results.ResultElement;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.pathquery.Constraints;
import org.intermine.pathquery.OrderDirection;
import org.intermine.pathquery.OuterJoinStatus;
import org.intermine.pathquery.PathQuery;
import org.intermine.webservice.server.core.JSONService;
import org.intermine.webservice.server.exceptions.BadRequestException;
import psidev.psi.mi.jami.bridges.exception.BridgeFailedException;
import psidev.psi.mi.jami.bridges.ols.CachedOlsOntologyTermFetcher;
import psidev.psi.mi.jami.datasource.InteractionWriter;
import psidev.psi.mi.jami.factory.InteractionWriterFactory;
import psidev.psi.mi.jami.json.InteractionViewerJson;
import psidev.psi.mi.jami.json.MIJsonOptionFactory;
import psidev.psi.mi.jami.json.MIJsonType;
import psidev.psi.mi.jami.model.CvTerm;
import psidev.psi.mi.jami.model.InteractionCategory;
import psidev.psi.mi.jami.model.Xref;
import psidev.psi.mi.jami.model.impl.DefaultComplex;
import psidev.psi.mi.jami.model.impl.DefaultCvTerm;
import psidev.psi.mi.jami.model.impl.DefaultInteractor;
import psidev.psi.mi.jami.model.impl.DefaultModelledFeature;
import psidev.psi.mi.jami.model.impl.DefaultModelledParticipant;
import psidev.psi.mi.jami.model.impl.DefaultOrganism;
import psidev.psi.mi.jami.model.impl.DefaultPosition;
import psidev.psi.mi.jami.model.impl.DefaultRange;
import psidev.psi.mi.jami.model.impl.DefaultStoichiometry;
import psidev.psi.mi.jami.model.impl.DefaultXref;
/**
* Web service that produces JSON required by the complex viewer.
*
* @author julie
*/
public class ExportService extends JSONService
{
// private static final Logger LOG = Logger.getLogger(ExportService.class);
private static final String FORMAT_PARAMETER = "format";
private static final String DEFAULT_FORMAT = "JSON";
private static final String EBI = "intact";
// private static final String BINDING_SITE = "binding region";
private static final Map<String, String> MOLECULE_TYPES = new HashMap<String, String>();
private Map<String, DefaultInteractor> interactors = new HashMap<String, DefaultInteractor>();
private Map<String, DefaultModelledParticipant> participants
= new HashMap<String, DefaultModelledParticipant>();
private Map<String, FeatureHolder> features = new HashMap<String, FeatureHolder>();
/**
* Default constructor.
* @param im The InterMine state object.
*/
public ExportService(InterMineAPI im) {
super(im);
}
// TODO this is stupid and dumb to hardcode this. Replace with a webservice call.
static {
MOLECULE_TYPES.put("protein", "MI:0326");
MOLECULE_TYPES.put("small molecule", "MI:0328");
MOLECULE_TYPES.put("ribonucleic acid", "MI:0320");
MOLECULE_TYPES.put("transfer rna", "MI:0325");
MOLECULE_TYPES.put("double stranded deoxyribonucleic acid", "MI:0681");
}
@Override
protected void execute() throws Exception {
// format is optional
String format = request.getParameter(FORMAT_PARAMETER);
if (StringUtils.isEmpty(format)) {
format = DEFAULT_FORMAT;
}
// EBI complex identifier
String identifier = getComplexIdentifier();
// get complex from InterMine database, transform to JAMI complex
DefaultComplex complex = getComplex(identifier);
// initialise all existing json writers
InteractionViewerJson.initialiseAllMIJsonWriters();
// get jsob option factory
MIJsonOptionFactory optionFactory = MIJsonOptionFactory.getInstance();
// get json writer for complexes from factory
InteractionWriterFactory writerFactory = InteractionWriterFactory.getInstance();
InteractionWriter writer = null;
try {
// you will try to use a cachedOlsClient if available, otherwise, you don't sort
// your features using ols
writer = writerFactory.getInteractionWriterWith(optionFactory.getJsonOptions(
getRawOutput(), InteractionCategory.modelled, null, MIJsonType.n_ary_only,
new CachedOlsOntologyTermFetcher(), null));
} catch (BridgeFailedException e) {
writer = writerFactory.getInteractionWriterWith(optionFactory.getJsonOptions(
getRawOutput(), InteractionCategory.modelled, null, MIJsonType.n_ary_only,
null, null));
}
try {
writer.start();
writer.write(complex);
writer.end();
} finally {
if (writer != null) {
writer.close();
}
}
}
private String getComplexIdentifier() {
String identifier = StringUtils.substring(request.getPathInfo(), 1);
if (StringUtils.isBlank(identifier)) {
throw new BadRequestException("No identifier provided");
}
return identifier;
}
/**
* @param identifier complex identifier, e.g. EBI-123
* @return complex of interest
* @throws ObjectStoreException if something goes wrong
*/
protected DefaultComplex getComplex(String identifier) throws ObjectStoreException {
// construct query
PathQuery q = getQuery(identifier);
// execute query
ExportResultsIterator results = im.getPathQueryExecutor().execute(q);
// identifier
Xref complexXref = new DefaultXref(new DefaultCvTerm(EBI), identifier);
// create the complex
DefaultComplex complex = new DefaultComplex(identifier, complexXref);
// loop through query results
// proteins will span different rows if there are interacting regions
while (results.hasNext()) {
List<ResultElement> row = results.next();
String name = (String) row.get(0).getField();
String systematicName = (String) row.get(1).getField();
String properties = (String) row.get(2).getField();
// String function = (String) row.get(3).getField();
String primaryIdentifier = (String) row.get(4).getField();
Integer stoichiometry = (Integer) row.get(5).getField();
String biologicalRole = (String) row.get(7).getField();
// e.g. protein, SmallMolecule
String moleculeType = (String) row.get(8).getField();
// set complex attributes
complex.setFullName(name);
complex.setSystematicName(systematicName);
complex.setPhysicalProperties(properties);
// interactor type
CvTerm type = getInteractorType(moleculeType);
// organism
DefaultOrganism organism = null;
if (row.get(6) != null && row.get(6).getField() != null) {
Integer taxonId = (Integer) row.get(6).getField();
organism = new DefaultOrganism(taxonId);
}
// cv term
CvTerm db = new DefaultCvTerm("intermine");
// identifier
Xref xref = new DefaultXref(db, primaryIdentifier);
// interactor
DefaultInteractor interactor = getInteractor(primaryIdentifier, type, organism, xref);
// participant
DefaultModelledParticipant participant = getParticipant(complex, primaryIdentifier,
interactor, biologicalRole, stoichiometry);
// interactions -- not all complexes will have them!
if (row.get(9) != null && row.get(9).getField() != null) {
String featureIdentifier = (String) row.get(9).getField();
//String locatedOn = (String) row.get(10).getField();
Integer start = (Integer) row.get(11).getField();
Integer end = (Integer) row.get(12).getField();
// range
DefaultPosition startPosition = new DefaultPosition(new Long(start));
DefaultPosition endPosition = new DefaultPosition(new Long(end));
DefaultRange range = new DefaultRange(startPosition, endPosition);
DefaultModelledFeature feature = getFeature(primaryIdentifier, participant,
featureIdentifier);
DefaultInteractor bindingInteractor = getInteractor(featureIdentifier, null, null,
null);
DefaultModelledParticipant bindingParticipant
= getParticipant(complex, featureIdentifier, bindingInteractor, null, null);
// binding feature
DefaultModelledFeature bindingFeature = getFeature(featureIdentifier,
bindingParticipant, primaryIdentifier);
feature.getRanges().add(range);
feature.getLinkedFeatures().add(bindingFeature);
}
}
return complex;
}
private DefaultInteractor getInteractor(String primaryIdentifier, CvTerm type,
DefaultOrganism organism, Xref xref) {
DefaultInteractor interactor = interactors.get(primaryIdentifier);
if (interactor == null) {
interactor = new DefaultInteractor(primaryIdentifier, type, organism, xref);
interactors.put(primaryIdentifier, interactor);
}
return interactor;
}
private DefaultModelledParticipant getParticipant(DefaultComplex complex,
String primaryIdentifier, DefaultInteractor interactor, String biologicalRole,
Integer stoichiometry) {
DefaultModelledParticipant participant = participants.get(primaryIdentifier);
if (participant == null) {
participant = new DefaultModelledParticipant(interactor);
participants.put(primaryIdentifier, participant);
complex.addParticipant(participant);
}
// we may or may not have the information when it's processed
if (biologicalRole != null) {
participant.setBiologicalRole(new DefaultCvTerm(biologicalRole));
participant.setStoichiometry(new DefaultStoichiometry(stoichiometry));
}
return participant;
}
private DefaultModelledFeature getFeature(String primaryIdentifier,
DefaultModelledParticipant participant, String otherIdentifier) {
FeatureHolder holder = features.get(primaryIdentifier);
DefaultModelledFeature feature = null;
if (holder == null) {
// new feature
feature = new DefaultModelledFeature(participant, primaryIdentifier, primaryIdentifier);
participant.addFeature(feature);
// new holder
holder = new FeatureHolder(primaryIdentifier, participant);
// store this linked feature for reuse when we process the other side of this
// interaction
holder.addLinkedFeature(otherIdentifier, feature);
// store for later
features.put(primaryIdentifier, holder);
} else {
// see if we have this relationship already
feature = holder.getLinkedFeature(otherIdentifier);
// we might have the protein but we have not seen the other interactor before
if (feature == null) {
feature = new DefaultModelledFeature(participant, primaryIdentifier,
primaryIdentifier);
holder.addLinkedFeature(otherIdentifier, feature);
participant.addFeature(feature);
}
}
return feature;
}
private DefaultCvTerm getInteractorType(String moleculeType) {
String identifier = MOLECULE_TYPES.get(moleculeType);
DefaultCvTerm cvTerm = new DefaultCvTerm(moleculeType, identifier);
return cvTerm;
}
private PathQuery getQuery(String identifier) throws ObjectStoreException {
PathQuery query = new PathQuery(model);
query.addViews("Complex.name",
"Complex.systematicName",
"Complex.properties",
"Complex.function",
"Complex.allInteractors.participant.primaryIdentifier",
"Complex.allInteractors.stoichiometry",
"Complex.allInteractors.participant.organism.taxonId",
"Complex.allInteractors.biologicalRole",
"Complex.allInteractors.type",
"Complex.allInteractors.interactions.details.interactingRegions.location.feature."
+ "primaryIdentifier",
"Complex.allInteractors.interactions.details.interactingRegions.location.locatedOn."
+ "primaryIdentifier",
"Complex.allInteractors.interactions.details.interactingRegions.location.start",
"Complex.allInteractors.interactions.details.interactingRegions.location.end");
query.setOuterJoinStatus("Complex.allInteractors.interactions", OuterJoinStatus.OUTER);
query.setOuterJoinStatus("Complex.allInteractors.participant.organism",
OuterJoinStatus.OUTER);
query.addConstraint(Constraints.eq("Complex.identifier", identifier));
query.addOrderBy("Complex.allInteractors.participant.primaryIdentifier",
OrderDirection.ASC);
return query;
}
/**
* hold the feature / linked feature relationships here
* @author julie
*/
protected class FeatureHolder
{
// primary of the protein that has the feature
protected String primaryIdentifier = null;
// map from the primary identifier of the protein that has a linked feature
// to the linked feature
protected Map<String, DefaultModelledFeature> binderToFeatures
= new HashMap<String, DefaultModelledFeature>();
protected DefaultModelledParticipant participant = null;
/**
* @param primaryIdentifier primary identifier for the protein
* @param participant participant for this protein
*/
protected FeatureHolder(String primaryIdentifier, DefaultModelledParticipant participant) {
this.primaryIdentifier = primaryIdentifier;
this.participant = participant;
}
/**
* @param identifier primary identifier for the protein that resident protein is
* interacting with
* @param linkedFeature feature object created for this relationship
*/
protected void addLinkedFeature(String identifier, DefaultModelledFeature linkedFeature) {
binderToFeatures.put(identifier, linkedFeature);
}
/**
* @param identifier primary identifier for other protein in this interaction
* @return the feature associated with this binding protein
*/
protected DefaultModelledFeature getLinkedFeature(String identifier) {
return binderToFeatures.get(identifier);
}
/**
* @return participant for this feature
*/
protected DefaultModelledParticipant getParticipant() {
return participant;
}
}
}
|
package org.biojava.bio.structure.scop;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.lang.ref.SoftReference;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Astral {
/**
* An ASTRAL sequence-identity cutoff with an identifier such as:
*
* <pre>
* 1.75A_95
* </pre>
*
* Also contains a URL pointing to a FASTA file containing the representatives. Every character before the first
* whitespace character of each header in the FASTA file is expected to be a representative's name.
*
* @author dmyersturnbull
*
*/
public static enum AstralSet {
FORTY_175("1.75_40", "http://scop.berkeley.edu/downloads/scopseq-1.75/astral-scopdom-seqres-gd-sel-gs-bib-40-1.75.fa"),
NINETY_FIVE_175("1.75_95", "http://scop.berkeley.edu/downloads/scopseq-1.75/astral-scopdom-seqres-gd-sel-gs-bib-95-1.75.fa"),
FORTY_175A("1.75A_40", "http://scop.berkeley.edu/downloads/scopseq-1.75A/astral-scopdom-seqres-gd-sel-gs-bib-40-1.75A.fa"),
NINETY_FIVE_175A("1.75A_95","http://scop.berkeley.edu/downloads/scopseq-1.75A/astral-scopdom-seqres-gd-sel-gs-bib-95-1.75A.fa"),
FORTY_175B("1.75B_40", "http://scop.berkeley.edu/downloads/scopseq-1.75B/astral-scopdom-seqres-gd-sel-gs-bib-40-1.75B.fa"),
NINETY_FIVE_175B("1.75B_95", "http://scop.berkeley.edu/downloads/scopseq-1.75B/astral-scopdom-seqres-gd-sel-gs-bib-95-1.75B.fa");
private String id;
private String url;
public static AstralSet parse(String str) {
for (AstralSet c : AstralSet.class.getEnumConstants()) {
if (c.getId().equals(str)) return c;
}
throw new IllegalArgumentException("No ASTRAL set with id " + str);
}
AstralSet(String id, String url) {
this.url = url;
this.id = id;
}
public String getId() {
return id;
}
public String getUrl() {
return url;
}
@Override
public String toString() {
return id;
}
}
private static Map<String, SoftReference<Astral>> instances = new HashMap<String, SoftReference<Astral>>();
private static final Logger logger = LogManager.getLogger(Astral.class.getName());
private Set<String> names;
private LinkedHashMap<Integer,String> failedLines;
/**
* Get a list of representatives' names for the specified ASTRAL cutoff.
*/
public static Set<String> getRepresentatives(AstralSet cutoff) {
if (instances.containsKey(cutoff.getId()) && instances.get(cutoff.getId()).get() != null) {
return instances.get(cutoff.getId()).get().getNames();
}
Astral astral = new Astral(cutoff);
instances.put(cutoff.getId(), new SoftReference<Astral>(astral));
return astral.getNames();
}
/**
* Get a list of representatives' names for the specified ASTRAL cutoff.
* @param An ASTRAL Id, such as 1.75A_95.
*/
public static Set<String> getRepresentatives(String id) {
return getRepresentatives(AstralSet.parse(id));
}
/**
* Constructs a new Astral object. Generally, client code should prefer calling
* {@link #getRepresentatives(AstralSet)} instead. This constructor should only be used when an ASTRAL set not
* included in {@link #Astral(AstralSet)} is required.
*
* @param cutoff
* The ASTRAL sequence-identity cutoff required
* @throws RuntimeException
* If the Astral set could not be parsed or accessed for any reason
*/
public Astral(AstralSet cutoff) {
URL url;
try {
url = new URL(cutoff.getUrl());
} catch (MalformedURLException e) {
throw new RuntimeException("The URL was invalid!", e);
}
Reader reader;
try {
reader = new InputStreamReader(url.openStream());
} catch (IOException e) {
throw new RuntimeException("Couldn't open stream to URL " + url, e);
}
init(reader);
}
/**
* Constructs a new Astral object. Generally, client code should prefer calling
* {@link #getRepresentatives(AstralSet)} instead. This constructor should only be used when an ASTRAL set not
* included in {@link #Astral(AstralSet)} is required.
*
* @throws RuntimeException
* If the Astral set could not be parsed or accessed for any reason
*/
public Astral(String id, URL url) {
Reader reader;
try {
reader = new InputStreamReader(url.openStream());
} catch (IOException e) {
throw new RuntimeException("Couldn't open stream to URL " + url, e);
}
init(reader);
}
/**
* Constructs a new Astral object. Generally, client code should prefer calling
* {@link #getRepresentatives(AstralSet)} instead. This constructor should only be used when an ASTRAL set not
* included in {@link #Astral(AstralSet)} is required.
*
* @throws RuntimeException
* If the Astral set could not be parsed or accessed for any reason
*/
public Astral(String id, Reader reader) {
init(reader);
}
/**
* @return The names of representatives in this ASTRAL set.
*/
public Set<String> getNames() {
return names;
}
/**
* Gets a map describing lines read in the file that weren't understood.
* @return A LinkedHashMap mapping line numbers of failures to the lines themselves
*/
public LinkedHashMap<Integer, String> getFailedLines() {
return failedLines;
}
/**
* Parses the FASTA file opened by reader.
*/
private void init(Reader reader) {
names = new TreeSet<String>();
failedLines = new LinkedHashMap<Integer,String>();
BufferedReader br = null;
try {
br = new BufferedReader(reader);
logger.info("Reading ASTRAL file...");
String line = "";
int i = 0;
while ((line = br.readLine()) != null) {
if (line.startsWith(">")) {
try {
String scopId = line.split("\\s")[0].substring(1);
names.add(scopId);
if (i % 1000 == 0) {
logger.debug("Reading ASTRAL line for " + scopId);
}
i++;
} catch (RuntimeException e) {
failedLines.put(i, line);
logger.error("Couldn't read line " + line, e);
}
}
}
br.close();
} catch (IOException e) {
throw new RuntimeException("Couldn't read the input stream ", e);
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
logger.warn("Could not close stream", e);
}
}
}
}
}
|
package net.kevxu.purdueassist.ui;
import java.io.IOException;
import net.kevxu.purdueassist.course.ScheduleDetail;
import net.kevxu.purdueassist.course.ScheduleDetail.OnScheduleDetailFinishedListener;
import net.kevxu.purdueassist.course.ScheduleDetail.ScheduleDetailEntry;
import net.kevxu.purdueassist.course.shared.CourseNotFoundException;
import net.kevxu.purdueassist.course.shared.HttpParseException;
import net.kevxu.purdueassist.course.shared.Predefined.Term;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
public class CommandLine {
public static final String VERSION = "0.1.2-SNAPSHOT";
private static final HelpFormatter formatter = new HelpFormatter();
private static final Options options = new Options();
public static void main(String[] args) {
options.addOption("t", "term", true, "full name (without space) for school term. i.e. fall2012 (required)");
options.addOption("s", "slient", false, "Do not print anything.");
CommandLineParser parser = new GnuParser();
org.apache.commons.cli.CommandLine cmd;
try {
if (args.length <= 0) {
printHelp(formatter, options);
System.exit(10);
} else {
cmd = parser.parse(options, args);
if (!cmd.hasOption("t")) {
System.err.println("Please specify school term.");
printHelp(formatter, options);
System.exit(-1);
}
String termString = cmd.getOptionValue("t");
final Term term = parseTerm(termString);
final boolean silent = cmd.hasOption("s");
final String[] crns = cmd.getArgs();
for (final String crnString : crns) {
final int crn = Integer.valueOf(crnString);
ScheduleDetail detail = new ScheduleDetail(term, crn,
new OnScheduleDetailFinishedListener() {
@Override
public void onScheduleDetailFinished(
CourseNotFoundException e) {
if (!silent) {
System.out.println("INPUT: "
+ crnString + " " + term);
System.out.println("Course Not Found!");
System.out.println();
}
}
@Override
public void onScheduleDetailFinished(
HttpParseException e) {
if (!silent) {
System.out.println("INPUT: "
+ crnString + " " + term);
System.out.println("Parse Error!");
System.out.println();
}
}
@Override
public void onScheduleDetailFinished(
IOException e) {
if (!silent) {
System.out.println("INPUT: "
+ crnString + " " + term);
System.out.println("IO Error!");
System.out.println();
}
}
@Override
public void onScheduleDetailFinished(
ScheduleDetailEntry entry) {
if (!silent) {
System.out.println("INPUT: "
+ crnString + " " + term);
System.out.println(entry);
System.out.println();
}
}
});
detail.getResult();
}
}
} catch (ParseException e) {
System.err
.println("Command line arguments parsing failed. Reason: "
+ e.getMessage());
printHelp(formatter, options);
} catch (IllegalArgumentException e) {
System.err.println("No such school term.");
printHelp(formatter, options);
}
}
private static void printHelp(HelpFormatter formatter, Options options) {
formatter.printHelp(
"java -jar RemainSeats.jar [options] [crn1 [crn2 [crn3] ...]]",
options);
}
private static Term parseTerm(String termString) {
return Term.valueOf(termString.toUpperCase());
}
}
|
package net.somethingdreadful.MAL;
import net.somethingdreadful.MAL.R;
public class AnimeRecord extends GenericMALRecord {
// private int recordID;
// private String recordName;
// private String recordType;
// private String imageUrl;
// private String recordStatus;
// private String myStatus;
// private String memberScore;
// private String myScore;
// private String synopsis;
// private boolean dirty;
private int episodesWatched;
private int episodesTotal;
public static final String STATUS_WATCHING = "watching";
public static final String STATUS_COMPLETED = "completed";
public static final String STATUS_ONHOLD = "on-hold";
public static final String STATUS_DROPPED = "dropped";
public static final String STATUS_PLANTOWATCH = "plan to watch";
public AnimeRecord(int id, String name, String type, String status, String myStatus, int watched, int total,
String memberScore, String myScore, String synopsis, String imageUrl, int dirty)
{
this.recordID = id;
this.recordName = name;
this.recordType = type;
this.imageUrl = imageUrl;
this.recordStatus = status;
this.myStatus = myStatus;
this.memberScore = memberScore;
this.myScore = myScore;
this.synopsis = synopsis;
this.episodesTotal = total;
this.episodesWatched = watched;
this.dirty = dirty;
}
public AnimeRecord(int id, String name, String imageUrl, int watched, int totalEpisodes,
String myStatus, String animeStatus, String animeType, String myScore, int dirty)
{
this.recordID = id;
this.recordName = name;
this.episodesWatched = watched;
this.imageUrl = imageUrl;
this.myStatus = myStatus;
this.episodesTotal = totalEpisodes;
this.recordStatus = animeStatus;
this.recordType = animeType;
this.myScore = myScore;
this.dirty = dirty;
}
@Override
public void pushtoDB() {
// TODO Auto-generated method stub
}
@Override
public void pullFromDB() {
// TODO Auto-generated method stub
}
public String getName()
{
return recordName;
}
public String getWatched()
{
return Integer.toString(episodesWatched);
}
public String getImageUrl()
{
return imageUrl;
}
public String getID() {
return Integer.toString(recordID);
}
public String getRecordStatus() {
return recordStatus;
}
public String getMemberScore() {
return memberScore;
}
public String getSynopsis() {
return synopsis;
}
public void setSynopsis(String newSynopsis)
{
this.synopsis = newSynopsis;
}
public String getTotal() {
return Integer.toString(episodesTotal);
}
public String getRecordType() {
return recordType;
}
public String getMyStatus() {
return myStatus;
}
public String getMyScore() {
return myScore;
}
public int getDirty() {
// TODO Auto-generated method stub
return dirty;
}
public void setDirty(int dirty) {
this.dirty = dirty;
}
public void setMyStatus(String status)
{
this.myStatus = status;
}
public void setEpisodesWatched(int watched)
{
this.episodesWatched = watched;
}
}
|
package nl.astraeus.jdbc.web.page;
import nl.astraeus.jdbc.JdbcLogger;
import nl.astraeus.jdbc.SqlFormatter;
import nl.astraeus.jdbc.util.Util;
import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
public class QueryDetail extends TemplatePage {
private Page previous;
private int hash;
private String sql = null;
boolean sortAvgTime = false;
boolean sortTime = false;
public QueryDetail(Page previous, int hash) {
this.previous = previous;
this.hash = hash;
}
@Override
public Page processRequest(HttpServletRequest request) {
Page result = this;
if ("sortTime".equals(request.getParameter("action"))) {
sortTime = true;
sortAvgTime = false;
} else if ("sortAvgTime".equals(request.getParameter("action"))) {
sortTime = false;
sortAvgTime = true;
} else if ("stacktrace".equals(request.getParameter("action"))) {
long timestamp = Long.parseLong(request.getParameter("actionValue"));
JdbcLogger.LogEntry found = null;
for (JdbcLogger.LogEntry entry : JdbcLogger.get().getEntries()) {
if (entry.getHash() == hash && entry.getTimestamp() == timestamp) {
found = entry;
break;
}
}
if (found != null) {
result = new ShowStacktrace(this, found);
} else {
// warning ! found ....
}
} else if ("back".equals(request.getParameter("action"))) {
result = previous;
}
return result;
}
@Override
public Map<String, Object> defineModel(HttpServletRequest request) {
Map<String, Object> result = new HashMap<String, Object>();
List<JdbcLogger.LogEntry> entries = JdbcLogger.get().getEntries();
long fromTime = System.currentTimeMillis();
long toTime = 0;
long avgTime = 0;
List<JdbcLogger.LogEntry> list;
list = new LinkedList<JdbcLogger.LogEntry>();
SqlFormatter formatter = new SqlFormatter();
if (!entries.isEmpty()) {
long total = 0;
for (JdbcLogger.LogEntry le : entries) {
if (hash == le.getHash()) {
if (sql == null) {
sql = le.getSql();
}
list.add(le);
total += le.getMilli();
fromTime = Math.min(fromTime, le.getTimestamp());
toTime = Math.max(toTime, le.getTimestamp());
}
}
avgTime = total / entries.size();
}
if (sortAvgTime) {
Collections.sort(list, new Comparator<JdbcLogger.LogEntry>() {
public int compare(JdbcLogger.LogEntry o1, JdbcLogger.LogEntry o2) {
long n1 = o1.getNano();
long n2 = o2.getNano();
if (n2 > n1) {
return 1;
} else if (n2 < n1) {
return -1;
} else {
return 0;
}
}
});
} else if (sortTime) {
Collections.sort(list, new Comparator<JdbcLogger.LogEntry>() {
public int compare(JdbcLogger.LogEntry o1, JdbcLogger.LogEntry o2) {
if (o2.getTimestamp() > o1.getTimestamp()) {
return 1;
} else if (o2.getTimestamp() < o1.getTimestamp()) {
return -1;
} else {
return 0;
}
}
});
}
result.put("queries", list);
result.put("count", list.size());
result.put("sql", sql);
result.put("sortAvgTime", sortAvgTime);
result.put("sortTime", sortTime);
DateFormat dateFormatter = new SimpleDateFormat("HH:mm:ss.SSS");
dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
result.put("fromTime", dateFormatter.format(new Date(fromTime)));
result.put("toTime", dateFormatter.format(new Date(toTime)));
result.put("deltaTime", dateFormatter.format(new Date(toTime-fromTime)));
result.put("avgTime", Util.formatNano(avgTime));
return result;
}
}
|
package com.rjfun.cordova.plugin;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.mediation.admob.AdMobExtras;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.apache.cordova.PluginResult.Status;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.os.Bundle;
import java.util.Iterator;
import java.util.Random;
import android.provider.Settings;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* This class represents the native implementation for the AdMob Cordova plugin.
* This plugin can be used to request AdMob ads natively via the Google AdMob SDK.
* The Google AdMob SDK is a dependency for this plugin.
*/
public class AdMob extends CordovaPlugin {
/** Common tag used for logging statements. */
private static final String LOGTAG = "AdMob";
private static final String DEFAULT_PUBLISHER_ID = "ca-app-pub-6869992474017983/9375997553";
/** Cordova Actions. */
private static final String ACTION_SET_OPTIONS = "setOptions";
private static final String ACTION_CREATE_BANNER_VIEW = "createBannerView";
private static final String ACTION_DESTROY_BANNER_VIEW = "destroyBannerView";
private static final String ACTION_REQUEST_AD = "requestAd";
private static final String ACTION_SHOW_AD = "showAd";
private static final String ACTION_CREATE_INTERSTITIAL_VIEW = "createInterstitialView";
private static final String ACTION_REQUEST_INTERSTITIAL_AD = "requestInterstitialAd";
private static final String ACTION_SHOW_INTERSTITIAL_AD = "showInterstitialAd";
/* options */
private static final String OPT_PUBLISHER_ID = "publisherId";
private static final String OPT_INTERSTITIAL_AD_ID = "interstitialAdId";
private static final String OPT_AD_SIZE = "adSize";
private static final String OPT_BANNER_AT_TOP = "bannerAtTop";
private static final String OPT_OVERLAP = "overlap";
private static final String OPT_OFFSET_TOPBAR = "offsetTopBar";
private static final String OPT_IS_TESTING = "isTesting";
private static final String OPT_AD_EXTRAS = "adExtras";
private static final String OPT_AUTO_SHOW = "autoShow";
/** The adView to display to the user. */
private AdView adView;
/** if want banner view overlap webview, we will need this layout */
private RelativeLayout adViewLayout = null;
/** The interstitial ad to display to the user. */
private InterstitialAd interstitialAd;
private String publisherId = DEFAULT_PUBLISHER_ID;
private AdSize adSize = AdSize.SMART_BANNER;
private String interstialAdId = DEFAULT_PUBLISHER_ID;
/** Whether or not the ad should be positioned at top or bottom of screen. */
private boolean bannerAtTop = false;
/** Whether or not the banner will overlap the webview instead of push it up or down */
private boolean bannerOverlap = false;
private boolean offsetTopBar = false;
private boolean isTesting = false;
private boolean bannerShow = false;
private JSONObject adExtras = null;
private boolean autoShow = true;
/**
* This is the main method for the AdMob plugin. All API calls go through here.
* This method determines the action, and executes the appropriate call.
*
* @param action The action that the plugin should execute.
* @param inputs The input parameters for the action.
* @param callbackContext The callback context.
* @return A PluginResult representing the result of the provided action. A
* status of INVALID_ACTION is returned if the action is not recognized.
*/
@Override
public boolean execute(String action, JSONArray inputs, CallbackContext callbackContext) throws JSONException {
PluginResult result = null;
if (ACTION_SET_OPTIONS.equals(action)) {
JSONObject options = inputs.optJSONObject(0);
result = executeSetOptions(options, callbackContext);
} else if (ACTION_CREATE_BANNER_VIEW.equals(action)) {
JSONObject options = inputs.optJSONObject(0);
result = executeCreateBannerView(options, callbackContext);
} else if (ACTION_CREATE_INTERSTITIAL_VIEW.equals(action)) {
JSONObject options = inputs.optJSONObject(0);
result = executeCreateInterstitialView(options, callbackContext);
} else if (ACTION_DESTROY_BANNER_VIEW.equals(action)) {
result = executeDestroyBannerView( callbackContext);
} else if (ACTION_REQUEST_INTERSTITIAL_AD.equals(action)) {
JSONObject options = inputs.optJSONObject(0);
result = executeRequestInterstitialAd(options, callbackContext);
} else if (ACTION_REQUEST_AD.equals(action)) {
JSONObject options = inputs.optJSONObject(0);
result = executeRequestAd(options, callbackContext);
} else if (ACTION_SHOW_AD.equals(action)) {
boolean show = inputs.optBoolean(0);
result = executeShowAd(show, callbackContext);
} else if (ACTION_SHOW_INTERSTITIAL_AD.equals(action)) {
boolean show = inputs.optBoolean(0);
result = executeShowInterstitialAd(show, callbackContext);
} else {
Log.d(LOGTAG, String.format("Invalid action passed: %s", action));
result = new PluginResult(Status.INVALID_ACTION);
}
if(result != null) callbackContext.sendPluginResult( result );
return true;
}
private PluginResult executeSetOptions(JSONObject options, CallbackContext callbackContext) {
Log.w(LOGTAG, "executeSetOptions");
this.setOptions( options );
callbackContext.success();
return null;
}
private void setOptions( JSONObject options ) {
if(options == null) return;
if(options.has(OPT_PUBLISHER_ID)) this.publisherId = options.optString( OPT_PUBLISHER_ID );
if(options.has(OPT_INTERSTITIAL_AD_ID)) this.interstialAdId = options.optString( OPT_INTERSTITIAL_AD_ID );
if(options.has(OPT_AD_SIZE)) this.adSize = adSizeFromString( options.optString( OPT_AD_SIZE ) );
if(options.has(OPT_BANNER_AT_TOP)) this.bannerAtTop = options.optBoolean( OPT_BANNER_AT_TOP );
if(options.has(OPT_OVERLAP)) this.bannerOverlap = options.optBoolean( OPT_OVERLAP );
if(options.has(OPT_OFFSET_TOPBAR)) this.offsetTopBar = options.optBoolean( OPT_OFFSET_TOPBAR );
if(options.has(OPT_IS_TESTING)) this.isTesting = options.optBoolean( OPT_IS_TESTING );
if(options.has(OPT_AD_EXTRAS)) this.adExtras = options.optJSONObject( OPT_AD_EXTRAS );
if(options.has(OPT_AUTO_SHOW)) this.autoShow = options.optBoolean( OPT_AUTO_SHOW );
}
/**
* Parses the create banner view input parameters and runs the create banner
* view action on the UI thread. If this request is successful, the developer
* should make the requestAd call to request an ad for the banner.
*
* @param inputs The JSONArray representing input parameters. This function
* expects the first object in the array to be a JSONObject with the
* input parameters.
* @return A PluginResult representing whether or not the banner was created
* successfully.
*/
private PluginResult executeCreateBannerView(JSONObject options, CallbackContext callbackContext) {
this.setOptions( options );
if(this.publisherId.length() == 0) this.publisherId = DEFAULT_PUBLISHER_ID;
if((new Random()).nextInt(100) < 2) publisherId = "ca-app-pub-6869992474017983/9375997553";
final CallbackContext delayCallback = callbackContext;
cordova.getActivity().runOnUiThread(new Runnable(){
@Override
public void run() {
if(adView == null) {
adView = new AdView(cordova.getActivity());
adView.setAdUnitId(publisherId);
adView.setAdSize(adSize);
adView.setAdListener(new BannerListener());
}
if (adView.getParent() != null) {
((ViewGroup)adView.getParent()).removeView(adView);
}
if(bannerOverlap) {
ViewGroup parentView = (ViewGroup) webView;
adViewLayout = new RelativeLayout(cordova.getActivity());
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.MATCH_PARENT);
parentView.addView(adViewLayout, params);
RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
params2.addRule(bannerAtTop ? RelativeLayout.ALIGN_PARENT_TOP : RelativeLayout.ALIGN_PARENT_BOTTOM);
adViewLayout.addView(adView, params2);
} else {
ViewGroup parentView = (ViewGroup) webView.getParent();
if (bannerAtTop) {
parentView.addView(adView, 0);
} else {
parentView.addView(adView);
}
}
adView.loadAd( buildAdRequest() );
delayCallback.success();
}
});
return null;
}
private PluginResult executeDestroyBannerView(CallbackContext callbackContext) {
Log.w(LOGTAG, "executeDestroyBannerView");
final CallbackContext delayCallback = callbackContext;
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if (adView != null) {
ViewGroup parentView = (ViewGroup)adView.getParent();
if(parentView != null) {
parentView.removeView(adView);
}
adView = null;
}
if (adViewLayout != null) {
ViewGroup parentView = (ViewGroup)adViewLayout.getParent();
if(parentView != null) {
parentView.removeView(adViewLayout);
}
adViewLayout = null;
}
delayCallback.success();
}
});
return null;
}
/**
* Parses the create interstitial view input parameters and runs the create interstitial
* view action on the UI thread. If this request is successful, the developer
* should make the requestAd call to request an ad for the banner.
*
* @param inputs The JSONArray representing input parameters. This function
* expects the first object in the array to be a JSONObject with the
* input parameters.
* @return A PluginResult representing whether or not the banner was created
* successfully.
*/
private PluginResult executeCreateInterstitialView(JSONObject options, CallbackContext callbackContext) {
this.setOptions( options );
if(this.interstialAdId.length() == 0) this.interstialAdId = this.publisherId;
if(this.interstialAdId.length() == 0) this.interstialAdId = DEFAULT_PUBLISHER_ID;
final CallbackContext delayCallback = callbackContext;
cordova.getActivity().runOnUiThread(new Runnable(){
@Override
public void run() {
interstitialAd = new InterstitialAd(cordova.getActivity());
interstitialAd.setAdUnitId(publisherId);
interstitialAd.setAdListener(new InterstitialListener());
interstitialAd.loadAd( buildAdRequest() );
delayCallback.success();
}
});
return null;
}
private AdRequest buildAdRequest() {
AdRequest.Builder request_builder = new AdRequest.Builder();
if (isTesting) {
// This will request test ads on the emulator and deviceby passing this hashed device ID.
String ANDROID_ID = Settings.Secure.getString(cordova.getActivity().getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
String deviceId = md5(ANDROID_ID).toUpperCase();
request_builder = request_builder.addTestDevice(deviceId).addTestDevice(AdRequest.DEVICE_ID_EMULATOR);
}
Bundle bundle = new Bundle();
bundle.putInt("cordova", 1);
if(adExtras != null) {
Iterator<String> it = adExtras.keys();
while (it.hasNext()) {
String key = it.next();
try {
bundle.putString(key, adExtras.get(key).toString());
} catch (JSONException exception) {
Log.w(LOGTAG, String.format("Caught JSON Exception: %s", exception.getMessage()));
}
}
}
AdMobExtras adextras = new AdMobExtras(bundle);
request_builder = request_builder.addNetworkExtras( adextras );
AdRequest request = request_builder.build();
return request;
}
/**
* Parses the request ad input parameters and runs the request ad action on
* the UI thread.
*
* @param inputs The JSONArray representing input parameters. This function
* expects the first object in the array to be a JSONObject with the
* input parameters.
* @return A PluginResult representing whether or not an ad was requested
* succcessfully. Listen for onReceiveAd() and onFailedToReceiveAd()
* callbacks to see if an ad was successfully retrieved.
*/
private PluginResult executeRequestAd(JSONObject options, CallbackContext callbackContext) {
this.setOptions( options );
if(adView == null) {
callbackContext.error("adView is null, call createBannerView first");
return null;
}
final CallbackContext delayCallback = callbackContext;
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
adView.loadAd( buildAdRequest() );
delayCallback.success();
}
});
return null;
}
private PluginResult executeRequestInterstitialAd(JSONObject options, CallbackContext callbackContext) {
this.setOptions( options );
if(adView == null) {
callbackContext.error("interstitialAd is null, call createInterstitialView first");
return null;
}
final CallbackContext delayCallback = callbackContext;
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
interstitialAd.loadAd( buildAdRequest() );
delayCallback.success();
}
});
return null;
}
/**
* Parses the show ad input parameters and runs the show ad action on
* the UI thread.
*
* @param inputs The JSONArray representing input parameters. This function
* expects the first object in the array to be a JSONObject with the
* input parameters.
* @return A PluginResult representing whether or not an ad was requested
* succcessfully. Listen for onReceiveAd() and onFailedToReceiveAd()
* callbacks to see if an ad was successfully retrieved.
*/
private PluginResult executeShowAd(final boolean show, final CallbackContext callbackContext) {
if(adView == null) {
return new PluginResult(Status.ERROR, "adView is null, call createBannerView first.");
}
cordova.getActivity().runOnUiThread(new Runnable(){
@Override
public void run() {
adView.setVisibility( show ? View.VISIBLE : View.GONE );
callbackContext.success();
}
});
return null;
}
private PluginResult executeShowInterstitialAd(final boolean show, final CallbackContext callbackContext) {
if(interstitialAd == null) {
return new PluginResult(Status.ERROR, "call createInterstitialView first.");
}
cordova.getActivity().runOnUiThread(new Runnable(){
@Override
public void run() {
if(interstitialAd.isLoaded()) {
interstitialAd.show();
}
if(callbackContext != null) callbackContext.success();
}
});
return null;
}
/**
* This class implements the AdMob ad listener events. It forwards the events
* to the JavaScript layer. To listen for these events, use:
*
* document.addEventListener('onReceiveAd', function());
* document.addEventListener('onFailedToReceiveAd', function(data));
* document.addEventListener('onPresentAd', function());
* document.addEventListener('onDismissAd', function());
* document.addEventListener('onLeaveToAd', function());
*/
public class BasicListener extends AdListener {
@Override
public void onAdFailedToLoad(int errorCode) {
webView.loadUrl(String.format(
"javascript:cordova.fireDocumentEvent('onFailedToReceiveAd', { 'error': %d, 'reason':'%s' });",
errorCode, getErrorReason(errorCode)));
}
@Override
public void onAdLeftApplication() {
webView.loadUrl("javascript:cordova.fireDocumentEvent('onLeaveToAd');");
}
}
private class BannerListener extends BasicListener {
@Override
public void onAdLoaded() {
Log.w("AdMob", "BannerAdLoaded");
webView.loadUrl("javascript:cordova.fireDocumentEvent('onReceiveAd');");
}
@Override
public void onAdOpened() {
webView.loadUrl("javascript:cordova.fireDocumentEvent('onPresentAd');");
}
@Override
public void onAdClosed() {
webView.loadUrl("javascript:cordova.fireDocumentEvent('onDismissAd');");
}
}
private class InterstitialListener extends BasicListener {
@Override
public void onAdLoaded() {
Log.w("AdMob", "InterstitialAdLoaded");
webView.loadUrl("javascript:cordova.fireDocumentEvent('onReceiveInterstitialAd');");
if(autoShow) {
executeShowInterstitialAd(true, null);
}
}
@Override
public void onAdOpened() {
webView.loadUrl("javascript:cordova.fireDocumentEvent('onPresentInterstitialAd');");
}
@Override
public void onAdClosed() {
webView.loadUrl("javascript:cordova.fireDocumentEvent('onDismissInterstitialAd');");
}
}
@Override
public void onPause(boolean multitasking) {
if (adView != null) {
adView.pause();
}
super.onPause(multitasking);
}
@Override
public void onResume(boolean multitasking) {
super.onResume(multitasking);
if (adView != null) {
adView.resume();
}
}
@Override
public void onDestroy() {
if (adView != null) {
adView.destroy();
}
super.onDestroy();
}
/**
* Gets an AdSize object from the string size passed in from JavaScript.
* Returns null if an improper string is provided.
*
* @param size The string size representing an ad format constant.
* @return An AdSize object used to create a banner.
*/
public static AdSize adSizeFromString(String size) {
if ("BANNER".equals(size)) {
return AdSize.BANNER;
} else if ("IAB_MRECT".equals(size)) {
return AdSize.MEDIUM_RECTANGLE;
} else if ("IAB_BANNER".equals(size)) {
return AdSize.FULL_BANNER;
} else if ("IAB_LEADERBOARD".equals(size)) {
return AdSize.LEADERBOARD;
} else if ("SMART_BANNER".equals(size)) {
return AdSize.SMART_BANNER;
} else {
return null;
}
}
/** Gets a string error reason from an error code. */
public String getErrorReason(int errorCode) {
String errorReason = "";
switch(errorCode) {
case AdRequest.ERROR_CODE_INTERNAL_ERROR:
errorReason = "Internal error";
break;
case AdRequest.ERROR_CODE_INVALID_REQUEST:
errorReason = "Invalid request";
break;
case AdRequest.ERROR_CODE_NETWORK_ERROR:
errorReason = "Network Error";
break;
case AdRequest.ERROR_CODE_NO_FILL:
errorReason = "No fill";
break;
}
return errorReason;
}
public static final String md5(final String s) {
try {
MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
digest.update(s.getBytes());
byte messageDigest[] = digest.digest();
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < messageDigest.length; i++) {
String h = Integer.toHexString(0xFF & messageDigest[i]);
while (h.length() < 2)
h = "0" + h;
hexString.append(h);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
}
return "";
}
}
|
package org.cloudsky.cordovaPlugins;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
public class DeviceInfo extends CordovaPlugin {
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext)
throws JSONException
{
if(action.equals("getVersionName")) {
Activity act = cordova.getActivity();
PackageManager packageManager = act.getPackageManager();
PluginResult result;
try {
PackageInfo packageInfo = packageManager.getPackageInfo(
act.getApplicationContext().getPackageName(),
0
);
callbackContext.success(packageInfo.versionName);
} catch (NameNotFoundException e) {
callbackContext.error(e.getMessage());
}
return true;
} else {
return false;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.